PackageManagerService.java revision 5da9dad2dd04586dbd665e6a73bfee1d0ed92a89
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 synchronized (mPackages) { 2054 for (String permission : pkg.requestedPermissions) { 2055 BasePermission bp = mSettings.mPermissions.get(permission); 2056 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2057 && (grantedPermissions == null 2058 || ArrayUtils.contains(grantedPermissions, permission))) { 2059 final int flags = permissionsState.getPermissionFlags(permission, userId); 2060 // Installer cannot change immutable permissions. 2061 if ((flags & immutableFlags) == 0) { 2062 grantRuntimePermission(pkg.packageName, permission, userId); 2063 } 2064 } 2065 } 2066 } 2067 } 2068 2069 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2070 Bundle extras = null; 2071 switch (res.returnCode) { 2072 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2073 extras = new Bundle(); 2074 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2075 res.origPermission); 2076 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2077 res.origPackage); 2078 break; 2079 } 2080 case PackageManager.INSTALL_SUCCEEDED: { 2081 extras = new Bundle(); 2082 extras.putBoolean(Intent.EXTRA_REPLACING, 2083 res.removedInfo != null && res.removedInfo.removedPackage != null); 2084 break; 2085 } 2086 } 2087 return extras; 2088 } 2089 2090 void scheduleWriteSettingsLocked() { 2091 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2092 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2093 } 2094 } 2095 2096 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2097 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2098 scheduleWritePackageRestrictionsLocked(userId); 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(int userId) { 2102 final int[] userIds = (userId == UserHandle.USER_ALL) 2103 ? sUserManager.getUserIds() : new int[]{userId}; 2104 for (int nextUserId : userIds) { 2105 if (!sUserManager.exists(nextUserId)) return; 2106 mDirtyUsers.add(nextUserId); 2107 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2108 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2109 } 2110 } 2111 } 2112 2113 public static PackageManagerService main(Context context, Installer installer, 2114 boolean factoryTest, boolean onlyCore) { 2115 // Self-check for initial settings. 2116 PackageManagerServiceCompilerMapping.checkProperties(); 2117 2118 PackageManagerService m = new PackageManagerService(context, installer, 2119 factoryTest, onlyCore); 2120 m.enableSystemUserPackages(); 2121 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2122 // disabled after already being started. 2123 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2124 UserHandle.USER_SYSTEM); 2125 ServiceManager.addService("package", m); 2126 return m; 2127 } 2128 2129 private void enableSystemUserPackages() { 2130 if (!UserManager.isSplitSystemUser()) { 2131 return; 2132 } 2133 // For system user, enable apps based on the following conditions: 2134 // - app is whitelisted or belong to one of these groups: 2135 // -- system app which has no launcher icons 2136 // -- system app which has INTERACT_ACROSS_USERS permission 2137 // -- system IME app 2138 // - app is not in the blacklist 2139 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2140 Set<String> enableApps = new ArraySet<>(); 2141 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2142 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2143 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2144 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2145 enableApps.addAll(wlApps); 2146 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2147 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2148 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2149 enableApps.removeAll(blApps); 2150 Log.i(TAG, "Applications installed for system user: " + enableApps); 2151 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2152 UserHandle.SYSTEM); 2153 final int allAppsSize = allAps.size(); 2154 synchronized (mPackages) { 2155 for (int i = 0; i < allAppsSize; i++) { 2156 String pName = allAps.get(i); 2157 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2158 // Should not happen, but we shouldn't be failing if it does 2159 if (pkgSetting == null) { 2160 continue; 2161 } 2162 boolean install = enableApps.contains(pName); 2163 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2164 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2165 + " for system user"); 2166 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2167 } 2168 } 2169 } 2170 } 2171 2172 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2173 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2174 Context.DISPLAY_SERVICE); 2175 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2176 } 2177 2178 public PackageManagerService(Context context, Installer installer, 2179 boolean factoryTest, boolean onlyCore) { 2180 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2181 SystemClock.uptimeMillis()); 2182 2183 if (mSdkVersion <= 0) { 2184 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2185 } 2186 2187 mContext = context; 2188 mFactoryTest = factoryTest; 2189 mOnlyCore = onlyCore; 2190 mMetrics = new DisplayMetrics(); 2191 mSettings = new Settings(mPackages); 2192 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2193 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2194 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2195 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2196 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2197 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2198 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2199 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2200 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2201 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2202 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2203 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2204 2205 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2206 if (separateProcesses != null && separateProcesses.length() > 0) { 2207 if ("*".equals(separateProcesses)) { 2208 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2209 mSeparateProcesses = null; 2210 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2211 } else { 2212 mDefParseFlags = 0; 2213 mSeparateProcesses = separateProcesses.split(","); 2214 Slog.w(TAG, "Running with debug.separate_processes: " 2215 + separateProcesses); 2216 } 2217 } else { 2218 mDefParseFlags = 0; 2219 mSeparateProcesses = null; 2220 } 2221 2222 mInstaller = installer; 2223 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2224 "*dexopt*"); 2225 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2226 2227 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2228 FgThread.get().getLooper()); 2229 2230 getDefaultDisplayMetrics(context, mMetrics); 2231 2232 SystemConfig systemConfig = SystemConfig.getInstance(); 2233 mGlobalGids = systemConfig.getGlobalGids(); 2234 mSystemPermissions = systemConfig.getSystemPermissions(); 2235 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2236 2237 synchronized (mInstallLock) { 2238 // writer 2239 synchronized (mPackages) { 2240 mHandlerThread = new ServiceThread(TAG, 2241 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2242 mHandlerThread.start(); 2243 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2244 mProcessLoggingHandler = new ProcessLoggingHandler(); 2245 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2246 2247 File dataDir = Environment.getDataDirectory(); 2248 mAppInstallDir = new File(dataDir, "app"); 2249 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2250 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2251 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2252 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2253 2254 sUserManager = new UserManagerService(context, this, mPackages); 2255 2256 // Propagate permission configuration in to package manager. 2257 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2258 = systemConfig.getPermissions(); 2259 for (int i=0; i<permConfig.size(); i++) { 2260 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2261 BasePermission bp = mSettings.mPermissions.get(perm.name); 2262 if (bp == null) { 2263 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2264 mSettings.mPermissions.put(perm.name, bp); 2265 } 2266 if (perm.gids != null) { 2267 bp.setGids(perm.gids, perm.perUser); 2268 } 2269 } 2270 2271 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2272 for (int i=0; i<libConfig.size(); i++) { 2273 mSharedLibraries.put(libConfig.keyAt(i), 2274 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2275 } 2276 2277 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2278 2279 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2280 2281 String customResolverActivity = Resources.getSystem().getString( 2282 R.string.config_customResolverActivity); 2283 if (TextUtils.isEmpty(customResolverActivity)) { 2284 customResolverActivity = null; 2285 } else { 2286 mCustomResolverComponentName = ComponentName.unflattenFromString( 2287 customResolverActivity); 2288 } 2289 2290 long startTime = SystemClock.uptimeMillis(); 2291 2292 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2293 startTime); 2294 2295 // Set flag to monitor and not change apk file paths when 2296 // scanning install directories. 2297 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2298 2299 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2300 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2301 2302 if (bootClassPath == null) { 2303 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2304 } 2305 2306 if (systemServerClassPath == null) { 2307 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2308 } 2309 2310 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2311 final String[] dexCodeInstructionSets = 2312 getDexCodeInstructionSets( 2313 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2314 2315 /** 2316 * Ensure all external libraries have had dexopt run on them. 2317 */ 2318 if (mSharedLibraries.size() > 0) { 2319 // NOTE: For now, we're compiling these system "shared libraries" 2320 // (and framework jars) into all available architectures. It's possible 2321 // to compile them only when we come across an app that uses them (there's 2322 // already logic for that in scanPackageLI) but that adds some complexity. 2323 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2324 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2325 final String lib = libEntry.path; 2326 if (lib == null) { 2327 continue; 2328 } 2329 2330 try { 2331 // Shared libraries do not have profiles so we perform a full 2332 // AOT compilation (if needed). 2333 int dexoptNeeded = DexFile.getDexOptNeeded( 2334 lib, dexCodeInstructionSet, 2335 getCompilerFilterForReason(REASON_SHARED_APK), 2336 false /* newProfile */); 2337 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2338 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2339 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2340 getCompilerFilterForReason(REASON_SHARED_APK), 2341 StorageManager.UUID_PRIVATE_INTERNAL); 2342 } 2343 } catch (FileNotFoundException e) { 2344 Slog.w(TAG, "Library not found: " + lib); 2345 } catch (IOException | InstallerException e) { 2346 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2347 + e.getMessage()); 2348 } 2349 } 2350 } 2351 } 2352 2353 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2354 2355 final VersionInfo ver = mSettings.getInternalVersion(); 2356 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2357 2358 // when upgrading from pre-M, promote system app permissions from install to runtime 2359 mPromoteSystemApps = 2360 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2361 2362 // save off the names of pre-existing system packages prior to scanning; we don't 2363 // want to automatically grant runtime permissions for new system apps 2364 if (mPromoteSystemApps) { 2365 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2366 while (pkgSettingIter.hasNext()) { 2367 PackageSetting ps = pkgSettingIter.next(); 2368 if (isSystemApp(ps)) { 2369 mExistingSystemPackages.add(ps.name); 2370 } 2371 } 2372 } 2373 2374 // When upgrading from pre-N, we need to handle package extraction like first boot, 2375 // as there is no profiling data available. 2376 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2377 mSettings.setNWorkDone(); 2378 2379 // Collect vendor overlay packages. 2380 // (Do this before scanning any apps.) 2381 // For security and version matching reason, only consider 2382 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2383 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2384 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2385 | PackageParser.PARSE_IS_SYSTEM 2386 | PackageParser.PARSE_IS_SYSTEM_DIR 2387 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2388 2389 // Find base frameworks (resource packages without code). 2390 scanDirTracedLI(frameworkDir, mDefParseFlags 2391 | PackageParser.PARSE_IS_SYSTEM 2392 | PackageParser.PARSE_IS_SYSTEM_DIR 2393 | PackageParser.PARSE_IS_PRIVILEGED, 2394 scanFlags | SCAN_NO_DEX, 0); 2395 2396 // Collected privileged system packages. 2397 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2398 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2399 | PackageParser.PARSE_IS_SYSTEM 2400 | PackageParser.PARSE_IS_SYSTEM_DIR 2401 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2402 2403 // Collect ordinary system packages. 2404 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2405 scanDirTracedLI(systemAppDir, mDefParseFlags 2406 | PackageParser.PARSE_IS_SYSTEM 2407 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2408 2409 // Collect all vendor packages. 2410 File vendorAppDir = new File("/vendor/app"); 2411 try { 2412 vendorAppDir = vendorAppDir.getCanonicalFile(); 2413 } catch (IOException e) { 2414 // failed to look up canonical path, continue with original one 2415 } 2416 scanDirTracedLI(vendorAppDir, mDefParseFlags 2417 | PackageParser.PARSE_IS_SYSTEM 2418 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2419 2420 // Collect all OEM packages. 2421 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2422 scanDirTracedLI(oemAppDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2425 2426 // Prune any system packages that no longer exist. 2427 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2428 if (!mOnlyCore) { 2429 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2430 while (psit.hasNext()) { 2431 PackageSetting ps = psit.next(); 2432 2433 /* 2434 * If this is not a system app, it can't be a 2435 * disable system app. 2436 */ 2437 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2438 continue; 2439 } 2440 2441 /* 2442 * If the package is scanned, it's not erased. 2443 */ 2444 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2445 if (scannedPkg != null) { 2446 /* 2447 * If the system app is both scanned and in the 2448 * disabled packages list, then it must have been 2449 * added via OTA. Remove it from the currently 2450 * scanned package so the previously user-installed 2451 * application can be scanned. 2452 */ 2453 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2454 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2455 + ps.name + "; removing system app. Last known codePath=" 2456 + ps.codePathString + ", installStatus=" + ps.installStatus 2457 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2458 + scannedPkg.mVersionCode); 2459 removePackageLI(scannedPkg, true); 2460 mExpectingBetter.put(ps.name, ps.codePath); 2461 } 2462 2463 continue; 2464 } 2465 2466 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2467 psit.remove(); 2468 logCriticalInfo(Log.WARN, "System package " + ps.name 2469 + " no longer exists; it's data will be wiped"); 2470 // Actual deletion of code and data will be handled by later 2471 // reconciliation step 2472 } else { 2473 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2474 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2475 possiblyDeletedUpdatedSystemApps.add(ps.name); 2476 } 2477 } 2478 } 2479 } 2480 2481 //look for any incomplete package installations 2482 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2483 for (int i = 0; i < deletePkgsList.size(); i++) { 2484 // Actual deletion of code and data will be handled by later 2485 // reconciliation step 2486 final String packageName = deletePkgsList.get(i).name; 2487 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2488 synchronized (mPackages) { 2489 mSettings.removePackageLPw(packageName); 2490 } 2491 } 2492 2493 //delete tmp files 2494 deleteTempPackageFiles(); 2495 2496 // Remove any shared userIDs that have no associated packages 2497 mSettings.pruneSharedUsersLPw(); 2498 2499 if (!mOnlyCore) { 2500 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2501 SystemClock.uptimeMillis()); 2502 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2503 2504 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2505 | PackageParser.PARSE_FORWARD_LOCK, 2506 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2507 2508 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2509 | PackageParser.PARSE_IS_EPHEMERAL, 2510 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2511 2512 /** 2513 * Remove disable package settings for any updated system 2514 * apps that were removed via an OTA. If they're not a 2515 * previously-updated app, remove them completely. 2516 * Otherwise, just revoke their system-level permissions. 2517 */ 2518 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2519 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2520 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2521 2522 String msg; 2523 if (deletedPkg == null) { 2524 msg = "Updated system package " + deletedAppName 2525 + " no longer exists; it's data will be wiped"; 2526 // Actual deletion of code and data will be handled by later 2527 // reconciliation step 2528 } else { 2529 msg = "Updated system app + " + deletedAppName 2530 + " no longer present; removing system privileges for " 2531 + deletedAppName; 2532 2533 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2534 2535 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2536 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2537 } 2538 logCriticalInfo(Log.WARN, msg); 2539 } 2540 2541 /** 2542 * Make sure all system apps that we expected to appear on 2543 * the userdata partition actually showed up. If they never 2544 * appeared, crawl back and revive the system version. 2545 */ 2546 for (int i = 0; i < mExpectingBetter.size(); i++) { 2547 final String packageName = mExpectingBetter.keyAt(i); 2548 if (!mPackages.containsKey(packageName)) { 2549 final File scanFile = mExpectingBetter.valueAt(i); 2550 2551 logCriticalInfo(Log.WARN, "Expected better " + packageName 2552 + " but never showed up; reverting to system"); 2553 2554 int reparseFlags = mDefParseFlags; 2555 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2556 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2557 | PackageParser.PARSE_IS_SYSTEM_DIR 2558 | PackageParser.PARSE_IS_PRIVILEGED; 2559 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2560 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2561 | PackageParser.PARSE_IS_SYSTEM_DIR; 2562 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2563 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2564 | PackageParser.PARSE_IS_SYSTEM_DIR; 2565 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2566 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2567 | PackageParser.PARSE_IS_SYSTEM_DIR; 2568 } else { 2569 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2570 continue; 2571 } 2572 2573 mSettings.enableSystemPackageLPw(packageName); 2574 2575 try { 2576 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2577 } catch (PackageManagerException e) { 2578 Slog.e(TAG, "Failed to parse original system package: " 2579 + e.getMessage()); 2580 } 2581 } 2582 } 2583 } 2584 mExpectingBetter.clear(); 2585 2586 // Resolve protected action filters. Only the setup wizard is allowed to 2587 // have a high priority filter for these actions. 2588 mSetupWizardPackage = getSetupWizardPackageName(); 2589 if (mProtectedFilters.size() > 0) { 2590 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2591 Slog.i(TAG, "No setup wizard;" 2592 + " All protected intents capped to priority 0"); 2593 } 2594 for (ActivityIntentInfo filter : mProtectedFilters) { 2595 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2596 if (DEBUG_FILTERS) { 2597 Slog.i(TAG, "Found setup wizard;" 2598 + " allow priority " + filter.getPriority() + ";" 2599 + " package: " + filter.activity.info.packageName 2600 + " activity: " + filter.activity.className 2601 + " priority: " + filter.getPriority()); 2602 } 2603 // skip setup wizard; allow it to keep the high priority filter 2604 continue; 2605 } 2606 Slog.w(TAG, "Protected action; cap priority to 0;" 2607 + " package: " + filter.activity.info.packageName 2608 + " activity: " + filter.activity.className 2609 + " origPrio: " + filter.getPriority()); 2610 filter.setPriority(0); 2611 } 2612 } 2613 mDeferProtectedFilters = false; 2614 mProtectedFilters.clear(); 2615 2616 // Now that we know all of the shared libraries, update all clients to have 2617 // the correct library paths. 2618 updateAllSharedLibrariesLPw(); 2619 2620 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2621 // NOTE: We ignore potential failures here during a system scan (like 2622 // the rest of the commands above) because there's precious little we 2623 // can do about it. A settings error is reported, though. 2624 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2625 false /* boot complete */); 2626 } 2627 2628 // Now that we know all the packages we are keeping, 2629 // read and update their last usage times. 2630 mPackageUsage.readLP(); 2631 2632 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2633 SystemClock.uptimeMillis()); 2634 Slog.i(TAG, "Time to scan packages: " 2635 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2636 + " seconds"); 2637 2638 // If the platform SDK has changed since the last time we booted, 2639 // we need to re-grant app permission to catch any new ones that 2640 // appear. This is really a hack, and means that apps can in some 2641 // cases get permissions that the user didn't initially explicitly 2642 // allow... it would be nice to have some better way to handle 2643 // this situation. 2644 int updateFlags = UPDATE_PERMISSIONS_ALL; 2645 if (ver.sdkVersion != mSdkVersion) { 2646 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2647 + mSdkVersion + "; regranting permissions for internal storage"); 2648 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2649 } 2650 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2651 ver.sdkVersion = mSdkVersion; 2652 2653 // If this is the first boot or an update from pre-M, and it is a normal 2654 // boot, then we need to initialize the default preferred apps across 2655 // all defined users. 2656 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2657 for (UserInfo user : sUserManager.getUsers(true)) { 2658 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2659 applyFactoryDefaultBrowserLPw(user.id); 2660 primeDomainVerificationsLPw(user.id); 2661 } 2662 } 2663 2664 // Prepare storage for system user really early during boot, 2665 // since core system apps like SettingsProvider and SystemUI 2666 // can't wait for user to start 2667 final int storageFlags; 2668 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2669 storageFlags = StorageManager.FLAG_STORAGE_DE; 2670 } else { 2671 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2672 } 2673 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2674 storageFlags); 2675 2676 // If this is first boot after an OTA, and a normal boot, then 2677 // we need to clear code cache directories. 2678 if (mIsUpgrade && !onlyCore) { 2679 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2680 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2681 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2682 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2683 // No apps are running this early, so no need to freeze 2684 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2685 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2686 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2687 } 2688 clearAppProfilesLIF(ps.pkg); 2689 } 2690 ver.fingerprint = Build.FINGERPRINT; 2691 } 2692 2693 checkDefaultBrowser(); 2694 2695 // clear only after permissions and other defaults have been updated 2696 mExistingSystemPackages.clear(); 2697 mPromoteSystemApps = false; 2698 2699 // All the changes are done during package scanning. 2700 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2701 2702 // can downgrade to reader 2703 mSettings.writeLPr(); 2704 2705 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2706 SystemClock.uptimeMillis()); 2707 2708 if (!mOnlyCore) { 2709 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2710 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2711 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2712 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2713 mIntentFilterVerifierComponent); 2714 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2715 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2716 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2717 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2718 } else { 2719 mRequiredVerifierPackage = null; 2720 mRequiredInstallerPackage = null; 2721 mIntentFilterVerifierComponent = null; 2722 mIntentFilterVerifier = null; 2723 mServicesSystemSharedLibraryPackageName = null; 2724 mSharedSystemSharedLibraryPackageName = null; 2725 } 2726 2727 mInstallerService = new PackageInstallerService(context, this); 2728 2729 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2730 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2731 // both the installer and resolver must be present to enable ephemeral 2732 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2733 if (DEBUG_EPHEMERAL) { 2734 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2735 + " installer:" + ephemeralInstallerComponent); 2736 } 2737 mEphemeralResolverComponent = ephemeralResolverComponent; 2738 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2739 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2740 mEphemeralResolverConnection = 2741 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2742 } else { 2743 if (DEBUG_EPHEMERAL) { 2744 final String missingComponent = 2745 (ephemeralResolverComponent == null) 2746 ? (ephemeralInstallerComponent == null) 2747 ? "resolver and installer" 2748 : "resolver" 2749 : "installer"; 2750 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2751 } 2752 mEphemeralResolverComponent = null; 2753 mEphemeralInstallerComponent = null; 2754 mEphemeralResolverConnection = null; 2755 } 2756 2757 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2758 } // synchronized (mPackages) 2759 } // synchronized (mInstallLock) 2760 2761 // Now after opening every single application zip, make sure they 2762 // are all flushed. Not really needed, but keeps things nice and 2763 // tidy. 2764 Runtime.getRuntime().gc(); 2765 2766 // The initial scanning above does many calls into installd while 2767 // holding the mPackages lock, but we're mostly interested in yelling 2768 // once we have a booted system. 2769 mInstaller.setWarnIfHeld(mPackages); 2770 2771 // Expose private service for system components to use. 2772 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2773 } 2774 2775 @Override 2776 public boolean isFirstBoot() { 2777 return !mRestoredSettings; 2778 } 2779 2780 @Override 2781 public boolean isOnlyCoreApps() { 2782 return mOnlyCore; 2783 } 2784 2785 @Override 2786 public boolean isUpgrade() { 2787 return mIsUpgrade; 2788 } 2789 2790 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2791 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2792 2793 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2794 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2795 UserHandle.USER_SYSTEM); 2796 if (matches.size() == 1) { 2797 return matches.get(0).getComponentInfo().packageName; 2798 } else { 2799 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2800 return null; 2801 } 2802 } 2803 2804 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2805 synchronized (mPackages) { 2806 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2807 if (libraryEntry == null) { 2808 throw new IllegalStateException("Missing required shared library:" + libraryName); 2809 } 2810 return libraryEntry.apk; 2811 } 2812 } 2813 2814 private @NonNull String getRequiredInstallerLPr() { 2815 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2816 intent.addCategory(Intent.CATEGORY_DEFAULT); 2817 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2818 2819 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2820 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2821 UserHandle.USER_SYSTEM); 2822 if (matches.size() == 1) { 2823 ResolveInfo resolveInfo = matches.get(0); 2824 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2825 throw new RuntimeException("The installer must be a privileged app"); 2826 } 2827 return matches.get(0).getComponentInfo().packageName; 2828 } else { 2829 throw new RuntimeException("There must be exactly one installer; found " + matches); 2830 } 2831 } 2832 2833 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2834 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2835 2836 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2837 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2838 UserHandle.USER_SYSTEM); 2839 ResolveInfo best = null; 2840 final int N = matches.size(); 2841 for (int i = 0; i < N; i++) { 2842 final ResolveInfo cur = matches.get(i); 2843 final String packageName = cur.getComponentInfo().packageName; 2844 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2845 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2846 continue; 2847 } 2848 2849 if (best == null || cur.priority > best.priority) { 2850 best = cur; 2851 } 2852 } 2853 2854 if (best != null) { 2855 return best.getComponentInfo().getComponentName(); 2856 } else { 2857 throw new RuntimeException("There must be at least one intent filter verifier"); 2858 } 2859 } 2860 2861 private @Nullable ComponentName getEphemeralResolverLPr() { 2862 final String[] packageArray = 2863 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2864 if (packageArray.length == 0) { 2865 if (DEBUG_EPHEMERAL) { 2866 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2867 } 2868 return null; 2869 } 2870 2871 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2872 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2873 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2874 UserHandle.USER_SYSTEM); 2875 2876 final int N = resolvers.size(); 2877 if (N == 0) { 2878 if (DEBUG_EPHEMERAL) { 2879 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2880 } 2881 return null; 2882 } 2883 2884 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2885 for (int i = 0; i < N; i++) { 2886 final ResolveInfo info = resolvers.get(i); 2887 2888 if (info.serviceInfo == null) { 2889 continue; 2890 } 2891 2892 final String packageName = info.serviceInfo.packageName; 2893 if (!possiblePackages.contains(packageName)) { 2894 if (DEBUG_EPHEMERAL) { 2895 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2896 + " pkg: " + packageName + ", info:" + info); 2897 } 2898 continue; 2899 } 2900 2901 if (DEBUG_EPHEMERAL) { 2902 Slog.v(TAG, "Ephemeral resolver found;" 2903 + " pkg: " + packageName + ", info:" + info); 2904 } 2905 return new ComponentName(packageName, info.serviceInfo.name); 2906 } 2907 if (DEBUG_EPHEMERAL) { 2908 Slog.v(TAG, "Ephemeral resolver NOT found"); 2909 } 2910 return null; 2911 } 2912 2913 private @Nullable ComponentName getEphemeralInstallerLPr() { 2914 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2915 intent.addCategory(Intent.CATEGORY_DEFAULT); 2916 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2917 2918 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2919 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2920 UserHandle.USER_SYSTEM); 2921 if (matches.size() == 0) { 2922 return null; 2923 } else if (matches.size() == 1) { 2924 return matches.get(0).getComponentInfo().getComponentName(); 2925 } else { 2926 throw new RuntimeException( 2927 "There must be at most one ephemeral installer; found " + matches); 2928 } 2929 } 2930 2931 private void primeDomainVerificationsLPw(int userId) { 2932 if (DEBUG_DOMAIN_VERIFICATION) { 2933 Slog.d(TAG, "Priming domain verifications in user " + userId); 2934 } 2935 2936 SystemConfig systemConfig = SystemConfig.getInstance(); 2937 ArraySet<String> packages = systemConfig.getLinkedApps(); 2938 ArraySet<String> domains = new ArraySet<String>(); 2939 2940 for (String packageName : packages) { 2941 PackageParser.Package pkg = mPackages.get(packageName); 2942 if (pkg != null) { 2943 if (!pkg.isSystemApp()) { 2944 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2945 continue; 2946 } 2947 2948 domains.clear(); 2949 for (PackageParser.Activity a : pkg.activities) { 2950 for (ActivityIntentInfo filter : a.intents) { 2951 if (hasValidDomains(filter)) { 2952 domains.addAll(filter.getHostsList()); 2953 } 2954 } 2955 } 2956 2957 if (domains.size() > 0) { 2958 if (DEBUG_DOMAIN_VERIFICATION) { 2959 Slog.v(TAG, " + " + packageName); 2960 } 2961 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2962 // state w.r.t. the formal app-linkage "no verification attempted" state; 2963 // and then 'always' in the per-user state actually used for intent resolution. 2964 final IntentFilterVerificationInfo ivi; 2965 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2966 new ArrayList<String>(domains)); 2967 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2968 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2969 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2970 } else { 2971 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2972 + "' does not handle web links"); 2973 } 2974 } else { 2975 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2976 } 2977 } 2978 2979 scheduleWritePackageRestrictionsLocked(userId); 2980 scheduleWriteSettingsLocked(); 2981 } 2982 2983 private void applyFactoryDefaultBrowserLPw(int userId) { 2984 // The default browser app's package name is stored in a string resource, 2985 // with a product-specific overlay used for vendor customization. 2986 String browserPkg = mContext.getResources().getString( 2987 com.android.internal.R.string.default_browser); 2988 if (!TextUtils.isEmpty(browserPkg)) { 2989 // non-empty string => required to be a known package 2990 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2991 if (ps == null) { 2992 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2993 browserPkg = null; 2994 } else { 2995 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2996 } 2997 } 2998 2999 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3000 // default. If there's more than one, just leave everything alone. 3001 if (browserPkg == null) { 3002 calculateDefaultBrowserLPw(userId); 3003 } 3004 } 3005 3006 private void calculateDefaultBrowserLPw(int userId) { 3007 List<String> allBrowsers = resolveAllBrowserApps(userId); 3008 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3009 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3010 } 3011 3012 private List<String> resolveAllBrowserApps(int userId) { 3013 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3014 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3015 PackageManager.MATCH_ALL, userId); 3016 3017 final int count = list.size(); 3018 List<String> result = new ArrayList<String>(count); 3019 for (int i=0; i<count; i++) { 3020 ResolveInfo info = list.get(i); 3021 if (info.activityInfo == null 3022 || !info.handleAllWebDataURI 3023 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3024 || result.contains(info.activityInfo.packageName)) { 3025 continue; 3026 } 3027 result.add(info.activityInfo.packageName); 3028 } 3029 3030 return result; 3031 } 3032 3033 private boolean packageIsBrowser(String packageName, int userId) { 3034 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3035 PackageManager.MATCH_ALL, userId); 3036 final int N = list.size(); 3037 for (int i = 0; i < N; i++) { 3038 ResolveInfo info = list.get(i); 3039 if (packageName.equals(info.activityInfo.packageName)) { 3040 return true; 3041 } 3042 } 3043 return false; 3044 } 3045 3046 private void checkDefaultBrowser() { 3047 final int myUserId = UserHandle.myUserId(); 3048 final String packageName = getDefaultBrowserPackageName(myUserId); 3049 if (packageName != null) { 3050 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3051 if (info == null) { 3052 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3053 synchronized (mPackages) { 3054 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3055 } 3056 } 3057 } 3058 } 3059 3060 @Override 3061 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3062 throws RemoteException { 3063 try { 3064 return super.onTransact(code, data, reply, flags); 3065 } catch (RuntimeException e) { 3066 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3067 Slog.wtf(TAG, "Package Manager Crash", e); 3068 } 3069 throw e; 3070 } 3071 } 3072 3073 static int[] appendInts(int[] cur, int[] add) { 3074 if (add == null) return cur; 3075 if (cur == null) return add; 3076 final int N = add.length; 3077 for (int i=0; i<N; i++) { 3078 cur = appendInt(cur, add[i]); 3079 } 3080 return cur; 3081 } 3082 3083 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return null; 3085 if (ps == null) { 3086 return null; 3087 } 3088 final PackageParser.Package p = ps.pkg; 3089 if (p == null) { 3090 return null; 3091 } 3092 3093 final PermissionsState permissionsState = ps.getPermissionsState(); 3094 3095 final int[] gids = permissionsState.computeGids(userId); 3096 final Set<String> permissions = permissionsState.getPermissions(userId); 3097 final PackageUserState state = ps.readUserState(userId); 3098 3099 return PackageParser.generatePackageInfo(p, gids, flags, 3100 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3101 } 3102 3103 @Override 3104 public void checkPackageStartable(String packageName, int userId) { 3105 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3106 3107 synchronized (mPackages) { 3108 final PackageSetting ps = mSettings.mPackages.get(packageName); 3109 if (ps == null) { 3110 throw new SecurityException("Package " + packageName + " was not found!"); 3111 } 3112 3113 if (!ps.getInstalled(userId)) { 3114 throw new SecurityException( 3115 "Package " + packageName + " was not installed for user " + userId + "!"); 3116 } 3117 3118 if (mSafeMode && !ps.isSystem()) { 3119 throw new SecurityException("Package " + packageName + " not a system app!"); 3120 } 3121 3122 if (mFrozenPackages.contains(packageName)) { 3123 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3124 } 3125 3126 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3127 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3128 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3129 } 3130 } 3131 } 3132 3133 @Override 3134 public boolean isPackageAvailable(String packageName, int userId) { 3135 if (!sUserManager.exists(userId)) return false; 3136 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3137 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3138 synchronized (mPackages) { 3139 PackageParser.Package p = mPackages.get(packageName); 3140 if (p != null) { 3141 final PackageSetting ps = (PackageSetting) p.mExtras; 3142 if (ps != null) { 3143 final PackageUserState state = ps.readUserState(userId); 3144 if (state != null) { 3145 return PackageParser.isAvailable(state); 3146 } 3147 } 3148 } 3149 } 3150 return false; 3151 } 3152 3153 @Override 3154 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3155 if (!sUserManager.exists(userId)) return null; 3156 flags = updateFlagsForPackage(flags, userId, packageName); 3157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3158 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3159 // reader 3160 synchronized (mPackages) { 3161 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3162 PackageParser.Package p = null; 3163 if (matchFactoryOnly) { 3164 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3165 if (ps != null) { 3166 return generatePackageInfo(ps, flags, userId); 3167 } 3168 } 3169 if (p == null) { 3170 p = mPackages.get(packageName); 3171 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3172 return null; 3173 } 3174 } 3175 if (DEBUG_PACKAGE_INFO) 3176 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3177 if (p != null) { 3178 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3179 } 3180 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3181 final PackageSetting ps = mSettings.mPackages.get(packageName); 3182 return generatePackageInfo(ps, flags, userId); 3183 } 3184 } 3185 return null; 3186 } 3187 3188 @Override 3189 public String[] currentToCanonicalPackageNames(String[] names) { 3190 String[] out = new String[names.length]; 3191 // reader 3192 synchronized (mPackages) { 3193 for (int i=names.length-1; i>=0; i--) { 3194 PackageSetting ps = mSettings.mPackages.get(names[i]); 3195 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3196 } 3197 } 3198 return out; 3199 } 3200 3201 @Override 3202 public String[] canonicalToCurrentPackageNames(String[] names) { 3203 String[] out = new String[names.length]; 3204 // reader 3205 synchronized (mPackages) { 3206 for (int i=names.length-1; i>=0; i--) { 3207 String cur = mSettings.mRenamedPackages.get(names[i]); 3208 out[i] = cur != null ? cur : names[i]; 3209 } 3210 } 3211 return out; 3212 } 3213 3214 @Override 3215 public int getPackageUid(String packageName, int flags, int userId) { 3216 if (!sUserManager.exists(userId)) return -1; 3217 flags = updateFlagsForPackage(flags, userId, packageName); 3218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3219 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3220 3221 // reader 3222 synchronized (mPackages) { 3223 final PackageParser.Package p = mPackages.get(packageName); 3224 if (p != null && p.isMatch(flags)) { 3225 return UserHandle.getUid(userId, p.applicationInfo.uid); 3226 } 3227 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3228 final PackageSetting ps = mSettings.mPackages.get(packageName); 3229 if (ps != null && ps.isMatch(flags)) { 3230 return UserHandle.getUid(userId, ps.appId); 3231 } 3232 } 3233 } 3234 3235 return -1; 3236 } 3237 3238 @Override 3239 public int[] getPackageGids(String packageName, int flags, int userId) { 3240 if (!sUserManager.exists(userId)) return null; 3241 flags = updateFlagsForPackage(flags, userId, packageName); 3242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3243 false /* requireFullPermission */, false /* checkShell */, 3244 "getPackageGids"); 3245 3246 // reader 3247 synchronized (mPackages) { 3248 final PackageParser.Package p = mPackages.get(packageName); 3249 if (p != null && p.isMatch(flags)) { 3250 PackageSetting ps = (PackageSetting) p.mExtras; 3251 return ps.getPermissionsState().computeGids(userId); 3252 } 3253 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3254 final PackageSetting ps = mSettings.mPackages.get(packageName); 3255 if (ps != null && ps.isMatch(flags)) { 3256 return ps.getPermissionsState().computeGids(userId); 3257 } 3258 } 3259 } 3260 3261 return null; 3262 } 3263 3264 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3265 if (bp.perm != null) { 3266 return PackageParser.generatePermissionInfo(bp.perm, flags); 3267 } 3268 PermissionInfo pi = new PermissionInfo(); 3269 pi.name = bp.name; 3270 pi.packageName = bp.sourcePackage; 3271 pi.nonLocalizedLabel = bp.name; 3272 pi.protectionLevel = bp.protectionLevel; 3273 return pi; 3274 } 3275 3276 @Override 3277 public PermissionInfo getPermissionInfo(String name, int flags) { 3278 // reader 3279 synchronized (mPackages) { 3280 final BasePermission p = mSettings.mPermissions.get(name); 3281 if (p != null) { 3282 return generatePermissionInfo(p, flags); 3283 } 3284 return null; 3285 } 3286 } 3287 3288 @Override 3289 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3290 int flags) { 3291 // reader 3292 synchronized (mPackages) { 3293 if (group != null && !mPermissionGroups.containsKey(group)) { 3294 // This is thrown as NameNotFoundException 3295 return null; 3296 } 3297 3298 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3299 for (BasePermission p : mSettings.mPermissions.values()) { 3300 if (group == null) { 3301 if (p.perm == null || p.perm.info.group == null) { 3302 out.add(generatePermissionInfo(p, flags)); 3303 } 3304 } else { 3305 if (p.perm != null && group.equals(p.perm.info.group)) { 3306 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3307 } 3308 } 3309 } 3310 return new ParceledListSlice<>(out); 3311 } 3312 } 3313 3314 @Override 3315 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3316 // reader 3317 synchronized (mPackages) { 3318 return PackageParser.generatePermissionGroupInfo( 3319 mPermissionGroups.get(name), flags); 3320 } 3321 } 3322 3323 @Override 3324 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3325 // reader 3326 synchronized (mPackages) { 3327 final int N = mPermissionGroups.size(); 3328 ArrayList<PermissionGroupInfo> out 3329 = new ArrayList<PermissionGroupInfo>(N); 3330 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3331 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3332 } 3333 return new ParceledListSlice<>(out); 3334 } 3335 } 3336 3337 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3338 int userId) { 3339 if (!sUserManager.exists(userId)) return null; 3340 PackageSetting ps = mSettings.mPackages.get(packageName); 3341 if (ps != null) { 3342 if (ps.pkg == null) { 3343 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3344 if (pInfo != null) { 3345 return pInfo.applicationInfo; 3346 } 3347 return null; 3348 } 3349 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3350 ps.readUserState(userId), userId); 3351 } 3352 return null; 3353 } 3354 3355 @Override 3356 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3357 if (!sUserManager.exists(userId)) return null; 3358 flags = updateFlagsForApplication(flags, userId, packageName); 3359 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3360 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3361 // writer 3362 synchronized (mPackages) { 3363 PackageParser.Package p = mPackages.get(packageName); 3364 if (DEBUG_PACKAGE_INFO) Log.v( 3365 TAG, "getApplicationInfo " + packageName 3366 + ": " + p); 3367 if (p != null) { 3368 PackageSetting ps = mSettings.mPackages.get(packageName); 3369 if (ps == null) return null; 3370 // Note: isEnabledLP() does not apply here - always return info 3371 return PackageParser.generateApplicationInfo( 3372 p, flags, ps.readUserState(userId), userId); 3373 } 3374 if ("android".equals(packageName)||"system".equals(packageName)) { 3375 return mAndroidApplication; 3376 } 3377 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3378 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3379 } 3380 } 3381 return null; 3382 } 3383 3384 @Override 3385 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3386 final IPackageDataObserver observer) { 3387 mContext.enforceCallingOrSelfPermission( 3388 android.Manifest.permission.CLEAR_APP_CACHE, null); 3389 // Queue up an async operation since clearing cache may take a little while. 3390 mHandler.post(new Runnable() { 3391 public void run() { 3392 mHandler.removeCallbacks(this); 3393 boolean success = true; 3394 synchronized (mInstallLock) { 3395 try { 3396 mInstaller.freeCache(volumeUuid, freeStorageSize); 3397 } catch (InstallerException e) { 3398 Slog.w(TAG, "Couldn't clear application caches: " + e); 3399 success = false; 3400 } 3401 } 3402 if (observer != null) { 3403 try { 3404 observer.onRemoveCompleted(null, success); 3405 } catch (RemoteException e) { 3406 Slog.w(TAG, "RemoveException when invoking call back"); 3407 } 3408 } 3409 } 3410 }); 3411 } 3412 3413 @Override 3414 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3415 final IntentSender pi) { 3416 mContext.enforceCallingOrSelfPermission( 3417 android.Manifest.permission.CLEAR_APP_CACHE, null); 3418 // Queue up an async operation since clearing cache may take a little while. 3419 mHandler.post(new Runnable() { 3420 public void run() { 3421 mHandler.removeCallbacks(this); 3422 boolean success = true; 3423 synchronized (mInstallLock) { 3424 try { 3425 mInstaller.freeCache(volumeUuid, freeStorageSize); 3426 } catch (InstallerException e) { 3427 Slog.w(TAG, "Couldn't clear application caches: " + e); 3428 success = false; 3429 } 3430 } 3431 if(pi != null) { 3432 try { 3433 // Callback via pending intent 3434 int code = success ? 1 : 0; 3435 pi.sendIntent(null, code, null, 3436 null, null); 3437 } catch (SendIntentException e1) { 3438 Slog.i(TAG, "Failed to send pending intent"); 3439 } 3440 } 3441 } 3442 }); 3443 } 3444 3445 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3446 synchronized (mInstallLock) { 3447 try { 3448 mInstaller.freeCache(volumeUuid, freeStorageSize); 3449 } catch (InstallerException e) { 3450 throw new IOException("Failed to free enough space", e); 3451 } 3452 } 3453 } 3454 3455 /** 3456 * Return if the user key is currently unlocked. 3457 */ 3458 private boolean isUserKeyUnlocked(int userId) { 3459 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3460 final IMountService mount = IMountService.Stub 3461 .asInterface(ServiceManager.getService("mount")); 3462 if (mount == null) { 3463 Slog.w(TAG, "Early during boot, assuming locked"); 3464 return false; 3465 } 3466 final long token = Binder.clearCallingIdentity(); 3467 try { 3468 return mount.isUserKeyUnlocked(userId); 3469 } catch (RemoteException e) { 3470 throw e.rethrowAsRuntimeException(); 3471 } finally { 3472 Binder.restoreCallingIdentity(token); 3473 } 3474 } else { 3475 return true; 3476 } 3477 } 3478 3479 /** 3480 * Update given flags based on encryption status of current user. 3481 */ 3482 private int updateFlags(int flags, int userId) { 3483 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3484 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3485 // Caller expressed an explicit opinion about what encryption 3486 // aware/unaware components they want to see, so fall through and 3487 // give them what they want 3488 } else { 3489 // Caller expressed no opinion, so match based on user state 3490 if (isUserKeyUnlocked(userId)) { 3491 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3492 } else { 3493 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3494 } 3495 } 3496 return flags; 3497 } 3498 3499 /** 3500 * Update given flags when being used to request {@link PackageInfo}. 3501 */ 3502 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3503 boolean triaged = true; 3504 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3505 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3506 // Caller is asking for component details, so they'd better be 3507 // asking for specific encryption matching behavior, or be triaged 3508 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3509 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3510 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3511 triaged = false; 3512 } 3513 } 3514 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3515 | PackageManager.MATCH_SYSTEM_ONLY 3516 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3517 triaged = false; 3518 } 3519 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3520 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3521 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3522 } 3523 return updateFlags(flags, userId); 3524 } 3525 3526 /** 3527 * Update given flags when being used to request {@link ApplicationInfo}. 3528 */ 3529 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3530 return updateFlagsForPackage(flags, userId, cookie); 3531 } 3532 3533 /** 3534 * Update given flags when being used to request {@link ComponentInfo}. 3535 */ 3536 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3537 if (cookie instanceof Intent) { 3538 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3539 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3540 } 3541 } 3542 3543 boolean triaged = true; 3544 // Caller is asking for component details, so they'd better be 3545 // asking for specific encryption matching behavior, or be triaged 3546 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3547 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3548 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3549 triaged = false; 3550 } 3551 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3552 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3553 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3554 } 3555 3556 return updateFlags(flags, userId); 3557 } 3558 3559 /** 3560 * Update given flags when being used to request {@link ResolveInfo}. 3561 */ 3562 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3563 // Safe mode means we shouldn't match any third-party components 3564 if (mSafeMode) { 3565 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3566 } 3567 3568 return updateFlagsForComponent(flags, userId, cookie); 3569 } 3570 3571 @Override 3572 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3573 if (!sUserManager.exists(userId)) return null; 3574 flags = updateFlagsForComponent(flags, userId, component); 3575 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3576 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3577 synchronized (mPackages) { 3578 PackageParser.Activity a = mActivities.mActivities.get(component); 3579 3580 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3581 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3582 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3583 if (ps == null) return null; 3584 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3585 userId); 3586 } 3587 if (mResolveComponentName.equals(component)) { 3588 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3589 new PackageUserState(), userId); 3590 } 3591 } 3592 return null; 3593 } 3594 3595 @Override 3596 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3597 String resolvedType) { 3598 synchronized (mPackages) { 3599 if (component.equals(mResolveComponentName)) { 3600 // The resolver supports EVERYTHING! 3601 return true; 3602 } 3603 PackageParser.Activity a = mActivities.mActivities.get(component); 3604 if (a == null) { 3605 return false; 3606 } 3607 for (int i=0; i<a.intents.size(); i++) { 3608 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3609 intent.getData(), intent.getCategories(), TAG) >= 0) { 3610 return true; 3611 } 3612 } 3613 return false; 3614 } 3615 } 3616 3617 @Override 3618 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3619 if (!sUserManager.exists(userId)) return null; 3620 flags = updateFlagsForComponent(flags, userId, component); 3621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3622 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3623 synchronized (mPackages) { 3624 PackageParser.Activity a = mReceivers.mActivities.get(component); 3625 if (DEBUG_PACKAGE_INFO) Log.v( 3626 TAG, "getReceiverInfo " + component + ": " + a); 3627 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3628 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3629 if (ps == null) return null; 3630 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3631 userId); 3632 } 3633 } 3634 return null; 3635 } 3636 3637 @Override 3638 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3639 if (!sUserManager.exists(userId)) return null; 3640 flags = updateFlagsForComponent(flags, userId, component); 3641 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3642 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3643 synchronized (mPackages) { 3644 PackageParser.Service s = mServices.mServices.get(component); 3645 if (DEBUG_PACKAGE_INFO) Log.v( 3646 TAG, "getServiceInfo " + component + ": " + s); 3647 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3648 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3649 if (ps == null) return null; 3650 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3651 userId); 3652 } 3653 } 3654 return null; 3655 } 3656 3657 @Override 3658 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3659 if (!sUserManager.exists(userId)) return null; 3660 flags = updateFlagsForComponent(flags, userId, component); 3661 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3662 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3663 synchronized (mPackages) { 3664 PackageParser.Provider p = mProviders.mProviders.get(component); 3665 if (DEBUG_PACKAGE_INFO) Log.v( 3666 TAG, "getProviderInfo " + component + ": " + p); 3667 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3668 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3669 if (ps == null) return null; 3670 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3671 userId); 3672 } 3673 } 3674 return null; 3675 } 3676 3677 @Override 3678 public String[] getSystemSharedLibraryNames() { 3679 Set<String> libSet; 3680 synchronized (mPackages) { 3681 libSet = mSharedLibraries.keySet(); 3682 int size = libSet.size(); 3683 if (size > 0) { 3684 String[] libs = new String[size]; 3685 libSet.toArray(libs); 3686 return libs; 3687 } 3688 } 3689 return null; 3690 } 3691 3692 @Override 3693 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3694 synchronized (mPackages) { 3695 return mServicesSystemSharedLibraryPackageName; 3696 } 3697 } 3698 3699 @Override 3700 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3701 synchronized (mPackages) { 3702 return mSharedSystemSharedLibraryPackageName; 3703 } 3704 } 3705 3706 @Override 3707 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3708 synchronized (mPackages) { 3709 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3710 3711 final FeatureInfo fi = new FeatureInfo(); 3712 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3713 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3714 res.add(fi); 3715 3716 return new ParceledListSlice<>(res); 3717 } 3718 } 3719 3720 @Override 3721 public boolean hasSystemFeature(String name, int version) { 3722 synchronized (mPackages) { 3723 final FeatureInfo feat = mAvailableFeatures.get(name); 3724 if (feat == null) { 3725 return false; 3726 } else { 3727 return feat.version >= version; 3728 } 3729 } 3730 } 3731 3732 @Override 3733 public int checkPermission(String permName, String pkgName, int userId) { 3734 if (!sUserManager.exists(userId)) { 3735 return PackageManager.PERMISSION_DENIED; 3736 } 3737 3738 synchronized (mPackages) { 3739 final PackageParser.Package p = mPackages.get(pkgName); 3740 if (p != null && p.mExtras != null) { 3741 final PackageSetting ps = (PackageSetting) p.mExtras; 3742 final PermissionsState permissionsState = ps.getPermissionsState(); 3743 if (permissionsState.hasPermission(permName, userId)) { 3744 return PackageManager.PERMISSION_GRANTED; 3745 } 3746 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3747 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3748 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3749 return PackageManager.PERMISSION_GRANTED; 3750 } 3751 } 3752 } 3753 3754 return PackageManager.PERMISSION_DENIED; 3755 } 3756 3757 @Override 3758 public int checkUidPermission(String permName, int uid) { 3759 final int userId = UserHandle.getUserId(uid); 3760 3761 if (!sUserManager.exists(userId)) { 3762 return PackageManager.PERMISSION_DENIED; 3763 } 3764 3765 synchronized (mPackages) { 3766 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3767 if (obj != null) { 3768 final SettingBase ps = (SettingBase) obj; 3769 final PermissionsState permissionsState = ps.getPermissionsState(); 3770 if (permissionsState.hasPermission(permName, userId)) { 3771 return PackageManager.PERMISSION_GRANTED; 3772 } 3773 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3774 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3775 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3776 return PackageManager.PERMISSION_GRANTED; 3777 } 3778 } else { 3779 ArraySet<String> perms = mSystemPermissions.get(uid); 3780 if (perms != null) { 3781 if (perms.contains(permName)) { 3782 return PackageManager.PERMISSION_GRANTED; 3783 } 3784 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3785 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3786 return PackageManager.PERMISSION_GRANTED; 3787 } 3788 } 3789 } 3790 } 3791 3792 return PackageManager.PERMISSION_DENIED; 3793 } 3794 3795 @Override 3796 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3797 if (UserHandle.getCallingUserId() != userId) { 3798 mContext.enforceCallingPermission( 3799 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3800 "isPermissionRevokedByPolicy for user " + userId); 3801 } 3802 3803 if (checkPermission(permission, packageName, userId) 3804 == PackageManager.PERMISSION_GRANTED) { 3805 return false; 3806 } 3807 3808 final long identity = Binder.clearCallingIdentity(); 3809 try { 3810 final int flags = getPermissionFlags(permission, packageName, userId); 3811 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3812 } finally { 3813 Binder.restoreCallingIdentity(identity); 3814 } 3815 } 3816 3817 @Override 3818 public String getPermissionControllerPackageName() { 3819 synchronized (mPackages) { 3820 return mRequiredInstallerPackage; 3821 } 3822 } 3823 3824 /** 3825 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3826 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3827 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3828 * @param message the message to log on security exception 3829 */ 3830 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3831 boolean checkShell, String message) { 3832 if (userId < 0) { 3833 throw new IllegalArgumentException("Invalid userId " + userId); 3834 } 3835 if (checkShell) { 3836 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3837 } 3838 if (userId == UserHandle.getUserId(callingUid)) return; 3839 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3840 if (requireFullPermission) { 3841 mContext.enforceCallingOrSelfPermission( 3842 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3843 } else { 3844 try { 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3847 } catch (SecurityException se) { 3848 mContext.enforceCallingOrSelfPermission( 3849 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3850 } 3851 } 3852 } 3853 } 3854 3855 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3856 if (callingUid == Process.SHELL_UID) { 3857 if (userHandle >= 0 3858 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3859 throw new SecurityException("Shell does not have permission to access user " 3860 + userHandle); 3861 } else if (userHandle < 0) { 3862 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3863 + Debug.getCallers(3)); 3864 } 3865 } 3866 } 3867 3868 private BasePermission findPermissionTreeLP(String permName) { 3869 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3870 if (permName.startsWith(bp.name) && 3871 permName.length() > bp.name.length() && 3872 permName.charAt(bp.name.length()) == '.') { 3873 return bp; 3874 } 3875 } 3876 return null; 3877 } 3878 3879 private BasePermission checkPermissionTreeLP(String permName) { 3880 if (permName != null) { 3881 BasePermission bp = findPermissionTreeLP(permName); 3882 if (bp != null) { 3883 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3884 return bp; 3885 } 3886 throw new SecurityException("Calling uid " 3887 + Binder.getCallingUid() 3888 + " is not allowed to add to permission tree " 3889 + bp.name + " owned by uid " + bp.uid); 3890 } 3891 } 3892 throw new SecurityException("No permission tree found for " + permName); 3893 } 3894 3895 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3896 if (s1 == null) { 3897 return s2 == null; 3898 } 3899 if (s2 == null) { 3900 return false; 3901 } 3902 if (s1.getClass() != s2.getClass()) { 3903 return false; 3904 } 3905 return s1.equals(s2); 3906 } 3907 3908 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3909 if (pi1.icon != pi2.icon) return false; 3910 if (pi1.logo != pi2.logo) return false; 3911 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3912 if (!compareStrings(pi1.name, pi2.name)) return false; 3913 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3914 // We'll take care of setting this one. 3915 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3916 // These are not currently stored in settings. 3917 //if (!compareStrings(pi1.group, pi2.group)) return false; 3918 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3919 //if (pi1.labelRes != pi2.labelRes) return false; 3920 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3921 return true; 3922 } 3923 3924 int permissionInfoFootprint(PermissionInfo info) { 3925 int size = info.name.length(); 3926 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3927 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3928 return size; 3929 } 3930 3931 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3932 int size = 0; 3933 for (BasePermission perm : mSettings.mPermissions.values()) { 3934 if (perm.uid == tree.uid) { 3935 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3936 } 3937 } 3938 return size; 3939 } 3940 3941 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3942 // We calculate the max size of permissions defined by this uid and throw 3943 // if that plus the size of 'info' would exceed our stated maximum. 3944 if (tree.uid != Process.SYSTEM_UID) { 3945 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3946 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3947 throw new SecurityException("Permission tree size cap exceeded"); 3948 } 3949 } 3950 } 3951 3952 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3953 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3954 throw new SecurityException("Label must be specified in permission"); 3955 } 3956 BasePermission tree = checkPermissionTreeLP(info.name); 3957 BasePermission bp = mSettings.mPermissions.get(info.name); 3958 boolean added = bp == null; 3959 boolean changed = true; 3960 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3961 if (added) { 3962 enforcePermissionCapLocked(info, tree); 3963 bp = new BasePermission(info.name, tree.sourcePackage, 3964 BasePermission.TYPE_DYNAMIC); 3965 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3966 throw new SecurityException( 3967 "Not allowed to modify non-dynamic permission " 3968 + info.name); 3969 } else { 3970 if (bp.protectionLevel == fixedLevel 3971 && bp.perm.owner.equals(tree.perm.owner) 3972 && bp.uid == tree.uid 3973 && comparePermissionInfos(bp.perm.info, info)) { 3974 changed = false; 3975 } 3976 } 3977 bp.protectionLevel = fixedLevel; 3978 info = new PermissionInfo(info); 3979 info.protectionLevel = fixedLevel; 3980 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3981 bp.perm.info.packageName = tree.perm.info.packageName; 3982 bp.uid = tree.uid; 3983 if (added) { 3984 mSettings.mPermissions.put(info.name, bp); 3985 } 3986 if (changed) { 3987 if (!async) { 3988 mSettings.writeLPr(); 3989 } else { 3990 scheduleWriteSettingsLocked(); 3991 } 3992 } 3993 return added; 3994 } 3995 3996 @Override 3997 public boolean addPermission(PermissionInfo info) { 3998 synchronized (mPackages) { 3999 return addPermissionLocked(info, false); 4000 } 4001 } 4002 4003 @Override 4004 public boolean addPermissionAsync(PermissionInfo info) { 4005 synchronized (mPackages) { 4006 return addPermissionLocked(info, true); 4007 } 4008 } 4009 4010 @Override 4011 public void removePermission(String name) { 4012 synchronized (mPackages) { 4013 checkPermissionTreeLP(name); 4014 BasePermission bp = mSettings.mPermissions.get(name); 4015 if (bp != null) { 4016 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4017 throw new SecurityException( 4018 "Not allowed to modify non-dynamic permission " 4019 + name); 4020 } 4021 mSettings.mPermissions.remove(name); 4022 mSettings.writeLPr(); 4023 } 4024 } 4025 } 4026 4027 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4028 BasePermission bp) { 4029 int index = pkg.requestedPermissions.indexOf(bp.name); 4030 if (index == -1) { 4031 throw new SecurityException("Package " + pkg.packageName 4032 + " has not requested permission " + bp.name); 4033 } 4034 if (!bp.isRuntime() && !bp.isDevelopment()) { 4035 throw new SecurityException("Permission " + bp.name 4036 + " is not a changeable permission type"); 4037 } 4038 } 4039 4040 @Override 4041 public void grantRuntimePermission(String packageName, String name, final int userId) { 4042 if (!sUserManager.exists(userId)) { 4043 Log.e(TAG, "No such user:" + userId); 4044 return; 4045 } 4046 4047 mContext.enforceCallingOrSelfPermission( 4048 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4049 "grantRuntimePermission"); 4050 4051 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4052 true /* requireFullPermission */, true /* checkShell */, 4053 "grantRuntimePermission"); 4054 4055 final int uid; 4056 final SettingBase sb; 4057 4058 synchronized (mPackages) { 4059 final PackageParser.Package pkg = mPackages.get(packageName); 4060 if (pkg == null) { 4061 throw new IllegalArgumentException("Unknown package: " + packageName); 4062 } 4063 4064 final BasePermission bp = mSettings.mPermissions.get(name); 4065 if (bp == null) { 4066 throw new IllegalArgumentException("Unknown permission: " + name); 4067 } 4068 4069 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4070 4071 // If a permission review is required for legacy apps we represent 4072 // their permissions as always granted runtime ones since we need 4073 // to keep the review required permission flag per user while an 4074 // install permission's state is shared across all users. 4075 if (Build.PERMISSIONS_REVIEW_REQUIRED 4076 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4077 && bp.isRuntime()) { 4078 return; 4079 } 4080 4081 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4082 sb = (SettingBase) pkg.mExtras; 4083 if (sb == null) { 4084 throw new IllegalArgumentException("Unknown package: " + packageName); 4085 } 4086 4087 final PermissionsState permissionsState = sb.getPermissionsState(); 4088 4089 final int flags = permissionsState.getPermissionFlags(name, userId); 4090 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4091 throw new SecurityException("Cannot grant system fixed permission " 4092 + name + " for package " + packageName); 4093 } 4094 4095 if (bp.isDevelopment()) { 4096 // Development permissions must be handled specially, since they are not 4097 // normal runtime permissions. For now they apply to all users. 4098 if (permissionsState.grantInstallPermission(bp) != 4099 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4100 scheduleWriteSettingsLocked(); 4101 } 4102 return; 4103 } 4104 4105 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4106 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4107 return; 4108 } 4109 4110 final int result = permissionsState.grantRuntimePermission(bp, userId); 4111 switch (result) { 4112 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4113 return; 4114 } 4115 4116 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4117 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4118 mHandler.post(new Runnable() { 4119 @Override 4120 public void run() { 4121 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4122 } 4123 }); 4124 } 4125 break; 4126 } 4127 4128 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4129 4130 // Not critical if that is lost - app has to request again. 4131 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4132 } 4133 4134 // Only need to do this if user is initialized. Otherwise it's a new user 4135 // and there are no processes running as the user yet and there's no need 4136 // to make an expensive call to remount processes for the changed permissions. 4137 if (READ_EXTERNAL_STORAGE.equals(name) 4138 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4139 final long token = Binder.clearCallingIdentity(); 4140 try { 4141 if (sUserManager.isInitialized(userId)) { 4142 MountServiceInternal mountServiceInternal = LocalServices.getService( 4143 MountServiceInternal.class); 4144 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4145 } 4146 } finally { 4147 Binder.restoreCallingIdentity(token); 4148 } 4149 } 4150 } 4151 4152 @Override 4153 public void revokeRuntimePermission(String packageName, String name, int userId) { 4154 if (!sUserManager.exists(userId)) { 4155 Log.e(TAG, "No such user:" + userId); 4156 return; 4157 } 4158 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4161 "revokeRuntimePermission"); 4162 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4164 true /* requireFullPermission */, true /* checkShell */, 4165 "revokeRuntimePermission"); 4166 4167 final int appId; 4168 4169 synchronized (mPackages) { 4170 final PackageParser.Package pkg = mPackages.get(packageName); 4171 if (pkg == null) { 4172 throw new IllegalArgumentException("Unknown package: " + packageName); 4173 } 4174 4175 final BasePermission bp = mSettings.mPermissions.get(name); 4176 if (bp == null) { 4177 throw new IllegalArgumentException("Unknown permission: " + name); 4178 } 4179 4180 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4181 4182 // If a permission review is required for legacy apps we represent 4183 // their permissions as always granted runtime ones since we need 4184 // to keep the review required permission flag per user while an 4185 // install permission's state is shared across all users. 4186 if (Build.PERMISSIONS_REVIEW_REQUIRED 4187 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4188 && bp.isRuntime()) { 4189 return; 4190 } 4191 4192 SettingBase sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 final int flags = permissionsState.getPermissionFlags(name, userId); 4200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4201 throw new SecurityException("Cannot revoke system fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 4205 if (bp.isDevelopment()) { 4206 // Development permissions must be handled specially, since they are not 4207 // normal runtime permissions. For now they apply to all users. 4208 if (permissionsState.revokeInstallPermission(bp) != 4209 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4210 scheduleWriteSettingsLocked(); 4211 } 4212 return; 4213 } 4214 4215 if (permissionsState.revokeRuntimePermission(bp, userId) == 4216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4217 return; 4218 } 4219 4220 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4221 4222 // Critical, after this call app should never have the permission. 4223 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4224 4225 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4226 } 4227 4228 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4229 } 4230 4231 @Override 4232 public void resetRuntimePermissions() { 4233 mContext.enforceCallingOrSelfPermission( 4234 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4235 "revokeRuntimePermission"); 4236 4237 int callingUid = Binder.getCallingUid(); 4238 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4239 mContext.enforceCallingOrSelfPermission( 4240 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4241 "resetRuntimePermissions"); 4242 } 4243 4244 synchronized (mPackages) { 4245 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4246 for (int userId : UserManagerService.getInstance().getUserIds()) { 4247 final int packageCount = mPackages.size(); 4248 for (int i = 0; i < packageCount; i++) { 4249 PackageParser.Package pkg = mPackages.valueAt(i); 4250 if (!(pkg.mExtras instanceof PackageSetting)) { 4251 continue; 4252 } 4253 PackageSetting ps = (PackageSetting) pkg.mExtras; 4254 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4255 } 4256 } 4257 } 4258 } 4259 4260 @Override 4261 public int getPermissionFlags(String name, String packageName, int userId) { 4262 if (!sUserManager.exists(userId)) { 4263 return 0; 4264 } 4265 4266 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4267 4268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4269 true /* requireFullPermission */, false /* checkShell */, 4270 "getPermissionFlags"); 4271 4272 synchronized (mPackages) { 4273 final PackageParser.Package pkg = mPackages.get(packageName); 4274 if (pkg == null) { 4275 throw new IllegalArgumentException("Unknown package: " + packageName); 4276 } 4277 4278 final BasePermission bp = mSettings.mPermissions.get(name); 4279 if (bp == null) { 4280 throw new IllegalArgumentException("Unknown permission: " + name); 4281 } 4282 4283 SettingBase sb = (SettingBase) pkg.mExtras; 4284 if (sb == null) { 4285 throw new IllegalArgumentException("Unknown package: " + packageName); 4286 } 4287 4288 PermissionsState permissionsState = sb.getPermissionsState(); 4289 return permissionsState.getPermissionFlags(name, userId); 4290 } 4291 } 4292 4293 @Override 4294 public void updatePermissionFlags(String name, String packageName, int flagMask, 4295 int flagValues, int userId) { 4296 if (!sUserManager.exists(userId)) { 4297 return; 4298 } 4299 4300 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4301 4302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4303 true /* requireFullPermission */, true /* checkShell */, 4304 "updatePermissionFlags"); 4305 4306 // Only the system can change these flags and nothing else. 4307 if (getCallingUid() != Process.SYSTEM_UID) { 4308 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4309 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4310 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4311 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4312 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4313 } 4314 4315 synchronized (mPackages) { 4316 final PackageParser.Package pkg = mPackages.get(packageName); 4317 if (pkg == null) { 4318 throw new IllegalArgumentException("Unknown package: " + packageName); 4319 } 4320 4321 final BasePermission bp = mSettings.mPermissions.get(name); 4322 if (bp == null) { 4323 throw new IllegalArgumentException("Unknown permission: " + name); 4324 } 4325 4326 SettingBase sb = (SettingBase) pkg.mExtras; 4327 if (sb == null) { 4328 throw new IllegalArgumentException("Unknown package: " + packageName); 4329 } 4330 4331 PermissionsState permissionsState = sb.getPermissionsState(); 4332 4333 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4334 4335 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4336 // Install and runtime permissions are stored in different places, 4337 // so figure out what permission changed and persist the change. 4338 if (permissionsState.getInstallPermissionState(name) != null) { 4339 scheduleWriteSettingsLocked(); 4340 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4341 || hadState) { 4342 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4343 } 4344 } 4345 } 4346 } 4347 4348 /** 4349 * Update the permission flags for all packages and runtime permissions of a user in order 4350 * to allow device or profile owner to remove POLICY_FIXED. 4351 */ 4352 @Override 4353 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4354 if (!sUserManager.exists(userId)) { 4355 return; 4356 } 4357 4358 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4359 4360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4361 true /* requireFullPermission */, true /* checkShell */, 4362 "updatePermissionFlagsForAllApps"); 4363 4364 // Only the system can change system fixed flags. 4365 if (getCallingUid() != Process.SYSTEM_UID) { 4366 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4367 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4368 } 4369 4370 synchronized (mPackages) { 4371 boolean changed = false; 4372 final int packageCount = mPackages.size(); 4373 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4374 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4375 SettingBase sb = (SettingBase) pkg.mExtras; 4376 if (sb == null) { 4377 continue; 4378 } 4379 PermissionsState permissionsState = sb.getPermissionsState(); 4380 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4381 userId, flagMask, flagValues); 4382 } 4383 if (changed) { 4384 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4385 } 4386 } 4387 } 4388 4389 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4390 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4391 != PackageManager.PERMISSION_GRANTED 4392 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4393 != PackageManager.PERMISSION_GRANTED) { 4394 throw new SecurityException(message + " requires " 4395 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4396 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4397 } 4398 } 4399 4400 @Override 4401 public boolean shouldShowRequestPermissionRationale(String permissionName, 4402 String packageName, int userId) { 4403 if (UserHandle.getCallingUserId() != userId) { 4404 mContext.enforceCallingPermission( 4405 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4406 "canShowRequestPermissionRationale for user " + userId); 4407 } 4408 4409 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4410 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4411 return false; 4412 } 4413 4414 if (checkPermission(permissionName, packageName, userId) 4415 == PackageManager.PERMISSION_GRANTED) { 4416 return false; 4417 } 4418 4419 final int flags; 4420 4421 final long identity = Binder.clearCallingIdentity(); 4422 try { 4423 flags = getPermissionFlags(permissionName, 4424 packageName, userId); 4425 } finally { 4426 Binder.restoreCallingIdentity(identity); 4427 } 4428 4429 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4430 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4431 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4432 4433 if ((flags & fixedFlags) != 0) { 4434 return false; 4435 } 4436 4437 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4438 } 4439 4440 @Override 4441 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4442 mContext.enforceCallingOrSelfPermission( 4443 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4444 "addOnPermissionsChangeListener"); 4445 4446 synchronized (mPackages) { 4447 mOnPermissionChangeListeners.addListenerLocked(listener); 4448 } 4449 } 4450 4451 @Override 4452 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4453 synchronized (mPackages) { 4454 mOnPermissionChangeListeners.removeListenerLocked(listener); 4455 } 4456 } 4457 4458 @Override 4459 public boolean isProtectedBroadcast(String actionName) { 4460 synchronized (mPackages) { 4461 if (mProtectedBroadcasts.contains(actionName)) { 4462 return true; 4463 } else if (actionName != null) { 4464 // TODO: remove these terrible hacks 4465 if (actionName.startsWith("android.net.netmon.lingerExpired") 4466 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4467 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4468 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4469 return true; 4470 } 4471 } 4472 } 4473 return false; 4474 } 4475 4476 @Override 4477 public int checkSignatures(String pkg1, String pkg2) { 4478 synchronized (mPackages) { 4479 final PackageParser.Package p1 = mPackages.get(pkg1); 4480 final PackageParser.Package p2 = mPackages.get(pkg2); 4481 if (p1 == null || p1.mExtras == null 4482 || p2 == null || p2.mExtras == null) { 4483 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4484 } 4485 return compareSignatures(p1.mSignatures, p2.mSignatures); 4486 } 4487 } 4488 4489 @Override 4490 public int checkUidSignatures(int uid1, int uid2) { 4491 // Map to base uids. 4492 uid1 = UserHandle.getAppId(uid1); 4493 uid2 = UserHandle.getAppId(uid2); 4494 // reader 4495 synchronized (mPackages) { 4496 Signature[] s1; 4497 Signature[] s2; 4498 Object obj = mSettings.getUserIdLPr(uid1); 4499 if (obj != null) { 4500 if (obj instanceof SharedUserSetting) { 4501 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4502 } else if (obj instanceof PackageSetting) { 4503 s1 = ((PackageSetting)obj).signatures.mSignatures; 4504 } else { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 } else { 4508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4509 } 4510 obj = mSettings.getUserIdLPr(uid2); 4511 if (obj != null) { 4512 if (obj instanceof SharedUserSetting) { 4513 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4514 } else if (obj instanceof PackageSetting) { 4515 s2 = ((PackageSetting)obj).signatures.mSignatures; 4516 } else { 4517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4518 } 4519 } else { 4520 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4521 } 4522 return compareSignatures(s1, s2); 4523 } 4524 } 4525 4526 /** 4527 * This method should typically only be used when granting or revoking 4528 * permissions, since the app may immediately restart after this call. 4529 * <p> 4530 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4531 * guard your work against the app being relaunched. 4532 */ 4533 private void killUid(int appId, int userId, String reason) { 4534 final long identity = Binder.clearCallingIdentity(); 4535 try { 4536 IActivityManager am = ActivityManagerNative.getDefault(); 4537 if (am != null) { 4538 try { 4539 am.killUid(appId, userId, reason); 4540 } catch (RemoteException e) { 4541 /* ignore - same process */ 4542 } 4543 } 4544 } finally { 4545 Binder.restoreCallingIdentity(identity); 4546 } 4547 } 4548 4549 /** 4550 * Compares two sets of signatures. Returns: 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4553 * <br /> 4554 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4555 * <br /> 4556 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4557 * <br /> 4558 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4559 * <br /> 4560 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4561 */ 4562 static int compareSignatures(Signature[] s1, Signature[] s2) { 4563 if (s1 == null) { 4564 return s2 == null 4565 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4566 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4567 } 4568 4569 if (s2 == null) { 4570 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4571 } 4572 4573 if (s1.length != s2.length) { 4574 return PackageManager.SIGNATURE_NO_MATCH; 4575 } 4576 4577 // Since both signature sets are of size 1, we can compare without HashSets. 4578 if (s1.length == 1) { 4579 return s1[0].equals(s2[0]) ? 4580 PackageManager.SIGNATURE_MATCH : 4581 PackageManager.SIGNATURE_NO_MATCH; 4582 } 4583 4584 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4585 for (Signature sig : s1) { 4586 set1.add(sig); 4587 } 4588 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4589 for (Signature sig : s2) { 4590 set2.add(sig); 4591 } 4592 // Make sure s2 contains all signatures in s1. 4593 if (set1.equals(set2)) { 4594 return PackageManager.SIGNATURE_MATCH; 4595 } 4596 return PackageManager.SIGNATURE_NO_MATCH; 4597 } 4598 4599 /** 4600 * If the database version for this type of package (internal storage or 4601 * external storage) is less than the version where package signatures 4602 * were updated, return true. 4603 */ 4604 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4605 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4606 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4607 } 4608 4609 /** 4610 * Used for backward compatibility to make sure any packages with 4611 * certificate chains get upgraded to the new style. {@code existingSigs} 4612 * will be in the old format (since they were stored on disk from before the 4613 * system upgrade) and {@code scannedSigs} will be in the newer format. 4614 */ 4615 private int compareSignaturesCompat(PackageSignatures existingSigs, 4616 PackageParser.Package scannedPkg) { 4617 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4618 return PackageManager.SIGNATURE_NO_MATCH; 4619 } 4620 4621 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4622 for (Signature sig : existingSigs.mSignatures) { 4623 existingSet.add(sig); 4624 } 4625 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4626 for (Signature sig : scannedPkg.mSignatures) { 4627 try { 4628 Signature[] chainSignatures = sig.getChainSignatures(); 4629 for (Signature chainSig : chainSignatures) { 4630 scannedCompatSet.add(chainSig); 4631 } 4632 } catch (CertificateEncodingException e) { 4633 scannedCompatSet.add(sig); 4634 } 4635 } 4636 /* 4637 * Make sure the expanded scanned set contains all signatures in the 4638 * existing one. 4639 */ 4640 if (scannedCompatSet.equals(existingSet)) { 4641 // Migrate the old signatures to the new scheme. 4642 existingSigs.assignSignatures(scannedPkg.mSignatures); 4643 // The new KeySets will be re-added later in the scanning process. 4644 synchronized (mPackages) { 4645 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4646 } 4647 return PackageManager.SIGNATURE_MATCH; 4648 } 4649 return PackageManager.SIGNATURE_NO_MATCH; 4650 } 4651 4652 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4653 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4654 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4655 } 4656 4657 private int compareSignaturesRecover(PackageSignatures existingSigs, 4658 PackageParser.Package scannedPkg) { 4659 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4660 return PackageManager.SIGNATURE_NO_MATCH; 4661 } 4662 4663 String msg = null; 4664 try { 4665 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4666 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4667 + scannedPkg.packageName); 4668 return PackageManager.SIGNATURE_MATCH; 4669 } 4670 } catch (CertificateException e) { 4671 msg = e.getMessage(); 4672 } 4673 4674 logCriticalInfo(Log.INFO, 4675 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4676 return PackageManager.SIGNATURE_NO_MATCH; 4677 } 4678 4679 @Override 4680 public List<String> getAllPackages() { 4681 synchronized (mPackages) { 4682 return new ArrayList<String>(mPackages.keySet()); 4683 } 4684 } 4685 4686 @Override 4687 public String[] getPackagesForUid(int uid) { 4688 uid = UserHandle.getAppId(uid); 4689 // reader 4690 synchronized (mPackages) { 4691 Object obj = mSettings.getUserIdLPr(uid); 4692 if (obj instanceof SharedUserSetting) { 4693 final SharedUserSetting sus = (SharedUserSetting) obj; 4694 final int N = sus.packages.size(); 4695 final String[] res = new String[N]; 4696 final Iterator<PackageSetting> it = sus.packages.iterator(); 4697 int i = 0; 4698 while (it.hasNext()) { 4699 res[i++] = it.next().name; 4700 } 4701 return res; 4702 } else if (obj instanceof PackageSetting) { 4703 final PackageSetting ps = (PackageSetting) obj; 4704 return new String[] { ps.name }; 4705 } 4706 } 4707 return null; 4708 } 4709 4710 @Override 4711 public String getNameForUid(int uid) { 4712 // reader 4713 synchronized (mPackages) { 4714 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4715 if (obj instanceof SharedUserSetting) { 4716 final SharedUserSetting sus = (SharedUserSetting) obj; 4717 return sus.name + ":" + sus.userId; 4718 } else if (obj instanceof PackageSetting) { 4719 final PackageSetting ps = (PackageSetting) obj; 4720 return ps.name; 4721 } 4722 } 4723 return null; 4724 } 4725 4726 @Override 4727 public int getUidForSharedUser(String sharedUserName) { 4728 if(sharedUserName == null) { 4729 return -1; 4730 } 4731 // reader 4732 synchronized (mPackages) { 4733 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4734 if (suid == null) { 4735 return -1; 4736 } 4737 return suid.userId; 4738 } 4739 } 4740 4741 @Override 4742 public int getFlagsForUid(int uid) { 4743 synchronized (mPackages) { 4744 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4745 if (obj instanceof SharedUserSetting) { 4746 final SharedUserSetting sus = (SharedUserSetting) obj; 4747 return sus.pkgFlags; 4748 } else if (obj instanceof PackageSetting) { 4749 final PackageSetting ps = (PackageSetting) obj; 4750 return ps.pkgFlags; 4751 } 4752 } 4753 return 0; 4754 } 4755 4756 @Override 4757 public int getPrivateFlagsForUid(int uid) { 4758 synchronized (mPackages) { 4759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4760 if (obj instanceof SharedUserSetting) { 4761 final SharedUserSetting sus = (SharedUserSetting) obj; 4762 return sus.pkgPrivateFlags; 4763 } else if (obj instanceof PackageSetting) { 4764 final PackageSetting ps = (PackageSetting) obj; 4765 return ps.pkgPrivateFlags; 4766 } 4767 } 4768 return 0; 4769 } 4770 4771 @Override 4772 public boolean isUidPrivileged(int uid) { 4773 uid = UserHandle.getAppId(uid); 4774 // reader 4775 synchronized (mPackages) { 4776 Object obj = mSettings.getUserIdLPr(uid); 4777 if (obj instanceof SharedUserSetting) { 4778 final SharedUserSetting sus = (SharedUserSetting) obj; 4779 final Iterator<PackageSetting> it = sus.packages.iterator(); 4780 while (it.hasNext()) { 4781 if (it.next().isPrivileged()) { 4782 return true; 4783 } 4784 } 4785 } else if (obj instanceof PackageSetting) { 4786 final PackageSetting ps = (PackageSetting) obj; 4787 return ps.isPrivileged(); 4788 } 4789 } 4790 return false; 4791 } 4792 4793 @Override 4794 public String[] getAppOpPermissionPackages(String permissionName) { 4795 synchronized (mPackages) { 4796 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4797 if (pkgs == null) { 4798 return null; 4799 } 4800 return pkgs.toArray(new String[pkgs.size()]); 4801 } 4802 } 4803 4804 @Override 4805 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4806 int flags, int userId) { 4807 try { 4808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4809 4810 if (!sUserManager.exists(userId)) return null; 4811 flags = updateFlagsForResolve(flags, userId, intent); 4812 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4813 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4814 4815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4816 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4817 flags, userId); 4818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4819 4820 final ResolveInfo bestChoice = 4821 chooseBestActivity(intent, resolvedType, flags, query, userId); 4822 4823 if (isEphemeralAllowed(intent, query, userId)) { 4824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4825 final EphemeralResolveInfo ai = 4826 getEphemeralResolveInfo(intent, resolvedType, userId); 4827 if (ai != null) { 4828 if (DEBUG_EPHEMERAL) { 4829 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4830 } 4831 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4832 bestChoice.ephemeralResolveInfo = ai; 4833 } 4834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4835 } 4836 return bestChoice; 4837 } finally { 4838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4839 } 4840 } 4841 4842 @Override 4843 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4844 IntentFilter filter, int match, ComponentName activity) { 4845 final int userId = UserHandle.getCallingUserId(); 4846 if (DEBUG_PREFERRED) { 4847 Log.v(TAG, "setLastChosenActivity intent=" + intent 4848 + " resolvedType=" + resolvedType 4849 + " flags=" + flags 4850 + " filter=" + filter 4851 + " match=" + match 4852 + " activity=" + activity); 4853 filter.dump(new PrintStreamPrinter(System.out), " "); 4854 } 4855 intent.setComponent(null); 4856 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4857 userId); 4858 // Find any earlier preferred or last chosen entries and nuke them 4859 findPreferredActivity(intent, resolvedType, 4860 flags, query, 0, false, true, false, userId); 4861 // Add the new activity as the last chosen for this filter 4862 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4863 "Setting last chosen"); 4864 } 4865 4866 @Override 4867 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4868 final int userId = UserHandle.getCallingUserId(); 4869 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4870 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4871 userId); 4872 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4873 false, false, false, userId); 4874 } 4875 4876 4877 private boolean isEphemeralAllowed( 4878 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4879 // Short circuit and return early if possible. 4880 if (DISABLE_EPHEMERAL_APPS) { 4881 return false; 4882 } 4883 final int callingUser = UserHandle.getCallingUserId(); 4884 if (callingUser != UserHandle.USER_SYSTEM) { 4885 return false; 4886 } 4887 if (mEphemeralResolverConnection == null) { 4888 return false; 4889 } 4890 if (intent.getComponent() != null) { 4891 return false; 4892 } 4893 if (intent.getPackage() != null) { 4894 return false; 4895 } 4896 final boolean isWebUri = hasWebURI(intent); 4897 if (!isWebUri) { 4898 return false; 4899 } 4900 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4901 synchronized (mPackages) { 4902 final int count = resolvedActivites.size(); 4903 for (int n = 0; n < count; n++) { 4904 ResolveInfo info = resolvedActivites.get(n); 4905 String packageName = info.activityInfo.packageName; 4906 PackageSetting ps = mSettings.mPackages.get(packageName); 4907 if (ps != null) { 4908 // Try to get the status from User settings first 4909 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4910 int status = (int) (packedStatus >> 32); 4911 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4912 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4913 if (DEBUG_EPHEMERAL) { 4914 Slog.v(TAG, "DENY ephemeral apps;" 4915 + " pkg: " + packageName + ", status: " + status); 4916 } 4917 return false; 4918 } 4919 } 4920 } 4921 } 4922 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4923 return true; 4924 } 4925 4926 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4927 int userId) { 4928 MessageDigest digest = null; 4929 try { 4930 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4931 } catch (NoSuchAlgorithmException e) { 4932 // If we can't create a digest, ignore ephemeral apps. 4933 return null; 4934 } 4935 4936 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4937 final byte[] digestBytes = digest.digest(hostBytes); 4938 int shaPrefix = 4939 digestBytes[0] << 24 4940 | digestBytes[1] << 16 4941 | digestBytes[2] << 8 4942 | digestBytes[3] << 0; 4943 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4944 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4945 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4946 // No hash prefix match; there are no ephemeral apps for this domain. 4947 return null; 4948 } 4949 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4950 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4951 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4952 continue; 4953 } 4954 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4955 // No filters; this should never happen. 4956 if (filters.isEmpty()) { 4957 continue; 4958 } 4959 // We have a domain match; resolve the filters to see if anything matches. 4960 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4961 for (int j = filters.size() - 1; j >= 0; --j) { 4962 final EphemeralResolveIntentInfo intentInfo = 4963 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4964 ephemeralResolver.addFilter(intentInfo); 4965 } 4966 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4967 intent, resolvedType, false /*defaultOnly*/, userId); 4968 if (!matchedResolveInfoList.isEmpty()) { 4969 return matchedResolveInfoList.get(0); 4970 } 4971 } 4972 // Hash or filter mis-match; no ephemeral apps for this domain. 4973 return null; 4974 } 4975 4976 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4977 int flags, List<ResolveInfo> query, int userId) { 4978 if (query != null) { 4979 final int N = query.size(); 4980 if (N == 1) { 4981 return query.get(0); 4982 } else if (N > 1) { 4983 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4984 // If there is more than one activity with the same priority, 4985 // then let the user decide between them. 4986 ResolveInfo r0 = query.get(0); 4987 ResolveInfo r1 = query.get(1); 4988 if (DEBUG_INTENT_MATCHING || debug) { 4989 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4990 + r1.activityInfo.name + "=" + r1.priority); 4991 } 4992 // If the first activity has a higher priority, or a different 4993 // default, then it is always desirable to pick it. 4994 if (r0.priority != r1.priority 4995 || r0.preferredOrder != r1.preferredOrder 4996 || r0.isDefault != r1.isDefault) { 4997 return query.get(0); 4998 } 4999 // If we have saved a preference for a preferred activity for 5000 // this Intent, use that. 5001 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5002 flags, query, r0.priority, true, false, debug, userId); 5003 if (ri != null) { 5004 return ri; 5005 } 5006 ri = new ResolveInfo(mResolveInfo); 5007 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5008 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5009 ri.activityInfo.applicationInfo = new ApplicationInfo( 5010 ri.activityInfo.applicationInfo); 5011 if (userId != 0) { 5012 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5013 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5014 } 5015 // Make sure that the resolver is displayable in car mode 5016 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5017 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5018 return ri; 5019 } 5020 } 5021 return null; 5022 } 5023 5024 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5025 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5026 final int N = query.size(); 5027 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5028 .get(userId); 5029 // Get the list of persistent preferred activities that handle the intent 5030 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5031 List<PersistentPreferredActivity> pprefs = ppir != null 5032 ? ppir.queryIntent(intent, resolvedType, 5033 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5034 : null; 5035 if (pprefs != null && pprefs.size() > 0) { 5036 final int M = pprefs.size(); 5037 for (int i=0; i<M; i++) { 5038 final PersistentPreferredActivity ppa = pprefs.get(i); 5039 if (DEBUG_PREFERRED || debug) { 5040 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5041 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5042 + "\n component=" + ppa.mComponent); 5043 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5044 } 5045 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5046 flags | MATCH_DISABLED_COMPONENTS, userId); 5047 if (DEBUG_PREFERRED || debug) { 5048 Slog.v(TAG, "Found persistent preferred activity:"); 5049 if (ai != null) { 5050 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5051 } else { 5052 Slog.v(TAG, " null"); 5053 } 5054 } 5055 if (ai == null) { 5056 // This previously registered persistent preferred activity 5057 // component is no longer known. Ignore it and do NOT remove it. 5058 continue; 5059 } 5060 for (int j=0; j<N; j++) { 5061 final ResolveInfo ri = query.get(j); 5062 if (!ri.activityInfo.applicationInfo.packageName 5063 .equals(ai.applicationInfo.packageName)) { 5064 continue; 5065 } 5066 if (!ri.activityInfo.name.equals(ai.name)) { 5067 continue; 5068 } 5069 // Found a persistent preference that can handle the intent. 5070 if (DEBUG_PREFERRED || debug) { 5071 Slog.v(TAG, "Returning persistent preferred activity: " + 5072 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5073 } 5074 return ri; 5075 } 5076 } 5077 } 5078 return null; 5079 } 5080 5081 // TODO: handle preferred activities missing while user has amnesia 5082 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5083 List<ResolveInfo> query, int priority, boolean always, 5084 boolean removeMatches, boolean debug, int userId) { 5085 if (!sUserManager.exists(userId)) return null; 5086 flags = updateFlagsForResolve(flags, userId, intent); 5087 // writer 5088 synchronized (mPackages) { 5089 if (intent.getSelector() != null) { 5090 intent = intent.getSelector(); 5091 } 5092 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5093 5094 // Try to find a matching persistent preferred activity. 5095 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5096 debug, userId); 5097 5098 // If a persistent preferred activity matched, use it. 5099 if (pri != null) { 5100 return pri; 5101 } 5102 5103 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5104 // Get the list of preferred activities that handle the intent 5105 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5106 List<PreferredActivity> prefs = pir != null 5107 ? pir.queryIntent(intent, resolvedType, 5108 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5109 : null; 5110 if (prefs != null && prefs.size() > 0) { 5111 boolean changed = false; 5112 try { 5113 // First figure out how good the original match set is. 5114 // We will only allow preferred activities that came 5115 // from the same match quality. 5116 int match = 0; 5117 5118 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5119 5120 final int N = query.size(); 5121 for (int j=0; j<N; j++) { 5122 final ResolveInfo ri = query.get(j); 5123 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5124 + ": 0x" + Integer.toHexString(match)); 5125 if (ri.match > match) { 5126 match = ri.match; 5127 } 5128 } 5129 5130 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5131 + Integer.toHexString(match)); 5132 5133 match &= IntentFilter.MATCH_CATEGORY_MASK; 5134 final int M = prefs.size(); 5135 for (int i=0; i<M; i++) { 5136 final PreferredActivity pa = prefs.get(i); 5137 if (DEBUG_PREFERRED || debug) { 5138 Slog.v(TAG, "Checking PreferredActivity ds=" 5139 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5140 + "\n component=" + pa.mPref.mComponent); 5141 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5142 } 5143 if (pa.mPref.mMatch != match) { 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5145 + Integer.toHexString(pa.mPref.mMatch)); 5146 continue; 5147 } 5148 // If it's not an "always" type preferred activity and that's what we're 5149 // looking for, skip it. 5150 if (always && !pa.mPref.mAlways) { 5151 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5152 continue; 5153 } 5154 final ActivityInfo ai = getActivityInfo( 5155 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5156 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5157 userId); 5158 if (DEBUG_PREFERRED || debug) { 5159 Slog.v(TAG, "Found preferred activity:"); 5160 if (ai != null) { 5161 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5162 } else { 5163 Slog.v(TAG, " null"); 5164 } 5165 } 5166 if (ai == null) { 5167 // This previously registered preferred activity 5168 // component is no longer known. Most likely an update 5169 // to the app was installed and in the new version this 5170 // component no longer exists. Clean it up by removing 5171 // it from the preferred activities list, and skip it. 5172 Slog.w(TAG, "Removing dangling preferred activity: " 5173 + pa.mPref.mComponent); 5174 pir.removeFilter(pa); 5175 changed = true; 5176 continue; 5177 } 5178 for (int j=0; j<N; j++) { 5179 final ResolveInfo ri = query.get(j); 5180 if (!ri.activityInfo.applicationInfo.packageName 5181 .equals(ai.applicationInfo.packageName)) { 5182 continue; 5183 } 5184 if (!ri.activityInfo.name.equals(ai.name)) { 5185 continue; 5186 } 5187 5188 if (removeMatches) { 5189 pir.removeFilter(pa); 5190 changed = true; 5191 if (DEBUG_PREFERRED) { 5192 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5193 } 5194 break; 5195 } 5196 5197 // Okay we found a previously set preferred or last chosen app. 5198 // If the result set is different from when this 5199 // was created, we need to clear it and re-ask the 5200 // user their preference, if we're looking for an "always" type entry. 5201 if (always && !pa.mPref.sameSet(query)) { 5202 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5203 + intent + " type " + resolvedType); 5204 if (DEBUG_PREFERRED) { 5205 Slog.v(TAG, "Removing preferred activity since set changed " 5206 + pa.mPref.mComponent); 5207 } 5208 pir.removeFilter(pa); 5209 // Re-add the filter as a "last chosen" entry (!always) 5210 PreferredActivity lastChosen = new PreferredActivity( 5211 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5212 pir.addFilter(lastChosen); 5213 changed = true; 5214 return null; 5215 } 5216 5217 // Yay! Either the set matched or we're looking for the last chosen 5218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5219 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5220 return ri; 5221 } 5222 } 5223 } finally { 5224 if (changed) { 5225 if (DEBUG_PREFERRED) { 5226 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5227 } 5228 scheduleWritePackageRestrictionsLocked(userId); 5229 } 5230 } 5231 } 5232 } 5233 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5234 return null; 5235 } 5236 5237 /* 5238 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5239 */ 5240 @Override 5241 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5242 int targetUserId) { 5243 mContext.enforceCallingOrSelfPermission( 5244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5245 List<CrossProfileIntentFilter> matches = 5246 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5247 if (matches != null) { 5248 int size = matches.size(); 5249 for (int i = 0; i < size; i++) { 5250 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5251 } 5252 } 5253 if (hasWebURI(intent)) { 5254 // cross-profile app linking works only towards the parent. 5255 final UserInfo parent = getProfileParent(sourceUserId); 5256 synchronized(mPackages) { 5257 int flags = updateFlagsForResolve(0, parent.id, intent); 5258 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5259 intent, resolvedType, flags, sourceUserId, parent.id); 5260 return xpDomainInfo != null; 5261 } 5262 } 5263 return false; 5264 } 5265 5266 private UserInfo getProfileParent(int userId) { 5267 final long identity = Binder.clearCallingIdentity(); 5268 try { 5269 return sUserManager.getProfileParent(userId); 5270 } finally { 5271 Binder.restoreCallingIdentity(identity); 5272 } 5273 } 5274 5275 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5276 String resolvedType, int userId) { 5277 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5278 if (resolver != null) { 5279 return resolver.queryIntent(intent, resolvedType, false, userId); 5280 } 5281 return null; 5282 } 5283 5284 @Override 5285 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5286 String resolvedType, int flags, int userId) { 5287 try { 5288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5289 5290 return new ParceledListSlice<>( 5291 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5292 } finally { 5293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5294 } 5295 } 5296 5297 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5298 String resolvedType, int flags, int userId) { 5299 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5300 flags = updateFlagsForResolve(flags, userId, intent); 5301 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5302 false /* requireFullPermission */, false /* checkShell */, 5303 "query intent activities"); 5304 ComponentName comp = intent.getComponent(); 5305 if (comp == null) { 5306 if (intent.getSelector() != null) { 5307 intent = intent.getSelector(); 5308 comp = intent.getComponent(); 5309 } 5310 } 5311 5312 if (comp != null) { 5313 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5314 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5315 if (ai != null) { 5316 final ResolveInfo ri = new ResolveInfo(); 5317 ri.activityInfo = ai; 5318 list.add(ri); 5319 } 5320 return list; 5321 } 5322 5323 // reader 5324 synchronized (mPackages) { 5325 final String pkgName = intent.getPackage(); 5326 if (pkgName == null) { 5327 List<CrossProfileIntentFilter> matchingFilters = 5328 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5329 // Check for results that need to skip the current profile. 5330 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5331 resolvedType, flags, userId); 5332 if (xpResolveInfo != null) { 5333 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5334 result.add(xpResolveInfo); 5335 return filterIfNotSystemUser(result, userId); 5336 } 5337 5338 // Check for results in the current profile. 5339 List<ResolveInfo> result = mActivities.queryIntent( 5340 intent, resolvedType, flags, userId); 5341 result = filterIfNotSystemUser(result, userId); 5342 5343 // Check for cross profile results. 5344 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5345 xpResolveInfo = queryCrossProfileIntents( 5346 matchingFilters, intent, resolvedType, flags, userId, 5347 hasNonNegativePriorityResult); 5348 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5349 boolean isVisibleToUser = filterIfNotSystemUser( 5350 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5351 if (isVisibleToUser) { 5352 result.add(xpResolveInfo); 5353 Collections.sort(result, mResolvePrioritySorter); 5354 } 5355 } 5356 if (hasWebURI(intent)) { 5357 CrossProfileDomainInfo xpDomainInfo = null; 5358 final UserInfo parent = getProfileParent(userId); 5359 if (parent != null) { 5360 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5361 flags, userId, parent.id); 5362 } 5363 if (xpDomainInfo != null) { 5364 if (xpResolveInfo != null) { 5365 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5366 // in the result. 5367 result.remove(xpResolveInfo); 5368 } 5369 if (result.size() == 0) { 5370 result.add(xpDomainInfo.resolveInfo); 5371 return result; 5372 } 5373 } else if (result.size() <= 1) { 5374 return result; 5375 } 5376 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5377 xpDomainInfo, userId); 5378 Collections.sort(result, mResolvePrioritySorter); 5379 } 5380 return result; 5381 } 5382 final PackageParser.Package pkg = mPackages.get(pkgName); 5383 if (pkg != null) { 5384 return filterIfNotSystemUser( 5385 mActivities.queryIntentForPackage( 5386 intent, resolvedType, flags, pkg.activities, userId), 5387 userId); 5388 } 5389 return new ArrayList<ResolveInfo>(); 5390 } 5391 } 5392 5393 private static class CrossProfileDomainInfo { 5394 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5395 ResolveInfo resolveInfo; 5396 /* Best domain verification status of the activities found in the other profile */ 5397 int bestDomainVerificationStatus; 5398 } 5399 5400 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5401 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5402 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5403 sourceUserId)) { 5404 return null; 5405 } 5406 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5407 resolvedType, flags, parentUserId); 5408 5409 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5410 return null; 5411 } 5412 CrossProfileDomainInfo result = null; 5413 int size = resultTargetUser.size(); 5414 for (int i = 0; i < size; i++) { 5415 ResolveInfo riTargetUser = resultTargetUser.get(i); 5416 // Intent filter verification is only for filters that specify a host. So don't return 5417 // those that handle all web uris. 5418 if (riTargetUser.handleAllWebDataURI) { 5419 continue; 5420 } 5421 String packageName = riTargetUser.activityInfo.packageName; 5422 PackageSetting ps = mSettings.mPackages.get(packageName); 5423 if (ps == null) { 5424 continue; 5425 } 5426 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5427 int status = (int)(verificationState >> 32); 5428 if (result == null) { 5429 result = new CrossProfileDomainInfo(); 5430 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5431 sourceUserId, parentUserId); 5432 result.bestDomainVerificationStatus = status; 5433 } else { 5434 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5435 result.bestDomainVerificationStatus); 5436 } 5437 } 5438 // Don't consider matches with status NEVER across profiles. 5439 if (result != null && result.bestDomainVerificationStatus 5440 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5441 return null; 5442 } 5443 return result; 5444 } 5445 5446 /** 5447 * Verification statuses are ordered from the worse to the best, except for 5448 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5449 */ 5450 private int bestDomainVerificationStatus(int status1, int status2) { 5451 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5452 return status2; 5453 } 5454 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5455 return status1; 5456 } 5457 return (int) MathUtils.max(status1, status2); 5458 } 5459 5460 private boolean isUserEnabled(int userId) { 5461 long callingId = Binder.clearCallingIdentity(); 5462 try { 5463 UserInfo userInfo = sUserManager.getUserInfo(userId); 5464 return userInfo != null && userInfo.isEnabled(); 5465 } finally { 5466 Binder.restoreCallingIdentity(callingId); 5467 } 5468 } 5469 5470 /** 5471 * Filter out activities with systemUserOnly flag set, when current user is not System. 5472 * 5473 * @return filtered list 5474 */ 5475 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5476 if (userId == UserHandle.USER_SYSTEM) { 5477 return resolveInfos; 5478 } 5479 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5480 ResolveInfo info = resolveInfos.get(i); 5481 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5482 resolveInfos.remove(i); 5483 } 5484 } 5485 return resolveInfos; 5486 } 5487 5488 /** 5489 * @param resolveInfos list of resolve infos in descending priority order 5490 * @return if the list contains a resolve info with non-negative priority 5491 */ 5492 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5493 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5494 } 5495 5496 private static boolean hasWebURI(Intent intent) { 5497 if (intent.getData() == null) { 5498 return false; 5499 } 5500 final String scheme = intent.getScheme(); 5501 if (TextUtils.isEmpty(scheme)) { 5502 return false; 5503 } 5504 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5505 } 5506 5507 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5508 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5509 int userId) { 5510 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5511 5512 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5513 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5514 candidates.size()); 5515 } 5516 5517 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5518 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5519 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5520 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5521 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5522 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5523 5524 synchronized (mPackages) { 5525 final int count = candidates.size(); 5526 // First, try to use linked apps. Partition the candidates into four lists: 5527 // one for the final results, one for the "do not use ever", one for "undefined status" 5528 // and finally one for "browser app type". 5529 for (int n=0; n<count; n++) { 5530 ResolveInfo info = candidates.get(n); 5531 String packageName = info.activityInfo.packageName; 5532 PackageSetting ps = mSettings.mPackages.get(packageName); 5533 if (ps != null) { 5534 // Add to the special match all list (Browser use case) 5535 if (info.handleAllWebDataURI) { 5536 matchAllList.add(info); 5537 continue; 5538 } 5539 // Try to get the status from User settings first 5540 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5541 int status = (int)(packedStatus >> 32); 5542 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5543 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5544 if (DEBUG_DOMAIN_VERIFICATION) { 5545 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5546 + " : linkgen=" + linkGeneration); 5547 } 5548 // Use link-enabled generation as preferredOrder, i.e. 5549 // prefer newly-enabled over earlier-enabled. 5550 info.preferredOrder = linkGeneration; 5551 alwaysList.add(info); 5552 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5553 if (DEBUG_DOMAIN_VERIFICATION) { 5554 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5555 } 5556 neverList.add(info); 5557 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5558 if (DEBUG_DOMAIN_VERIFICATION) { 5559 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5560 } 5561 alwaysAskList.add(info); 5562 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5563 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5564 if (DEBUG_DOMAIN_VERIFICATION) { 5565 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5566 } 5567 undefinedList.add(info); 5568 } 5569 } 5570 } 5571 5572 // We'll want to include browser possibilities in a few cases 5573 boolean includeBrowser = false; 5574 5575 // First try to add the "always" resolution(s) for the current user, if any 5576 if (alwaysList.size() > 0) { 5577 result.addAll(alwaysList); 5578 } else { 5579 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5580 result.addAll(undefinedList); 5581 // Maybe add one for the other profile. 5582 if (xpDomainInfo != null && ( 5583 xpDomainInfo.bestDomainVerificationStatus 5584 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5585 result.add(xpDomainInfo.resolveInfo); 5586 } 5587 includeBrowser = true; 5588 } 5589 5590 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5591 // If there were 'always' entries their preferred order has been set, so we also 5592 // back that off to make the alternatives equivalent 5593 if (alwaysAskList.size() > 0) { 5594 for (ResolveInfo i : result) { 5595 i.preferredOrder = 0; 5596 } 5597 result.addAll(alwaysAskList); 5598 includeBrowser = true; 5599 } 5600 5601 if (includeBrowser) { 5602 // Also add browsers (all of them or only the default one) 5603 if (DEBUG_DOMAIN_VERIFICATION) { 5604 Slog.v(TAG, " ...including browsers in candidate set"); 5605 } 5606 if ((matchFlags & MATCH_ALL) != 0) { 5607 result.addAll(matchAllList); 5608 } else { 5609 // Browser/generic handling case. If there's a default browser, go straight 5610 // to that (but only if there is no other higher-priority match). 5611 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5612 int maxMatchPrio = 0; 5613 ResolveInfo defaultBrowserMatch = null; 5614 final int numCandidates = matchAllList.size(); 5615 for (int n = 0; n < numCandidates; n++) { 5616 ResolveInfo info = matchAllList.get(n); 5617 // track the highest overall match priority... 5618 if (info.priority > maxMatchPrio) { 5619 maxMatchPrio = info.priority; 5620 } 5621 // ...and the highest-priority default browser match 5622 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5623 if (defaultBrowserMatch == null 5624 || (defaultBrowserMatch.priority < info.priority)) { 5625 if (debug) { 5626 Slog.v(TAG, "Considering default browser match " + info); 5627 } 5628 defaultBrowserMatch = info; 5629 } 5630 } 5631 } 5632 if (defaultBrowserMatch != null 5633 && defaultBrowserMatch.priority >= maxMatchPrio 5634 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5635 { 5636 if (debug) { 5637 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5638 } 5639 result.add(defaultBrowserMatch); 5640 } else { 5641 result.addAll(matchAllList); 5642 } 5643 } 5644 5645 // If there is nothing selected, add all candidates and remove the ones that the user 5646 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5647 if (result.size() == 0) { 5648 result.addAll(candidates); 5649 result.removeAll(neverList); 5650 } 5651 } 5652 } 5653 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5654 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5655 result.size()); 5656 for (ResolveInfo info : result) { 5657 Slog.v(TAG, " + " + info.activityInfo); 5658 } 5659 } 5660 return result; 5661 } 5662 5663 // Returns a packed value as a long: 5664 // 5665 // high 'int'-sized word: link status: undefined/ask/never/always. 5666 // low 'int'-sized word: relative priority among 'always' results. 5667 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5668 long result = ps.getDomainVerificationStatusForUser(userId); 5669 // if none available, get the master status 5670 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5671 if (ps.getIntentFilterVerificationInfo() != null) { 5672 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5673 } 5674 } 5675 return result; 5676 } 5677 5678 private ResolveInfo querySkipCurrentProfileIntents( 5679 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5680 int flags, int sourceUserId) { 5681 if (matchingFilters != null) { 5682 int size = matchingFilters.size(); 5683 for (int i = 0; i < size; i ++) { 5684 CrossProfileIntentFilter filter = matchingFilters.get(i); 5685 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5686 // Checking if there are activities in the target user that can handle the 5687 // intent. 5688 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5689 resolvedType, flags, sourceUserId); 5690 if (resolveInfo != null) { 5691 return resolveInfo; 5692 } 5693 } 5694 } 5695 } 5696 return null; 5697 } 5698 5699 // Return matching ResolveInfo in target user if any. 5700 private ResolveInfo queryCrossProfileIntents( 5701 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5702 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5703 if (matchingFilters != null) { 5704 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5705 // match the same intent. For performance reasons, it is better not to 5706 // run queryIntent twice for the same userId 5707 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5708 int size = matchingFilters.size(); 5709 for (int i = 0; i < size; i++) { 5710 CrossProfileIntentFilter filter = matchingFilters.get(i); 5711 int targetUserId = filter.getTargetUserId(); 5712 boolean skipCurrentProfile = 5713 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5714 boolean skipCurrentProfileIfNoMatchFound = 5715 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5716 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5717 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5718 // Checking if there are activities in the target user that can handle the 5719 // intent. 5720 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5721 resolvedType, flags, sourceUserId); 5722 if (resolveInfo != null) return resolveInfo; 5723 alreadyTriedUserIds.put(targetUserId, true); 5724 } 5725 } 5726 } 5727 return null; 5728 } 5729 5730 /** 5731 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5732 * will forward the intent to the filter's target user. 5733 * Otherwise, returns null. 5734 */ 5735 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5736 String resolvedType, int flags, int sourceUserId) { 5737 int targetUserId = filter.getTargetUserId(); 5738 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5739 resolvedType, flags, targetUserId); 5740 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5741 // If all the matches in the target profile are suspended, return null. 5742 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5743 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5744 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5745 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5746 targetUserId); 5747 } 5748 } 5749 } 5750 return null; 5751 } 5752 5753 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5754 int sourceUserId, int targetUserId) { 5755 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5756 long ident = Binder.clearCallingIdentity(); 5757 boolean targetIsProfile; 5758 try { 5759 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5760 } finally { 5761 Binder.restoreCallingIdentity(ident); 5762 } 5763 String className; 5764 if (targetIsProfile) { 5765 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5766 } else { 5767 className = FORWARD_INTENT_TO_PARENT; 5768 } 5769 ComponentName forwardingActivityComponentName = new ComponentName( 5770 mAndroidApplication.packageName, className); 5771 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5772 sourceUserId); 5773 if (!targetIsProfile) { 5774 forwardingActivityInfo.showUserIcon = targetUserId; 5775 forwardingResolveInfo.noResourceId = true; 5776 } 5777 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5778 forwardingResolveInfo.priority = 0; 5779 forwardingResolveInfo.preferredOrder = 0; 5780 forwardingResolveInfo.match = 0; 5781 forwardingResolveInfo.isDefault = true; 5782 forwardingResolveInfo.filter = filter; 5783 forwardingResolveInfo.targetUserId = targetUserId; 5784 return forwardingResolveInfo; 5785 } 5786 5787 @Override 5788 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5789 Intent[] specifics, String[] specificTypes, Intent intent, 5790 String resolvedType, int flags, int userId) { 5791 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5792 specificTypes, intent, resolvedType, flags, userId)); 5793 } 5794 5795 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5796 Intent[] specifics, String[] specificTypes, Intent intent, 5797 String resolvedType, int flags, int userId) { 5798 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5799 flags = updateFlagsForResolve(flags, userId, intent); 5800 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5801 false /* requireFullPermission */, false /* checkShell */, 5802 "query intent activity options"); 5803 final String resultsAction = intent.getAction(); 5804 5805 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5806 | PackageManager.GET_RESOLVED_FILTER, userId); 5807 5808 if (DEBUG_INTENT_MATCHING) { 5809 Log.v(TAG, "Query " + intent + ": " + results); 5810 } 5811 5812 int specificsPos = 0; 5813 int N; 5814 5815 // todo: note that the algorithm used here is O(N^2). This 5816 // isn't a problem in our current environment, but if we start running 5817 // into situations where we have more than 5 or 10 matches then this 5818 // should probably be changed to something smarter... 5819 5820 // First we go through and resolve each of the specific items 5821 // that were supplied, taking care of removing any corresponding 5822 // duplicate items in the generic resolve list. 5823 if (specifics != null) { 5824 for (int i=0; i<specifics.length; i++) { 5825 final Intent sintent = specifics[i]; 5826 if (sintent == null) { 5827 continue; 5828 } 5829 5830 if (DEBUG_INTENT_MATCHING) { 5831 Log.v(TAG, "Specific #" + i + ": " + sintent); 5832 } 5833 5834 String action = sintent.getAction(); 5835 if (resultsAction != null && resultsAction.equals(action)) { 5836 // If this action was explicitly requested, then don't 5837 // remove things that have it. 5838 action = null; 5839 } 5840 5841 ResolveInfo ri = null; 5842 ActivityInfo ai = null; 5843 5844 ComponentName comp = sintent.getComponent(); 5845 if (comp == null) { 5846 ri = resolveIntent( 5847 sintent, 5848 specificTypes != null ? specificTypes[i] : null, 5849 flags, userId); 5850 if (ri == null) { 5851 continue; 5852 } 5853 if (ri == mResolveInfo) { 5854 // ACK! Must do something better with this. 5855 } 5856 ai = ri.activityInfo; 5857 comp = new ComponentName(ai.applicationInfo.packageName, 5858 ai.name); 5859 } else { 5860 ai = getActivityInfo(comp, flags, userId); 5861 if (ai == null) { 5862 continue; 5863 } 5864 } 5865 5866 // Look for any generic query activities that are duplicates 5867 // of this specific one, and remove them from the results. 5868 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5869 N = results.size(); 5870 int j; 5871 for (j=specificsPos; j<N; j++) { 5872 ResolveInfo sri = results.get(j); 5873 if ((sri.activityInfo.name.equals(comp.getClassName()) 5874 && sri.activityInfo.applicationInfo.packageName.equals( 5875 comp.getPackageName())) 5876 || (action != null && sri.filter.matchAction(action))) { 5877 results.remove(j); 5878 if (DEBUG_INTENT_MATCHING) Log.v( 5879 TAG, "Removing duplicate item from " + j 5880 + " due to specific " + specificsPos); 5881 if (ri == null) { 5882 ri = sri; 5883 } 5884 j--; 5885 N--; 5886 } 5887 } 5888 5889 // Add this specific item to its proper place. 5890 if (ri == null) { 5891 ri = new ResolveInfo(); 5892 ri.activityInfo = ai; 5893 } 5894 results.add(specificsPos, ri); 5895 ri.specificIndex = i; 5896 specificsPos++; 5897 } 5898 } 5899 5900 // Now we go through the remaining generic results and remove any 5901 // duplicate actions that are found here. 5902 N = results.size(); 5903 for (int i=specificsPos; i<N-1; i++) { 5904 final ResolveInfo rii = results.get(i); 5905 if (rii.filter == null) { 5906 continue; 5907 } 5908 5909 // Iterate over all of the actions of this result's intent 5910 // filter... typically this should be just one. 5911 final Iterator<String> it = rii.filter.actionsIterator(); 5912 if (it == null) { 5913 continue; 5914 } 5915 while (it.hasNext()) { 5916 final String action = it.next(); 5917 if (resultsAction != null && resultsAction.equals(action)) { 5918 // If this action was explicitly requested, then don't 5919 // remove things that have it. 5920 continue; 5921 } 5922 for (int j=i+1; j<N; j++) { 5923 final ResolveInfo rij = results.get(j); 5924 if (rij.filter != null && rij.filter.hasAction(action)) { 5925 results.remove(j); 5926 if (DEBUG_INTENT_MATCHING) Log.v( 5927 TAG, "Removing duplicate item from " + j 5928 + " due to action " + action + " at " + i); 5929 j--; 5930 N--; 5931 } 5932 } 5933 } 5934 5935 // If the caller didn't request filter information, drop it now 5936 // so we don't have to marshall/unmarshall it. 5937 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5938 rii.filter = null; 5939 } 5940 } 5941 5942 // Filter out the caller activity if so requested. 5943 if (caller != null) { 5944 N = results.size(); 5945 for (int i=0; i<N; i++) { 5946 ActivityInfo ainfo = results.get(i).activityInfo; 5947 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5948 && caller.getClassName().equals(ainfo.name)) { 5949 results.remove(i); 5950 break; 5951 } 5952 } 5953 } 5954 5955 // If the caller didn't request filter information, 5956 // drop them now so we don't have to 5957 // marshall/unmarshall it. 5958 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5959 N = results.size(); 5960 for (int i=0; i<N; i++) { 5961 results.get(i).filter = null; 5962 } 5963 } 5964 5965 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5966 return results; 5967 } 5968 5969 @Override 5970 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5971 String resolvedType, int flags, int userId) { 5972 return new ParceledListSlice<>( 5973 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5974 } 5975 5976 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5977 String resolvedType, int flags, int userId) { 5978 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5979 flags = updateFlagsForResolve(flags, userId, intent); 5980 ComponentName comp = intent.getComponent(); 5981 if (comp == null) { 5982 if (intent.getSelector() != null) { 5983 intent = intent.getSelector(); 5984 comp = intent.getComponent(); 5985 } 5986 } 5987 if (comp != null) { 5988 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5989 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5990 if (ai != null) { 5991 ResolveInfo ri = new ResolveInfo(); 5992 ri.activityInfo = ai; 5993 list.add(ri); 5994 } 5995 return list; 5996 } 5997 5998 // reader 5999 synchronized (mPackages) { 6000 String pkgName = intent.getPackage(); 6001 if (pkgName == null) { 6002 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6003 } 6004 final PackageParser.Package pkg = mPackages.get(pkgName); 6005 if (pkg != null) { 6006 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6007 userId); 6008 } 6009 return Collections.emptyList(); 6010 } 6011 } 6012 6013 @Override 6014 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6015 if (!sUserManager.exists(userId)) return null; 6016 flags = updateFlagsForResolve(flags, userId, intent); 6017 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6018 if (query != null) { 6019 if (query.size() >= 1) { 6020 // If there is more than one service with the same priority, 6021 // just arbitrarily pick the first one. 6022 return query.get(0); 6023 } 6024 } 6025 return null; 6026 } 6027 6028 @Override 6029 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 return new ParceledListSlice<>( 6032 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6033 } 6034 6035 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6036 String resolvedType, int flags, int userId) { 6037 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6038 flags = updateFlagsForResolve(flags, userId, intent); 6039 ComponentName comp = intent.getComponent(); 6040 if (comp == null) { 6041 if (intent.getSelector() != null) { 6042 intent = intent.getSelector(); 6043 comp = intent.getComponent(); 6044 } 6045 } 6046 if (comp != null) { 6047 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6048 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6049 if (si != null) { 6050 final ResolveInfo ri = new ResolveInfo(); 6051 ri.serviceInfo = si; 6052 list.add(ri); 6053 } 6054 return list; 6055 } 6056 6057 // reader 6058 synchronized (mPackages) { 6059 String pkgName = intent.getPackage(); 6060 if (pkgName == null) { 6061 return mServices.queryIntent(intent, resolvedType, flags, userId); 6062 } 6063 final PackageParser.Package pkg = mPackages.get(pkgName); 6064 if (pkg != null) { 6065 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6066 userId); 6067 } 6068 return Collections.emptyList(); 6069 } 6070 } 6071 6072 @Override 6073 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6074 String resolvedType, int flags, int userId) { 6075 return new ParceledListSlice<>( 6076 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6077 } 6078 6079 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6080 Intent intent, String resolvedType, int flags, int userId) { 6081 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6082 flags = updateFlagsForResolve(flags, userId, intent); 6083 ComponentName comp = intent.getComponent(); 6084 if (comp == null) { 6085 if (intent.getSelector() != null) { 6086 intent = intent.getSelector(); 6087 comp = intent.getComponent(); 6088 } 6089 } 6090 if (comp != null) { 6091 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6092 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6093 if (pi != null) { 6094 final ResolveInfo ri = new ResolveInfo(); 6095 ri.providerInfo = pi; 6096 list.add(ri); 6097 } 6098 return list; 6099 } 6100 6101 // reader 6102 synchronized (mPackages) { 6103 String pkgName = intent.getPackage(); 6104 if (pkgName == null) { 6105 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6106 } 6107 final PackageParser.Package pkg = mPackages.get(pkgName); 6108 if (pkg != null) { 6109 return mProviders.queryIntentForPackage( 6110 intent, resolvedType, flags, pkg.providers, userId); 6111 } 6112 return Collections.emptyList(); 6113 } 6114 } 6115 6116 @Override 6117 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6118 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6119 flags = updateFlagsForPackage(flags, userId, null); 6120 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6121 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6122 true /* requireFullPermission */, false /* checkShell */, 6123 "get installed packages"); 6124 6125 // writer 6126 synchronized (mPackages) { 6127 ArrayList<PackageInfo> list; 6128 if (listUninstalled) { 6129 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6130 for (PackageSetting ps : mSettings.mPackages.values()) { 6131 final PackageInfo pi; 6132 if (ps.pkg != null) { 6133 pi = generatePackageInfo(ps, flags, userId); 6134 } else { 6135 pi = generatePackageInfo(ps, flags, userId); 6136 } 6137 if (pi != null) { 6138 list.add(pi); 6139 } 6140 } 6141 } else { 6142 list = new ArrayList<PackageInfo>(mPackages.size()); 6143 for (PackageParser.Package p : mPackages.values()) { 6144 final PackageInfo pi = 6145 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6146 if (pi != null) { 6147 list.add(pi); 6148 } 6149 } 6150 } 6151 6152 return new ParceledListSlice<PackageInfo>(list); 6153 } 6154 } 6155 6156 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6157 String[] permissions, boolean[] tmp, int flags, int userId) { 6158 int numMatch = 0; 6159 final PermissionsState permissionsState = ps.getPermissionsState(); 6160 for (int i=0; i<permissions.length; i++) { 6161 final String permission = permissions[i]; 6162 if (permissionsState.hasPermission(permission, userId)) { 6163 tmp[i] = true; 6164 numMatch++; 6165 } else { 6166 tmp[i] = false; 6167 } 6168 } 6169 if (numMatch == 0) { 6170 return; 6171 } 6172 final PackageInfo pi; 6173 if (ps.pkg != null) { 6174 pi = generatePackageInfo(ps, flags, userId); 6175 } else { 6176 pi = generatePackageInfo(ps, flags, userId); 6177 } 6178 // The above might return null in cases of uninstalled apps or install-state 6179 // skew across users/profiles. 6180 if (pi != null) { 6181 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6182 if (numMatch == permissions.length) { 6183 pi.requestedPermissions = permissions; 6184 } else { 6185 pi.requestedPermissions = new String[numMatch]; 6186 numMatch = 0; 6187 for (int i=0; i<permissions.length; i++) { 6188 if (tmp[i]) { 6189 pi.requestedPermissions[numMatch] = permissions[i]; 6190 numMatch++; 6191 } 6192 } 6193 } 6194 } 6195 list.add(pi); 6196 } 6197 } 6198 6199 @Override 6200 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6201 String[] permissions, int flags, int userId) { 6202 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6203 flags = updateFlagsForPackage(flags, userId, permissions); 6204 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6205 6206 // writer 6207 synchronized (mPackages) { 6208 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6209 boolean[] tmpBools = new boolean[permissions.length]; 6210 if (listUninstalled) { 6211 for (PackageSetting ps : mSettings.mPackages.values()) { 6212 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6213 } 6214 } else { 6215 for (PackageParser.Package pkg : mPackages.values()) { 6216 PackageSetting ps = (PackageSetting)pkg.mExtras; 6217 if (ps != null) { 6218 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6219 userId); 6220 } 6221 } 6222 } 6223 6224 return new ParceledListSlice<PackageInfo>(list); 6225 } 6226 } 6227 6228 @Override 6229 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6230 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6231 flags = updateFlagsForApplication(flags, userId, null); 6232 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6233 6234 // writer 6235 synchronized (mPackages) { 6236 ArrayList<ApplicationInfo> list; 6237 if (listUninstalled) { 6238 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6239 for (PackageSetting ps : mSettings.mPackages.values()) { 6240 ApplicationInfo ai; 6241 if (ps.pkg != null) { 6242 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6243 ps.readUserState(userId), userId); 6244 } else { 6245 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6246 } 6247 if (ai != null) { 6248 list.add(ai); 6249 } 6250 } 6251 } else { 6252 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6253 for (PackageParser.Package p : mPackages.values()) { 6254 if (p.mExtras != null) { 6255 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6256 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6257 if (ai != null) { 6258 list.add(ai); 6259 } 6260 } 6261 } 6262 } 6263 6264 return new ParceledListSlice<ApplicationInfo>(list); 6265 } 6266 } 6267 6268 @Override 6269 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6270 if (DISABLE_EPHEMERAL_APPS) { 6271 return null; 6272 } 6273 6274 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6275 "getEphemeralApplications"); 6276 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6277 true /* requireFullPermission */, false /* checkShell */, 6278 "getEphemeralApplications"); 6279 synchronized (mPackages) { 6280 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6281 .getEphemeralApplicationsLPw(userId); 6282 if (ephemeralApps != null) { 6283 return new ParceledListSlice<>(ephemeralApps); 6284 } 6285 } 6286 return null; 6287 } 6288 6289 @Override 6290 public boolean isEphemeralApplication(String packageName, int userId) { 6291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6292 true /* requireFullPermission */, false /* checkShell */, 6293 "isEphemeral"); 6294 if (DISABLE_EPHEMERAL_APPS) { 6295 return false; 6296 } 6297 6298 if (!isCallerSameApp(packageName)) { 6299 return false; 6300 } 6301 synchronized (mPackages) { 6302 PackageParser.Package pkg = mPackages.get(packageName); 6303 if (pkg != null) { 6304 return pkg.applicationInfo.isEphemeralApp(); 6305 } 6306 } 6307 return false; 6308 } 6309 6310 @Override 6311 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6312 if (DISABLE_EPHEMERAL_APPS) { 6313 return null; 6314 } 6315 6316 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6317 true /* requireFullPermission */, false /* checkShell */, 6318 "getCookie"); 6319 if (!isCallerSameApp(packageName)) { 6320 return null; 6321 } 6322 synchronized (mPackages) { 6323 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6324 packageName, userId); 6325 } 6326 } 6327 6328 @Override 6329 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6330 if (DISABLE_EPHEMERAL_APPS) { 6331 return true; 6332 } 6333 6334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6335 true /* requireFullPermission */, true /* checkShell */, 6336 "setCookie"); 6337 if (!isCallerSameApp(packageName)) { 6338 return false; 6339 } 6340 synchronized (mPackages) { 6341 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6342 packageName, cookie, userId); 6343 } 6344 } 6345 6346 @Override 6347 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6348 if (DISABLE_EPHEMERAL_APPS) { 6349 return null; 6350 } 6351 6352 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6353 "getEphemeralApplicationIcon"); 6354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6355 true /* requireFullPermission */, false /* checkShell */, 6356 "getEphemeralApplicationIcon"); 6357 synchronized (mPackages) { 6358 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6359 packageName, userId); 6360 } 6361 } 6362 6363 private boolean isCallerSameApp(String packageName) { 6364 PackageParser.Package pkg = mPackages.get(packageName); 6365 return pkg != null 6366 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6367 } 6368 6369 @Override 6370 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6371 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6372 } 6373 6374 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6375 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6376 6377 // reader 6378 synchronized (mPackages) { 6379 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6380 final int userId = UserHandle.getCallingUserId(); 6381 while (i.hasNext()) { 6382 final PackageParser.Package p = i.next(); 6383 if (p.applicationInfo == null) continue; 6384 6385 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6386 && !p.applicationInfo.isDirectBootAware(); 6387 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6388 && p.applicationInfo.isDirectBootAware(); 6389 6390 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6391 && (!mSafeMode || isSystemApp(p)) 6392 && (matchesUnaware || matchesAware)) { 6393 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6394 if (ps != null) { 6395 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6396 ps.readUserState(userId), userId); 6397 if (ai != null) { 6398 finalList.add(ai); 6399 } 6400 } 6401 } 6402 } 6403 } 6404 6405 return finalList; 6406 } 6407 6408 @Override 6409 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6410 if (!sUserManager.exists(userId)) return null; 6411 flags = updateFlagsForComponent(flags, userId, name); 6412 // reader 6413 synchronized (mPackages) { 6414 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6415 PackageSetting ps = provider != null 6416 ? mSettings.mPackages.get(provider.owner.packageName) 6417 : null; 6418 return ps != null 6419 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6420 ? PackageParser.generateProviderInfo(provider, flags, 6421 ps.readUserState(userId), userId) 6422 : null; 6423 } 6424 } 6425 6426 /** 6427 * @deprecated 6428 */ 6429 @Deprecated 6430 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6431 // reader 6432 synchronized (mPackages) { 6433 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6434 .entrySet().iterator(); 6435 final int userId = UserHandle.getCallingUserId(); 6436 while (i.hasNext()) { 6437 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6438 PackageParser.Provider p = entry.getValue(); 6439 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6440 6441 if (ps != null && p.syncable 6442 && (!mSafeMode || (p.info.applicationInfo.flags 6443 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6444 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6445 ps.readUserState(userId), userId); 6446 if (info != null) { 6447 outNames.add(entry.getKey()); 6448 outInfo.add(info); 6449 } 6450 } 6451 } 6452 } 6453 } 6454 6455 @Override 6456 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6457 int uid, int flags) { 6458 final int userId = processName != null ? UserHandle.getUserId(uid) 6459 : UserHandle.getCallingUserId(); 6460 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6461 flags = updateFlagsForComponent(flags, userId, processName); 6462 6463 ArrayList<ProviderInfo> finalList = null; 6464 // reader 6465 synchronized (mPackages) { 6466 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6467 while (i.hasNext()) { 6468 final PackageParser.Provider p = i.next(); 6469 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6470 if (ps != null && p.info.authority != null 6471 && (processName == null 6472 || (p.info.processName.equals(processName) 6473 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6474 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6475 if (finalList == null) { 6476 finalList = new ArrayList<ProviderInfo>(3); 6477 } 6478 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6479 ps.readUserState(userId), userId); 6480 if (info != null) { 6481 finalList.add(info); 6482 } 6483 } 6484 } 6485 } 6486 6487 if (finalList != null) { 6488 Collections.sort(finalList, mProviderInitOrderSorter); 6489 return new ParceledListSlice<ProviderInfo>(finalList); 6490 } 6491 6492 return ParceledListSlice.emptyList(); 6493 } 6494 6495 @Override 6496 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6497 // reader 6498 synchronized (mPackages) { 6499 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6500 return PackageParser.generateInstrumentationInfo(i, flags); 6501 } 6502 } 6503 6504 @Override 6505 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6506 String targetPackage, int flags) { 6507 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6508 } 6509 6510 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6511 int flags) { 6512 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6513 6514 // reader 6515 synchronized (mPackages) { 6516 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6517 while (i.hasNext()) { 6518 final PackageParser.Instrumentation p = i.next(); 6519 if (targetPackage == null 6520 || targetPackage.equals(p.info.targetPackage)) { 6521 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6522 flags); 6523 if (ii != null) { 6524 finalList.add(ii); 6525 } 6526 } 6527 } 6528 } 6529 6530 return finalList; 6531 } 6532 6533 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6534 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6535 if (overlays == null) { 6536 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6537 return; 6538 } 6539 for (PackageParser.Package opkg : overlays.values()) { 6540 // Not much to do if idmap fails: we already logged the error 6541 // and we certainly don't want to abort installation of pkg simply 6542 // because an overlay didn't fit properly. For these reasons, 6543 // ignore the return value of createIdmapForPackagePairLI. 6544 createIdmapForPackagePairLI(pkg, opkg); 6545 } 6546 } 6547 6548 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6549 PackageParser.Package opkg) { 6550 if (!opkg.mTrustedOverlay) { 6551 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6552 opkg.baseCodePath + ": overlay not trusted"); 6553 return false; 6554 } 6555 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6556 if (overlaySet == null) { 6557 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6558 opkg.baseCodePath + " but target package has no known overlays"); 6559 return false; 6560 } 6561 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6562 // TODO: generate idmap for split APKs 6563 try { 6564 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6565 } catch (InstallerException e) { 6566 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6567 + opkg.baseCodePath); 6568 return false; 6569 } 6570 PackageParser.Package[] overlayArray = 6571 overlaySet.values().toArray(new PackageParser.Package[0]); 6572 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6573 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6574 return p1.mOverlayPriority - p2.mOverlayPriority; 6575 } 6576 }; 6577 Arrays.sort(overlayArray, cmp); 6578 6579 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6580 int i = 0; 6581 for (PackageParser.Package p : overlayArray) { 6582 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6583 } 6584 return true; 6585 } 6586 6587 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6589 try { 6590 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6591 } finally { 6592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6593 } 6594 } 6595 6596 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6597 final File[] files = dir.listFiles(); 6598 if (ArrayUtils.isEmpty(files)) { 6599 Log.d(TAG, "No files in app dir " + dir); 6600 return; 6601 } 6602 6603 if (DEBUG_PACKAGE_SCANNING) { 6604 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6605 + " flags=0x" + Integer.toHexString(parseFlags)); 6606 } 6607 6608 for (File file : files) { 6609 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6610 && !PackageInstallerService.isStageName(file.getName()); 6611 if (!isPackage) { 6612 // Ignore entries which are not packages 6613 continue; 6614 } 6615 try { 6616 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6617 scanFlags, currentTime, null); 6618 } catch (PackageManagerException e) { 6619 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6620 6621 // Delete invalid userdata apps 6622 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6623 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6624 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6625 removeCodePathLI(file); 6626 } 6627 } 6628 } 6629 } 6630 6631 private static File getSettingsProblemFile() { 6632 File dataDir = Environment.getDataDirectory(); 6633 File systemDir = new File(dataDir, "system"); 6634 File fname = new File(systemDir, "uiderrors.txt"); 6635 return fname; 6636 } 6637 6638 static void reportSettingsProblem(int priority, String msg) { 6639 logCriticalInfo(priority, msg); 6640 } 6641 6642 static void logCriticalInfo(int priority, String msg) { 6643 Slog.println(priority, TAG, msg); 6644 EventLogTags.writePmCriticalInfo(msg); 6645 try { 6646 File fname = getSettingsProblemFile(); 6647 FileOutputStream out = new FileOutputStream(fname, true); 6648 PrintWriter pw = new FastPrintWriter(out); 6649 SimpleDateFormat formatter = new SimpleDateFormat(); 6650 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6651 pw.println(dateString + ": " + msg); 6652 pw.close(); 6653 FileUtils.setPermissions( 6654 fname.toString(), 6655 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6656 -1, -1); 6657 } catch (java.io.IOException e) { 6658 } 6659 } 6660 6661 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6662 final int policyFlags) throws PackageManagerException { 6663 if (ps != null 6664 && ps.codePath.equals(srcFile) 6665 && ps.timeStamp == srcFile.lastModified() 6666 && !isCompatSignatureUpdateNeeded(pkg) 6667 && !isRecoverSignatureUpdateNeeded(pkg)) { 6668 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6669 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6670 ArraySet<PublicKey> signingKs; 6671 synchronized (mPackages) { 6672 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6673 } 6674 if (ps.signatures.mSignatures != null 6675 && ps.signatures.mSignatures.length != 0 6676 && signingKs != null) { 6677 // Optimization: reuse the existing cached certificates 6678 // if the package appears to be unchanged. 6679 pkg.mSignatures = ps.signatures.mSignatures; 6680 pkg.mSigningKeys = signingKs; 6681 return; 6682 } 6683 6684 Slog.w(TAG, "PackageSetting for " + ps.name 6685 + " is missing signatures. Collecting certs again to recover them."); 6686 } else { 6687 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6688 } 6689 6690 try { 6691 PackageParser.collectCertificates(pkg, policyFlags); 6692 } catch (PackageParserException e) { 6693 throw PackageManagerException.from(e); 6694 } 6695 } 6696 6697 /** 6698 * Traces a package scan. 6699 * @see #scanPackageLI(File, int, int, long, UserHandle) 6700 */ 6701 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6702 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6704 try { 6705 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6706 } finally { 6707 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6708 } 6709 } 6710 6711 /** 6712 * Scans a package and returns the newly parsed package. 6713 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6714 */ 6715 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6716 long currentTime, UserHandle user) throws PackageManagerException { 6717 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6718 PackageParser pp = new PackageParser(); 6719 pp.setSeparateProcesses(mSeparateProcesses); 6720 pp.setOnlyCoreApps(mOnlyCore); 6721 pp.setDisplayMetrics(mMetrics); 6722 6723 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6724 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6725 } 6726 6727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6728 final PackageParser.Package pkg; 6729 try { 6730 pkg = pp.parsePackage(scanFile, parseFlags); 6731 } catch (PackageParserException e) { 6732 throw PackageManagerException.from(e); 6733 } finally { 6734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6735 } 6736 6737 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6738 } 6739 6740 /** 6741 * Scans a package and returns the newly parsed package. 6742 * @throws PackageManagerException on a parse error. 6743 */ 6744 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6745 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6746 throws PackageManagerException { 6747 // If the package has children and this is the first dive in the function 6748 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6749 // packages (parent and children) would be successfully scanned before the 6750 // actual scan since scanning mutates internal state and we want to atomically 6751 // install the package and its children. 6752 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6753 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6754 scanFlags |= SCAN_CHECK_ONLY; 6755 } 6756 } else { 6757 scanFlags &= ~SCAN_CHECK_ONLY; 6758 } 6759 6760 // Scan the parent 6761 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6762 scanFlags, currentTime, user); 6763 6764 // Scan the children 6765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6766 for (int i = 0; i < childCount; i++) { 6767 PackageParser.Package childPackage = pkg.childPackages.get(i); 6768 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6769 currentTime, user); 6770 } 6771 6772 6773 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6774 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6775 } 6776 6777 return scannedPkg; 6778 } 6779 6780 /** 6781 * Scans a package and returns the newly parsed package. 6782 * @throws PackageManagerException on a parse error. 6783 */ 6784 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6785 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6786 throws PackageManagerException { 6787 PackageSetting ps = null; 6788 PackageSetting updatedPkg; 6789 // reader 6790 synchronized (mPackages) { 6791 // Look to see if we already know about this package. 6792 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6793 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6794 // This package has been renamed to its original name. Let's 6795 // use that. 6796 ps = mSettings.peekPackageLPr(oldName); 6797 } 6798 // If there was no original package, see one for the real package name. 6799 if (ps == null) { 6800 ps = mSettings.peekPackageLPr(pkg.packageName); 6801 } 6802 // Check to see if this package could be hiding/updating a system 6803 // package. Must look for it either under the original or real 6804 // package name depending on our state. 6805 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6806 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6807 6808 // If this is a package we don't know about on the system partition, we 6809 // may need to remove disabled child packages on the system partition 6810 // or may need to not add child packages if the parent apk is updated 6811 // on the data partition and no longer defines this child package. 6812 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6813 // If this is a parent package for an updated system app and this system 6814 // app got an OTA update which no longer defines some of the child packages 6815 // we have to prune them from the disabled system packages. 6816 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6817 if (disabledPs != null) { 6818 final int scannedChildCount = (pkg.childPackages != null) 6819 ? pkg.childPackages.size() : 0; 6820 final int disabledChildCount = disabledPs.childPackageNames != null 6821 ? disabledPs.childPackageNames.size() : 0; 6822 for (int i = 0; i < disabledChildCount; i++) { 6823 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6824 boolean disabledPackageAvailable = false; 6825 for (int j = 0; j < scannedChildCount; j++) { 6826 PackageParser.Package childPkg = pkg.childPackages.get(j); 6827 if (childPkg.packageName.equals(disabledChildPackageName)) { 6828 disabledPackageAvailable = true; 6829 break; 6830 } 6831 } 6832 if (!disabledPackageAvailable) { 6833 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6834 } 6835 } 6836 } 6837 } 6838 } 6839 6840 boolean updatedPkgBetter = false; 6841 // First check if this is a system package that may involve an update 6842 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6843 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6844 // it needs to drop FLAG_PRIVILEGED. 6845 if (locationIsPrivileged(scanFile)) { 6846 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6847 } else { 6848 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6849 } 6850 6851 if (ps != null && !ps.codePath.equals(scanFile)) { 6852 // The path has changed from what was last scanned... check the 6853 // version of the new path against what we have stored to determine 6854 // what to do. 6855 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6856 if (pkg.mVersionCode <= ps.versionCode) { 6857 // The system package has been updated and the code path does not match 6858 // Ignore entry. Skip it. 6859 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6860 + " ignored: updated version " + ps.versionCode 6861 + " better than this " + pkg.mVersionCode); 6862 if (!updatedPkg.codePath.equals(scanFile)) { 6863 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6864 + ps.name + " changing from " + updatedPkg.codePathString 6865 + " to " + scanFile); 6866 updatedPkg.codePath = scanFile; 6867 updatedPkg.codePathString = scanFile.toString(); 6868 updatedPkg.resourcePath = scanFile; 6869 updatedPkg.resourcePathString = scanFile.toString(); 6870 } 6871 updatedPkg.pkg = pkg; 6872 updatedPkg.versionCode = pkg.mVersionCode; 6873 6874 // Update the disabled system child packages to point to the package too. 6875 final int childCount = updatedPkg.childPackageNames != null 6876 ? updatedPkg.childPackageNames.size() : 0; 6877 for (int i = 0; i < childCount; i++) { 6878 String childPackageName = updatedPkg.childPackageNames.get(i); 6879 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6880 childPackageName); 6881 if (updatedChildPkg != null) { 6882 updatedChildPkg.pkg = pkg; 6883 updatedChildPkg.versionCode = pkg.mVersionCode; 6884 } 6885 } 6886 6887 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6888 + scanFile + " ignored: updated version " + ps.versionCode 6889 + " better than this " + pkg.mVersionCode); 6890 } else { 6891 // The current app on the system partition is better than 6892 // what we have updated to on the data partition; switch 6893 // back to the system partition version. 6894 // At this point, its safely assumed that package installation for 6895 // apps in system partition will go through. If not there won't be a working 6896 // version of the app 6897 // writer 6898 synchronized (mPackages) { 6899 // Just remove the loaded entries from package lists. 6900 mPackages.remove(ps.name); 6901 } 6902 6903 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6904 + " reverting from " + ps.codePathString 6905 + ": new version " + pkg.mVersionCode 6906 + " better than installed " + ps.versionCode); 6907 6908 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6909 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6910 synchronized (mInstallLock) { 6911 args.cleanUpResourcesLI(); 6912 } 6913 synchronized (mPackages) { 6914 mSettings.enableSystemPackageLPw(ps.name); 6915 } 6916 updatedPkgBetter = true; 6917 } 6918 } 6919 } 6920 6921 if (updatedPkg != null) { 6922 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6923 // initially 6924 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6925 6926 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6927 // flag set initially 6928 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6929 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6930 } 6931 } 6932 6933 // Verify certificates against what was last scanned 6934 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6935 6936 /* 6937 * A new system app appeared, but we already had a non-system one of the 6938 * same name installed earlier. 6939 */ 6940 boolean shouldHideSystemApp = false; 6941 if (updatedPkg == null && ps != null 6942 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6943 /* 6944 * Check to make sure the signatures match first. If they don't, 6945 * wipe the installed application and its data. 6946 */ 6947 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6948 != PackageManager.SIGNATURE_MATCH) { 6949 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6950 + " signatures don't match existing userdata copy; removing"); 6951 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6952 "scanPackageInternalLI")) { 6953 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6954 } 6955 ps = null; 6956 } else { 6957 /* 6958 * If the newly-added system app is an older version than the 6959 * already installed version, hide it. It will be scanned later 6960 * and re-added like an update. 6961 */ 6962 if (pkg.mVersionCode <= ps.versionCode) { 6963 shouldHideSystemApp = true; 6964 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6965 + " but new version " + pkg.mVersionCode + " better than installed " 6966 + ps.versionCode + "; hiding system"); 6967 } else { 6968 /* 6969 * The newly found system app is a newer version that the 6970 * one previously installed. Simply remove the 6971 * already-installed application and replace it with our own 6972 * while keeping the application data. 6973 */ 6974 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6975 + " reverting from " + ps.codePathString + ": new version " 6976 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6977 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6978 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6979 synchronized (mInstallLock) { 6980 args.cleanUpResourcesLI(); 6981 } 6982 } 6983 } 6984 } 6985 6986 // The apk is forward locked (not public) if its code and resources 6987 // are kept in different files. (except for app in either system or 6988 // vendor path). 6989 // TODO grab this value from PackageSettings 6990 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6991 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6992 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6993 } 6994 } 6995 6996 // TODO: extend to support forward-locked splits 6997 String resourcePath = null; 6998 String baseResourcePath = null; 6999 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7000 if (ps != null && ps.resourcePathString != null) { 7001 resourcePath = ps.resourcePathString; 7002 baseResourcePath = ps.resourcePathString; 7003 } else { 7004 // Should not happen at all. Just log an error. 7005 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7006 } 7007 } else { 7008 resourcePath = pkg.codePath; 7009 baseResourcePath = pkg.baseCodePath; 7010 } 7011 7012 // Set application objects path explicitly. 7013 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7014 pkg.setApplicationInfoCodePath(pkg.codePath); 7015 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7016 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7017 pkg.setApplicationInfoResourcePath(resourcePath); 7018 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7019 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7020 7021 // Note that we invoke the following method only if we are about to unpack an application 7022 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7023 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7024 7025 /* 7026 * If the system app should be overridden by a previously installed 7027 * data, hide the system app now and let the /data/app scan pick it up 7028 * again. 7029 */ 7030 if (shouldHideSystemApp) { 7031 synchronized (mPackages) { 7032 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7033 } 7034 } 7035 7036 return scannedPkg; 7037 } 7038 7039 private static String fixProcessName(String defProcessName, 7040 String processName, int uid) { 7041 if (processName == null) { 7042 return defProcessName; 7043 } 7044 return processName; 7045 } 7046 7047 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7048 throws PackageManagerException { 7049 if (pkgSetting.signatures.mSignatures != null) { 7050 // Already existing package. Make sure signatures match 7051 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7052 == PackageManager.SIGNATURE_MATCH; 7053 if (!match) { 7054 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7055 == PackageManager.SIGNATURE_MATCH; 7056 } 7057 if (!match) { 7058 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7059 == PackageManager.SIGNATURE_MATCH; 7060 } 7061 if (!match) { 7062 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7063 + pkg.packageName + " signatures do not match the " 7064 + "previously installed version; ignoring!"); 7065 } 7066 } 7067 7068 // Check for shared user signatures 7069 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7070 // Already existing package. Make sure signatures match 7071 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7072 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7073 if (!match) { 7074 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7075 == PackageManager.SIGNATURE_MATCH; 7076 } 7077 if (!match) { 7078 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7079 == PackageManager.SIGNATURE_MATCH; 7080 } 7081 if (!match) { 7082 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7083 "Package " + pkg.packageName 7084 + " has no signatures that match those in shared user " 7085 + pkgSetting.sharedUser.name + "; ignoring!"); 7086 } 7087 } 7088 } 7089 7090 /** 7091 * Enforces that only the system UID or root's UID can call a method exposed 7092 * via Binder. 7093 * 7094 * @param message used as message if SecurityException is thrown 7095 * @throws SecurityException if the caller is not system or root 7096 */ 7097 private static final void enforceSystemOrRoot(String message) { 7098 final int uid = Binder.getCallingUid(); 7099 if (uid != Process.SYSTEM_UID && uid != 0) { 7100 throw new SecurityException(message); 7101 } 7102 } 7103 7104 @Override 7105 public void performFstrimIfNeeded() { 7106 enforceSystemOrRoot("Only the system can request fstrim"); 7107 7108 // Before everything else, see whether we need to fstrim. 7109 try { 7110 IMountService ms = PackageHelper.getMountService(); 7111 if (ms != null) { 7112 final boolean isUpgrade = isUpgrade(); 7113 boolean doTrim = isUpgrade; 7114 if (doTrim) { 7115 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7116 } else { 7117 final long interval = android.provider.Settings.Global.getLong( 7118 mContext.getContentResolver(), 7119 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7120 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7121 if (interval > 0) { 7122 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7123 if (timeSinceLast > interval) { 7124 doTrim = true; 7125 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7126 + "; running immediately"); 7127 } 7128 } 7129 } 7130 if (doTrim) { 7131 if (!isFirstBoot()) { 7132 try { 7133 ActivityManagerNative.getDefault().showBootMessage( 7134 mContext.getResources().getString( 7135 R.string.android_upgrading_fstrim), true); 7136 } catch (RemoteException e) { 7137 } 7138 } 7139 ms.runMaintenance(); 7140 } 7141 } else { 7142 Slog.e(TAG, "Mount service unavailable!"); 7143 } 7144 } catch (RemoteException e) { 7145 // Can't happen; MountService is local 7146 } 7147 } 7148 7149 @Override 7150 public void updatePackagesIfNeeded() { 7151 enforceSystemOrRoot("Only the system can request package update"); 7152 7153 // We need to re-extract after an OTA. 7154 boolean causeUpgrade = isUpgrade(); 7155 7156 // First boot or factory reset. 7157 // Note: we also handle devices that are upgrading to N right now as if it is their 7158 // first boot, as they do not have profile data. 7159 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7160 7161 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7162 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7163 7164 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7165 return; 7166 } 7167 7168 List<PackageParser.Package> pkgs; 7169 synchronized (mPackages) { 7170 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7171 } 7172 7173 int curr = 0; 7174 int total = pkgs.size(); 7175 for (PackageParser.Package pkg : pkgs) { 7176 curr++; 7177 7178 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7179 if (DEBUG_DEXOPT) { 7180 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7181 } 7182 continue; 7183 } 7184 7185 if (DEBUG_DEXOPT) { 7186 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7187 } 7188 7189 if (!isFirstBoot()) { 7190 try { 7191 ActivityManagerNative.getDefault().showBootMessage( 7192 mContext.getResources().getString(R.string.android_upgrading_apk, 7193 curr, total), true); 7194 } catch (RemoteException e) { 7195 } 7196 } 7197 7198 performDexOpt(pkg.packageName, 7199 null /* instructionSet */, 7200 true /* checkProfiles */, 7201 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7202 false /* force */); 7203 } 7204 } 7205 7206 @Override 7207 public void notifyPackageUse(String packageName, int reason) { 7208 synchronized (mPackages) { 7209 PackageParser.Package p = mPackages.get(packageName); 7210 if (p == null) { 7211 return; 7212 } 7213 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7214 } 7215 } 7216 7217 // TODO: this is not used nor needed. Delete it. 7218 @Override 7219 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7220 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7221 getFullCompilerFilter(), false /* force */); 7222 } 7223 7224 @Override 7225 public boolean performDexOpt(String packageName, String instructionSet, 7226 boolean checkProfiles, int compileReason, boolean force) { 7227 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7228 getCompilerFilterForReason(compileReason), force); 7229 } 7230 7231 @Override 7232 public boolean performDexOptMode(String packageName, String instructionSet, 7233 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7234 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7235 targetCompilerFilter, force); 7236 } 7237 7238 private boolean performDexOptTraced(String packageName, String instructionSet, 7239 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7240 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7241 try { 7242 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7243 targetCompilerFilter, force); 7244 } finally { 7245 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7246 } 7247 } 7248 7249 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7250 // if the package can now be considered up to date for the given filter. 7251 private boolean performDexOptInternal(String packageName, String instructionSet, 7252 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7253 PackageParser.Package p; 7254 final String targetInstructionSet; 7255 synchronized (mPackages) { 7256 p = mPackages.get(packageName); 7257 if (p == null) { 7258 return false; 7259 } 7260 mPackageUsage.write(false); 7261 7262 targetInstructionSet = instructionSet != null ? instructionSet : 7263 getPrimaryInstructionSet(p.applicationInfo); 7264 } 7265 long callingId = Binder.clearCallingIdentity(); 7266 try { 7267 synchronized (mInstallLock) { 7268 final String[] instructionSets = new String[] { targetInstructionSet }; 7269 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7270 checkProfiles, targetCompilerFilter, force); 7271 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7272 } 7273 } finally { 7274 Binder.restoreCallingIdentity(callingId); 7275 } 7276 } 7277 7278 public ArraySet<String> getOptimizablePackages() { 7279 ArraySet<String> pkgs = new ArraySet<String>(); 7280 synchronized (mPackages) { 7281 for (PackageParser.Package p : mPackages.values()) { 7282 if (PackageDexOptimizer.canOptimizePackage(p)) { 7283 pkgs.add(p.packageName); 7284 } 7285 } 7286 } 7287 return pkgs; 7288 } 7289 7290 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7291 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7292 boolean force) { 7293 // Select the dex optimizer based on the force parameter. 7294 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7295 // allocate an object here. 7296 PackageDexOptimizer pdo = force 7297 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7298 : mPackageDexOptimizer; 7299 7300 // Optimize all dependencies first. Note: we ignore the return value and march on 7301 // on errors. 7302 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7303 if (!deps.isEmpty()) { 7304 for (PackageParser.Package depPackage : deps) { 7305 // TODO: Analyze and investigate if we (should) profile libraries. 7306 // Currently this will do a full compilation of the library by default. 7307 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7308 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7309 } 7310 } 7311 7312 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7313 } 7314 7315 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7316 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7317 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7318 Set<String> collectedNames = new HashSet<>(); 7319 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7320 7321 retValue.remove(p); 7322 7323 return retValue; 7324 } else { 7325 return Collections.emptyList(); 7326 } 7327 } 7328 7329 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7330 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7331 if (!collectedNames.contains(p.packageName)) { 7332 collectedNames.add(p.packageName); 7333 collected.add(p); 7334 7335 if (p.usesLibraries != null) { 7336 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7337 } 7338 if (p.usesOptionalLibraries != null) { 7339 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7340 collectedNames); 7341 } 7342 } 7343 } 7344 7345 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7346 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7347 for (String libName : libs) { 7348 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7349 if (libPkg != null) { 7350 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7351 } 7352 } 7353 } 7354 7355 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7356 synchronized (mPackages) { 7357 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7358 if (lib != null && lib.apk != null) { 7359 return mPackages.get(lib.apk); 7360 } 7361 } 7362 return null; 7363 } 7364 7365 public void shutdown() { 7366 mPackageUsage.write(true); 7367 } 7368 7369 @Override 7370 public void forceDexOpt(String packageName) { 7371 enforceSystemOrRoot("forceDexOpt"); 7372 7373 PackageParser.Package pkg; 7374 synchronized (mPackages) { 7375 pkg = mPackages.get(packageName); 7376 if (pkg == null) { 7377 throw new IllegalArgumentException("Unknown package: " + packageName); 7378 } 7379 } 7380 7381 synchronized (mInstallLock) { 7382 final String[] instructionSets = new String[] { 7383 getPrimaryInstructionSet(pkg.applicationInfo) }; 7384 7385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7386 7387 // Whoever is calling forceDexOpt wants a fully compiled package. 7388 // Don't use profiles since that may cause compilation to be skipped. 7389 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7390 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7391 true /* force */); 7392 7393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7394 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7395 throw new IllegalStateException("Failed to dexopt: " + res); 7396 } 7397 } 7398 } 7399 7400 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7401 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7402 Slog.w(TAG, "Unable to update from " + oldPkg.name 7403 + " to " + newPkg.packageName 7404 + ": old package not in system partition"); 7405 return false; 7406 } else if (mPackages.get(oldPkg.name) != null) { 7407 Slog.w(TAG, "Unable to update from " + oldPkg.name 7408 + " to " + newPkg.packageName 7409 + ": old package still exists"); 7410 return false; 7411 } 7412 return true; 7413 } 7414 7415 void removeCodePathLI(File codePath) { 7416 if (codePath.isDirectory()) { 7417 try { 7418 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7419 } catch (InstallerException e) { 7420 Slog.w(TAG, "Failed to remove code path", e); 7421 } 7422 } else { 7423 codePath.delete(); 7424 } 7425 } 7426 7427 private int[] resolveUserIds(int userId) { 7428 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7429 } 7430 7431 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7432 if (pkg == null) { 7433 Slog.wtf(TAG, "Package was null!", new Throwable()); 7434 return; 7435 } 7436 clearAppDataLeafLIF(pkg, userId, flags); 7437 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7438 for (int i = 0; i < childCount; i++) { 7439 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7440 } 7441 } 7442 7443 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7444 final PackageSetting ps; 7445 synchronized (mPackages) { 7446 ps = mSettings.mPackages.get(pkg.packageName); 7447 } 7448 for (int realUserId : resolveUserIds(userId)) { 7449 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7450 try { 7451 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7452 ceDataInode); 7453 } catch (InstallerException e) { 7454 Slog.w(TAG, String.valueOf(e)); 7455 } 7456 } 7457 } 7458 7459 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7460 if (pkg == null) { 7461 Slog.wtf(TAG, "Package was null!", new Throwable()); 7462 return; 7463 } 7464 destroyAppDataLeafLIF(pkg, userId, flags); 7465 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7466 for (int i = 0; i < childCount; i++) { 7467 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7468 } 7469 } 7470 7471 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7472 final PackageSetting ps; 7473 synchronized (mPackages) { 7474 ps = mSettings.mPackages.get(pkg.packageName); 7475 } 7476 for (int realUserId : resolveUserIds(userId)) { 7477 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7478 try { 7479 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7480 ceDataInode); 7481 } catch (InstallerException e) { 7482 Slog.w(TAG, String.valueOf(e)); 7483 } 7484 } 7485 } 7486 7487 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7488 if (pkg == null) { 7489 Slog.wtf(TAG, "Package was null!", new Throwable()); 7490 return; 7491 } 7492 destroyAppProfilesLeafLIF(pkg); 7493 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7494 for (int i = 0; i < childCount; i++) { 7495 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7496 } 7497 } 7498 7499 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7500 try { 7501 mInstaller.destroyAppProfiles(pkg.packageName); 7502 } catch (InstallerException e) { 7503 Slog.w(TAG, String.valueOf(e)); 7504 } 7505 } 7506 7507 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7508 if (pkg == null) { 7509 Slog.wtf(TAG, "Package was null!", new Throwable()); 7510 return; 7511 } 7512 clearAppProfilesLeafLIF(pkg); 7513 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7514 for (int i = 0; i < childCount; i++) { 7515 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7516 } 7517 } 7518 7519 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7520 try { 7521 mInstaller.clearAppProfiles(pkg.packageName); 7522 } catch (InstallerException e) { 7523 Slog.w(TAG, String.valueOf(e)); 7524 } 7525 } 7526 7527 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7528 long lastUpdateTime) { 7529 // Set parent install/update time 7530 PackageSetting ps = (PackageSetting) pkg.mExtras; 7531 if (ps != null) { 7532 ps.firstInstallTime = firstInstallTime; 7533 ps.lastUpdateTime = lastUpdateTime; 7534 } 7535 // Set children install/update time 7536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7537 for (int i = 0; i < childCount; i++) { 7538 PackageParser.Package childPkg = pkg.childPackages.get(i); 7539 ps = (PackageSetting) childPkg.mExtras; 7540 if (ps != null) { 7541 ps.firstInstallTime = firstInstallTime; 7542 ps.lastUpdateTime = lastUpdateTime; 7543 } 7544 } 7545 } 7546 7547 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7548 PackageParser.Package changingLib) { 7549 if (file.path != null) { 7550 usesLibraryFiles.add(file.path); 7551 return; 7552 } 7553 PackageParser.Package p = mPackages.get(file.apk); 7554 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7555 // If we are doing this while in the middle of updating a library apk, 7556 // then we need to make sure to use that new apk for determining the 7557 // dependencies here. (We haven't yet finished committing the new apk 7558 // to the package manager state.) 7559 if (p == null || p.packageName.equals(changingLib.packageName)) { 7560 p = changingLib; 7561 } 7562 } 7563 if (p != null) { 7564 usesLibraryFiles.addAll(p.getAllCodePaths()); 7565 } 7566 } 7567 7568 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7569 PackageParser.Package changingLib) throws PackageManagerException { 7570 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7571 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7572 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7573 for (int i=0; i<N; i++) { 7574 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7575 if (file == null) { 7576 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7577 "Package " + pkg.packageName + " requires unavailable shared library " 7578 + pkg.usesLibraries.get(i) + "; failing!"); 7579 } 7580 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7581 } 7582 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7583 for (int i=0; i<N; i++) { 7584 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7585 if (file == null) { 7586 Slog.w(TAG, "Package " + pkg.packageName 7587 + " desires unavailable shared library " 7588 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7589 } else { 7590 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7591 } 7592 } 7593 N = usesLibraryFiles.size(); 7594 if (N > 0) { 7595 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7596 } else { 7597 pkg.usesLibraryFiles = null; 7598 } 7599 } 7600 } 7601 7602 private static boolean hasString(List<String> list, List<String> which) { 7603 if (list == null) { 7604 return false; 7605 } 7606 for (int i=list.size()-1; i>=0; i--) { 7607 for (int j=which.size()-1; j>=0; j--) { 7608 if (which.get(j).equals(list.get(i))) { 7609 return true; 7610 } 7611 } 7612 } 7613 return false; 7614 } 7615 7616 private void updateAllSharedLibrariesLPw() { 7617 for (PackageParser.Package pkg : mPackages.values()) { 7618 try { 7619 updateSharedLibrariesLPw(pkg, null); 7620 } catch (PackageManagerException e) { 7621 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7622 } 7623 } 7624 } 7625 7626 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7627 PackageParser.Package changingPkg) { 7628 ArrayList<PackageParser.Package> res = null; 7629 for (PackageParser.Package pkg : mPackages.values()) { 7630 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7631 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7632 if (res == null) { 7633 res = new ArrayList<PackageParser.Package>(); 7634 } 7635 res.add(pkg); 7636 try { 7637 updateSharedLibrariesLPw(pkg, changingPkg); 7638 } catch (PackageManagerException e) { 7639 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7640 } 7641 } 7642 } 7643 return res; 7644 } 7645 7646 /** 7647 * Derive the value of the {@code cpuAbiOverride} based on the provided 7648 * value and an optional stored value from the package settings. 7649 */ 7650 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7651 String cpuAbiOverride = null; 7652 7653 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7654 cpuAbiOverride = null; 7655 } else if (abiOverride != null) { 7656 cpuAbiOverride = abiOverride; 7657 } else if (settings != null) { 7658 cpuAbiOverride = settings.cpuAbiOverrideString; 7659 } 7660 7661 return cpuAbiOverride; 7662 } 7663 7664 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7665 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7666 throws PackageManagerException { 7667 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7668 // If the package has children and this is the first dive in the function 7669 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7670 // whether all packages (parent and children) would be successfully scanned 7671 // before the actual scan since scanning mutates internal state and we want 7672 // to atomically install the package and its children. 7673 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7674 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7675 scanFlags |= SCAN_CHECK_ONLY; 7676 } 7677 } else { 7678 scanFlags &= ~SCAN_CHECK_ONLY; 7679 } 7680 7681 final PackageParser.Package scannedPkg; 7682 try { 7683 // Scan the parent 7684 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7685 // Scan the children 7686 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7687 for (int i = 0; i < childCount; i++) { 7688 PackageParser.Package childPkg = pkg.childPackages.get(i); 7689 scanPackageLI(childPkg, policyFlags, 7690 scanFlags, currentTime, user); 7691 } 7692 } finally { 7693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7694 } 7695 7696 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7697 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7698 } 7699 7700 return scannedPkg; 7701 } 7702 7703 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7704 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7705 boolean success = false; 7706 try { 7707 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7708 currentTime, user); 7709 success = true; 7710 return res; 7711 } finally { 7712 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7713 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7714 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7715 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7716 destroyAppProfilesLIF(pkg); 7717 } 7718 } 7719 } 7720 7721 /** 7722 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7723 */ 7724 private static boolean apkHasCode(String fileName) { 7725 StrictJarFile jarFile = null; 7726 try { 7727 jarFile = new StrictJarFile(fileName, 7728 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7729 return jarFile.findEntry("classes.dex") != null; 7730 } catch (IOException ignore) { 7731 } finally { 7732 try { 7733 jarFile.close(); 7734 } catch (IOException ignore) {} 7735 } 7736 return false; 7737 } 7738 7739 /** 7740 * Enforces code policy for the package. This ensures that if an APK has 7741 * declared hasCode="true" in its manifest that the APK actually contains 7742 * code. 7743 * 7744 * @throws PackageManagerException If bytecode could not be found when it should exist 7745 */ 7746 private static void enforceCodePolicy(PackageParser.Package pkg) 7747 throws PackageManagerException { 7748 final boolean shouldHaveCode = 7749 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7750 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7751 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7752 "Package " + pkg.baseCodePath + " code is missing"); 7753 } 7754 7755 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7756 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7757 final boolean splitShouldHaveCode = 7758 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7759 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7760 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7761 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7762 } 7763 } 7764 } 7765 } 7766 7767 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7768 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7769 throws PackageManagerException { 7770 final File scanFile = new File(pkg.codePath); 7771 if (pkg.applicationInfo.getCodePath() == null || 7772 pkg.applicationInfo.getResourcePath() == null) { 7773 // Bail out. The resource and code paths haven't been set. 7774 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7775 "Code and resource paths haven't been set correctly"); 7776 } 7777 7778 // Apply policy 7779 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7780 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7781 if (pkg.applicationInfo.isDirectBootAware()) { 7782 // we're direct boot aware; set for all components 7783 for (PackageParser.Service s : pkg.services) { 7784 s.info.encryptionAware = s.info.directBootAware = true; 7785 } 7786 for (PackageParser.Provider p : pkg.providers) { 7787 p.info.encryptionAware = p.info.directBootAware = true; 7788 } 7789 for (PackageParser.Activity a : pkg.activities) { 7790 a.info.encryptionAware = a.info.directBootAware = true; 7791 } 7792 for (PackageParser.Activity r : pkg.receivers) { 7793 r.info.encryptionAware = r.info.directBootAware = true; 7794 } 7795 } 7796 } else { 7797 // Only allow system apps to be flagged as core apps. 7798 pkg.coreApp = false; 7799 // clear flags not applicable to regular apps 7800 pkg.applicationInfo.privateFlags &= 7801 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7802 pkg.applicationInfo.privateFlags &= 7803 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7804 } 7805 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7806 7807 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7808 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7809 } 7810 7811 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7812 enforceCodePolicy(pkg); 7813 } 7814 7815 if (mCustomResolverComponentName != null && 7816 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7817 setUpCustomResolverActivity(pkg); 7818 } 7819 7820 if (pkg.packageName.equals("android")) { 7821 synchronized (mPackages) { 7822 if (mAndroidApplication != null) { 7823 Slog.w(TAG, "*************************************************"); 7824 Slog.w(TAG, "Core android package being redefined. Skipping."); 7825 Slog.w(TAG, " file=" + scanFile); 7826 Slog.w(TAG, "*************************************************"); 7827 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7828 "Core android package being redefined. Skipping."); 7829 } 7830 7831 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7832 // Set up information for our fall-back user intent resolution activity. 7833 mPlatformPackage = pkg; 7834 pkg.mVersionCode = mSdkVersion; 7835 mAndroidApplication = pkg.applicationInfo; 7836 7837 if (!mResolverReplaced) { 7838 mResolveActivity.applicationInfo = mAndroidApplication; 7839 mResolveActivity.name = ResolverActivity.class.getName(); 7840 mResolveActivity.packageName = mAndroidApplication.packageName; 7841 mResolveActivity.processName = "system:ui"; 7842 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7843 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7844 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7845 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7846 mResolveActivity.exported = true; 7847 mResolveActivity.enabled = true; 7848 mResolveInfo.activityInfo = mResolveActivity; 7849 mResolveInfo.priority = 0; 7850 mResolveInfo.preferredOrder = 0; 7851 mResolveInfo.match = 0; 7852 mResolveComponentName = new ComponentName( 7853 mAndroidApplication.packageName, mResolveActivity.name); 7854 } 7855 } 7856 } 7857 } 7858 7859 if (DEBUG_PACKAGE_SCANNING) { 7860 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7861 Log.d(TAG, "Scanning package " + pkg.packageName); 7862 } 7863 7864 synchronized (mPackages) { 7865 if (mPackages.containsKey(pkg.packageName) 7866 || mSharedLibraries.containsKey(pkg.packageName)) { 7867 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7868 "Application package " + pkg.packageName 7869 + " already installed. Skipping duplicate."); 7870 } 7871 7872 // If we're only installing presumed-existing packages, require that the 7873 // scanned APK is both already known and at the path previously established 7874 // for it. Previously unknown packages we pick up normally, but if we have an 7875 // a priori expectation about this package's install presence, enforce it. 7876 // With a singular exception for new system packages. When an OTA contains 7877 // a new system package, we allow the codepath to change from a system location 7878 // to the user-installed location. If we don't allow this change, any newer, 7879 // user-installed version of the application will be ignored. 7880 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7881 if (mExpectingBetter.containsKey(pkg.packageName)) { 7882 logCriticalInfo(Log.WARN, 7883 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7884 } else { 7885 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7886 if (known != null) { 7887 if (DEBUG_PACKAGE_SCANNING) { 7888 Log.d(TAG, "Examining " + pkg.codePath 7889 + " and requiring known paths " + known.codePathString 7890 + " & " + known.resourcePathString); 7891 } 7892 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7893 || !pkg.applicationInfo.getResourcePath().equals( 7894 known.resourcePathString)) { 7895 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7896 "Application package " + pkg.packageName 7897 + " found at " + pkg.applicationInfo.getCodePath() 7898 + " but expected at " + known.codePathString 7899 + "; ignoring."); 7900 } 7901 } 7902 } 7903 } 7904 } 7905 7906 // Initialize package source and resource directories 7907 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7908 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7909 7910 SharedUserSetting suid = null; 7911 PackageSetting pkgSetting = null; 7912 7913 if (!isSystemApp(pkg)) { 7914 // Only system apps can use these features. 7915 pkg.mOriginalPackages = null; 7916 pkg.mRealPackage = null; 7917 pkg.mAdoptPermissions = null; 7918 } 7919 7920 // Getting the package setting may have a side-effect, so if we 7921 // are only checking if scan would succeed, stash a copy of the 7922 // old setting to restore at the end. 7923 PackageSetting nonMutatedPs = null; 7924 7925 // writer 7926 synchronized (mPackages) { 7927 if (pkg.mSharedUserId != null) { 7928 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7929 if (suid == null) { 7930 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7931 "Creating application package " + pkg.packageName 7932 + " for shared user failed"); 7933 } 7934 if (DEBUG_PACKAGE_SCANNING) { 7935 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7936 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7937 + "): packages=" + suid.packages); 7938 } 7939 } 7940 7941 // Check if we are renaming from an original package name. 7942 PackageSetting origPackage = null; 7943 String realName = null; 7944 if (pkg.mOriginalPackages != null) { 7945 // This package may need to be renamed to a previously 7946 // installed name. Let's check on that... 7947 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7948 if (pkg.mOriginalPackages.contains(renamed)) { 7949 // This package had originally been installed as the 7950 // original name, and we have already taken care of 7951 // transitioning to the new one. Just update the new 7952 // one to continue using the old name. 7953 realName = pkg.mRealPackage; 7954 if (!pkg.packageName.equals(renamed)) { 7955 // Callers into this function may have already taken 7956 // care of renaming the package; only do it here if 7957 // it is not already done. 7958 pkg.setPackageName(renamed); 7959 } 7960 7961 } else { 7962 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7963 if ((origPackage = mSettings.peekPackageLPr( 7964 pkg.mOriginalPackages.get(i))) != null) { 7965 // We do have the package already installed under its 7966 // original name... should we use it? 7967 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7968 // New package is not compatible with original. 7969 origPackage = null; 7970 continue; 7971 } else if (origPackage.sharedUser != null) { 7972 // Make sure uid is compatible between packages. 7973 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7974 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7975 + " to " + pkg.packageName + ": old uid " 7976 + origPackage.sharedUser.name 7977 + " differs from " + pkg.mSharedUserId); 7978 origPackage = null; 7979 continue; 7980 } 7981 // TODO: Add case when shared user id is added [b/28144775] 7982 } else { 7983 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7984 + pkg.packageName + " to old name " + origPackage.name); 7985 } 7986 break; 7987 } 7988 } 7989 } 7990 } 7991 7992 if (mTransferedPackages.contains(pkg.packageName)) { 7993 Slog.w(TAG, "Package " + pkg.packageName 7994 + " was transferred to another, but its .apk remains"); 7995 } 7996 7997 // See comments in nonMutatedPs declaration 7998 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7999 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8000 if (foundPs != null) { 8001 nonMutatedPs = new PackageSetting(foundPs); 8002 } 8003 } 8004 8005 // Just create the setting, don't add it yet. For already existing packages 8006 // the PkgSetting exists already and doesn't have to be created. 8007 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8008 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8009 pkg.applicationInfo.primaryCpuAbi, 8010 pkg.applicationInfo.secondaryCpuAbi, 8011 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8012 user, false); 8013 if (pkgSetting == null) { 8014 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8015 "Creating application package " + pkg.packageName + " failed"); 8016 } 8017 8018 if (pkgSetting.origPackage != null) { 8019 // If we are first transitioning from an original package, 8020 // fix up the new package's name now. We need to do this after 8021 // looking up the package under its new name, so getPackageLP 8022 // can take care of fiddling things correctly. 8023 pkg.setPackageName(origPackage.name); 8024 8025 // File a report about this. 8026 String msg = "New package " + pkgSetting.realName 8027 + " renamed to replace old package " + pkgSetting.name; 8028 reportSettingsProblem(Log.WARN, msg); 8029 8030 // Make a note of it. 8031 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8032 mTransferedPackages.add(origPackage.name); 8033 } 8034 8035 // No longer need to retain this. 8036 pkgSetting.origPackage = null; 8037 } 8038 8039 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8040 // Make a note of it. 8041 mTransferedPackages.add(pkg.packageName); 8042 } 8043 8044 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8045 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8046 } 8047 8048 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8049 // Check all shared libraries and map to their actual file path. 8050 // We only do this here for apps not on a system dir, because those 8051 // are the only ones that can fail an install due to this. We 8052 // will take care of the system apps by updating all of their 8053 // library paths after the scan is done. 8054 updateSharedLibrariesLPw(pkg, null); 8055 } 8056 8057 if (mFoundPolicyFile) { 8058 SELinuxMMAC.assignSeinfoValue(pkg); 8059 } 8060 8061 pkg.applicationInfo.uid = pkgSetting.appId; 8062 pkg.mExtras = pkgSetting; 8063 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8064 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8065 // We just determined the app is signed correctly, so bring 8066 // over the latest parsed certs. 8067 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8068 } else { 8069 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8070 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8071 "Package " + pkg.packageName + " upgrade keys do not match the " 8072 + "previously installed version"); 8073 } else { 8074 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8075 String msg = "System package " + pkg.packageName 8076 + " signature changed; retaining data."; 8077 reportSettingsProblem(Log.WARN, msg); 8078 } 8079 } 8080 } else { 8081 try { 8082 verifySignaturesLP(pkgSetting, pkg); 8083 // We just determined the app is signed correctly, so bring 8084 // over the latest parsed certs. 8085 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8086 } catch (PackageManagerException e) { 8087 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8088 throw e; 8089 } 8090 // The signature has changed, but this package is in the system 8091 // image... let's recover! 8092 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8093 // However... if this package is part of a shared user, but it 8094 // doesn't match the signature of the shared user, let's fail. 8095 // What this means is that you can't change the signatures 8096 // associated with an overall shared user, which doesn't seem all 8097 // that unreasonable. 8098 if (pkgSetting.sharedUser != null) { 8099 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8100 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8101 throw new PackageManagerException( 8102 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8103 "Signature mismatch for shared user: " 8104 + pkgSetting.sharedUser); 8105 } 8106 } 8107 // File a report about this. 8108 String msg = "System package " + pkg.packageName 8109 + " signature changed; retaining data."; 8110 reportSettingsProblem(Log.WARN, msg); 8111 } 8112 } 8113 // Verify that this new package doesn't have any content providers 8114 // that conflict with existing packages. Only do this if the 8115 // package isn't already installed, since we don't want to break 8116 // things that are installed. 8117 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8118 final int N = pkg.providers.size(); 8119 int i; 8120 for (i=0; i<N; i++) { 8121 PackageParser.Provider p = pkg.providers.get(i); 8122 if (p.info.authority != null) { 8123 String names[] = p.info.authority.split(";"); 8124 for (int j = 0; j < names.length; j++) { 8125 if (mProvidersByAuthority.containsKey(names[j])) { 8126 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8127 final String otherPackageName = 8128 ((other != null && other.getComponentName() != null) ? 8129 other.getComponentName().getPackageName() : "?"); 8130 throw new PackageManagerException( 8131 INSTALL_FAILED_CONFLICTING_PROVIDER, 8132 "Can't install because provider name " + names[j] 8133 + " (in package " + pkg.applicationInfo.packageName 8134 + ") is already used by " + otherPackageName); 8135 } 8136 } 8137 } 8138 } 8139 } 8140 8141 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8142 // This package wants to adopt ownership of permissions from 8143 // another package. 8144 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8145 final String origName = pkg.mAdoptPermissions.get(i); 8146 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8147 if (orig != null) { 8148 if (verifyPackageUpdateLPr(orig, pkg)) { 8149 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8150 + pkg.packageName); 8151 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8152 } 8153 } 8154 } 8155 } 8156 } 8157 8158 final String pkgName = pkg.packageName; 8159 8160 final long scanFileTime = scanFile.lastModified(); 8161 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8162 pkg.applicationInfo.processName = fixProcessName( 8163 pkg.applicationInfo.packageName, 8164 pkg.applicationInfo.processName, 8165 pkg.applicationInfo.uid); 8166 8167 if (pkg != mPlatformPackage) { 8168 // Get all of our default paths setup 8169 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8170 } 8171 8172 final String path = scanFile.getPath(); 8173 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8174 8175 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8176 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8177 8178 // Some system apps still use directory structure for native libraries 8179 // in which case we might end up not detecting abi solely based on apk 8180 // structure. Try to detect abi based on directory structure. 8181 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8182 pkg.applicationInfo.primaryCpuAbi == null) { 8183 setBundledAppAbisAndRoots(pkg, pkgSetting); 8184 setNativeLibraryPaths(pkg); 8185 } 8186 8187 } else { 8188 if ((scanFlags & SCAN_MOVE) != 0) { 8189 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8190 // but we already have this packages package info in the PackageSetting. We just 8191 // use that and derive the native library path based on the new codepath. 8192 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8193 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8194 } 8195 8196 // Set native library paths again. For moves, the path will be updated based on the 8197 // ABIs we've determined above. For non-moves, the path will be updated based on the 8198 // ABIs we determined during compilation, but the path will depend on the final 8199 // package path (after the rename away from the stage path). 8200 setNativeLibraryPaths(pkg); 8201 } 8202 8203 // This is a special case for the "system" package, where the ABI is 8204 // dictated by the zygote configuration (and init.rc). We should keep track 8205 // of this ABI so that we can deal with "normal" applications that run under 8206 // the same UID correctly. 8207 if (mPlatformPackage == pkg) { 8208 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8209 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8210 } 8211 8212 // If there's a mismatch between the abi-override in the package setting 8213 // and the abiOverride specified for the install. Warn about this because we 8214 // would've already compiled the app without taking the package setting into 8215 // account. 8216 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8217 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8218 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8219 " for package " + pkg.packageName); 8220 } 8221 } 8222 8223 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8224 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8225 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8226 8227 // Copy the derived override back to the parsed package, so that we can 8228 // update the package settings accordingly. 8229 pkg.cpuAbiOverride = cpuAbiOverride; 8230 8231 if (DEBUG_ABI_SELECTION) { 8232 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8233 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8234 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8235 } 8236 8237 // Push the derived path down into PackageSettings so we know what to 8238 // clean up at uninstall time. 8239 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8240 8241 if (DEBUG_ABI_SELECTION) { 8242 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8243 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8244 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8245 } 8246 8247 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8248 // We don't do this here during boot because we can do it all 8249 // at once after scanning all existing packages. 8250 // 8251 // We also do this *before* we perform dexopt on this package, so that 8252 // we can avoid redundant dexopts, and also to make sure we've got the 8253 // code and package path correct. 8254 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8255 pkg, true /* boot complete */); 8256 } 8257 8258 if (mFactoryTest && pkg.requestedPermissions.contains( 8259 android.Manifest.permission.FACTORY_TEST)) { 8260 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8261 } 8262 8263 ArrayList<PackageParser.Package> clientLibPkgs = null; 8264 8265 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8266 if (nonMutatedPs != null) { 8267 synchronized (mPackages) { 8268 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8269 } 8270 } 8271 return pkg; 8272 } 8273 8274 // Only privileged apps and updated privileged apps can add child packages. 8275 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8276 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8277 throw new PackageManagerException("Only privileged apps and updated " 8278 + "privileged apps can add child packages. Ignoring package " 8279 + pkg.packageName); 8280 } 8281 final int childCount = pkg.childPackages.size(); 8282 for (int i = 0; i < childCount; i++) { 8283 PackageParser.Package childPkg = pkg.childPackages.get(i); 8284 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8285 childPkg.packageName)) { 8286 throw new PackageManagerException("Cannot override a child package of " 8287 + "another disabled system app. Ignoring package " + pkg.packageName); 8288 } 8289 } 8290 } 8291 8292 // writer 8293 synchronized (mPackages) { 8294 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8295 // Only system apps can add new shared libraries. 8296 if (pkg.libraryNames != null) { 8297 for (int i=0; i<pkg.libraryNames.size(); i++) { 8298 String name = pkg.libraryNames.get(i); 8299 boolean allowed = false; 8300 if (pkg.isUpdatedSystemApp()) { 8301 // New library entries can only be added through the 8302 // system image. This is important to get rid of a lot 8303 // of nasty edge cases: for example if we allowed a non- 8304 // system update of the app to add a library, then uninstalling 8305 // the update would make the library go away, and assumptions 8306 // we made such as through app install filtering would now 8307 // have allowed apps on the device which aren't compatible 8308 // with it. Better to just have the restriction here, be 8309 // conservative, and create many fewer cases that can negatively 8310 // impact the user experience. 8311 final PackageSetting sysPs = mSettings 8312 .getDisabledSystemPkgLPr(pkg.packageName); 8313 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8314 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8315 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8316 allowed = true; 8317 break; 8318 } 8319 } 8320 } 8321 } else { 8322 allowed = true; 8323 } 8324 if (allowed) { 8325 if (!mSharedLibraries.containsKey(name)) { 8326 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8327 } else if (!name.equals(pkg.packageName)) { 8328 Slog.w(TAG, "Package " + pkg.packageName + " library " 8329 + name + " already exists; skipping"); 8330 } 8331 } else { 8332 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8333 + name + " that is not declared on system image; skipping"); 8334 } 8335 } 8336 if ((scanFlags & SCAN_BOOTING) == 0) { 8337 // If we are not booting, we need to update any applications 8338 // that are clients of our shared library. If we are booting, 8339 // this will all be done once the scan is complete. 8340 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8341 } 8342 } 8343 } 8344 } 8345 8346 if ((scanFlags & SCAN_BOOTING) != 0) { 8347 // No apps can run during boot scan, so they don't need to be frozen 8348 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8349 // Caller asked to not kill app, so it's probably not frozen 8350 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8351 // Caller asked us to ignore frozen check for some reason; they 8352 // probably didn't know the package name 8353 } else { 8354 // We're doing major surgery on this package, so it better be frozen 8355 // right now to keep it from launching 8356 checkPackageFrozen(pkgName); 8357 } 8358 8359 // Also need to kill any apps that are dependent on the library. 8360 if (clientLibPkgs != null) { 8361 for (int i=0; i<clientLibPkgs.size(); i++) { 8362 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8363 killApplication(clientPkg.applicationInfo.packageName, 8364 clientPkg.applicationInfo.uid, "update lib"); 8365 } 8366 } 8367 8368 // Make sure we're not adding any bogus keyset info 8369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8370 ksms.assertScannedPackageValid(pkg); 8371 8372 // writer 8373 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8374 8375 boolean createIdmapFailed = false; 8376 synchronized (mPackages) { 8377 // We don't expect installation to fail beyond this point 8378 8379 // Add the new setting to mSettings 8380 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8381 // Add the new setting to mPackages 8382 mPackages.put(pkg.applicationInfo.packageName, pkg); 8383 // Make sure we don't accidentally delete its data. 8384 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8385 while (iter.hasNext()) { 8386 PackageCleanItem item = iter.next(); 8387 if (pkgName.equals(item.packageName)) { 8388 iter.remove(); 8389 } 8390 } 8391 8392 // Take care of first install / last update times. 8393 if (currentTime != 0) { 8394 if (pkgSetting.firstInstallTime == 0) { 8395 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8396 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8397 pkgSetting.lastUpdateTime = currentTime; 8398 } 8399 } else if (pkgSetting.firstInstallTime == 0) { 8400 // We need *something*. Take time time stamp of the file. 8401 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8402 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8403 if (scanFileTime != pkgSetting.timeStamp) { 8404 // A package on the system image has changed; consider this 8405 // to be an update. 8406 pkgSetting.lastUpdateTime = scanFileTime; 8407 } 8408 } 8409 8410 // Add the package's KeySets to the global KeySetManagerService 8411 ksms.addScannedPackageLPw(pkg); 8412 8413 int N = pkg.providers.size(); 8414 StringBuilder r = null; 8415 int i; 8416 for (i=0; i<N; i++) { 8417 PackageParser.Provider p = pkg.providers.get(i); 8418 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8419 p.info.processName, pkg.applicationInfo.uid); 8420 mProviders.addProvider(p); 8421 p.syncable = p.info.isSyncable; 8422 if (p.info.authority != null) { 8423 String names[] = p.info.authority.split(";"); 8424 p.info.authority = null; 8425 for (int j = 0; j < names.length; j++) { 8426 if (j == 1 && p.syncable) { 8427 // We only want the first authority for a provider to possibly be 8428 // syncable, so if we already added this provider using a different 8429 // authority clear the syncable flag. We copy the provider before 8430 // changing it because the mProviders object contains a reference 8431 // to a provider that we don't want to change. 8432 // Only do this for the second authority since the resulting provider 8433 // object can be the same for all future authorities for this provider. 8434 p = new PackageParser.Provider(p); 8435 p.syncable = false; 8436 } 8437 if (!mProvidersByAuthority.containsKey(names[j])) { 8438 mProvidersByAuthority.put(names[j], p); 8439 if (p.info.authority == null) { 8440 p.info.authority = names[j]; 8441 } else { 8442 p.info.authority = p.info.authority + ";" + names[j]; 8443 } 8444 if (DEBUG_PACKAGE_SCANNING) { 8445 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8446 Log.d(TAG, "Registered content provider: " + names[j] 8447 + ", className = " + p.info.name + ", isSyncable = " 8448 + p.info.isSyncable); 8449 } 8450 } else { 8451 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8452 Slog.w(TAG, "Skipping provider name " + names[j] + 8453 " (in package " + pkg.applicationInfo.packageName + 8454 "): name already used by " 8455 + ((other != null && other.getComponentName() != null) 8456 ? other.getComponentName().getPackageName() : "?")); 8457 } 8458 } 8459 } 8460 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8461 if (r == null) { 8462 r = new StringBuilder(256); 8463 } else { 8464 r.append(' '); 8465 } 8466 r.append(p.info.name); 8467 } 8468 } 8469 if (r != null) { 8470 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8471 } 8472 8473 N = pkg.services.size(); 8474 r = null; 8475 for (i=0; i<N; i++) { 8476 PackageParser.Service s = pkg.services.get(i); 8477 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8478 s.info.processName, pkg.applicationInfo.uid); 8479 mServices.addService(s); 8480 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8481 if (r == null) { 8482 r = new StringBuilder(256); 8483 } else { 8484 r.append(' '); 8485 } 8486 r.append(s.info.name); 8487 } 8488 } 8489 if (r != null) { 8490 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8491 } 8492 8493 N = pkg.receivers.size(); 8494 r = null; 8495 for (i=0; i<N; i++) { 8496 PackageParser.Activity a = pkg.receivers.get(i); 8497 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8498 a.info.processName, pkg.applicationInfo.uid); 8499 mReceivers.addActivity(a, "receiver"); 8500 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8501 if (r == null) { 8502 r = new StringBuilder(256); 8503 } else { 8504 r.append(' '); 8505 } 8506 r.append(a.info.name); 8507 } 8508 } 8509 if (r != null) { 8510 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8511 } 8512 8513 N = pkg.activities.size(); 8514 r = null; 8515 for (i=0; i<N; i++) { 8516 PackageParser.Activity a = pkg.activities.get(i); 8517 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8518 a.info.processName, pkg.applicationInfo.uid); 8519 mActivities.addActivity(a, "activity"); 8520 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8521 if (r == null) { 8522 r = new StringBuilder(256); 8523 } else { 8524 r.append(' '); 8525 } 8526 r.append(a.info.name); 8527 } 8528 } 8529 if (r != null) { 8530 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8531 } 8532 8533 N = pkg.permissionGroups.size(); 8534 r = null; 8535 for (i=0; i<N; i++) { 8536 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8537 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8538 if (cur == null) { 8539 mPermissionGroups.put(pg.info.name, pg); 8540 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8541 if (r == null) { 8542 r = new StringBuilder(256); 8543 } else { 8544 r.append(' '); 8545 } 8546 r.append(pg.info.name); 8547 } 8548 } else { 8549 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8550 + pg.info.packageName + " ignored: original from " 8551 + cur.info.packageName); 8552 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8553 if (r == null) { 8554 r = new StringBuilder(256); 8555 } else { 8556 r.append(' '); 8557 } 8558 r.append("DUP:"); 8559 r.append(pg.info.name); 8560 } 8561 } 8562 } 8563 if (r != null) { 8564 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8565 } 8566 8567 N = pkg.permissions.size(); 8568 r = null; 8569 for (i=0; i<N; i++) { 8570 PackageParser.Permission p = pkg.permissions.get(i); 8571 8572 // Assume by default that we did not install this permission into the system. 8573 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8574 8575 // Now that permission groups have a special meaning, we ignore permission 8576 // groups for legacy apps to prevent unexpected behavior. In particular, 8577 // permissions for one app being granted to someone just becase they happen 8578 // to be in a group defined by another app (before this had no implications). 8579 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8580 p.group = mPermissionGroups.get(p.info.group); 8581 // Warn for a permission in an unknown group. 8582 if (p.info.group != null && p.group == null) { 8583 Slog.w(TAG, "Permission " + p.info.name + " from package " 8584 + p.info.packageName + " in an unknown group " + p.info.group); 8585 } 8586 } 8587 8588 ArrayMap<String, BasePermission> permissionMap = 8589 p.tree ? mSettings.mPermissionTrees 8590 : mSettings.mPermissions; 8591 BasePermission bp = permissionMap.get(p.info.name); 8592 8593 // Allow system apps to redefine non-system permissions 8594 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8595 final boolean currentOwnerIsSystem = (bp.perm != null 8596 && isSystemApp(bp.perm.owner)); 8597 if (isSystemApp(p.owner)) { 8598 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8599 // It's a built-in permission and no owner, take ownership now 8600 bp.packageSetting = pkgSetting; 8601 bp.perm = p; 8602 bp.uid = pkg.applicationInfo.uid; 8603 bp.sourcePackage = p.info.packageName; 8604 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8605 } else if (!currentOwnerIsSystem) { 8606 String msg = "New decl " + p.owner + " of permission " 8607 + p.info.name + " is system; overriding " + bp.sourcePackage; 8608 reportSettingsProblem(Log.WARN, msg); 8609 bp = null; 8610 } 8611 } 8612 } 8613 8614 if (bp == null) { 8615 bp = new BasePermission(p.info.name, p.info.packageName, 8616 BasePermission.TYPE_NORMAL); 8617 permissionMap.put(p.info.name, bp); 8618 } 8619 8620 if (bp.perm == null) { 8621 if (bp.sourcePackage == null 8622 || bp.sourcePackage.equals(p.info.packageName)) { 8623 BasePermission tree = findPermissionTreeLP(p.info.name); 8624 if (tree == null 8625 || tree.sourcePackage.equals(p.info.packageName)) { 8626 bp.packageSetting = pkgSetting; 8627 bp.perm = p; 8628 bp.uid = pkg.applicationInfo.uid; 8629 bp.sourcePackage = p.info.packageName; 8630 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8631 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8632 if (r == null) { 8633 r = new StringBuilder(256); 8634 } else { 8635 r.append(' '); 8636 } 8637 r.append(p.info.name); 8638 } 8639 } else { 8640 Slog.w(TAG, "Permission " + p.info.name + " from package " 8641 + p.info.packageName + " ignored: base tree " 8642 + tree.name + " is from package " 8643 + tree.sourcePackage); 8644 } 8645 } else { 8646 Slog.w(TAG, "Permission " + p.info.name + " from package " 8647 + p.info.packageName + " ignored: original from " 8648 + bp.sourcePackage); 8649 } 8650 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8651 if (r == null) { 8652 r = new StringBuilder(256); 8653 } else { 8654 r.append(' '); 8655 } 8656 r.append("DUP:"); 8657 r.append(p.info.name); 8658 } 8659 if (bp.perm == p) { 8660 bp.protectionLevel = p.info.protectionLevel; 8661 } 8662 } 8663 8664 if (r != null) { 8665 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8666 } 8667 8668 N = pkg.instrumentation.size(); 8669 r = null; 8670 for (i=0; i<N; i++) { 8671 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8672 a.info.packageName = pkg.applicationInfo.packageName; 8673 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8674 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8675 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8676 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8677 a.info.dataDir = pkg.applicationInfo.dataDir; 8678 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8679 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8680 8681 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8682 // need other information about the application, like the ABI and what not ? 8683 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8684 mInstrumentation.put(a.getComponentName(), a); 8685 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8686 if (r == null) { 8687 r = new StringBuilder(256); 8688 } else { 8689 r.append(' '); 8690 } 8691 r.append(a.info.name); 8692 } 8693 } 8694 if (r != null) { 8695 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8696 } 8697 8698 if (pkg.protectedBroadcasts != null) { 8699 N = pkg.protectedBroadcasts.size(); 8700 for (i=0; i<N; i++) { 8701 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8702 } 8703 } 8704 8705 pkgSetting.setTimeStamp(scanFileTime); 8706 8707 // Create idmap files for pairs of (packages, overlay packages). 8708 // Note: "android", ie framework-res.apk, is handled by native layers. 8709 if (pkg.mOverlayTarget != null) { 8710 // This is an overlay package. 8711 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8712 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8713 mOverlays.put(pkg.mOverlayTarget, 8714 new ArrayMap<String, PackageParser.Package>()); 8715 } 8716 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8717 map.put(pkg.packageName, pkg); 8718 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8719 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8720 createIdmapFailed = true; 8721 } 8722 } 8723 } else if (mOverlays.containsKey(pkg.packageName) && 8724 !pkg.packageName.equals("android")) { 8725 // This is a regular package, with one or more known overlay packages. 8726 createIdmapsForPackageLI(pkg); 8727 } 8728 } 8729 8730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8731 8732 if (createIdmapFailed) { 8733 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8734 "scanPackageLI failed to createIdmap"); 8735 } 8736 return pkg; 8737 } 8738 8739 /** 8740 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8741 * is derived purely on the basis of the contents of {@code scanFile} and 8742 * {@code cpuAbiOverride}. 8743 * 8744 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8745 */ 8746 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8747 String cpuAbiOverride, boolean extractLibs) 8748 throws PackageManagerException { 8749 // TODO: We can probably be smarter about this stuff. For installed apps, 8750 // we can calculate this information at install time once and for all. For 8751 // system apps, we can probably assume that this information doesn't change 8752 // after the first boot scan. As things stand, we do lots of unnecessary work. 8753 8754 // Give ourselves some initial paths; we'll come back for another 8755 // pass once we've determined ABI below. 8756 setNativeLibraryPaths(pkg); 8757 8758 // We would never need to extract libs for forward-locked and external packages, 8759 // since the container service will do it for us. We shouldn't attempt to 8760 // extract libs from system app when it was not updated. 8761 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8762 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8763 extractLibs = false; 8764 } 8765 8766 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8767 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8768 8769 NativeLibraryHelper.Handle handle = null; 8770 try { 8771 handle = NativeLibraryHelper.Handle.create(pkg); 8772 // TODO(multiArch): This can be null for apps that didn't go through the 8773 // usual installation process. We can calculate it again, like we 8774 // do during install time. 8775 // 8776 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8777 // unnecessary. 8778 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8779 8780 // Null out the abis so that they can be recalculated. 8781 pkg.applicationInfo.primaryCpuAbi = null; 8782 pkg.applicationInfo.secondaryCpuAbi = null; 8783 if (isMultiArch(pkg.applicationInfo)) { 8784 // Warn if we've set an abiOverride for multi-lib packages.. 8785 // By definition, we need to copy both 32 and 64 bit libraries for 8786 // such packages. 8787 if (pkg.cpuAbiOverride != null 8788 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8789 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8790 } 8791 8792 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8793 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8794 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8795 if (extractLibs) { 8796 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8797 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8798 useIsaSpecificSubdirs); 8799 } else { 8800 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8801 } 8802 } 8803 8804 maybeThrowExceptionForMultiArchCopy( 8805 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8806 8807 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8808 if (extractLibs) { 8809 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8810 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8811 useIsaSpecificSubdirs); 8812 } else { 8813 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8814 } 8815 } 8816 8817 maybeThrowExceptionForMultiArchCopy( 8818 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8819 8820 if (abi64 >= 0) { 8821 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8822 } 8823 8824 if (abi32 >= 0) { 8825 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8826 if (abi64 >= 0) { 8827 if (pkg.use32bitAbi) { 8828 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8829 pkg.applicationInfo.primaryCpuAbi = abi; 8830 } else { 8831 pkg.applicationInfo.secondaryCpuAbi = abi; 8832 } 8833 } else { 8834 pkg.applicationInfo.primaryCpuAbi = abi; 8835 } 8836 } 8837 8838 } else { 8839 String[] abiList = (cpuAbiOverride != null) ? 8840 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8841 8842 // Enable gross and lame hacks for apps that are built with old 8843 // SDK tools. We must scan their APKs for renderscript bitcode and 8844 // not launch them if it's present. Don't bother checking on devices 8845 // that don't have 64 bit support. 8846 boolean needsRenderScriptOverride = false; 8847 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8848 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8849 abiList = Build.SUPPORTED_32_BIT_ABIS; 8850 needsRenderScriptOverride = true; 8851 } 8852 8853 final int copyRet; 8854 if (extractLibs) { 8855 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8856 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8857 } else { 8858 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8859 } 8860 8861 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8862 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8863 "Error unpackaging native libs for app, errorCode=" + copyRet); 8864 } 8865 8866 if (copyRet >= 0) { 8867 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8868 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8869 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8870 } else if (needsRenderScriptOverride) { 8871 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8872 } 8873 } 8874 } catch (IOException ioe) { 8875 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8876 } finally { 8877 IoUtils.closeQuietly(handle); 8878 } 8879 8880 // Now that we've calculated the ABIs and determined if it's an internal app, 8881 // we will go ahead and populate the nativeLibraryPath. 8882 setNativeLibraryPaths(pkg); 8883 } 8884 8885 /** 8886 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8887 * i.e, so that all packages can be run inside a single process if required. 8888 * 8889 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8890 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8891 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8892 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8893 * updating a package that belongs to a shared user. 8894 * 8895 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8896 * adds unnecessary complexity. 8897 */ 8898 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8899 PackageParser.Package scannedPackage, boolean bootComplete) { 8900 String requiredInstructionSet = null; 8901 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8902 requiredInstructionSet = VMRuntime.getInstructionSet( 8903 scannedPackage.applicationInfo.primaryCpuAbi); 8904 } 8905 8906 PackageSetting requirer = null; 8907 for (PackageSetting ps : packagesForUser) { 8908 // If packagesForUser contains scannedPackage, we skip it. This will happen 8909 // when scannedPackage is an update of an existing package. Without this check, 8910 // we will never be able to change the ABI of any package belonging to a shared 8911 // user, even if it's compatible with other packages. 8912 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8913 if (ps.primaryCpuAbiString == null) { 8914 continue; 8915 } 8916 8917 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8918 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8919 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8920 // this but there's not much we can do. 8921 String errorMessage = "Instruction set mismatch, " 8922 + ((requirer == null) ? "[caller]" : requirer) 8923 + " requires " + requiredInstructionSet + " whereas " + ps 8924 + " requires " + instructionSet; 8925 Slog.w(TAG, errorMessage); 8926 } 8927 8928 if (requiredInstructionSet == null) { 8929 requiredInstructionSet = instructionSet; 8930 requirer = ps; 8931 } 8932 } 8933 } 8934 8935 if (requiredInstructionSet != null) { 8936 String adjustedAbi; 8937 if (requirer != null) { 8938 // requirer != null implies that either scannedPackage was null or that scannedPackage 8939 // did not require an ABI, in which case we have to adjust scannedPackage to match 8940 // the ABI of the set (which is the same as requirer's ABI) 8941 adjustedAbi = requirer.primaryCpuAbiString; 8942 if (scannedPackage != null) { 8943 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8944 } 8945 } else { 8946 // requirer == null implies that we're updating all ABIs in the set to 8947 // match scannedPackage. 8948 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8949 } 8950 8951 for (PackageSetting ps : packagesForUser) { 8952 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8953 if (ps.primaryCpuAbiString != null) { 8954 continue; 8955 } 8956 8957 ps.primaryCpuAbiString = adjustedAbi; 8958 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8959 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8960 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8961 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8962 + " (requirer=" 8963 + (requirer == null ? "null" : requirer.pkg.packageName) 8964 + ", scannedPackage=" 8965 + (scannedPackage != null ? scannedPackage.packageName : "null") 8966 + ")"); 8967 try { 8968 mInstaller.rmdex(ps.codePathString, 8969 getDexCodeInstructionSet(getPreferredInstructionSet())); 8970 } catch (InstallerException ignored) { 8971 } 8972 } 8973 } 8974 } 8975 } 8976 } 8977 8978 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8979 synchronized (mPackages) { 8980 mResolverReplaced = true; 8981 // Set up information for custom user intent resolution activity. 8982 mResolveActivity.applicationInfo = pkg.applicationInfo; 8983 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8984 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8985 mResolveActivity.processName = pkg.applicationInfo.packageName; 8986 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8987 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8988 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8989 mResolveActivity.theme = 0; 8990 mResolveActivity.exported = true; 8991 mResolveActivity.enabled = true; 8992 mResolveInfo.activityInfo = mResolveActivity; 8993 mResolveInfo.priority = 0; 8994 mResolveInfo.preferredOrder = 0; 8995 mResolveInfo.match = 0; 8996 mResolveComponentName = mCustomResolverComponentName; 8997 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8998 mResolveComponentName); 8999 } 9000 } 9001 9002 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9003 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9004 9005 // Set up information for ephemeral installer activity 9006 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9007 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9008 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9009 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9010 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9011 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9012 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9013 mEphemeralInstallerActivity.theme = 0; 9014 mEphemeralInstallerActivity.exported = true; 9015 mEphemeralInstallerActivity.enabled = true; 9016 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9017 mEphemeralInstallerInfo.priority = 0; 9018 mEphemeralInstallerInfo.preferredOrder = 0; 9019 mEphemeralInstallerInfo.match = 0; 9020 9021 if (DEBUG_EPHEMERAL) { 9022 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9023 } 9024 } 9025 9026 private static String calculateBundledApkRoot(final String codePathString) { 9027 final File codePath = new File(codePathString); 9028 final File codeRoot; 9029 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9030 codeRoot = Environment.getRootDirectory(); 9031 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9032 codeRoot = Environment.getOemDirectory(); 9033 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9034 codeRoot = Environment.getVendorDirectory(); 9035 } else { 9036 // Unrecognized code path; take its top real segment as the apk root: 9037 // e.g. /something/app/blah.apk => /something 9038 try { 9039 File f = codePath.getCanonicalFile(); 9040 File parent = f.getParentFile(); // non-null because codePath is a file 9041 File tmp; 9042 while ((tmp = parent.getParentFile()) != null) { 9043 f = parent; 9044 parent = tmp; 9045 } 9046 codeRoot = f; 9047 Slog.w(TAG, "Unrecognized code path " 9048 + codePath + " - using " + codeRoot); 9049 } catch (IOException e) { 9050 // Can't canonicalize the code path -- shenanigans? 9051 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9052 return Environment.getRootDirectory().getPath(); 9053 } 9054 } 9055 return codeRoot.getPath(); 9056 } 9057 9058 /** 9059 * Derive and set the location of native libraries for the given package, 9060 * which varies depending on where and how the package was installed. 9061 */ 9062 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9063 final ApplicationInfo info = pkg.applicationInfo; 9064 final String codePath = pkg.codePath; 9065 final File codeFile = new File(codePath); 9066 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9067 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9068 9069 info.nativeLibraryRootDir = null; 9070 info.nativeLibraryRootRequiresIsa = false; 9071 info.nativeLibraryDir = null; 9072 info.secondaryNativeLibraryDir = null; 9073 9074 if (isApkFile(codeFile)) { 9075 // Monolithic install 9076 if (bundledApp) { 9077 // If "/system/lib64/apkname" exists, assume that is the per-package 9078 // native library directory to use; otherwise use "/system/lib/apkname". 9079 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9080 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9081 getPrimaryInstructionSet(info)); 9082 9083 // This is a bundled system app so choose the path based on the ABI. 9084 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9085 // is just the default path. 9086 final String apkName = deriveCodePathName(codePath); 9087 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9088 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9089 apkName).getAbsolutePath(); 9090 9091 if (info.secondaryCpuAbi != null) { 9092 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9093 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9094 secondaryLibDir, apkName).getAbsolutePath(); 9095 } 9096 } else if (asecApp) { 9097 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9098 .getAbsolutePath(); 9099 } else { 9100 final String apkName = deriveCodePathName(codePath); 9101 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9102 .getAbsolutePath(); 9103 } 9104 9105 info.nativeLibraryRootRequiresIsa = false; 9106 info.nativeLibraryDir = info.nativeLibraryRootDir; 9107 } else { 9108 // Cluster install 9109 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9110 info.nativeLibraryRootRequiresIsa = true; 9111 9112 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9113 getPrimaryInstructionSet(info)).getAbsolutePath(); 9114 9115 if (info.secondaryCpuAbi != null) { 9116 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9117 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9118 } 9119 } 9120 } 9121 9122 /** 9123 * Calculate the abis and roots for a bundled app. These can uniquely 9124 * be determined from the contents of the system partition, i.e whether 9125 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9126 * of this information, and instead assume that the system was built 9127 * sensibly. 9128 */ 9129 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9130 PackageSetting pkgSetting) { 9131 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9132 9133 // If "/system/lib64/apkname" exists, assume that is the per-package 9134 // native library directory to use; otherwise use "/system/lib/apkname". 9135 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9136 setBundledAppAbi(pkg, apkRoot, apkName); 9137 // pkgSetting might be null during rescan following uninstall of updates 9138 // to a bundled app, so accommodate that possibility. The settings in 9139 // that case will be established later from the parsed package. 9140 // 9141 // If the settings aren't null, sync them up with what we've just derived. 9142 // note that apkRoot isn't stored in the package settings. 9143 if (pkgSetting != null) { 9144 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9145 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9146 } 9147 } 9148 9149 /** 9150 * Deduces the ABI of a bundled app and sets the relevant fields on the 9151 * parsed pkg object. 9152 * 9153 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9154 * under which system libraries are installed. 9155 * @param apkName the name of the installed package. 9156 */ 9157 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9158 final File codeFile = new File(pkg.codePath); 9159 9160 final boolean has64BitLibs; 9161 final boolean has32BitLibs; 9162 if (isApkFile(codeFile)) { 9163 // Monolithic install 9164 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9165 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9166 } else { 9167 // Cluster install 9168 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9169 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9170 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9171 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9172 has64BitLibs = (new File(rootDir, isa)).exists(); 9173 } else { 9174 has64BitLibs = false; 9175 } 9176 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9177 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9178 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9179 has32BitLibs = (new File(rootDir, isa)).exists(); 9180 } else { 9181 has32BitLibs = false; 9182 } 9183 } 9184 9185 if (has64BitLibs && !has32BitLibs) { 9186 // The package has 64 bit libs, but not 32 bit libs. Its primary 9187 // ABI should be 64 bit. We can safely assume here that the bundled 9188 // native libraries correspond to the most preferred ABI in the list. 9189 9190 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9191 pkg.applicationInfo.secondaryCpuAbi = null; 9192 } else if (has32BitLibs && !has64BitLibs) { 9193 // The package has 32 bit libs but not 64 bit libs. Its primary 9194 // ABI should be 32 bit. 9195 9196 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9197 pkg.applicationInfo.secondaryCpuAbi = null; 9198 } else if (has32BitLibs && has64BitLibs) { 9199 // The application has both 64 and 32 bit bundled libraries. We check 9200 // here that the app declares multiArch support, and warn if it doesn't. 9201 // 9202 // We will be lenient here and record both ABIs. The primary will be the 9203 // ABI that's higher on the list, i.e, a device that's configured to prefer 9204 // 64 bit apps will see a 64 bit primary ABI, 9205 9206 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9207 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9208 } 9209 9210 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9211 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9212 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9213 } else { 9214 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9215 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9216 } 9217 } else { 9218 pkg.applicationInfo.primaryCpuAbi = null; 9219 pkg.applicationInfo.secondaryCpuAbi = null; 9220 } 9221 } 9222 9223 private void killApplication(String pkgName, int appId, String reason) { 9224 // Request the ActivityManager to kill the process(only for existing packages) 9225 // so that we do not end up in a confused state while the user is still using the older 9226 // version of the application while the new one gets installed. 9227 final long token = Binder.clearCallingIdentity(); 9228 try { 9229 IActivityManager am = ActivityManagerNative.getDefault(); 9230 if (am != null) { 9231 try { 9232 am.killApplicationWithAppId(pkgName, appId, reason); 9233 } catch (RemoteException e) { 9234 } 9235 } 9236 } finally { 9237 Binder.restoreCallingIdentity(token); 9238 } 9239 } 9240 9241 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9242 // Remove the parent package setting 9243 PackageSetting ps = (PackageSetting) pkg.mExtras; 9244 if (ps != null) { 9245 removePackageLI(ps, chatty); 9246 } 9247 // Remove the child package setting 9248 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9249 for (int i = 0; i < childCount; i++) { 9250 PackageParser.Package childPkg = pkg.childPackages.get(i); 9251 ps = (PackageSetting) childPkg.mExtras; 9252 if (ps != null) { 9253 removePackageLI(ps, chatty); 9254 } 9255 } 9256 } 9257 9258 void removePackageLI(PackageSetting ps, boolean chatty) { 9259 if (DEBUG_INSTALL) { 9260 if (chatty) 9261 Log.d(TAG, "Removing package " + ps.name); 9262 } 9263 9264 // writer 9265 synchronized (mPackages) { 9266 mPackages.remove(ps.name); 9267 final PackageParser.Package pkg = ps.pkg; 9268 if (pkg != null) { 9269 cleanPackageDataStructuresLILPw(pkg, chatty); 9270 } 9271 } 9272 } 9273 9274 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9275 if (DEBUG_INSTALL) { 9276 if (chatty) 9277 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9278 } 9279 9280 // writer 9281 synchronized (mPackages) { 9282 // Remove the parent package 9283 mPackages.remove(pkg.applicationInfo.packageName); 9284 cleanPackageDataStructuresLILPw(pkg, chatty); 9285 9286 // Remove the child packages 9287 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9288 for (int i = 0; i < childCount; i++) { 9289 PackageParser.Package childPkg = pkg.childPackages.get(i); 9290 mPackages.remove(childPkg.applicationInfo.packageName); 9291 cleanPackageDataStructuresLILPw(childPkg, chatty); 9292 } 9293 } 9294 } 9295 9296 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9297 int N = pkg.providers.size(); 9298 StringBuilder r = null; 9299 int i; 9300 for (i=0; i<N; i++) { 9301 PackageParser.Provider p = pkg.providers.get(i); 9302 mProviders.removeProvider(p); 9303 if (p.info.authority == null) { 9304 9305 /* There was another ContentProvider with this authority when 9306 * this app was installed so this authority is null, 9307 * Ignore it as we don't have to unregister the provider. 9308 */ 9309 continue; 9310 } 9311 String names[] = p.info.authority.split(";"); 9312 for (int j = 0; j < names.length; j++) { 9313 if (mProvidersByAuthority.get(names[j]) == p) { 9314 mProvidersByAuthority.remove(names[j]); 9315 if (DEBUG_REMOVE) { 9316 if (chatty) 9317 Log.d(TAG, "Unregistered content provider: " + names[j] 9318 + ", className = " + p.info.name + ", isSyncable = " 9319 + p.info.isSyncable); 9320 } 9321 } 9322 } 9323 if (DEBUG_REMOVE && chatty) { 9324 if (r == null) { 9325 r = new StringBuilder(256); 9326 } else { 9327 r.append(' '); 9328 } 9329 r.append(p.info.name); 9330 } 9331 } 9332 if (r != null) { 9333 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9334 } 9335 9336 N = pkg.services.size(); 9337 r = null; 9338 for (i=0; i<N; i++) { 9339 PackageParser.Service s = pkg.services.get(i); 9340 mServices.removeService(s); 9341 if (chatty) { 9342 if (r == null) { 9343 r = new StringBuilder(256); 9344 } else { 9345 r.append(' '); 9346 } 9347 r.append(s.info.name); 9348 } 9349 } 9350 if (r != null) { 9351 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9352 } 9353 9354 N = pkg.receivers.size(); 9355 r = null; 9356 for (i=0; i<N; i++) { 9357 PackageParser.Activity a = pkg.receivers.get(i); 9358 mReceivers.removeActivity(a, "receiver"); 9359 if (DEBUG_REMOVE && chatty) { 9360 if (r == null) { 9361 r = new StringBuilder(256); 9362 } else { 9363 r.append(' '); 9364 } 9365 r.append(a.info.name); 9366 } 9367 } 9368 if (r != null) { 9369 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9370 } 9371 9372 N = pkg.activities.size(); 9373 r = null; 9374 for (i=0; i<N; i++) { 9375 PackageParser.Activity a = pkg.activities.get(i); 9376 mActivities.removeActivity(a, "activity"); 9377 if (DEBUG_REMOVE && chatty) { 9378 if (r == null) { 9379 r = new StringBuilder(256); 9380 } else { 9381 r.append(' '); 9382 } 9383 r.append(a.info.name); 9384 } 9385 } 9386 if (r != null) { 9387 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9388 } 9389 9390 N = pkg.permissions.size(); 9391 r = null; 9392 for (i=0; i<N; i++) { 9393 PackageParser.Permission p = pkg.permissions.get(i); 9394 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9395 if (bp == null) { 9396 bp = mSettings.mPermissionTrees.get(p.info.name); 9397 } 9398 if (bp != null && bp.perm == p) { 9399 bp.perm = null; 9400 if (DEBUG_REMOVE && chatty) { 9401 if (r == null) { 9402 r = new StringBuilder(256); 9403 } else { 9404 r.append(' '); 9405 } 9406 r.append(p.info.name); 9407 } 9408 } 9409 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9410 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9411 if (appOpPkgs != null) { 9412 appOpPkgs.remove(pkg.packageName); 9413 } 9414 } 9415 } 9416 if (r != null) { 9417 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9418 } 9419 9420 N = pkg.requestedPermissions.size(); 9421 r = null; 9422 for (i=0; i<N; i++) { 9423 String perm = pkg.requestedPermissions.get(i); 9424 BasePermission bp = mSettings.mPermissions.get(perm); 9425 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9426 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9427 if (appOpPkgs != null) { 9428 appOpPkgs.remove(pkg.packageName); 9429 if (appOpPkgs.isEmpty()) { 9430 mAppOpPermissionPackages.remove(perm); 9431 } 9432 } 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9437 } 9438 9439 N = pkg.instrumentation.size(); 9440 r = null; 9441 for (i=0; i<N; i++) { 9442 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9443 mInstrumentation.remove(a.getComponentName()); 9444 if (DEBUG_REMOVE && chatty) { 9445 if (r == null) { 9446 r = new StringBuilder(256); 9447 } else { 9448 r.append(' '); 9449 } 9450 r.append(a.info.name); 9451 } 9452 } 9453 if (r != null) { 9454 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9455 } 9456 9457 r = null; 9458 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9459 // Only system apps can hold shared libraries. 9460 if (pkg.libraryNames != null) { 9461 for (i=0; i<pkg.libraryNames.size(); i++) { 9462 String name = pkg.libraryNames.get(i); 9463 SharedLibraryEntry cur = mSharedLibraries.get(name); 9464 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9465 mSharedLibraries.remove(name); 9466 if (DEBUG_REMOVE && chatty) { 9467 if (r == null) { 9468 r = new StringBuilder(256); 9469 } else { 9470 r.append(' '); 9471 } 9472 r.append(name); 9473 } 9474 } 9475 } 9476 } 9477 } 9478 if (r != null) { 9479 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9480 } 9481 } 9482 9483 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9484 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9485 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9486 return true; 9487 } 9488 } 9489 return false; 9490 } 9491 9492 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9493 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9494 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9495 9496 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9497 // Update the parent permissions 9498 updatePermissionsLPw(pkg.packageName, pkg, flags); 9499 // Update the child permissions 9500 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9501 for (int i = 0; i < childCount; i++) { 9502 PackageParser.Package childPkg = pkg.childPackages.get(i); 9503 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9504 } 9505 } 9506 9507 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9508 int flags) { 9509 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9510 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9511 } 9512 9513 private void updatePermissionsLPw(String changingPkg, 9514 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9515 // Make sure there are no dangling permission trees. 9516 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9517 while (it.hasNext()) { 9518 final BasePermission bp = it.next(); 9519 if (bp.packageSetting == null) { 9520 // We may not yet have parsed the package, so just see if 9521 // we still know about its settings. 9522 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9523 } 9524 if (bp.packageSetting == null) { 9525 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9526 + " from package " + bp.sourcePackage); 9527 it.remove(); 9528 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9529 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9530 Slog.i(TAG, "Removing old permission tree: " + bp.name 9531 + " from package " + bp.sourcePackage); 9532 flags |= UPDATE_PERMISSIONS_ALL; 9533 it.remove(); 9534 } 9535 } 9536 } 9537 9538 // Make sure all dynamic permissions have been assigned to a package, 9539 // and make sure there are no dangling permissions. 9540 it = mSettings.mPermissions.values().iterator(); 9541 while (it.hasNext()) { 9542 final BasePermission bp = it.next(); 9543 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9544 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9545 + bp.name + " pkg=" + bp.sourcePackage 9546 + " info=" + bp.pendingInfo); 9547 if (bp.packageSetting == null && bp.pendingInfo != null) { 9548 final BasePermission tree = findPermissionTreeLP(bp.name); 9549 if (tree != null && tree.perm != null) { 9550 bp.packageSetting = tree.packageSetting; 9551 bp.perm = new PackageParser.Permission(tree.perm.owner, 9552 new PermissionInfo(bp.pendingInfo)); 9553 bp.perm.info.packageName = tree.perm.info.packageName; 9554 bp.perm.info.name = bp.name; 9555 bp.uid = tree.uid; 9556 } 9557 } 9558 } 9559 if (bp.packageSetting == null) { 9560 // We may not yet have parsed the package, so just see if 9561 // we still know about its settings. 9562 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9563 } 9564 if (bp.packageSetting == null) { 9565 Slog.w(TAG, "Removing dangling permission: " + bp.name 9566 + " from package " + bp.sourcePackage); 9567 it.remove(); 9568 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9569 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9570 Slog.i(TAG, "Removing old permission: " + bp.name 9571 + " from package " + bp.sourcePackage); 9572 flags |= UPDATE_PERMISSIONS_ALL; 9573 it.remove(); 9574 } 9575 } 9576 } 9577 9578 // Now update the permissions for all packages, in particular 9579 // replace the granted permissions of the system packages. 9580 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9581 for (PackageParser.Package pkg : mPackages.values()) { 9582 if (pkg != pkgInfo) { 9583 // Only replace for packages on requested volume 9584 final String volumeUuid = getVolumeUuidForPackage(pkg); 9585 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9586 && Objects.equals(replaceVolumeUuid, volumeUuid); 9587 grantPermissionsLPw(pkg, replace, changingPkg); 9588 } 9589 } 9590 } 9591 9592 if (pkgInfo != null) { 9593 // Only replace for packages on requested volume 9594 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9595 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9596 && Objects.equals(replaceVolumeUuid, volumeUuid); 9597 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9598 } 9599 } 9600 9601 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9602 String packageOfInterest) { 9603 // IMPORTANT: There are two types of permissions: install and runtime. 9604 // Install time permissions are granted when the app is installed to 9605 // all device users and users added in the future. Runtime permissions 9606 // are granted at runtime explicitly to specific users. Normal and signature 9607 // protected permissions are install time permissions. Dangerous permissions 9608 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9609 // otherwise they are runtime permissions. This function does not manage 9610 // runtime permissions except for the case an app targeting Lollipop MR1 9611 // being upgraded to target a newer SDK, in which case dangerous permissions 9612 // are transformed from install time to runtime ones. 9613 9614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9615 if (ps == null) { 9616 return; 9617 } 9618 9619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9620 9621 PermissionsState permissionsState = ps.getPermissionsState(); 9622 PermissionsState origPermissions = permissionsState; 9623 9624 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9625 9626 boolean runtimePermissionsRevoked = false; 9627 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9628 9629 boolean changedInstallPermission = false; 9630 9631 if (replace) { 9632 ps.installPermissionsFixed = false; 9633 if (!ps.isSharedUser()) { 9634 origPermissions = new PermissionsState(permissionsState); 9635 permissionsState.reset(); 9636 } else { 9637 // We need to know only about runtime permission changes since the 9638 // calling code always writes the install permissions state but 9639 // the runtime ones are written only if changed. The only cases of 9640 // changed runtime permissions here are promotion of an install to 9641 // runtime and revocation of a runtime from a shared user. 9642 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9643 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9644 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9645 runtimePermissionsRevoked = true; 9646 } 9647 } 9648 } 9649 9650 permissionsState.setGlobalGids(mGlobalGids); 9651 9652 final int N = pkg.requestedPermissions.size(); 9653 for (int i=0; i<N; i++) { 9654 final String name = pkg.requestedPermissions.get(i); 9655 final BasePermission bp = mSettings.mPermissions.get(name); 9656 9657 if (DEBUG_INSTALL) { 9658 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9659 } 9660 9661 if (bp == null || bp.packageSetting == null) { 9662 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9663 Slog.w(TAG, "Unknown permission " + name 9664 + " in package " + pkg.packageName); 9665 } 9666 continue; 9667 } 9668 9669 final String perm = bp.name; 9670 boolean allowedSig = false; 9671 int grant = GRANT_DENIED; 9672 9673 // Keep track of app op permissions. 9674 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9675 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9676 if (pkgs == null) { 9677 pkgs = new ArraySet<>(); 9678 mAppOpPermissionPackages.put(bp.name, pkgs); 9679 } 9680 pkgs.add(pkg.packageName); 9681 } 9682 9683 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9684 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9685 >= Build.VERSION_CODES.M; 9686 switch (level) { 9687 case PermissionInfo.PROTECTION_NORMAL: { 9688 // For all apps normal permissions are install time ones. 9689 grant = GRANT_INSTALL; 9690 } break; 9691 9692 case PermissionInfo.PROTECTION_DANGEROUS: { 9693 // If a permission review is required for legacy apps we represent 9694 // their permissions as always granted runtime ones since we need 9695 // to keep the review required permission flag per user while an 9696 // install permission's state is shared across all users. 9697 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9698 // For legacy apps dangerous permissions are install time ones. 9699 grant = GRANT_INSTALL; 9700 } else if (origPermissions.hasInstallPermission(bp.name)) { 9701 // For legacy apps that became modern, install becomes runtime. 9702 grant = GRANT_UPGRADE; 9703 } else if (mPromoteSystemApps 9704 && isSystemApp(ps) 9705 && mExistingSystemPackages.contains(ps.name)) { 9706 // For legacy system apps, install becomes runtime. 9707 // We cannot check hasInstallPermission() for system apps since those 9708 // permissions were granted implicitly and not persisted pre-M. 9709 grant = GRANT_UPGRADE; 9710 } else { 9711 // For modern apps keep runtime permissions unchanged. 9712 grant = GRANT_RUNTIME; 9713 } 9714 } break; 9715 9716 case PermissionInfo.PROTECTION_SIGNATURE: { 9717 // For all apps signature permissions are install time ones. 9718 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9719 if (allowedSig) { 9720 grant = GRANT_INSTALL; 9721 } 9722 } break; 9723 } 9724 9725 if (DEBUG_INSTALL) { 9726 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9727 } 9728 9729 if (grant != GRANT_DENIED) { 9730 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9731 // If this is an existing, non-system package, then 9732 // we can't add any new permissions to it. 9733 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9734 // Except... if this is a permission that was added 9735 // to the platform (note: need to only do this when 9736 // updating the platform). 9737 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9738 grant = GRANT_DENIED; 9739 } 9740 } 9741 } 9742 9743 switch (grant) { 9744 case GRANT_INSTALL: { 9745 // Revoke this as runtime permission to handle the case of 9746 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9747 for (int userId : UserManagerService.getInstance().getUserIds()) { 9748 if (origPermissions.getRuntimePermissionState( 9749 bp.name, userId) != null) { 9750 // Revoke the runtime permission and clear the flags. 9751 origPermissions.revokeRuntimePermission(bp, userId); 9752 origPermissions.updatePermissionFlags(bp, userId, 9753 PackageManager.MASK_PERMISSION_FLAGS, 0); 9754 // If we revoked a permission permission, we have to write. 9755 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9756 changedRuntimePermissionUserIds, userId); 9757 } 9758 } 9759 // Grant an install permission. 9760 if (permissionsState.grantInstallPermission(bp) != 9761 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9762 changedInstallPermission = true; 9763 } 9764 } break; 9765 9766 case GRANT_RUNTIME: { 9767 // Grant previously granted runtime permissions. 9768 for (int userId : UserManagerService.getInstance().getUserIds()) { 9769 PermissionState permissionState = origPermissions 9770 .getRuntimePermissionState(bp.name, userId); 9771 int flags = permissionState != null 9772 ? permissionState.getFlags() : 0; 9773 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9774 if (permissionsState.grantRuntimePermission(bp, userId) == 9775 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9776 // If we cannot put the permission as it was, we have to write. 9777 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9778 changedRuntimePermissionUserIds, userId); 9779 } 9780 // If the app supports runtime permissions no need for a review. 9781 if (Build.PERMISSIONS_REVIEW_REQUIRED 9782 && appSupportsRuntimePermissions 9783 && (flags & PackageManager 9784 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9785 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9786 // Since we changed the flags, we have to write. 9787 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9788 changedRuntimePermissionUserIds, userId); 9789 } 9790 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9791 && !appSupportsRuntimePermissions) { 9792 // For legacy apps that need a permission review, every new 9793 // runtime permission is granted but it is pending a review. 9794 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9795 permissionsState.grantRuntimePermission(bp, userId); 9796 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9797 // We changed the permission and flags, hence have to write. 9798 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9799 changedRuntimePermissionUserIds, userId); 9800 } 9801 } 9802 // Propagate the permission flags. 9803 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9804 } 9805 } break; 9806 9807 case GRANT_UPGRADE: { 9808 // Grant runtime permissions for a previously held install permission. 9809 PermissionState permissionState = origPermissions 9810 .getInstallPermissionState(bp.name); 9811 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9812 9813 if (origPermissions.revokeInstallPermission(bp) 9814 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9815 // We will be transferring the permission flags, so clear them. 9816 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9817 PackageManager.MASK_PERMISSION_FLAGS, 0); 9818 changedInstallPermission = true; 9819 } 9820 9821 // If the permission is not to be promoted to runtime we ignore it and 9822 // also its other flags as they are not applicable to install permissions. 9823 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9824 for (int userId : currentUserIds) { 9825 if (permissionsState.grantRuntimePermission(bp, userId) != 9826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9827 // Transfer the permission flags. 9828 permissionsState.updatePermissionFlags(bp, userId, 9829 flags, flags); 9830 // If we granted the permission, we have to write. 9831 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9832 changedRuntimePermissionUserIds, userId); 9833 } 9834 } 9835 } 9836 } break; 9837 9838 default: { 9839 if (packageOfInterest == null 9840 || packageOfInterest.equals(pkg.packageName)) { 9841 Slog.w(TAG, "Not granting permission " + perm 9842 + " to package " + pkg.packageName 9843 + " because it was previously installed without"); 9844 } 9845 } break; 9846 } 9847 } else { 9848 if (permissionsState.revokeInstallPermission(bp) != 9849 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9850 // Also drop the permission flags. 9851 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9852 PackageManager.MASK_PERMISSION_FLAGS, 0); 9853 changedInstallPermission = true; 9854 Slog.i(TAG, "Un-granting permission " + perm 9855 + " from package " + pkg.packageName 9856 + " (protectionLevel=" + bp.protectionLevel 9857 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9858 + ")"); 9859 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9860 // Don't print warning for app op permissions, since it is fine for them 9861 // not to be granted, there is a UI for the user to decide. 9862 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9863 Slog.w(TAG, "Not granting permission " + perm 9864 + " to package " + pkg.packageName 9865 + " (protectionLevel=" + bp.protectionLevel 9866 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9867 + ")"); 9868 } 9869 } 9870 } 9871 } 9872 9873 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9874 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9875 // This is the first that we have heard about this package, so the 9876 // permissions we have now selected are fixed until explicitly 9877 // changed. 9878 ps.installPermissionsFixed = true; 9879 } 9880 9881 // Persist the runtime permissions state for users with changes. If permissions 9882 // were revoked because no app in the shared user declares them we have to 9883 // write synchronously to avoid losing runtime permissions state. 9884 for (int userId : changedRuntimePermissionUserIds) { 9885 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9886 } 9887 9888 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9889 } 9890 9891 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9892 boolean allowed = false; 9893 final int NP = PackageParser.NEW_PERMISSIONS.length; 9894 for (int ip=0; ip<NP; ip++) { 9895 final PackageParser.NewPermissionInfo npi 9896 = PackageParser.NEW_PERMISSIONS[ip]; 9897 if (npi.name.equals(perm) 9898 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9899 allowed = true; 9900 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9901 + pkg.packageName); 9902 break; 9903 } 9904 } 9905 return allowed; 9906 } 9907 9908 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9909 BasePermission bp, PermissionsState origPermissions) { 9910 boolean allowed; 9911 allowed = (compareSignatures( 9912 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9913 == PackageManager.SIGNATURE_MATCH) 9914 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9915 == PackageManager.SIGNATURE_MATCH); 9916 if (!allowed && (bp.protectionLevel 9917 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9918 if (isSystemApp(pkg)) { 9919 // For updated system applications, a system permission 9920 // is granted only if it had been defined by the original application. 9921 if (pkg.isUpdatedSystemApp()) { 9922 final PackageSetting sysPs = mSettings 9923 .getDisabledSystemPkgLPr(pkg.packageName); 9924 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9925 // If the original was granted this permission, we take 9926 // that grant decision as read and propagate it to the 9927 // update. 9928 if (sysPs.isPrivileged()) { 9929 allowed = true; 9930 } 9931 } else { 9932 // The system apk may have been updated with an older 9933 // version of the one on the data partition, but which 9934 // granted a new system permission that it didn't have 9935 // before. In this case we do want to allow the app to 9936 // now get the new permission if the ancestral apk is 9937 // privileged to get it. 9938 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9939 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9940 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9941 allowed = true; 9942 break; 9943 } 9944 } 9945 } 9946 // Also if a privileged parent package on the system image or any of 9947 // its children requested a privileged permission, the updated child 9948 // packages can also get the permission. 9949 if (pkg.parentPackage != null) { 9950 final PackageSetting disabledSysParentPs = mSettings 9951 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9952 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9953 && disabledSysParentPs.isPrivileged()) { 9954 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9955 allowed = true; 9956 } else if (disabledSysParentPs.pkg.childPackages != null) { 9957 final int count = disabledSysParentPs.pkg.childPackages.size(); 9958 for (int i = 0; i < count; i++) { 9959 PackageParser.Package disabledSysChildPkg = 9960 disabledSysParentPs.pkg.childPackages.get(i); 9961 if (isPackageRequestingPermission(disabledSysChildPkg, 9962 perm)) { 9963 allowed = true; 9964 break; 9965 } 9966 } 9967 } 9968 } 9969 } 9970 } 9971 } else { 9972 allowed = isPrivilegedApp(pkg); 9973 } 9974 } 9975 } 9976 if (!allowed) { 9977 if (!allowed && (bp.protectionLevel 9978 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9979 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9980 // If this was a previously normal/dangerous permission that got moved 9981 // to a system permission as part of the runtime permission redesign, then 9982 // we still want to blindly grant it to old apps. 9983 allowed = true; 9984 } 9985 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9986 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9987 // If this permission is to be granted to the system installer and 9988 // this app is an installer, then it gets the permission. 9989 allowed = true; 9990 } 9991 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9992 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9993 // If this permission is to be granted to the system verifier and 9994 // this app is a verifier, then it gets the permission. 9995 allowed = true; 9996 } 9997 if (!allowed && (bp.protectionLevel 9998 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9999 && isSystemApp(pkg)) { 10000 // Any pre-installed system app is allowed to get this permission. 10001 allowed = true; 10002 } 10003 if (!allowed && (bp.protectionLevel 10004 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10005 // For development permissions, a development permission 10006 // is granted only if it was already granted. 10007 allowed = origPermissions.hasInstallPermission(perm); 10008 } 10009 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10010 && pkg.packageName.equals(mSetupWizardPackage)) { 10011 // If this permission is to be granted to the system setup wizard and 10012 // this app is a setup wizard, then it gets the permission. 10013 allowed = true; 10014 } 10015 } 10016 return allowed; 10017 } 10018 10019 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10020 final int permCount = pkg.requestedPermissions.size(); 10021 for (int j = 0; j < permCount; j++) { 10022 String requestedPermission = pkg.requestedPermissions.get(j); 10023 if (permission.equals(requestedPermission)) { 10024 return true; 10025 } 10026 } 10027 return false; 10028 } 10029 10030 final class ActivityIntentResolver 10031 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10033 boolean defaultOnly, int userId) { 10034 if (!sUserManager.exists(userId)) return null; 10035 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10036 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10037 } 10038 10039 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10040 int userId) { 10041 if (!sUserManager.exists(userId)) return null; 10042 mFlags = flags; 10043 return super.queryIntent(intent, resolvedType, 10044 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10045 } 10046 10047 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10048 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10049 if (!sUserManager.exists(userId)) return null; 10050 if (packageActivities == null) { 10051 return null; 10052 } 10053 mFlags = flags; 10054 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10055 final int N = packageActivities.size(); 10056 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10057 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10058 10059 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10060 for (int i = 0; i < N; ++i) { 10061 intentFilters = packageActivities.get(i).intents; 10062 if (intentFilters != null && intentFilters.size() > 0) { 10063 PackageParser.ActivityIntentInfo[] array = 10064 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10065 intentFilters.toArray(array); 10066 listCut.add(array); 10067 } 10068 } 10069 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10070 } 10071 10072 /** 10073 * Finds a privileged activity that matches the specified activity names. 10074 */ 10075 private PackageParser.Activity findMatchingActivity( 10076 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10077 for (PackageParser.Activity sysActivity : activityList) { 10078 if (sysActivity.info.name.equals(activityInfo.name)) { 10079 return sysActivity; 10080 } 10081 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10082 return sysActivity; 10083 } 10084 if (sysActivity.info.targetActivity != null) { 10085 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10086 return sysActivity; 10087 } 10088 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10089 return sysActivity; 10090 } 10091 } 10092 } 10093 return null; 10094 } 10095 10096 public class IterGenerator<E> { 10097 public Iterator<E> generate(ActivityIntentInfo info) { 10098 return null; 10099 } 10100 } 10101 10102 public class ActionIterGenerator extends IterGenerator<String> { 10103 @Override 10104 public Iterator<String> generate(ActivityIntentInfo info) { 10105 return info.actionsIterator(); 10106 } 10107 } 10108 10109 public class CategoriesIterGenerator extends IterGenerator<String> { 10110 @Override 10111 public Iterator<String> generate(ActivityIntentInfo info) { 10112 return info.categoriesIterator(); 10113 } 10114 } 10115 10116 public class SchemesIterGenerator extends IterGenerator<String> { 10117 @Override 10118 public Iterator<String> generate(ActivityIntentInfo info) { 10119 return info.schemesIterator(); 10120 } 10121 } 10122 10123 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10124 @Override 10125 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10126 return info.authoritiesIterator(); 10127 } 10128 } 10129 10130 /** 10131 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10132 * MODIFIED. Do not pass in a list that should not be changed. 10133 */ 10134 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10135 IterGenerator<T> generator, Iterator<T> searchIterator) { 10136 // loop through the set of actions; every one must be found in the intent filter 10137 while (searchIterator.hasNext()) { 10138 // we must have at least one filter in the list to consider a match 10139 if (intentList.size() == 0) { 10140 break; 10141 } 10142 10143 final T searchAction = searchIterator.next(); 10144 10145 // loop through the set of intent filters 10146 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10147 while (intentIter.hasNext()) { 10148 final ActivityIntentInfo intentInfo = intentIter.next(); 10149 boolean selectionFound = false; 10150 10151 // loop through the intent filter's selection criteria; at least one 10152 // of them must match the searched criteria 10153 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10154 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10155 final T intentSelection = intentSelectionIter.next(); 10156 if (intentSelection != null && intentSelection.equals(searchAction)) { 10157 selectionFound = true; 10158 break; 10159 } 10160 } 10161 10162 // the selection criteria wasn't found in this filter's set; this filter 10163 // is not a potential match 10164 if (!selectionFound) { 10165 intentIter.remove(); 10166 } 10167 } 10168 } 10169 } 10170 10171 private boolean isProtectedAction(ActivityIntentInfo filter) { 10172 final Iterator<String> actionsIter = filter.actionsIterator(); 10173 while (actionsIter != null && actionsIter.hasNext()) { 10174 final String filterAction = actionsIter.next(); 10175 if (PROTECTED_ACTIONS.contains(filterAction)) { 10176 return true; 10177 } 10178 } 10179 return false; 10180 } 10181 10182 /** 10183 * Adjusts the priority of the given intent filter according to policy. 10184 * <p> 10185 * <ul> 10186 * <li>The priority for non privileged applications is capped to '0'</li> 10187 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10188 * <li>The priority for unbundled updates to privileged applications is capped to the 10189 * priority defined on the system partition</li> 10190 * </ul> 10191 * <p> 10192 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10193 * allowed to obtain any priority on any action. 10194 */ 10195 private void adjustPriority( 10196 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10197 // nothing to do; priority is fine as-is 10198 if (intent.getPriority() <= 0) { 10199 return; 10200 } 10201 10202 final ActivityInfo activityInfo = intent.activity.info; 10203 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10204 10205 final boolean privilegedApp = 10206 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10207 if (!privilegedApp) { 10208 // non-privileged applications can never define a priority >0 10209 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10210 + " package: " + applicationInfo.packageName 10211 + " activity: " + intent.activity.className 10212 + " origPrio: " + intent.getPriority()); 10213 intent.setPriority(0); 10214 return; 10215 } 10216 10217 if (systemActivities == null) { 10218 // the system package is not disabled; we're parsing the system partition 10219 if (isProtectedAction(intent)) { 10220 if (mDeferProtectedFilters) { 10221 // We can't deal with these just yet. No component should ever obtain a 10222 // >0 priority for a protected actions, with ONE exception -- the setup 10223 // wizard. The setup wizard, however, cannot be known until we're able to 10224 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10225 // until all intent filters have been processed. Chicken, meet egg. 10226 // Let the filter temporarily have a high priority and rectify the 10227 // priorities after all system packages have been scanned. 10228 mProtectedFilters.add(intent); 10229 if (DEBUG_FILTERS) { 10230 Slog.i(TAG, "Protected action; save for later;" 10231 + " package: " + applicationInfo.packageName 10232 + " activity: " + intent.activity.className 10233 + " origPrio: " + intent.getPriority()); 10234 } 10235 return; 10236 } else { 10237 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10238 Slog.i(TAG, "No setup wizard;" 10239 + " All protected intents capped to priority 0"); 10240 } 10241 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10242 if (DEBUG_FILTERS) { 10243 Slog.i(TAG, "Found setup wizard;" 10244 + " allow priority " + intent.getPriority() + ";" 10245 + " package: " + intent.activity.info.packageName 10246 + " activity: " + intent.activity.className 10247 + " priority: " + intent.getPriority()); 10248 } 10249 // setup wizard gets whatever it wants 10250 return; 10251 } 10252 Slog.w(TAG, "Protected action; cap priority to 0;" 10253 + " package: " + intent.activity.info.packageName 10254 + " activity: " + intent.activity.className 10255 + " origPrio: " + intent.getPriority()); 10256 intent.setPriority(0); 10257 return; 10258 } 10259 } 10260 // privileged apps on the system image get whatever priority they request 10261 return; 10262 } 10263 10264 // privileged app unbundled update ... try to find the same activity 10265 final PackageParser.Activity foundActivity = 10266 findMatchingActivity(systemActivities, activityInfo); 10267 if (foundActivity == null) { 10268 // this is a new activity; it cannot obtain >0 priority 10269 if (DEBUG_FILTERS) { 10270 Slog.i(TAG, "New activity; cap priority to 0;" 10271 + " package: " + applicationInfo.packageName 10272 + " activity: " + intent.activity.className 10273 + " origPrio: " + intent.getPriority()); 10274 } 10275 intent.setPriority(0); 10276 return; 10277 } 10278 10279 // found activity, now check for filter equivalence 10280 10281 // a shallow copy is enough; we modify the list, not its contents 10282 final List<ActivityIntentInfo> intentListCopy = 10283 new ArrayList<>(foundActivity.intents); 10284 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10285 10286 // find matching action subsets 10287 final Iterator<String> actionsIterator = intent.actionsIterator(); 10288 if (actionsIterator != null) { 10289 getIntentListSubset( 10290 intentListCopy, new ActionIterGenerator(), actionsIterator); 10291 if (intentListCopy.size() == 0) { 10292 // no more intents to match; we're not equivalent 10293 if (DEBUG_FILTERS) { 10294 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10295 + " package: " + applicationInfo.packageName 10296 + " activity: " + intent.activity.className 10297 + " origPrio: " + intent.getPriority()); 10298 } 10299 intent.setPriority(0); 10300 return; 10301 } 10302 } 10303 10304 // find matching category subsets 10305 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10306 if (categoriesIterator != null) { 10307 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10308 categoriesIterator); 10309 if (intentListCopy.size() == 0) { 10310 // no more intents to match; we're not equivalent 10311 if (DEBUG_FILTERS) { 10312 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10313 + " package: " + applicationInfo.packageName 10314 + " activity: " + intent.activity.className 10315 + " origPrio: " + intent.getPriority()); 10316 } 10317 intent.setPriority(0); 10318 return; 10319 } 10320 } 10321 10322 // find matching schemes subsets 10323 final Iterator<String> schemesIterator = intent.schemesIterator(); 10324 if (schemesIterator != null) { 10325 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10326 schemesIterator); 10327 if (intentListCopy.size() == 0) { 10328 // no more intents to match; we're not equivalent 10329 if (DEBUG_FILTERS) { 10330 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10331 + " package: " + applicationInfo.packageName 10332 + " activity: " + intent.activity.className 10333 + " origPrio: " + intent.getPriority()); 10334 } 10335 intent.setPriority(0); 10336 return; 10337 } 10338 } 10339 10340 // find matching authorities subsets 10341 final Iterator<IntentFilter.AuthorityEntry> 10342 authoritiesIterator = intent.authoritiesIterator(); 10343 if (authoritiesIterator != null) { 10344 getIntentListSubset(intentListCopy, 10345 new AuthoritiesIterGenerator(), 10346 authoritiesIterator); 10347 if (intentListCopy.size() == 0) { 10348 // no more intents to match; we're not equivalent 10349 if (DEBUG_FILTERS) { 10350 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10351 + " package: " + applicationInfo.packageName 10352 + " activity: " + intent.activity.className 10353 + " origPrio: " + intent.getPriority()); 10354 } 10355 intent.setPriority(0); 10356 return; 10357 } 10358 } 10359 10360 // we found matching filter(s); app gets the max priority of all intents 10361 int cappedPriority = 0; 10362 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10363 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10364 } 10365 if (intent.getPriority() > cappedPriority) { 10366 if (DEBUG_FILTERS) { 10367 Slog.i(TAG, "Found matching filter(s);" 10368 + " cap priority to " + cappedPriority + ";" 10369 + " package: " + applicationInfo.packageName 10370 + " activity: " + intent.activity.className 10371 + " origPrio: " + intent.getPriority()); 10372 } 10373 intent.setPriority(cappedPriority); 10374 return; 10375 } 10376 // all this for nothing; the requested priority was <= what was on the system 10377 } 10378 10379 public final void addActivity(PackageParser.Activity a, String type) { 10380 mActivities.put(a.getComponentName(), a); 10381 if (DEBUG_SHOW_INFO) 10382 Log.v( 10383 TAG, " " + type + " " + 10384 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10385 if (DEBUG_SHOW_INFO) 10386 Log.v(TAG, " Class=" + a.info.name); 10387 final int NI = a.intents.size(); 10388 for (int j=0; j<NI; j++) { 10389 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10390 if ("activity".equals(type)) { 10391 final PackageSetting ps = 10392 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10393 final List<PackageParser.Activity> systemActivities = 10394 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10395 adjustPriority(systemActivities, intent); 10396 } 10397 if (DEBUG_SHOW_INFO) { 10398 Log.v(TAG, " IntentFilter:"); 10399 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10400 } 10401 if (!intent.debugCheck()) { 10402 Log.w(TAG, "==> For Activity " + a.info.name); 10403 } 10404 addFilter(intent); 10405 } 10406 } 10407 10408 public final void removeActivity(PackageParser.Activity a, String type) { 10409 mActivities.remove(a.getComponentName()); 10410 if (DEBUG_SHOW_INFO) { 10411 Log.v(TAG, " " + type + " " 10412 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10413 : a.info.name) + ":"); 10414 Log.v(TAG, " Class=" + a.info.name); 10415 } 10416 final int NI = a.intents.size(); 10417 for (int j=0; j<NI; j++) { 10418 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10419 if (DEBUG_SHOW_INFO) { 10420 Log.v(TAG, " IntentFilter:"); 10421 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10422 } 10423 removeFilter(intent); 10424 } 10425 } 10426 10427 @Override 10428 protected boolean allowFilterResult( 10429 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10430 ActivityInfo filterAi = filter.activity.info; 10431 for (int i=dest.size()-1; i>=0; i--) { 10432 ActivityInfo destAi = dest.get(i).activityInfo; 10433 if (destAi.name == filterAi.name 10434 && destAi.packageName == filterAi.packageName) { 10435 return false; 10436 } 10437 } 10438 return true; 10439 } 10440 10441 @Override 10442 protected ActivityIntentInfo[] newArray(int size) { 10443 return new ActivityIntentInfo[size]; 10444 } 10445 10446 @Override 10447 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10448 if (!sUserManager.exists(userId)) return true; 10449 PackageParser.Package p = filter.activity.owner; 10450 if (p != null) { 10451 PackageSetting ps = (PackageSetting)p.mExtras; 10452 if (ps != null) { 10453 // System apps are never considered stopped for purposes of 10454 // filtering, because there may be no way for the user to 10455 // actually re-launch them. 10456 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10457 && ps.getStopped(userId); 10458 } 10459 } 10460 return false; 10461 } 10462 10463 @Override 10464 protected boolean isPackageForFilter(String packageName, 10465 PackageParser.ActivityIntentInfo info) { 10466 return packageName.equals(info.activity.owner.packageName); 10467 } 10468 10469 @Override 10470 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10471 int match, int userId) { 10472 if (!sUserManager.exists(userId)) return null; 10473 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10474 return null; 10475 } 10476 final PackageParser.Activity activity = info.activity; 10477 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10478 if (ps == null) { 10479 return null; 10480 } 10481 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10482 ps.readUserState(userId), userId); 10483 if (ai == null) { 10484 return null; 10485 } 10486 final ResolveInfo res = new ResolveInfo(); 10487 res.activityInfo = ai; 10488 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10489 res.filter = info; 10490 } 10491 if (info != null) { 10492 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10493 } 10494 res.priority = info.getPriority(); 10495 res.preferredOrder = activity.owner.mPreferredOrder; 10496 //System.out.println("Result: " + res.activityInfo.className + 10497 // " = " + res.priority); 10498 res.match = match; 10499 res.isDefault = info.hasDefault; 10500 res.labelRes = info.labelRes; 10501 res.nonLocalizedLabel = info.nonLocalizedLabel; 10502 if (userNeedsBadging(userId)) { 10503 res.noResourceId = true; 10504 } else { 10505 res.icon = info.icon; 10506 } 10507 res.iconResourceId = info.icon; 10508 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10509 return res; 10510 } 10511 10512 @Override 10513 protected void sortResults(List<ResolveInfo> results) { 10514 Collections.sort(results, mResolvePrioritySorter); 10515 } 10516 10517 @Override 10518 protected void dumpFilter(PrintWriter out, String prefix, 10519 PackageParser.ActivityIntentInfo filter) { 10520 out.print(prefix); out.print( 10521 Integer.toHexString(System.identityHashCode(filter.activity))); 10522 out.print(' '); 10523 filter.activity.printComponentShortName(out); 10524 out.print(" filter "); 10525 out.println(Integer.toHexString(System.identityHashCode(filter))); 10526 } 10527 10528 @Override 10529 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10530 return filter.activity; 10531 } 10532 10533 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10534 PackageParser.Activity activity = (PackageParser.Activity)label; 10535 out.print(prefix); out.print( 10536 Integer.toHexString(System.identityHashCode(activity))); 10537 out.print(' '); 10538 activity.printComponentShortName(out); 10539 if (count > 1) { 10540 out.print(" ("); out.print(count); out.print(" filters)"); 10541 } 10542 out.println(); 10543 } 10544 10545 // Keys are String (activity class name), values are Activity. 10546 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10547 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10548 private int mFlags; 10549 } 10550 10551 private final class ServiceIntentResolver 10552 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10553 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10554 boolean defaultOnly, int userId) { 10555 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10556 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10557 } 10558 10559 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10560 int userId) { 10561 if (!sUserManager.exists(userId)) return null; 10562 mFlags = flags; 10563 return super.queryIntent(intent, resolvedType, 10564 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10565 } 10566 10567 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10568 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10569 if (!sUserManager.exists(userId)) return null; 10570 if (packageServices == null) { 10571 return null; 10572 } 10573 mFlags = flags; 10574 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10575 final int N = packageServices.size(); 10576 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10577 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10578 10579 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10580 for (int i = 0; i < N; ++i) { 10581 intentFilters = packageServices.get(i).intents; 10582 if (intentFilters != null && intentFilters.size() > 0) { 10583 PackageParser.ServiceIntentInfo[] array = 10584 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10585 intentFilters.toArray(array); 10586 listCut.add(array); 10587 } 10588 } 10589 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10590 } 10591 10592 public final void addService(PackageParser.Service s) { 10593 mServices.put(s.getComponentName(), s); 10594 if (DEBUG_SHOW_INFO) { 10595 Log.v(TAG, " " 10596 + (s.info.nonLocalizedLabel != null 10597 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10598 Log.v(TAG, " Class=" + s.info.name); 10599 } 10600 final int NI = s.intents.size(); 10601 int j; 10602 for (j=0; j<NI; j++) { 10603 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10604 if (DEBUG_SHOW_INFO) { 10605 Log.v(TAG, " IntentFilter:"); 10606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10607 } 10608 if (!intent.debugCheck()) { 10609 Log.w(TAG, "==> For Service " + s.info.name); 10610 } 10611 addFilter(intent); 10612 } 10613 } 10614 10615 public final void removeService(PackageParser.Service s) { 10616 mServices.remove(s.getComponentName()); 10617 if (DEBUG_SHOW_INFO) { 10618 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10619 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10620 Log.v(TAG, " Class=" + s.info.name); 10621 } 10622 final int NI = s.intents.size(); 10623 int j; 10624 for (j=0; j<NI; j++) { 10625 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10626 if (DEBUG_SHOW_INFO) { 10627 Log.v(TAG, " IntentFilter:"); 10628 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10629 } 10630 removeFilter(intent); 10631 } 10632 } 10633 10634 @Override 10635 protected boolean allowFilterResult( 10636 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10637 ServiceInfo filterSi = filter.service.info; 10638 for (int i=dest.size()-1; i>=0; i--) { 10639 ServiceInfo destAi = dest.get(i).serviceInfo; 10640 if (destAi.name == filterSi.name 10641 && destAi.packageName == filterSi.packageName) { 10642 return false; 10643 } 10644 } 10645 return true; 10646 } 10647 10648 @Override 10649 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10650 return new PackageParser.ServiceIntentInfo[size]; 10651 } 10652 10653 @Override 10654 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10655 if (!sUserManager.exists(userId)) return true; 10656 PackageParser.Package p = filter.service.owner; 10657 if (p != null) { 10658 PackageSetting ps = (PackageSetting)p.mExtras; 10659 if (ps != null) { 10660 // System apps are never considered stopped for purposes of 10661 // filtering, because there may be no way for the user to 10662 // actually re-launch them. 10663 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10664 && ps.getStopped(userId); 10665 } 10666 } 10667 return false; 10668 } 10669 10670 @Override 10671 protected boolean isPackageForFilter(String packageName, 10672 PackageParser.ServiceIntentInfo info) { 10673 return packageName.equals(info.service.owner.packageName); 10674 } 10675 10676 @Override 10677 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10678 int match, int userId) { 10679 if (!sUserManager.exists(userId)) return null; 10680 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10681 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10682 return null; 10683 } 10684 final PackageParser.Service service = info.service; 10685 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10686 if (ps == null) { 10687 return null; 10688 } 10689 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10690 ps.readUserState(userId), userId); 10691 if (si == null) { 10692 return null; 10693 } 10694 final ResolveInfo res = new ResolveInfo(); 10695 res.serviceInfo = si; 10696 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10697 res.filter = filter; 10698 } 10699 res.priority = info.getPriority(); 10700 res.preferredOrder = service.owner.mPreferredOrder; 10701 res.match = match; 10702 res.isDefault = info.hasDefault; 10703 res.labelRes = info.labelRes; 10704 res.nonLocalizedLabel = info.nonLocalizedLabel; 10705 res.icon = info.icon; 10706 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10707 return res; 10708 } 10709 10710 @Override 10711 protected void sortResults(List<ResolveInfo> results) { 10712 Collections.sort(results, mResolvePrioritySorter); 10713 } 10714 10715 @Override 10716 protected void dumpFilter(PrintWriter out, String prefix, 10717 PackageParser.ServiceIntentInfo filter) { 10718 out.print(prefix); out.print( 10719 Integer.toHexString(System.identityHashCode(filter.service))); 10720 out.print(' '); 10721 filter.service.printComponentShortName(out); 10722 out.print(" filter "); 10723 out.println(Integer.toHexString(System.identityHashCode(filter))); 10724 } 10725 10726 @Override 10727 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10728 return filter.service; 10729 } 10730 10731 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10732 PackageParser.Service service = (PackageParser.Service)label; 10733 out.print(prefix); out.print( 10734 Integer.toHexString(System.identityHashCode(service))); 10735 out.print(' '); 10736 service.printComponentShortName(out); 10737 if (count > 1) { 10738 out.print(" ("); out.print(count); out.print(" filters)"); 10739 } 10740 out.println(); 10741 } 10742 10743// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10744// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10745// final List<ResolveInfo> retList = Lists.newArrayList(); 10746// while (i.hasNext()) { 10747// final ResolveInfo resolveInfo = (ResolveInfo) i; 10748// if (isEnabledLP(resolveInfo.serviceInfo)) { 10749// retList.add(resolveInfo); 10750// } 10751// } 10752// return retList; 10753// } 10754 10755 // Keys are String (activity class name), values are Activity. 10756 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10757 = new ArrayMap<ComponentName, PackageParser.Service>(); 10758 private int mFlags; 10759 }; 10760 10761 private final class ProviderIntentResolver 10762 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10763 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10764 boolean defaultOnly, int userId) { 10765 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10766 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10767 } 10768 10769 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10770 int userId) { 10771 if (!sUserManager.exists(userId)) 10772 return null; 10773 mFlags = flags; 10774 return super.queryIntent(intent, resolvedType, 10775 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10776 } 10777 10778 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10779 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10780 if (!sUserManager.exists(userId)) 10781 return null; 10782 if (packageProviders == null) { 10783 return null; 10784 } 10785 mFlags = flags; 10786 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10787 final int N = packageProviders.size(); 10788 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10789 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10790 10791 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10792 for (int i = 0; i < N; ++i) { 10793 intentFilters = packageProviders.get(i).intents; 10794 if (intentFilters != null && intentFilters.size() > 0) { 10795 PackageParser.ProviderIntentInfo[] array = 10796 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10797 intentFilters.toArray(array); 10798 listCut.add(array); 10799 } 10800 } 10801 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10802 } 10803 10804 public final void addProvider(PackageParser.Provider p) { 10805 if (mProviders.containsKey(p.getComponentName())) { 10806 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10807 return; 10808 } 10809 10810 mProviders.put(p.getComponentName(), p); 10811 if (DEBUG_SHOW_INFO) { 10812 Log.v(TAG, " " 10813 + (p.info.nonLocalizedLabel != null 10814 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10815 Log.v(TAG, " Class=" + p.info.name); 10816 } 10817 final int NI = p.intents.size(); 10818 int j; 10819 for (j = 0; j < NI; j++) { 10820 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10821 if (DEBUG_SHOW_INFO) { 10822 Log.v(TAG, " IntentFilter:"); 10823 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10824 } 10825 if (!intent.debugCheck()) { 10826 Log.w(TAG, "==> For Provider " + p.info.name); 10827 } 10828 addFilter(intent); 10829 } 10830 } 10831 10832 public final void removeProvider(PackageParser.Provider p) { 10833 mProviders.remove(p.getComponentName()); 10834 if (DEBUG_SHOW_INFO) { 10835 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10836 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10837 Log.v(TAG, " Class=" + p.info.name); 10838 } 10839 final int NI = p.intents.size(); 10840 int j; 10841 for (j = 0; j < NI; j++) { 10842 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10843 if (DEBUG_SHOW_INFO) { 10844 Log.v(TAG, " IntentFilter:"); 10845 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10846 } 10847 removeFilter(intent); 10848 } 10849 } 10850 10851 @Override 10852 protected boolean allowFilterResult( 10853 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10854 ProviderInfo filterPi = filter.provider.info; 10855 for (int i = dest.size() - 1; i >= 0; i--) { 10856 ProviderInfo destPi = dest.get(i).providerInfo; 10857 if (destPi.name == filterPi.name 10858 && destPi.packageName == filterPi.packageName) { 10859 return false; 10860 } 10861 } 10862 return true; 10863 } 10864 10865 @Override 10866 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10867 return new PackageParser.ProviderIntentInfo[size]; 10868 } 10869 10870 @Override 10871 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10872 if (!sUserManager.exists(userId)) 10873 return true; 10874 PackageParser.Package p = filter.provider.owner; 10875 if (p != null) { 10876 PackageSetting ps = (PackageSetting) p.mExtras; 10877 if (ps != null) { 10878 // System apps are never considered stopped for purposes of 10879 // filtering, because there may be no way for the user to 10880 // actually re-launch them. 10881 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10882 && ps.getStopped(userId); 10883 } 10884 } 10885 return false; 10886 } 10887 10888 @Override 10889 protected boolean isPackageForFilter(String packageName, 10890 PackageParser.ProviderIntentInfo info) { 10891 return packageName.equals(info.provider.owner.packageName); 10892 } 10893 10894 @Override 10895 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10896 int match, int userId) { 10897 if (!sUserManager.exists(userId)) 10898 return null; 10899 final PackageParser.ProviderIntentInfo info = filter; 10900 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10901 return null; 10902 } 10903 final PackageParser.Provider provider = info.provider; 10904 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10905 if (ps == null) { 10906 return null; 10907 } 10908 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10909 ps.readUserState(userId), userId); 10910 if (pi == null) { 10911 return null; 10912 } 10913 final ResolveInfo res = new ResolveInfo(); 10914 res.providerInfo = pi; 10915 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10916 res.filter = filter; 10917 } 10918 res.priority = info.getPriority(); 10919 res.preferredOrder = provider.owner.mPreferredOrder; 10920 res.match = match; 10921 res.isDefault = info.hasDefault; 10922 res.labelRes = info.labelRes; 10923 res.nonLocalizedLabel = info.nonLocalizedLabel; 10924 res.icon = info.icon; 10925 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10926 return res; 10927 } 10928 10929 @Override 10930 protected void sortResults(List<ResolveInfo> results) { 10931 Collections.sort(results, mResolvePrioritySorter); 10932 } 10933 10934 @Override 10935 protected void dumpFilter(PrintWriter out, String prefix, 10936 PackageParser.ProviderIntentInfo filter) { 10937 out.print(prefix); 10938 out.print( 10939 Integer.toHexString(System.identityHashCode(filter.provider))); 10940 out.print(' '); 10941 filter.provider.printComponentShortName(out); 10942 out.print(" filter "); 10943 out.println(Integer.toHexString(System.identityHashCode(filter))); 10944 } 10945 10946 @Override 10947 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10948 return filter.provider; 10949 } 10950 10951 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10952 PackageParser.Provider provider = (PackageParser.Provider)label; 10953 out.print(prefix); out.print( 10954 Integer.toHexString(System.identityHashCode(provider))); 10955 out.print(' '); 10956 provider.printComponentShortName(out); 10957 if (count > 1) { 10958 out.print(" ("); out.print(count); out.print(" filters)"); 10959 } 10960 out.println(); 10961 } 10962 10963 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10964 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10965 private int mFlags; 10966 } 10967 10968 private static final class EphemeralIntentResolver 10969 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10970 @Override 10971 protected EphemeralResolveIntentInfo[] newArray(int size) { 10972 return new EphemeralResolveIntentInfo[size]; 10973 } 10974 10975 @Override 10976 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10977 return true; 10978 } 10979 10980 @Override 10981 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10982 int userId) { 10983 if (!sUserManager.exists(userId)) { 10984 return null; 10985 } 10986 return info.getEphemeralResolveInfo(); 10987 } 10988 } 10989 10990 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10991 new Comparator<ResolveInfo>() { 10992 public int compare(ResolveInfo r1, ResolveInfo r2) { 10993 int v1 = r1.priority; 10994 int v2 = r2.priority; 10995 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10996 if (v1 != v2) { 10997 return (v1 > v2) ? -1 : 1; 10998 } 10999 v1 = r1.preferredOrder; 11000 v2 = r2.preferredOrder; 11001 if (v1 != v2) { 11002 return (v1 > v2) ? -1 : 1; 11003 } 11004 if (r1.isDefault != r2.isDefault) { 11005 return r1.isDefault ? -1 : 1; 11006 } 11007 v1 = r1.match; 11008 v2 = r2.match; 11009 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11010 if (v1 != v2) { 11011 return (v1 > v2) ? -1 : 1; 11012 } 11013 if (r1.system != r2.system) { 11014 return r1.system ? -1 : 1; 11015 } 11016 if (r1.activityInfo != null) { 11017 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11018 } 11019 if (r1.serviceInfo != null) { 11020 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11021 } 11022 if (r1.providerInfo != null) { 11023 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11024 } 11025 return 0; 11026 } 11027 }; 11028 11029 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11030 new Comparator<ProviderInfo>() { 11031 public int compare(ProviderInfo p1, ProviderInfo p2) { 11032 final int v1 = p1.initOrder; 11033 final int v2 = p2.initOrder; 11034 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11035 } 11036 }; 11037 11038 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11039 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11040 final int[] userIds) { 11041 mHandler.post(new Runnable() { 11042 @Override 11043 public void run() { 11044 try { 11045 final IActivityManager am = ActivityManagerNative.getDefault(); 11046 if (am == null) return; 11047 final int[] resolvedUserIds; 11048 if (userIds == null) { 11049 resolvedUserIds = am.getRunningUserIds(); 11050 } else { 11051 resolvedUserIds = userIds; 11052 } 11053 for (int id : resolvedUserIds) { 11054 final Intent intent = new Intent(action, 11055 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11056 if (extras != null) { 11057 intent.putExtras(extras); 11058 } 11059 if (targetPkg != null) { 11060 intent.setPackage(targetPkg); 11061 } 11062 // Modify the UID when posting to other users 11063 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11064 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11065 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11066 intent.putExtra(Intent.EXTRA_UID, uid); 11067 } 11068 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11069 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11070 if (DEBUG_BROADCASTS) { 11071 RuntimeException here = new RuntimeException("here"); 11072 here.fillInStackTrace(); 11073 Slog.d(TAG, "Sending to user " + id + ": " 11074 + intent.toShortString(false, true, false, false) 11075 + " " + intent.getExtras(), here); 11076 } 11077 am.broadcastIntent(null, intent, null, finishedReceiver, 11078 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11079 null, finishedReceiver != null, false, id); 11080 } 11081 } catch (RemoteException ex) { 11082 } 11083 } 11084 }); 11085 } 11086 11087 /** 11088 * Check if the external storage media is available. This is true if there 11089 * is a mounted external storage medium or if the external storage is 11090 * emulated. 11091 */ 11092 private boolean isExternalMediaAvailable() { 11093 return mMediaMounted || Environment.isExternalStorageEmulated(); 11094 } 11095 11096 @Override 11097 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11098 // writer 11099 synchronized (mPackages) { 11100 if (!isExternalMediaAvailable()) { 11101 // If the external storage is no longer mounted at this point, 11102 // the caller may not have been able to delete all of this 11103 // packages files and can not delete any more. Bail. 11104 return null; 11105 } 11106 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11107 if (lastPackage != null) { 11108 pkgs.remove(lastPackage); 11109 } 11110 if (pkgs.size() > 0) { 11111 return pkgs.get(0); 11112 } 11113 } 11114 return null; 11115 } 11116 11117 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11118 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11119 userId, andCode ? 1 : 0, packageName); 11120 if (mSystemReady) { 11121 msg.sendToTarget(); 11122 } else { 11123 if (mPostSystemReadyMessages == null) { 11124 mPostSystemReadyMessages = new ArrayList<>(); 11125 } 11126 mPostSystemReadyMessages.add(msg); 11127 } 11128 } 11129 11130 void startCleaningPackages() { 11131 // reader 11132 if (!isExternalMediaAvailable()) { 11133 return; 11134 } 11135 synchronized (mPackages) { 11136 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11137 return; 11138 } 11139 } 11140 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11141 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11142 IActivityManager am = ActivityManagerNative.getDefault(); 11143 if (am != null) { 11144 try { 11145 am.startService(null, intent, null, mContext.getOpPackageName(), 11146 UserHandle.USER_SYSTEM); 11147 } catch (RemoteException e) { 11148 } 11149 } 11150 } 11151 11152 @Override 11153 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11154 int installFlags, String installerPackageName, int userId) { 11155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11156 11157 final int callingUid = Binder.getCallingUid(); 11158 enforceCrossUserPermission(callingUid, userId, 11159 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11160 11161 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11162 try { 11163 if (observer != null) { 11164 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11165 } 11166 } catch (RemoteException re) { 11167 } 11168 return; 11169 } 11170 11171 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11172 installFlags |= PackageManager.INSTALL_FROM_ADB; 11173 11174 } else { 11175 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11176 // about installerPackageName. 11177 11178 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11179 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11180 } 11181 11182 UserHandle user; 11183 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11184 user = UserHandle.ALL; 11185 } else { 11186 user = new UserHandle(userId); 11187 } 11188 11189 // Only system components can circumvent runtime permissions when installing. 11190 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11191 && mContext.checkCallingOrSelfPermission(Manifest.permission 11192 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11193 throw new SecurityException("You need the " 11194 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11195 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11196 } 11197 11198 final File originFile = new File(originPath); 11199 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11200 11201 final Message msg = mHandler.obtainMessage(INIT_COPY); 11202 final VerificationInfo verificationInfo = new VerificationInfo( 11203 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11204 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11205 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11206 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11207 null /*certificates*/); 11208 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11209 msg.obj = params; 11210 11211 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11212 System.identityHashCode(msg.obj)); 11213 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11214 System.identityHashCode(msg.obj)); 11215 11216 mHandler.sendMessage(msg); 11217 } 11218 11219 void installStage(String packageName, File stagedDir, String stagedCid, 11220 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11221 String installerPackageName, int installerUid, UserHandle user, 11222 Certificate[][] certificates) { 11223 if (DEBUG_EPHEMERAL) { 11224 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11225 Slog.d(TAG, "Ephemeral install of " + packageName); 11226 } 11227 } 11228 final VerificationInfo verificationInfo = new VerificationInfo( 11229 sessionParams.originatingUri, sessionParams.referrerUri, 11230 sessionParams.originatingUid, installerUid); 11231 11232 final OriginInfo origin; 11233 if (stagedDir != null) { 11234 origin = OriginInfo.fromStagedFile(stagedDir); 11235 } else { 11236 origin = OriginInfo.fromStagedContainer(stagedCid); 11237 } 11238 11239 final Message msg = mHandler.obtainMessage(INIT_COPY); 11240 final InstallParams params = new InstallParams(origin, null, observer, 11241 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11242 verificationInfo, user, sessionParams.abiOverride, 11243 sessionParams.grantedRuntimePermissions, certificates); 11244 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11245 msg.obj = params; 11246 11247 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11248 System.identityHashCode(msg.obj)); 11249 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11250 System.identityHashCode(msg.obj)); 11251 11252 mHandler.sendMessage(msg); 11253 } 11254 11255 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11256 int userId) { 11257 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11258 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11259 } 11260 11261 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11262 int appId, int userId) { 11263 Bundle extras = new Bundle(1); 11264 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11265 11266 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11267 packageName, extras, 0, null, null, new int[] {userId}); 11268 try { 11269 IActivityManager am = ActivityManagerNative.getDefault(); 11270 if (isSystem && am.isUserRunning(userId, 0)) { 11271 // The just-installed/enabled app is bundled on the system, so presumed 11272 // to be able to run automatically without needing an explicit launch. 11273 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11274 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11275 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11276 .setPackage(packageName); 11277 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11278 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11279 } 11280 } catch (RemoteException e) { 11281 // shouldn't happen 11282 Slog.w(TAG, "Unable to bootstrap installed package", e); 11283 } 11284 } 11285 11286 @Override 11287 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11288 int userId) { 11289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11290 PackageSetting pkgSetting; 11291 final int uid = Binder.getCallingUid(); 11292 enforceCrossUserPermission(uid, userId, 11293 true /* requireFullPermission */, true /* checkShell */, 11294 "setApplicationHiddenSetting for user " + userId); 11295 11296 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11297 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11298 return false; 11299 } 11300 11301 long callingId = Binder.clearCallingIdentity(); 11302 try { 11303 boolean sendAdded = false; 11304 boolean sendRemoved = false; 11305 // writer 11306 synchronized (mPackages) { 11307 pkgSetting = mSettings.mPackages.get(packageName); 11308 if (pkgSetting == null) { 11309 return false; 11310 } 11311 if (pkgSetting.getHidden(userId) != hidden) { 11312 pkgSetting.setHidden(hidden, userId); 11313 mSettings.writePackageRestrictionsLPr(userId); 11314 if (hidden) { 11315 sendRemoved = true; 11316 } else { 11317 sendAdded = true; 11318 } 11319 } 11320 } 11321 if (sendAdded) { 11322 sendPackageAddedForUser(packageName, pkgSetting, userId); 11323 return true; 11324 } 11325 if (sendRemoved) { 11326 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11327 "hiding pkg"); 11328 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11329 return true; 11330 } 11331 } finally { 11332 Binder.restoreCallingIdentity(callingId); 11333 } 11334 return false; 11335 } 11336 11337 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11338 int userId) { 11339 final PackageRemovedInfo info = new PackageRemovedInfo(); 11340 info.removedPackage = packageName; 11341 info.removedUsers = new int[] {userId}; 11342 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11343 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11344 } 11345 11346 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11347 if (pkgList.length > 0) { 11348 Bundle extras = new Bundle(1); 11349 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11350 11351 sendPackageBroadcast( 11352 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11353 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11354 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11355 new int[] {userId}); 11356 } 11357 } 11358 11359 /** 11360 * Returns true if application is not found or there was an error. Otherwise it returns 11361 * the hidden state of the package for the given user. 11362 */ 11363 @Override 11364 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11367 true /* requireFullPermission */, false /* checkShell */, 11368 "getApplicationHidden for user " + userId); 11369 PackageSetting pkgSetting; 11370 long callingId = Binder.clearCallingIdentity(); 11371 try { 11372 // writer 11373 synchronized (mPackages) { 11374 pkgSetting = mSettings.mPackages.get(packageName); 11375 if (pkgSetting == null) { 11376 return true; 11377 } 11378 return pkgSetting.getHidden(userId); 11379 } 11380 } finally { 11381 Binder.restoreCallingIdentity(callingId); 11382 } 11383 } 11384 11385 /** 11386 * @hide 11387 */ 11388 @Override 11389 public int installExistingPackageAsUser(String packageName, int userId) { 11390 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11391 null); 11392 PackageSetting pkgSetting; 11393 final int uid = Binder.getCallingUid(); 11394 enforceCrossUserPermission(uid, userId, 11395 true /* requireFullPermission */, true /* checkShell */, 11396 "installExistingPackage for user " + userId); 11397 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11398 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11399 } 11400 11401 long callingId = Binder.clearCallingIdentity(); 11402 try { 11403 boolean installed = false; 11404 11405 // writer 11406 synchronized (mPackages) { 11407 pkgSetting = mSettings.mPackages.get(packageName); 11408 if (pkgSetting == null) { 11409 return PackageManager.INSTALL_FAILED_INVALID_URI; 11410 } 11411 if (!pkgSetting.getInstalled(userId)) { 11412 pkgSetting.setInstalled(true, userId); 11413 pkgSetting.setHidden(false, userId); 11414 mSettings.writePackageRestrictionsLPr(userId); 11415 installed = true; 11416 } 11417 } 11418 11419 if (installed) { 11420 if (pkgSetting.pkg != null) { 11421 synchronized (mInstallLock) { 11422 // We don't need to freeze for a brand new install 11423 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11424 } 11425 } 11426 sendPackageAddedForUser(packageName, pkgSetting, userId); 11427 } 11428 } finally { 11429 Binder.restoreCallingIdentity(callingId); 11430 } 11431 11432 return PackageManager.INSTALL_SUCCEEDED; 11433 } 11434 11435 boolean isUserRestricted(int userId, String restrictionKey) { 11436 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11437 if (restrictions.getBoolean(restrictionKey, false)) { 11438 Log.w(TAG, "User is restricted: " + restrictionKey); 11439 return true; 11440 } 11441 return false; 11442 } 11443 11444 @Override 11445 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11446 int userId) { 11447 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11448 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11449 true /* requireFullPermission */, true /* checkShell */, 11450 "setPackagesSuspended for user " + userId); 11451 11452 if (ArrayUtils.isEmpty(packageNames)) { 11453 return packageNames; 11454 } 11455 11456 // List of package names for whom the suspended state has changed. 11457 List<String> changedPackages = new ArrayList<>(packageNames.length); 11458 // List of package names for whom the suspended state is not set as requested in this 11459 // method. 11460 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11461 for (int i = 0; i < packageNames.length; i++) { 11462 String packageName = packageNames[i]; 11463 long callingId = Binder.clearCallingIdentity(); 11464 try { 11465 boolean changed = false; 11466 final int appId; 11467 synchronized (mPackages) { 11468 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11469 if (pkgSetting == null) { 11470 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11471 + "\". Skipping suspending/un-suspending."); 11472 unactionedPackages.add(packageName); 11473 continue; 11474 } 11475 appId = pkgSetting.appId; 11476 if (pkgSetting.getSuspended(userId) != suspended) { 11477 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11478 unactionedPackages.add(packageName); 11479 continue; 11480 } 11481 pkgSetting.setSuspended(suspended, userId); 11482 mSettings.writePackageRestrictionsLPr(userId); 11483 changed = true; 11484 changedPackages.add(packageName); 11485 } 11486 } 11487 11488 if (changed && suspended) { 11489 killApplication(packageName, UserHandle.getUid(userId, appId), 11490 "suspending package"); 11491 } 11492 } finally { 11493 Binder.restoreCallingIdentity(callingId); 11494 } 11495 } 11496 11497 if (!changedPackages.isEmpty()) { 11498 sendPackagesSuspendedForUser(changedPackages.toArray( 11499 new String[changedPackages.size()]), userId, suspended); 11500 } 11501 11502 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11503 } 11504 11505 @Override 11506 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11507 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11508 true /* requireFullPermission */, false /* checkShell */, 11509 "isPackageSuspendedForUser for user " + userId); 11510 synchronized (mPackages) { 11511 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11512 if (pkgSetting == null) { 11513 throw new IllegalArgumentException("Unknown target package: " + packageName); 11514 } 11515 return pkgSetting.getSuspended(userId); 11516 } 11517 } 11518 11519 /** 11520 * TODO: cache and disallow blocking the active dialer. 11521 * 11522 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11523 */ 11524 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11525 if (isPackageDeviceAdmin(packageName, userId)) { 11526 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11527 + "\": has an active device admin"); 11528 return false; 11529 } 11530 11531 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11532 if (packageName.equals(activeLauncherPackageName)) { 11533 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11534 + "\": contains the active launcher"); 11535 return false; 11536 } 11537 11538 if (packageName.equals(mRequiredInstallerPackage)) { 11539 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11540 + "\": required for package installation"); 11541 return false; 11542 } 11543 11544 if (packageName.equals(mRequiredVerifierPackage)) { 11545 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11546 + "\": required for package verification"); 11547 return false; 11548 } 11549 11550 final PackageParser.Package pkg = mPackages.get(packageName); 11551 if (pkg != null && isPrivilegedApp(pkg)) { 11552 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11553 + "\": is a privileged app"); 11554 return false; 11555 } 11556 11557 return true; 11558 } 11559 11560 private String getActiveLauncherPackageName(int userId) { 11561 Intent intent = new Intent(Intent.ACTION_MAIN); 11562 intent.addCategory(Intent.CATEGORY_HOME); 11563 ResolveInfo resolveInfo = resolveIntent( 11564 intent, 11565 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11566 PackageManager.MATCH_DEFAULT_ONLY, 11567 userId); 11568 11569 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11570 } 11571 11572 @Override 11573 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11574 mContext.enforceCallingOrSelfPermission( 11575 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11576 "Only package verification agents can verify applications"); 11577 11578 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11579 final PackageVerificationResponse response = new PackageVerificationResponse( 11580 verificationCode, Binder.getCallingUid()); 11581 msg.arg1 = id; 11582 msg.obj = response; 11583 mHandler.sendMessage(msg); 11584 } 11585 11586 @Override 11587 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11588 long millisecondsToDelay) { 11589 mContext.enforceCallingOrSelfPermission( 11590 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11591 "Only package verification agents can extend verification timeouts"); 11592 11593 final PackageVerificationState state = mPendingVerification.get(id); 11594 final PackageVerificationResponse response = new PackageVerificationResponse( 11595 verificationCodeAtTimeout, Binder.getCallingUid()); 11596 11597 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11598 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11599 } 11600 if (millisecondsToDelay < 0) { 11601 millisecondsToDelay = 0; 11602 } 11603 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11604 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11605 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11606 } 11607 11608 if ((state != null) && !state.timeoutExtended()) { 11609 state.extendTimeout(); 11610 11611 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11612 msg.arg1 = id; 11613 msg.obj = response; 11614 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11615 } 11616 } 11617 11618 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11619 int verificationCode, UserHandle user) { 11620 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11621 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11622 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11623 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11624 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11625 11626 mContext.sendBroadcastAsUser(intent, user, 11627 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11628 } 11629 11630 private ComponentName matchComponentForVerifier(String packageName, 11631 List<ResolveInfo> receivers) { 11632 ActivityInfo targetReceiver = null; 11633 11634 final int NR = receivers.size(); 11635 for (int i = 0; i < NR; i++) { 11636 final ResolveInfo info = receivers.get(i); 11637 if (info.activityInfo == null) { 11638 continue; 11639 } 11640 11641 if (packageName.equals(info.activityInfo.packageName)) { 11642 targetReceiver = info.activityInfo; 11643 break; 11644 } 11645 } 11646 11647 if (targetReceiver == null) { 11648 return null; 11649 } 11650 11651 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11652 } 11653 11654 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11655 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11656 if (pkgInfo.verifiers.length == 0) { 11657 return null; 11658 } 11659 11660 final int N = pkgInfo.verifiers.length; 11661 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11662 for (int i = 0; i < N; i++) { 11663 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11664 11665 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11666 receivers); 11667 if (comp == null) { 11668 continue; 11669 } 11670 11671 final int verifierUid = getUidForVerifier(verifierInfo); 11672 if (verifierUid == -1) { 11673 continue; 11674 } 11675 11676 if (DEBUG_VERIFY) { 11677 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11678 + " with the correct signature"); 11679 } 11680 sufficientVerifiers.add(comp); 11681 verificationState.addSufficientVerifier(verifierUid); 11682 } 11683 11684 return sufficientVerifiers; 11685 } 11686 11687 private int getUidForVerifier(VerifierInfo verifierInfo) { 11688 synchronized (mPackages) { 11689 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11690 if (pkg == null) { 11691 return -1; 11692 } else if (pkg.mSignatures.length != 1) { 11693 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11694 + " has more than one signature; ignoring"); 11695 return -1; 11696 } 11697 11698 /* 11699 * If the public key of the package's signature does not match 11700 * our expected public key, then this is a different package and 11701 * we should skip. 11702 */ 11703 11704 final byte[] expectedPublicKey; 11705 try { 11706 final Signature verifierSig = pkg.mSignatures[0]; 11707 final PublicKey publicKey = verifierSig.getPublicKey(); 11708 expectedPublicKey = publicKey.getEncoded(); 11709 } catch (CertificateException e) { 11710 return -1; 11711 } 11712 11713 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11714 11715 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11716 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11717 + " does not have the expected public key; ignoring"); 11718 return -1; 11719 } 11720 11721 return pkg.applicationInfo.uid; 11722 } 11723 } 11724 11725 @Override 11726 public void finishPackageInstall(int token) { 11727 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11728 11729 if (DEBUG_INSTALL) { 11730 Slog.v(TAG, "BM finishing package install for " + token); 11731 } 11732 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11733 11734 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11735 mHandler.sendMessage(msg); 11736 } 11737 11738 /** 11739 * Get the verification agent timeout. 11740 * 11741 * @return verification timeout in milliseconds 11742 */ 11743 private long getVerificationTimeout() { 11744 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11745 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11746 DEFAULT_VERIFICATION_TIMEOUT); 11747 } 11748 11749 /** 11750 * Get the default verification agent response code. 11751 * 11752 * @return default verification response code 11753 */ 11754 private int getDefaultVerificationResponse() { 11755 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11756 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11757 DEFAULT_VERIFICATION_RESPONSE); 11758 } 11759 11760 /** 11761 * Check whether or not package verification has been enabled. 11762 * 11763 * @return true if verification should be performed 11764 */ 11765 private boolean isVerificationEnabled(int userId, int installFlags) { 11766 if (!DEFAULT_VERIFY_ENABLE) { 11767 return false; 11768 } 11769 // Ephemeral apps don't get the full verification treatment 11770 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11771 if (DEBUG_EPHEMERAL) { 11772 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11773 } 11774 return false; 11775 } 11776 11777 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11778 11779 // Check if installing from ADB 11780 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11781 // Do not run verification in a test harness environment 11782 if (ActivityManager.isRunningInTestHarness()) { 11783 return false; 11784 } 11785 if (ensureVerifyAppsEnabled) { 11786 return true; 11787 } 11788 // Check if the developer does not want package verification for ADB installs 11789 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11790 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11791 return false; 11792 } 11793 } 11794 11795 if (ensureVerifyAppsEnabled) { 11796 return true; 11797 } 11798 11799 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11800 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11801 } 11802 11803 @Override 11804 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11805 throws RemoteException { 11806 mContext.enforceCallingOrSelfPermission( 11807 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11808 "Only intentfilter verification agents can verify applications"); 11809 11810 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11811 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11812 Binder.getCallingUid(), verificationCode, failedDomains); 11813 msg.arg1 = id; 11814 msg.obj = response; 11815 mHandler.sendMessage(msg); 11816 } 11817 11818 @Override 11819 public int getIntentVerificationStatus(String packageName, int userId) { 11820 synchronized (mPackages) { 11821 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11822 } 11823 } 11824 11825 @Override 11826 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11827 mContext.enforceCallingOrSelfPermission( 11828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11829 11830 boolean result = false; 11831 synchronized (mPackages) { 11832 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11833 } 11834 if (result) { 11835 scheduleWritePackageRestrictionsLocked(userId); 11836 } 11837 return result; 11838 } 11839 11840 @Override 11841 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11842 String packageName) { 11843 synchronized (mPackages) { 11844 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11845 } 11846 } 11847 11848 @Override 11849 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11850 if (TextUtils.isEmpty(packageName)) { 11851 return ParceledListSlice.emptyList(); 11852 } 11853 synchronized (mPackages) { 11854 PackageParser.Package pkg = mPackages.get(packageName); 11855 if (pkg == null || pkg.activities == null) { 11856 return ParceledListSlice.emptyList(); 11857 } 11858 final int count = pkg.activities.size(); 11859 ArrayList<IntentFilter> result = new ArrayList<>(); 11860 for (int n=0; n<count; n++) { 11861 PackageParser.Activity activity = pkg.activities.get(n); 11862 if (activity.intents != null && activity.intents.size() > 0) { 11863 result.addAll(activity.intents); 11864 } 11865 } 11866 return new ParceledListSlice<>(result); 11867 } 11868 } 11869 11870 @Override 11871 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11872 mContext.enforceCallingOrSelfPermission( 11873 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11874 11875 synchronized (mPackages) { 11876 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11877 if (packageName != null) { 11878 result |= updateIntentVerificationStatus(packageName, 11879 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11880 userId); 11881 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11882 packageName, userId); 11883 } 11884 return result; 11885 } 11886 } 11887 11888 @Override 11889 public String getDefaultBrowserPackageName(int userId) { 11890 synchronized (mPackages) { 11891 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11892 } 11893 } 11894 11895 /** 11896 * Get the "allow unknown sources" setting. 11897 * 11898 * @return the current "allow unknown sources" setting 11899 */ 11900 private int getUnknownSourcesSettings() { 11901 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11902 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11903 -1); 11904 } 11905 11906 @Override 11907 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11908 final int uid = Binder.getCallingUid(); 11909 // writer 11910 synchronized (mPackages) { 11911 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11912 if (targetPackageSetting == null) { 11913 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11914 } 11915 11916 PackageSetting installerPackageSetting; 11917 if (installerPackageName != null) { 11918 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11919 if (installerPackageSetting == null) { 11920 throw new IllegalArgumentException("Unknown installer package: " 11921 + installerPackageName); 11922 } 11923 } else { 11924 installerPackageSetting = null; 11925 } 11926 11927 Signature[] callerSignature; 11928 Object obj = mSettings.getUserIdLPr(uid); 11929 if (obj != null) { 11930 if (obj instanceof SharedUserSetting) { 11931 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11932 } else if (obj instanceof PackageSetting) { 11933 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11934 } else { 11935 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11936 } 11937 } else { 11938 throw new SecurityException("Unknown calling UID: " + uid); 11939 } 11940 11941 // Verify: can't set installerPackageName to a package that is 11942 // not signed with the same cert as the caller. 11943 if (installerPackageSetting != null) { 11944 if (compareSignatures(callerSignature, 11945 installerPackageSetting.signatures.mSignatures) 11946 != PackageManager.SIGNATURE_MATCH) { 11947 throw new SecurityException( 11948 "Caller does not have same cert as new installer package " 11949 + installerPackageName); 11950 } 11951 } 11952 11953 // Verify: if target already has an installer package, it must 11954 // be signed with the same cert as the caller. 11955 if (targetPackageSetting.installerPackageName != null) { 11956 PackageSetting setting = mSettings.mPackages.get( 11957 targetPackageSetting.installerPackageName); 11958 // If the currently set package isn't valid, then it's always 11959 // okay to change it. 11960 if (setting != null) { 11961 if (compareSignatures(callerSignature, 11962 setting.signatures.mSignatures) 11963 != PackageManager.SIGNATURE_MATCH) { 11964 throw new SecurityException( 11965 "Caller does not have same cert as old installer package " 11966 + targetPackageSetting.installerPackageName); 11967 } 11968 } 11969 } 11970 11971 // Okay! 11972 targetPackageSetting.installerPackageName = installerPackageName; 11973 if (installerPackageName != null) { 11974 mSettings.mInstallerPackages.add(installerPackageName); 11975 } 11976 scheduleWriteSettingsLocked(); 11977 } 11978 } 11979 11980 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11981 // Queue up an async operation since the package installation may take a little while. 11982 mHandler.post(new Runnable() { 11983 public void run() { 11984 mHandler.removeCallbacks(this); 11985 // Result object to be returned 11986 PackageInstalledInfo res = new PackageInstalledInfo(); 11987 res.setReturnCode(currentStatus); 11988 res.uid = -1; 11989 res.pkg = null; 11990 res.removedInfo = null; 11991 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11992 args.doPreInstall(res.returnCode); 11993 synchronized (mInstallLock) { 11994 installPackageTracedLI(args, res); 11995 } 11996 args.doPostInstall(res.returnCode, res.uid); 11997 } 11998 11999 // A restore should be performed at this point if (a) the install 12000 // succeeded, (b) the operation is not an update, and (c) the new 12001 // package has not opted out of backup participation. 12002 final boolean update = res.removedInfo != null 12003 && res.removedInfo.removedPackage != null; 12004 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12005 boolean doRestore = !update 12006 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12007 12008 // Set up the post-install work request bookkeeping. This will be used 12009 // and cleaned up by the post-install event handling regardless of whether 12010 // there's a restore pass performed. Token values are >= 1. 12011 int token; 12012 if (mNextInstallToken < 0) mNextInstallToken = 1; 12013 token = mNextInstallToken++; 12014 12015 PostInstallData data = new PostInstallData(args, res); 12016 mRunningInstalls.put(token, data); 12017 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12018 12019 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12020 // Pass responsibility to the Backup Manager. It will perform a 12021 // restore if appropriate, then pass responsibility back to the 12022 // Package Manager to run the post-install observer callbacks 12023 // and broadcasts. 12024 IBackupManager bm = IBackupManager.Stub.asInterface( 12025 ServiceManager.getService(Context.BACKUP_SERVICE)); 12026 if (bm != null) { 12027 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12028 + " to BM for possible restore"); 12029 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12030 try { 12031 // TODO: http://b/22388012 12032 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12033 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12034 } else { 12035 doRestore = false; 12036 } 12037 } catch (RemoteException e) { 12038 // can't happen; the backup manager is local 12039 } catch (Exception e) { 12040 Slog.e(TAG, "Exception trying to enqueue restore", e); 12041 doRestore = false; 12042 } 12043 } else { 12044 Slog.e(TAG, "Backup Manager not found!"); 12045 doRestore = false; 12046 } 12047 } 12048 12049 if (!doRestore) { 12050 // No restore possible, or the Backup Manager was mysteriously not 12051 // available -- just fire the post-install work request directly. 12052 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12053 12054 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12055 12056 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12057 mHandler.sendMessage(msg); 12058 } 12059 } 12060 }); 12061 } 12062 12063 private abstract class HandlerParams { 12064 private static final int MAX_RETRIES = 4; 12065 12066 /** 12067 * Number of times startCopy() has been attempted and had a non-fatal 12068 * error. 12069 */ 12070 private int mRetries = 0; 12071 12072 /** User handle for the user requesting the information or installation. */ 12073 private final UserHandle mUser; 12074 String traceMethod; 12075 int traceCookie; 12076 12077 HandlerParams(UserHandle user) { 12078 mUser = user; 12079 } 12080 12081 UserHandle getUser() { 12082 return mUser; 12083 } 12084 12085 HandlerParams setTraceMethod(String traceMethod) { 12086 this.traceMethod = traceMethod; 12087 return this; 12088 } 12089 12090 HandlerParams setTraceCookie(int traceCookie) { 12091 this.traceCookie = traceCookie; 12092 return this; 12093 } 12094 12095 final boolean startCopy() { 12096 boolean res; 12097 try { 12098 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12099 12100 if (++mRetries > MAX_RETRIES) { 12101 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12102 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12103 handleServiceError(); 12104 return false; 12105 } else { 12106 handleStartCopy(); 12107 res = true; 12108 } 12109 } catch (RemoteException e) { 12110 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12111 mHandler.sendEmptyMessage(MCS_RECONNECT); 12112 res = false; 12113 } 12114 handleReturnCode(); 12115 return res; 12116 } 12117 12118 final void serviceError() { 12119 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12120 handleServiceError(); 12121 handleReturnCode(); 12122 } 12123 12124 abstract void handleStartCopy() throws RemoteException; 12125 abstract void handleServiceError(); 12126 abstract void handleReturnCode(); 12127 } 12128 12129 class MeasureParams extends HandlerParams { 12130 private final PackageStats mStats; 12131 private boolean mSuccess; 12132 12133 private final IPackageStatsObserver mObserver; 12134 12135 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12136 super(new UserHandle(stats.userHandle)); 12137 mObserver = observer; 12138 mStats = stats; 12139 } 12140 12141 @Override 12142 public String toString() { 12143 return "MeasureParams{" 12144 + Integer.toHexString(System.identityHashCode(this)) 12145 + " " + mStats.packageName + "}"; 12146 } 12147 12148 @Override 12149 void handleStartCopy() throws RemoteException { 12150 synchronized (mInstallLock) { 12151 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12152 } 12153 12154 if (mSuccess) { 12155 final boolean mounted; 12156 if (Environment.isExternalStorageEmulated()) { 12157 mounted = true; 12158 } else { 12159 final String status = Environment.getExternalStorageState(); 12160 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12161 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12162 } 12163 12164 if (mounted) { 12165 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12166 12167 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12168 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12169 12170 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12171 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12172 12173 // Always subtract cache size, since it's a subdirectory 12174 mStats.externalDataSize -= mStats.externalCacheSize; 12175 12176 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12177 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12178 12179 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12180 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12181 } 12182 } 12183 } 12184 12185 @Override 12186 void handleReturnCode() { 12187 if (mObserver != null) { 12188 try { 12189 mObserver.onGetStatsCompleted(mStats, mSuccess); 12190 } catch (RemoteException e) { 12191 Slog.i(TAG, "Observer no longer exists."); 12192 } 12193 } 12194 } 12195 12196 @Override 12197 void handleServiceError() { 12198 Slog.e(TAG, "Could not measure application " + mStats.packageName 12199 + " external storage"); 12200 } 12201 } 12202 12203 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12204 throws RemoteException { 12205 long result = 0; 12206 for (File path : paths) { 12207 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12208 } 12209 return result; 12210 } 12211 12212 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12213 for (File path : paths) { 12214 try { 12215 mcs.clearDirectory(path.getAbsolutePath()); 12216 } catch (RemoteException e) { 12217 } 12218 } 12219 } 12220 12221 static class OriginInfo { 12222 /** 12223 * Location where install is coming from, before it has been 12224 * copied/renamed into place. This could be a single monolithic APK 12225 * file, or a cluster directory. This location may be untrusted. 12226 */ 12227 final File file; 12228 final String cid; 12229 12230 /** 12231 * Flag indicating that {@link #file} or {@link #cid} has already been 12232 * staged, meaning downstream users don't need to defensively copy the 12233 * contents. 12234 */ 12235 final boolean staged; 12236 12237 /** 12238 * Flag indicating that {@link #file} or {@link #cid} is an already 12239 * installed app that is being moved. 12240 */ 12241 final boolean existing; 12242 12243 final String resolvedPath; 12244 final File resolvedFile; 12245 12246 static OriginInfo fromNothing() { 12247 return new OriginInfo(null, null, false, false); 12248 } 12249 12250 static OriginInfo fromUntrustedFile(File file) { 12251 return new OriginInfo(file, null, false, false); 12252 } 12253 12254 static OriginInfo fromExistingFile(File file) { 12255 return new OriginInfo(file, null, false, true); 12256 } 12257 12258 static OriginInfo fromStagedFile(File file) { 12259 return new OriginInfo(file, null, true, false); 12260 } 12261 12262 static OriginInfo fromStagedContainer(String cid) { 12263 return new OriginInfo(null, cid, true, false); 12264 } 12265 12266 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12267 this.file = file; 12268 this.cid = cid; 12269 this.staged = staged; 12270 this.existing = existing; 12271 12272 if (cid != null) { 12273 resolvedPath = PackageHelper.getSdDir(cid); 12274 resolvedFile = new File(resolvedPath); 12275 } else if (file != null) { 12276 resolvedPath = file.getAbsolutePath(); 12277 resolvedFile = file; 12278 } else { 12279 resolvedPath = null; 12280 resolvedFile = null; 12281 } 12282 } 12283 } 12284 12285 static class MoveInfo { 12286 final int moveId; 12287 final String fromUuid; 12288 final String toUuid; 12289 final String packageName; 12290 final String dataAppName; 12291 final int appId; 12292 final String seinfo; 12293 final int targetSdkVersion; 12294 12295 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12296 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12297 this.moveId = moveId; 12298 this.fromUuid = fromUuid; 12299 this.toUuid = toUuid; 12300 this.packageName = packageName; 12301 this.dataAppName = dataAppName; 12302 this.appId = appId; 12303 this.seinfo = seinfo; 12304 this.targetSdkVersion = targetSdkVersion; 12305 } 12306 } 12307 12308 static class VerificationInfo { 12309 /** A constant used to indicate that a uid value is not present. */ 12310 public static final int NO_UID = -1; 12311 12312 /** URI referencing where the package was downloaded from. */ 12313 final Uri originatingUri; 12314 12315 /** HTTP referrer URI associated with the originatingURI. */ 12316 final Uri referrer; 12317 12318 /** UID of the application that the install request originated from. */ 12319 final int originatingUid; 12320 12321 /** UID of application requesting the install */ 12322 final int installerUid; 12323 12324 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12325 this.originatingUri = originatingUri; 12326 this.referrer = referrer; 12327 this.originatingUid = originatingUid; 12328 this.installerUid = installerUid; 12329 } 12330 } 12331 12332 class InstallParams extends HandlerParams { 12333 final OriginInfo origin; 12334 final MoveInfo move; 12335 final IPackageInstallObserver2 observer; 12336 int installFlags; 12337 final String installerPackageName; 12338 final String volumeUuid; 12339 private InstallArgs mArgs; 12340 private int mRet; 12341 final String packageAbiOverride; 12342 final String[] grantedRuntimePermissions; 12343 final VerificationInfo verificationInfo; 12344 final Certificate[][] certificates; 12345 12346 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12347 int installFlags, String installerPackageName, String volumeUuid, 12348 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12349 String[] grantedPermissions, Certificate[][] certificates) { 12350 super(user); 12351 this.origin = origin; 12352 this.move = move; 12353 this.observer = observer; 12354 this.installFlags = installFlags; 12355 this.installerPackageName = installerPackageName; 12356 this.volumeUuid = volumeUuid; 12357 this.verificationInfo = verificationInfo; 12358 this.packageAbiOverride = packageAbiOverride; 12359 this.grantedRuntimePermissions = grantedPermissions; 12360 this.certificates = certificates; 12361 } 12362 12363 @Override 12364 public String toString() { 12365 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12366 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12367 } 12368 12369 private int installLocationPolicy(PackageInfoLite pkgLite) { 12370 String packageName = pkgLite.packageName; 12371 int installLocation = pkgLite.installLocation; 12372 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12373 // reader 12374 synchronized (mPackages) { 12375 // Currently installed package which the new package is attempting to replace or 12376 // null if no such package is installed. 12377 PackageParser.Package installedPkg = mPackages.get(packageName); 12378 // Package which currently owns the data which the new package will own if installed. 12379 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12380 // will be null whereas dataOwnerPkg will contain information about the package 12381 // which was uninstalled while keeping its data. 12382 PackageParser.Package dataOwnerPkg = installedPkg; 12383 if (dataOwnerPkg == null) { 12384 PackageSetting ps = mSettings.mPackages.get(packageName); 12385 if (ps != null) { 12386 dataOwnerPkg = ps.pkg; 12387 } 12388 } 12389 12390 if (dataOwnerPkg != null) { 12391 // If installed, the package will get access to data left on the device by its 12392 // predecessor. As a security measure, this is permited only if this is not a 12393 // version downgrade or if the predecessor package is marked as debuggable and 12394 // a downgrade is explicitly requested. 12395 // 12396 // On debuggable platform builds, downgrades are permitted even for 12397 // non-debuggable packages to make testing easier. Debuggable platform builds do 12398 // not offer security guarantees and thus it's OK to disable some security 12399 // mechanisms to make debugging/testing easier on those builds. However, even on 12400 // debuggable builds downgrades of packages are permitted only if requested via 12401 // installFlags. This is because we aim to keep the behavior of debuggable 12402 // platform builds as close as possible to the behavior of non-debuggable 12403 // platform builds. 12404 final boolean downgradeRequested = 12405 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12406 final boolean packageDebuggable = 12407 (dataOwnerPkg.applicationInfo.flags 12408 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12409 final boolean downgradePermitted = 12410 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12411 if (!downgradePermitted) { 12412 try { 12413 checkDowngrade(dataOwnerPkg, pkgLite); 12414 } catch (PackageManagerException e) { 12415 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12416 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12417 } 12418 } 12419 } 12420 12421 if (installedPkg != null) { 12422 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12423 // Check for updated system application. 12424 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12425 if (onSd) { 12426 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12427 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12428 } 12429 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12430 } else { 12431 if (onSd) { 12432 // Install flag overrides everything. 12433 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12434 } 12435 // If current upgrade specifies particular preference 12436 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12437 // Application explicitly specified internal. 12438 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12439 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12440 // App explictly prefers external. Let policy decide 12441 } else { 12442 // Prefer previous location 12443 if (isExternal(installedPkg)) { 12444 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12445 } 12446 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12447 } 12448 } 12449 } else { 12450 // Invalid install. Return error code 12451 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12452 } 12453 } 12454 } 12455 // All the special cases have been taken care of. 12456 // Return result based on recommended install location. 12457 if (onSd) { 12458 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12459 } 12460 return pkgLite.recommendedInstallLocation; 12461 } 12462 12463 /* 12464 * Invoke remote method to get package information and install 12465 * location values. Override install location based on default 12466 * policy if needed and then create install arguments based 12467 * on the install location. 12468 */ 12469 public void handleStartCopy() throws RemoteException { 12470 int ret = PackageManager.INSTALL_SUCCEEDED; 12471 12472 // If we're already staged, we've firmly committed to an install location 12473 if (origin.staged) { 12474 if (origin.file != null) { 12475 installFlags |= PackageManager.INSTALL_INTERNAL; 12476 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12477 } else if (origin.cid != null) { 12478 installFlags |= PackageManager.INSTALL_EXTERNAL; 12479 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12480 } else { 12481 throw new IllegalStateException("Invalid stage location"); 12482 } 12483 } 12484 12485 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12486 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12487 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12488 PackageInfoLite pkgLite = null; 12489 12490 if (onInt && onSd) { 12491 // Check if both bits are set. 12492 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12493 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12494 } else if (onSd && ephemeral) { 12495 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12496 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12497 } else { 12498 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12499 packageAbiOverride); 12500 12501 if (DEBUG_EPHEMERAL && ephemeral) { 12502 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12503 } 12504 12505 /* 12506 * If we have too little free space, try to free cache 12507 * before giving up. 12508 */ 12509 if (!origin.staged && pkgLite.recommendedInstallLocation 12510 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12511 // TODO: focus freeing disk space on the target device 12512 final StorageManager storage = StorageManager.from(mContext); 12513 final long lowThreshold = storage.getStorageLowBytes( 12514 Environment.getDataDirectory()); 12515 12516 final long sizeBytes = mContainerService.calculateInstalledSize( 12517 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12518 12519 try { 12520 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12521 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12522 installFlags, packageAbiOverride); 12523 } catch (InstallerException e) { 12524 Slog.w(TAG, "Failed to free cache", e); 12525 } 12526 12527 /* 12528 * The cache free must have deleted the file we 12529 * downloaded to install. 12530 * 12531 * TODO: fix the "freeCache" call to not delete 12532 * the file we care about. 12533 */ 12534 if (pkgLite.recommendedInstallLocation 12535 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12536 pkgLite.recommendedInstallLocation 12537 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12538 } 12539 } 12540 } 12541 12542 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12543 int loc = pkgLite.recommendedInstallLocation; 12544 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12545 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12546 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12547 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12548 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12549 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12550 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12551 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12552 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12553 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12554 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12555 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12556 } else { 12557 // Override with defaults if needed. 12558 loc = installLocationPolicy(pkgLite); 12559 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12560 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12561 } else if (!onSd && !onInt) { 12562 // Override install location with flags 12563 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12564 // Set the flag to install on external media. 12565 installFlags |= PackageManager.INSTALL_EXTERNAL; 12566 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12567 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12568 if (DEBUG_EPHEMERAL) { 12569 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12570 } 12571 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12572 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12573 |PackageManager.INSTALL_INTERNAL); 12574 } else { 12575 // Make sure the flag for installing on external 12576 // media is unset 12577 installFlags |= PackageManager.INSTALL_INTERNAL; 12578 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12579 } 12580 } 12581 } 12582 } 12583 12584 final InstallArgs args = createInstallArgs(this); 12585 mArgs = args; 12586 12587 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12588 // TODO: http://b/22976637 12589 // Apps installed for "all" users use the device owner to verify the app 12590 UserHandle verifierUser = getUser(); 12591 if (verifierUser == UserHandle.ALL) { 12592 verifierUser = UserHandle.SYSTEM; 12593 } 12594 12595 /* 12596 * Determine if we have any installed package verifiers. If we 12597 * do, then we'll defer to them to verify the packages. 12598 */ 12599 final int requiredUid = mRequiredVerifierPackage == null ? -1 12600 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12601 verifierUser.getIdentifier()); 12602 if (!origin.existing && requiredUid != -1 12603 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12604 final Intent verification = new Intent( 12605 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12606 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12607 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12608 PACKAGE_MIME_TYPE); 12609 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12610 12611 // Query all live verifiers based on current user state 12612 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12613 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12614 12615 if (DEBUG_VERIFY) { 12616 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12617 + verification.toString() + " with " + pkgLite.verifiers.length 12618 + " optional verifiers"); 12619 } 12620 12621 final int verificationId = mPendingVerificationToken++; 12622 12623 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12624 12625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12626 installerPackageName); 12627 12628 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12629 installFlags); 12630 12631 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12632 pkgLite.packageName); 12633 12634 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12635 pkgLite.versionCode); 12636 12637 if (verificationInfo != null) { 12638 if (verificationInfo.originatingUri != null) { 12639 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12640 verificationInfo.originatingUri); 12641 } 12642 if (verificationInfo.referrer != null) { 12643 verification.putExtra(Intent.EXTRA_REFERRER, 12644 verificationInfo.referrer); 12645 } 12646 if (verificationInfo.originatingUid >= 0) { 12647 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12648 verificationInfo.originatingUid); 12649 } 12650 if (verificationInfo.installerUid >= 0) { 12651 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12652 verificationInfo.installerUid); 12653 } 12654 } 12655 12656 final PackageVerificationState verificationState = new PackageVerificationState( 12657 requiredUid, args); 12658 12659 mPendingVerification.append(verificationId, verificationState); 12660 12661 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12662 receivers, verificationState); 12663 12664 /* 12665 * If any sufficient verifiers were listed in the package 12666 * manifest, attempt to ask them. 12667 */ 12668 if (sufficientVerifiers != null) { 12669 final int N = sufficientVerifiers.size(); 12670 if (N == 0) { 12671 Slog.i(TAG, "Additional verifiers required, but none installed."); 12672 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12673 } else { 12674 for (int i = 0; i < N; i++) { 12675 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12676 12677 final Intent sufficientIntent = new Intent(verification); 12678 sufficientIntent.setComponent(verifierComponent); 12679 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12680 } 12681 } 12682 } 12683 12684 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12685 mRequiredVerifierPackage, receivers); 12686 if (ret == PackageManager.INSTALL_SUCCEEDED 12687 && mRequiredVerifierPackage != null) { 12688 Trace.asyncTraceBegin( 12689 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12690 /* 12691 * Send the intent to the required verification agent, 12692 * but only start the verification timeout after the 12693 * target BroadcastReceivers have run. 12694 */ 12695 verification.setComponent(requiredVerifierComponent); 12696 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12697 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12698 new BroadcastReceiver() { 12699 @Override 12700 public void onReceive(Context context, Intent intent) { 12701 final Message msg = mHandler 12702 .obtainMessage(CHECK_PENDING_VERIFICATION); 12703 msg.arg1 = verificationId; 12704 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12705 } 12706 }, null, 0, null, null); 12707 12708 /* 12709 * We don't want the copy to proceed until verification 12710 * succeeds, so null out this field. 12711 */ 12712 mArgs = null; 12713 } 12714 } else { 12715 /* 12716 * No package verification is enabled, so immediately start 12717 * the remote call to initiate copy using temporary file. 12718 */ 12719 ret = args.copyApk(mContainerService, true); 12720 } 12721 } 12722 12723 mRet = ret; 12724 } 12725 12726 @Override 12727 void handleReturnCode() { 12728 // If mArgs is null, then MCS couldn't be reached. When it 12729 // reconnects, it will try again to install. At that point, this 12730 // will succeed. 12731 if (mArgs != null) { 12732 processPendingInstall(mArgs, mRet); 12733 } 12734 } 12735 12736 @Override 12737 void handleServiceError() { 12738 mArgs = createInstallArgs(this); 12739 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12740 } 12741 12742 public boolean isForwardLocked() { 12743 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12744 } 12745 } 12746 12747 /** 12748 * Used during creation of InstallArgs 12749 * 12750 * @param installFlags package installation flags 12751 * @return true if should be installed on external storage 12752 */ 12753 private static boolean installOnExternalAsec(int installFlags) { 12754 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12755 return false; 12756 } 12757 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12758 return true; 12759 } 12760 return false; 12761 } 12762 12763 /** 12764 * Used during creation of InstallArgs 12765 * 12766 * @param installFlags package installation flags 12767 * @return true if should be installed as forward locked 12768 */ 12769 private static boolean installForwardLocked(int installFlags) { 12770 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12771 } 12772 12773 private InstallArgs createInstallArgs(InstallParams params) { 12774 if (params.move != null) { 12775 return new MoveInstallArgs(params); 12776 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12777 return new AsecInstallArgs(params); 12778 } else { 12779 return new FileInstallArgs(params); 12780 } 12781 } 12782 12783 /** 12784 * Create args that describe an existing installed package. Typically used 12785 * when cleaning up old installs, or used as a move source. 12786 */ 12787 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12788 String resourcePath, String[] instructionSets) { 12789 final boolean isInAsec; 12790 if (installOnExternalAsec(installFlags)) { 12791 /* Apps on SD card are always in ASEC containers. */ 12792 isInAsec = true; 12793 } else if (installForwardLocked(installFlags) 12794 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12795 /* 12796 * Forward-locked apps are only in ASEC containers if they're the 12797 * new style 12798 */ 12799 isInAsec = true; 12800 } else { 12801 isInAsec = false; 12802 } 12803 12804 if (isInAsec) { 12805 return new AsecInstallArgs(codePath, instructionSets, 12806 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12807 } else { 12808 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12809 } 12810 } 12811 12812 static abstract class InstallArgs { 12813 /** @see InstallParams#origin */ 12814 final OriginInfo origin; 12815 /** @see InstallParams#move */ 12816 final MoveInfo move; 12817 12818 final IPackageInstallObserver2 observer; 12819 // Always refers to PackageManager flags only 12820 final int installFlags; 12821 final String installerPackageName; 12822 final String volumeUuid; 12823 final UserHandle user; 12824 final String abiOverride; 12825 final String[] installGrantPermissions; 12826 /** If non-null, drop an async trace when the install completes */ 12827 final String traceMethod; 12828 final int traceCookie; 12829 final Certificate[][] certificates; 12830 12831 // The list of instruction sets supported by this app. This is currently 12832 // only used during the rmdex() phase to clean up resources. We can get rid of this 12833 // if we move dex files under the common app path. 12834 /* nullable */ String[] instructionSets; 12835 12836 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12837 int installFlags, String installerPackageName, String volumeUuid, 12838 UserHandle user, String[] instructionSets, 12839 String abiOverride, String[] installGrantPermissions, 12840 String traceMethod, int traceCookie, Certificate[][] certificates) { 12841 this.origin = origin; 12842 this.move = move; 12843 this.installFlags = installFlags; 12844 this.observer = observer; 12845 this.installerPackageName = installerPackageName; 12846 this.volumeUuid = volumeUuid; 12847 this.user = user; 12848 this.instructionSets = instructionSets; 12849 this.abiOverride = abiOverride; 12850 this.installGrantPermissions = installGrantPermissions; 12851 this.traceMethod = traceMethod; 12852 this.traceCookie = traceCookie; 12853 this.certificates = certificates; 12854 } 12855 12856 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12857 abstract int doPreInstall(int status); 12858 12859 /** 12860 * Rename package into final resting place. All paths on the given 12861 * scanned package should be updated to reflect the rename. 12862 */ 12863 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12864 abstract int doPostInstall(int status, int uid); 12865 12866 /** @see PackageSettingBase#codePathString */ 12867 abstract String getCodePath(); 12868 /** @see PackageSettingBase#resourcePathString */ 12869 abstract String getResourcePath(); 12870 12871 // Need installer lock especially for dex file removal. 12872 abstract void cleanUpResourcesLI(); 12873 abstract boolean doPostDeleteLI(boolean delete); 12874 12875 /** 12876 * Called before the source arguments are copied. This is used mostly 12877 * for MoveParams when it needs to read the source file to put it in the 12878 * destination. 12879 */ 12880 int doPreCopy() { 12881 return PackageManager.INSTALL_SUCCEEDED; 12882 } 12883 12884 /** 12885 * Called after the source arguments are copied. This is used mostly for 12886 * MoveParams when it needs to read the source file to put it in the 12887 * destination. 12888 */ 12889 int doPostCopy(int uid) { 12890 return PackageManager.INSTALL_SUCCEEDED; 12891 } 12892 12893 protected boolean isFwdLocked() { 12894 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12895 } 12896 12897 protected boolean isExternalAsec() { 12898 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12899 } 12900 12901 protected boolean isEphemeral() { 12902 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12903 } 12904 12905 UserHandle getUser() { 12906 return user; 12907 } 12908 } 12909 12910 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12911 if (!allCodePaths.isEmpty()) { 12912 if (instructionSets == null) { 12913 throw new IllegalStateException("instructionSet == null"); 12914 } 12915 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12916 for (String codePath : allCodePaths) { 12917 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12918 try { 12919 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12920 } catch (InstallerException ignored) { 12921 } 12922 } 12923 } 12924 } 12925 } 12926 12927 /** 12928 * Logic to handle installation of non-ASEC applications, including copying 12929 * and renaming logic. 12930 */ 12931 class FileInstallArgs extends InstallArgs { 12932 private File codeFile; 12933 private File resourceFile; 12934 12935 // Example topology: 12936 // /data/app/com.example/base.apk 12937 // /data/app/com.example/split_foo.apk 12938 // /data/app/com.example/lib/arm/libfoo.so 12939 // /data/app/com.example/lib/arm64/libfoo.so 12940 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12941 12942 /** New install */ 12943 FileInstallArgs(InstallParams params) { 12944 super(params.origin, params.move, params.observer, params.installFlags, 12945 params.installerPackageName, params.volumeUuid, 12946 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12947 params.grantedRuntimePermissions, 12948 params.traceMethod, params.traceCookie, params.certificates); 12949 if (isFwdLocked()) { 12950 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12951 } 12952 } 12953 12954 /** Existing install */ 12955 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12956 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12957 null, null, null, 0, null /*certificates*/); 12958 this.codeFile = (codePath != null) ? new File(codePath) : null; 12959 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12960 } 12961 12962 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12964 try { 12965 return doCopyApk(imcs, temp); 12966 } finally { 12967 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12968 } 12969 } 12970 12971 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12972 if (origin.staged) { 12973 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12974 codeFile = origin.file; 12975 resourceFile = origin.file; 12976 return PackageManager.INSTALL_SUCCEEDED; 12977 } 12978 12979 try { 12980 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12981 final File tempDir = 12982 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12983 codeFile = tempDir; 12984 resourceFile = tempDir; 12985 } catch (IOException e) { 12986 Slog.w(TAG, "Failed to create copy file: " + e); 12987 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12988 } 12989 12990 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12991 @Override 12992 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12993 if (!FileUtils.isValidExtFilename(name)) { 12994 throw new IllegalArgumentException("Invalid filename: " + name); 12995 } 12996 try { 12997 final File file = new File(codeFile, name); 12998 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12999 O_RDWR | O_CREAT, 0644); 13000 Os.chmod(file.getAbsolutePath(), 0644); 13001 return new ParcelFileDescriptor(fd); 13002 } catch (ErrnoException e) { 13003 throw new RemoteException("Failed to open: " + e.getMessage()); 13004 } 13005 } 13006 }; 13007 13008 int ret = PackageManager.INSTALL_SUCCEEDED; 13009 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13010 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13011 Slog.e(TAG, "Failed to copy package"); 13012 return ret; 13013 } 13014 13015 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13016 NativeLibraryHelper.Handle handle = null; 13017 try { 13018 handle = NativeLibraryHelper.Handle.create(codeFile); 13019 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13020 abiOverride); 13021 } catch (IOException e) { 13022 Slog.e(TAG, "Copying native libraries failed", e); 13023 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13024 } finally { 13025 IoUtils.closeQuietly(handle); 13026 } 13027 13028 return ret; 13029 } 13030 13031 int doPreInstall(int status) { 13032 if (status != PackageManager.INSTALL_SUCCEEDED) { 13033 cleanUp(); 13034 } 13035 return status; 13036 } 13037 13038 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13039 if (status != PackageManager.INSTALL_SUCCEEDED) { 13040 cleanUp(); 13041 return false; 13042 } 13043 13044 final File targetDir = codeFile.getParentFile(); 13045 final File beforeCodeFile = codeFile; 13046 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13047 13048 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13049 try { 13050 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13051 } catch (ErrnoException e) { 13052 Slog.w(TAG, "Failed to rename", e); 13053 return false; 13054 } 13055 13056 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13057 Slog.w(TAG, "Failed to restorecon"); 13058 return false; 13059 } 13060 13061 // Reflect the rename internally 13062 codeFile = afterCodeFile; 13063 resourceFile = afterCodeFile; 13064 13065 // Reflect the rename in scanned details 13066 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13067 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13068 afterCodeFile, pkg.baseCodePath)); 13069 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13070 afterCodeFile, pkg.splitCodePaths)); 13071 13072 // Reflect the rename in app info 13073 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13074 pkg.setApplicationInfoCodePath(pkg.codePath); 13075 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13076 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13077 pkg.setApplicationInfoResourcePath(pkg.codePath); 13078 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13079 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13080 13081 return true; 13082 } 13083 13084 int doPostInstall(int status, int uid) { 13085 if (status != PackageManager.INSTALL_SUCCEEDED) { 13086 cleanUp(); 13087 } 13088 return status; 13089 } 13090 13091 @Override 13092 String getCodePath() { 13093 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13094 } 13095 13096 @Override 13097 String getResourcePath() { 13098 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13099 } 13100 13101 private boolean cleanUp() { 13102 if (codeFile == null || !codeFile.exists()) { 13103 return false; 13104 } 13105 13106 removeCodePathLI(codeFile); 13107 13108 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13109 resourceFile.delete(); 13110 } 13111 13112 return true; 13113 } 13114 13115 void cleanUpResourcesLI() { 13116 // Try enumerating all code paths before deleting 13117 List<String> allCodePaths = Collections.EMPTY_LIST; 13118 if (codeFile != null && codeFile.exists()) { 13119 try { 13120 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13121 allCodePaths = pkg.getAllCodePaths(); 13122 } catch (PackageParserException e) { 13123 // Ignored; we tried our best 13124 } 13125 } 13126 13127 cleanUp(); 13128 removeDexFiles(allCodePaths, instructionSets); 13129 } 13130 13131 boolean doPostDeleteLI(boolean delete) { 13132 // XXX err, shouldn't we respect the delete flag? 13133 cleanUpResourcesLI(); 13134 return true; 13135 } 13136 } 13137 13138 private boolean isAsecExternal(String cid) { 13139 final String asecPath = PackageHelper.getSdFilesystem(cid); 13140 return !asecPath.startsWith(mAsecInternalPath); 13141 } 13142 13143 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13144 PackageManagerException { 13145 if (copyRet < 0) { 13146 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13147 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13148 throw new PackageManagerException(copyRet, message); 13149 } 13150 } 13151 } 13152 13153 /** 13154 * Extract the MountService "container ID" from the full code path of an 13155 * .apk. 13156 */ 13157 static String cidFromCodePath(String fullCodePath) { 13158 int eidx = fullCodePath.lastIndexOf("/"); 13159 String subStr1 = fullCodePath.substring(0, eidx); 13160 int sidx = subStr1.lastIndexOf("/"); 13161 return subStr1.substring(sidx+1, eidx); 13162 } 13163 13164 /** 13165 * Logic to handle installation of ASEC applications, including copying and 13166 * renaming logic. 13167 */ 13168 class AsecInstallArgs extends InstallArgs { 13169 static final String RES_FILE_NAME = "pkg.apk"; 13170 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13171 13172 String cid; 13173 String packagePath; 13174 String resourcePath; 13175 13176 /** New install */ 13177 AsecInstallArgs(InstallParams params) { 13178 super(params.origin, params.move, params.observer, params.installFlags, 13179 params.installerPackageName, params.volumeUuid, 13180 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13181 params.grantedRuntimePermissions, 13182 params.traceMethod, params.traceCookie, params.certificates); 13183 } 13184 13185 /** Existing install */ 13186 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13187 boolean isExternal, boolean isForwardLocked) { 13188 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13189 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13190 instructionSets, null, null, null, 0, null /*certificates*/); 13191 // Hackily pretend we're still looking at a full code path 13192 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13193 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13194 } 13195 13196 // Extract cid from fullCodePath 13197 int eidx = fullCodePath.lastIndexOf("/"); 13198 String subStr1 = fullCodePath.substring(0, eidx); 13199 int sidx = subStr1.lastIndexOf("/"); 13200 cid = subStr1.substring(sidx+1, eidx); 13201 setMountPath(subStr1); 13202 } 13203 13204 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13205 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13206 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13207 instructionSets, null, null, null, 0, null /*certificates*/); 13208 this.cid = cid; 13209 setMountPath(PackageHelper.getSdDir(cid)); 13210 } 13211 13212 void createCopyFile() { 13213 cid = mInstallerService.allocateExternalStageCidLegacy(); 13214 } 13215 13216 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13217 if (origin.staged && origin.cid != null) { 13218 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13219 cid = origin.cid; 13220 setMountPath(PackageHelper.getSdDir(cid)); 13221 return PackageManager.INSTALL_SUCCEEDED; 13222 } 13223 13224 if (temp) { 13225 createCopyFile(); 13226 } else { 13227 /* 13228 * Pre-emptively destroy the container since it's destroyed if 13229 * copying fails due to it existing anyway. 13230 */ 13231 PackageHelper.destroySdDir(cid); 13232 } 13233 13234 final String newMountPath = imcs.copyPackageToContainer( 13235 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13236 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13237 13238 if (newMountPath != null) { 13239 setMountPath(newMountPath); 13240 return PackageManager.INSTALL_SUCCEEDED; 13241 } else { 13242 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13243 } 13244 } 13245 13246 @Override 13247 String getCodePath() { 13248 return packagePath; 13249 } 13250 13251 @Override 13252 String getResourcePath() { 13253 return resourcePath; 13254 } 13255 13256 int doPreInstall(int status) { 13257 if (status != PackageManager.INSTALL_SUCCEEDED) { 13258 // Destroy container 13259 PackageHelper.destroySdDir(cid); 13260 } else { 13261 boolean mounted = PackageHelper.isContainerMounted(cid); 13262 if (!mounted) { 13263 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13264 Process.SYSTEM_UID); 13265 if (newMountPath != null) { 13266 setMountPath(newMountPath); 13267 } else { 13268 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13269 } 13270 } 13271 } 13272 return status; 13273 } 13274 13275 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13276 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13277 String newMountPath = null; 13278 if (PackageHelper.isContainerMounted(cid)) { 13279 // Unmount the container 13280 if (!PackageHelper.unMountSdDir(cid)) { 13281 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13282 return false; 13283 } 13284 } 13285 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13286 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13287 " which might be stale. Will try to clean up."); 13288 // Clean up the stale container and proceed to recreate. 13289 if (!PackageHelper.destroySdDir(newCacheId)) { 13290 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13291 return false; 13292 } 13293 // Successfully cleaned up stale container. Try to rename again. 13294 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13295 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13296 + " inspite of cleaning it up."); 13297 return false; 13298 } 13299 } 13300 if (!PackageHelper.isContainerMounted(newCacheId)) { 13301 Slog.w(TAG, "Mounting container " + newCacheId); 13302 newMountPath = PackageHelper.mountSdDir(newCacheId, 13303 getEncryptKey(), Process.SYSTEM_UID); 13304 } else { 13305 newMountPath = PackageHelper.getSdDir(newCacheId); 13306 } 13307 if (newMountPath == null) { 13308 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13309 return false; 13310 } 13311 Log.i(TAG, "Succesfully renamed " + cid + 13312 " to " + newCacheId + 13313 " at new path: " + newMountPath); 13314 cid = newCacheId; 13315 13316 final File beforeCodeFile = new File(packagePath); 13317 setMountPath(newMountPath); 13318 final File afterCodeFile = new File(packagePath); 13319 13320 // Reflect the rename in scanned details 13321 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13322 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13323 afterCodeFile, pkg.baseCodePath)); 13324 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13325 afterCodeFile, pkg.splitCodePaths)); 13326 13327 // Reflect the rename in app info 13328 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13329 pkg.setApplicationInfoCodePath(pkg.codePath); 13330 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13331 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13332 pkg.setApplicationInfoResourcePath(pkg.codePath); 13333 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13334 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13335 13336 return true; 13337 } 13338 13339 private void setMountPath(String mountPath) { 13340 final File mountFile = new File(mountPath); 13341 13342 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13343 if (monolithicFile.exists()) { 13344 packagePath = monolithicFile.getAbsolutePath(); 13345 if (isFwdLocked()) { 13346 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13347 } else { 13348 resourcePath = packagePath; 13349 } 13350 } else { 13351 packagePath = mountFile.getAbsolutePath(); 13352 resourcePath = packagePath; 13353 } 13354 } 13355 13356 int doPostInstall(int status, int uid) { 13357 if (status != PackageManager.INSTALL_SUCCEEDED) { 13358 cleanUp(); 13359 } else { 13360 final int groupOwner; 13361 final String protectedFile; 13362 if (isFwdLocked()) { 13363 groupOwner = UserHandle.getSharedAppGid(uid); 13364 protectedFile = RES_FILE_NAME; 13365 } else { 13366 groupOwner = -1; 13367 protectedFile = null; 13368 } 13369 13370 if (uid < Process.FIRST_APPLICATION_UID 13371 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13372 Slog.e(TAG, "Failed to finalize " + cid); 13373 PackageHelper.destroySdDir(cid); 13374 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13375 } 13376 13377 boolean mounted = PackageHelper.isContainerMounted(cid); 13378 if (!mounted) { 13379 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13380 } 13381 } 13382 return status; 13383 } 13384 13385 private void cleanUp() { 13386 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13387 13388 // Destroy secure container 13389 PackageHelper.destroySdDir(cid); 13390 } 13391 13392 private List<String> getAllCodePaths() { 13393 final File codeFile = new File(getCodePath()); 13394 if (codeFile != null && codeFile.exists()) { 13395 try { 13396 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13397 return pkg.getAllCodePaths(); 13398 } catch (PackageParserException e) { 13399 // Ignored; we tried our best 13400 } 13401 } 13402 return Collections.EMPTY_LIST; 13403 } 13404 13405 void cleanUpResourcesLI() { 13406 // Enumerate all code paths before deleting 13407 cleanUpResourcesLI(getAllCodePaths()); 13408 } 13409 13410 private void cleanUpResourcesLI(List<String> allCodePaths) { 13411 cleanUp(); 13412 removeDexFiles(allCodePaths, instructionSets); 13413 } 13414 13415 String getPackageName() { 13416 return getAsecPackageName(cid); 13417 } 13418 13419 boolean doPostDeleteLI(boolean delete) { 13420 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13421 final List<String> allCodePaths = getAllCodePaths(); 13422 boolean mounted = PackageHelper.isContainerMounted(cid); 13423 if (mounted) { 13424 // Unmount first 13425 if (PackageHelper.unMountSdDir(cid)) { 13426 mounted = false; 13427 } 13428 } 13429 if (!mounted && delete) { 13430 cleanUpResourcesLI(allCodePaths); 13431 } 13432 return !mounted; 13433 } 13434 13435 @Override 13436 int doPreCopy() { 13437 if (isFwdLocked()) { 13438 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13439 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13440 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13441 } 13442 } 13443 13444 return PackageManager.INSTALL_SUCCEEDED; 13445 } 13446 13447 @Override 13448 int doPostCopy(int uid) { 13449 if (isFwdLocked()) { 13450 if (uid < Process.FIRST_APPLICATION_UID 13451 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13452 RES_FILE_NAME)) { 13453 Slog.e(TAG, "Failed to finalize " + cid); 13454 PackageHelper.destroySdDir(cid); 13455 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13456 } 13457 } 13458 13459 return PackageManager.INSTALL_SUCCEEDED; 13460 } 13461 } 13462 13463 /** 13464 * Logic to handle movement of existing installed applications. 13465 */ 13466 class MoveInstallArgs extends InstallArgs { 13467 private File codeFile; 13468 private File resourceFile; 13469 13470 /** New install */ 13471 MoveInstallArgs(InstallParams params) { 13472 super(params.origin, params.move, params.observer, params.installFlags, 13473 params.installerPackageName, params.volumeUuid, 13474 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13475 params.grantedRuntimePermissions, 13476 params.traceMethod, params.traceCookie, params.certificates); 13477 } 13478 13479 int copyApk(IMediaContainerService imcs, boolean temp) { 13480 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13481 + move.fromUuid + " to " + move.toUuid); 13482 synchronized (mInstaller) { 13483 try { 13484 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13485 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13486 } catch (InstallerException e) { 13487 Slog.w(TAG, "Failed to move app", e); 13488 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13489 } 13490 } 13491 13492 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13493 resourceFile = codeFile; 13494 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13495 13496 return PackageManager.INSTALL_SUCCEEDED; 13497 } 13498 13499 int doPreInstall(int status) { 13500 if (status != PackageManager.INSTALL_SUCCEEDED) { 13501 cleanUp(move.toUuid); 13502 } 13503 return status; 13504 } 13505 13506 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13507 if (status != PackageManager.INSTALL_SUCCEEDED) { 13508 cleanUp(move.toUuid); 13509 return false; 13510 } 13511 13512 // Reflect the move in app info 13513 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13514 pkg.setApplicationInfoCodePath(pkg.codePath); 13515 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13516 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13517 pkg.setApplicationInfoResourcePath(pkg.codePath); 13518 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13519 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13520 13521 return true; 13522 } 13523 13524 int doPostInstall(int status, int uid) { 13525 if (status == PackageManager.INSTALL_SUCCEEDED) { 13526 cleanUp(move.fromUuid); 13527 } else { 13528 cleanUp(move.toUuid); 13529 } 13530 return status; 13531 } 13532 13533 @Override 13534 String getCodePath() { 13535 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13536 } 13537 13538 @Override 13539 String getResourcePath() { 13540 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13541 } 13542 13543 private boolean cleanUp(String volumeUuid) { 13544 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13545 move.dataAppName); 13546 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13547 final int[] userIds = sUserManager.getUserIds(); 13548 synchronized (mInstallLock) { 13549 // Clean up both app data and code 13550 // All package moves are frozen until finished 13551 for (int userId : userIds) { 13552 try { 13553 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13554 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13555 } catch (InstallerException e) { 13556 Slog.w(TAG, String.valueOf(e)); 13557 } 13558 } 13559 removeCodePathLI(codeFile); 13560 } 13561 return true; 13562 } 13563 13564 void cleanUpResourcesLI() { 13565 throw new UnsupportedOperationException(); 13566 } 13567 13568 boolean doPostDeleteLI(boolean delete) { 13569 throw new UnsupportedOperationException(); 13570 } 13571 } 13572 13573 static String getAsecPackageName(String packageCid) { 13574 int idx = packageCid.lastIndexOf("-"); 13575 if (idx == -1) { 13576 return packageCid; 13577 } 13578 return packageCid.substring(0, idx); 13579 } 13580 13581 // Utility method used to create code paths based on package name and available index. 13582 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13583 String idxStr = ""; 13584 int idx = 1; 13585 // Fall back to default value of idx=1 if prefix is not 13586 // part of oldCodePath 13587 if (oldCodePath != null) { 13588 String subStr = oldCodePath; 13589 // Drop the suffix right away 13590 if (suffix != null && subStr.endsWith(suffix)) { 13591 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13592 } 13593 // If oldCodePath already contains prefix find out the 13594 // ending index to either increment or decrement. 13595 int sidx = subStr.lastIndexOf(prefix); 13596 if (sidx != -1) { 13597 subStr = subStr.substring(sidx + prefix.length()); 13598 if (subStr != null) { 13599 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13600 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13601 } 13602 try { 13603 idx = Integer.parseInt(subStr); 13604 if (idx <= 1) { 13605 idx++; 13606 } else { 13607 idx--; 13608 } 13609 } catch(NumberFormatException e) { 13610 } 13611 } 13612 } 13613 } 13614 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13615 return prefix + idxStr; 13616 } 13617 13618 private File getNextCodePath(File targetDir, String packageName) { 13619 int suffix = 1; 13620 File result; 13621 do { 13622 result = new File(targetDir, packageName + "-" + suffix); 13623 suffix++; 13624 } while (result.exists()); 13625 return result; 13626 } 13627 13628 // Utility method that returns the relative package path with respect 13629 // to the installation directory. Like say for /data/data/com.test-1.apk 13630 // string com.test-1 is returned. 13631 static String deriveCodePathName(String codePath) { 13632 if (codePath == null) { 13633 return null; 13634 } 13635 final File codeFile = new File(codePath); 13636 final String name = codeFile.getName(); 13637 if (codeFile.isDirectory()) { 13638 return name; 13639 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13640 final int lastDot = name.lastIndexOf('.'); 13641 return name.substring(0, lastDot); 13642 } else { 13643 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13644 return null; 13645 } 13646 } 13647 13648 static class PackageInstalledInfo { 13649 String name; 13650 int uid; 13651 // The set of users that originally had this package installed. 13652 int[] origUsers; 13653 // The set of users that now have this package installed. 13654 int[] newUsers; 13655 PackageParser.Package pkg; 13656 int returnCode; 13657 String returnMsg; 13658 PackageRemovedInfo removedInfo; 13659 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13660 13661 public void setError(int code, String msg) { 13662 setReturnCode(code); 13663 setReturnMessage(msg); 13664 Slog.w(TAG, msg); 13665 } 13666 13667 public void setError(String msg, PackageParserException e) { 13668 setReturnCode(e.error); 13669 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13670 Slog.w(TAG, msg, e); 13671 } 13672 13673 public void setError(String msg, PackageManagerException e) { 13674 returnCode = e.error; 13675 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13676 Slog.w(TAG, msg, e); 13677 } 13678 13679 public void setReturnCode(int returnCode) { 13680 this.returnCode = returnCode; 13681 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13682 for (int i = 0; i < childCount; i++) { 13683 addedChildPackages.valueAt(i).returnCode = returnCode; 13684 } 13685 } 13686 13687 private void setReturnMessage(String returnMsg) { 13688 this.returnMsg = returnMsg; 13689 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13690 for (int i = 0; i < childCount; i++) { 13691 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13692 } 13693 } 13694 13695 // In some error cases we want to convey more info back to the observer 13696 String origPackage; 13697 String origPermission; 13698 } 13699 13700 /* 13701 * Install a non-existing package. 13702 */ 13703 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13704 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13705 PackageInstalledInfo res) { 13706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13707 13708 // Remember this for later, in case we need to rollback this install 13709 String pkgName = pkg.packageName; 13710 13711 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13712 13713 synchronized(mPackages) { 13714 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13715 // A package with the same name is already installed, though 13716 // it has been renamed to an older name. The package we 13717 // are trying to install should be installed as an update to 13718 // the existing one, but that has not been requested, so bail. 13719 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13720 + " without first uninstalling package running as " 13721 + mSettings.mRenamedPackages.get(pkgName)); 13722 return; 13723 } 13724 if (mPackages.containsKey(pkgName)) { 13725 // Don't allow installation over an existing package with the same name. 13726 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13727 + " without first uninstalling."); 13728 return; 13729 } 13730 } 13731 13732 try { 13733 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13734 System.currentTimeMillis(), user); 13735 13736 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13737 13738 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13739 prepareAppDataAfterInstallLIF(newPackage); 13740 13741 } else { 13742 // Remove package from internal structures, but keep around any 13743 // data that might have already existed 13744 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13745 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13746 } 13747 } catch (PackageManagerException e) { 13748 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13749 } 13750 13751 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13752 } 13753 13754 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13755 // Can't rotate keys during boot or if sharedUser. 13756 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13757 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13758 return false; 13759 } 13760 // app is using upgradeKeySets; make sure all are valid 13761 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13762 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13763 for (int i = 0; i < upgradeKeySets.length; i++) { 13764 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13765 Slog.wtf(TAG, "Package " 13766 + (oldPs.name != null ? oldPs.name : "<null>") 13767 + " contains upgrade-key-set reference to unknown key-set: " 13768 + upgradeKeySets[i] 13769 + " reverting to signatures check."); 13770 return false; 13771 } 13772 } 13773 return true; 13774 } 13775 13776 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13777 // Upgrade keysets are being used. Determine if new package has a superset of the 13778 // required keys. 13779 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13780 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13781 for (int i = 0; i < upgradeKeySets.length; i++) { 13782 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13783 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13784 return true; 13785 } 13786 } 13787 return false; 13788 } 13789 13790 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13791 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13792 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13793 13794 final PackageParser.Package oldPackage; 13795 final String pkgName = pkg.packageName; 13796 final int[] allUsers; 13797 13798 // First find the old package info and check signatures 13799 synchronized(mPackages) { 13800 oldPackage = mPackages.get(pkgName); 13801 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13802 if (isEphemeral && !oldIsEphemeral) { 13803 // can't downgrade from full to ephemeral 13804 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13805 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13806 return; 13807 } 13808 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13809 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13810 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13811 if (!checkUpgradeKeySetLP(ps, pkg)) { 13812 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13813 "New package not signed by keys specified by upgrade-keysets: " 13814 + pkgName); 13815 return; 13816 } 13817 } else { 13818 // default to original signature matching 13819 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13820 != PackageManager.SIGNATURE_MATCH) { 13821 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13822 "New package has a different signature: " + pkgName); 13823 return; 13824 } 13825 } 13826 13827 // Check for shared user id changes 13828 String invalidPackageName = 13829 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13830 if (invalidPackageName != null) { 13831 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13832 "Package " + invalidPackageName + " tried to change user " 13833 + oldPackage.mSharedUserId); 13834 return; 13835 } 13836 13837 // In case of rollback, remember per-user/profile install state 13838 allUsers = sUserManager.getUserIds(); 13839 } 13840 13841 // Update what is removed 13842 res.removedInfo = new PackageRemovedInfo(); 13843 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13844 res.removedInfo.removedPackage = oldPackage.packageName; 13845 res.removedInfo.isUpdate = true; 13846 final int childCount = (oldPackage.childPackages != null) 13847 ? oldPackage.childPackages.size() : 0; 13848 for (int i = 0; i < childCount; i++) { 13849 boolean childPackageUpdated = false; 13850 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13851 if (res.addedChildPackages != null) { 13852 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13853 if (childRes != null) { 13854 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13855 childRes.removedInfo.removedPackage = childPkg.packageName; 13856 childRes.removedInfo.isUpdate = true; 13857 childPackageUpdated = true; 13858 } 13859 } 13860 if (!childPackageUpdated) { 13861 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13862 childRemovedRes.removedPackage = childPkg.packageName; 13863 childRemovedRes.isUpdate = false; 13864 childRemovedRes.dataRemoved = true; 13865 synchronized (mPackages) { 13866 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13867 if (childPs != null) { 13868 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13869 } 13870 } 13871 if (res.removedInfo.removedChildPackages == null) { 13872 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13873 } 13874 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13875 } 13876 } 13877 13878 boolean sysPkg = (isSystemApp(oldPackage)); 13879 if (sysPkg) { 13880 // Set the system/privileged flags as needed 13881 final boolean privileged = 13882 (oldPackage.applicationInfo.privateFlags 13883 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13884 final int systemPolicyFlags = policyFlags 13885 | PackageParser.PARSE_IS_SYSTEM 13886 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13887 13888 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13889 user, allUsers, installerPackageName, res); 13890 } else { 13891 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13892 user, allUsers, installerPackageName, res); 13893 } 13894 } 13895 13896 public List<String> getPreviousCodePaths(String packageName) { 13897 final PackageSetting ps = mSettings.mPackages.get(packageName); 13898 final List<String> result = new ArrayList<String>(); 13899 if (ps != null && ps.oldCodePaths != null) { 13900 result.addAll(ps.oldCodePaths); 13901 } 13902 return result; 13903 } 13904 13905 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13906 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13907 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13908 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13909 + deletedPackage); 13910 13911 String pkgName = deletedPackage.packageName; 13912 boolean deletedPkg = true; 13913 boolean addedPkg = false; 13914 boolean updatedSettings = false; 13915 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13916 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13917 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13918 13919 final long origUpdateTime = (pkg.mExtras != null) 13920 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13921 13922 // First delete the existing package while retaining the data directory 13923 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13924 res.removedInfo, true, pkg)) { 13925 // If the existing package wasn't successfully deleted 13926 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13927 deletedPkg = false; 13928 } else { 13929 // Successfully deleted the old package; proceed with replace. 13930 13931 // If deleted package lived in a container, give users a chance to 13932 // relinquish resources before killing. 13933 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13934 if (DEBUG_INSTALL) { 13935 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13936 } 13937 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13938 final ArrayList<String> pkgList = new ArrayList<String>(1); 13939 pkgList.add(deletedPackage.applicationInfo.packageName); 13940 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13941 } 13942 13943 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13944 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13945 clearAppProfilesLIF(pkg); 13946 13947 try { 13948 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13949 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13950 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13951 13952 // Update the in-memory copy of the previous code paths. 13953 PackageSetting ps = mSettings.mPackages.get(pkgName); 13954 if (!killApp) { 13955 if (ps.oldCodePaths == null) { 13956 ps.oldCodePaths = new ArraySet<>(); 13957 } 13958 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13959 if (deletedPackage.splitCodePaths != null) { 13960 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13961 } 13962 } else { 13963 ps.oldCodePaths = null; 13964 } 13965 if (ps.childPackageNames != null) { 13966 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13967 final String childPkgName = ps.childPackageNames.get(i); 13968 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13969 childPs.oldCodePaths = ps.oldCodePaths; 13970 } 13971 } 13972 prepareAppDataAfterInstallLIF(newPackage); 13973 addedPkg = true; 13974 } catch (PackageManagerException e) { 13975 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13976 } 13977 } 13978 13979 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13980 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13981 13982 // Revert all internal state mutations and added folders for the failed install 13983 if (addedPkg) { 13984 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13985 res.removedInfo, true, null); 13986 } 13987 13988 // Restore the old package 13989 if (deletedPkg) { 13990 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13991 File restoreFile = new File(deletedPackage.codePath); 13992 // Parse old package 13993 boolean oldExternal = isExternal(deletedPackage); 13994 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13995 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13996 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13997 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13998 try { 13999 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14000 null); 14001 } catch (PackageManagerException e) { 14002 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14003 + e.getMessage()); 14004 return; 14005 } 14006 14007 synchronized (mPackages) { 14008 // Ensure the installer package name up to date 14009 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14010 14011 // Update permissions for restored package 14012 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14013 14014 mSettings.writeLPr(); 14015 } 14016 14017 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14018 } 14019 } else { 14020 synchronized (mPackages) { 14021 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14022 if (ps != null) { 14023 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14024 if (res.removedInfo.removedChildPackages != null) { 14025 final int childCount = res.removedInfo.removedChildPackages.size(); 14026 // Iterate in reverse as we may modify the collection 14027 for (int i = childCount - 1; i >= 0; i--) { 14028 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14029 if (res.addedChildPackages.containsKey(childPackageName)) { 14030 res.removedInfo.removedChildPackages.removeAt(i); 14031 } else { 14032 PackageRemovedInfo childInfo = res.removedInfo 14033 .removedChildPackages.valueAt(i); 14034 childInfo.removedForAllUsers = mPackages.get( 14035 childInfo.removedPackage) == null; 14036 } 14037 } 14038 } 14039 } 14040 } 14041 } 14042 } 14043 14044 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14045 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14046 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14047 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14048 + ", old=" + deletedPackage); 14049 14050 final boolean disabledSystem; 14051 14052 // Remove existing system package 14053 removePackageLI(deletedPackage, true); 14054 14055 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14056 if (!disabledSystem) { 14057 // We didn't need to disable the .apk as a current system package, 14058 // which means we are replacing another update that is already 14059 // installed. We need to make sure to delete the older one's .apk. 14060 res.removedInfo.args = createInstallArgsForExisting(0, 14061 deletedPackage.applicationInfo.getCodePath(), 14062 deletedPackage.applicationInfo.getResourcePath(), 14063 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14064 } else { 14065 res.removedInfo.args = null; 14066 } 14067 14068 // Successfully disabled the old package. Now proceed with re-installation 14069 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14070 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14071 clearAppProfilesLIF(pkg); 14072 14073 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14074 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14075 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14076 14077 PackageParser.Package newPackage = null; 14078 try { 14079 // Add the package to the internal data structures 14080 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14081 14082 // Set the update and install times 14083 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14084 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14085 System.currentTimeMillis()); 14086 14087 // Update the package dynamic state if succeeded 14088 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14089 // Now that the install succeeded make sure we remove data 14090 // directories for any child package the update removed. 14091 final int deletedChildCount = (deletedPackage.childPackages != null) 14092 ? deletedPackage.childPackages.size() : 0; 14093 final int newChildCount = (newPackage.childPackages != null) 14094 ? newPackage.childPackages.size() : 0; 14095 for (int i = 0; i < deletedChildCount; i++) { 14096 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14097 boolean childPackageDeleted = true; 14098 for (int j = 0; j < newChildCount; j++) { 14099 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14100 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14101 childPackageDeleted = false; 14102 break; 14103 } 14104 } 14105 if (childPackageDeleted) { 14106 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14107 deletedChildPkg.packageName); 14108 if (ps != null && res.removedInfo.removedChildPackages != null) { 14109 PackageRemovedInfo removedChildRes = res.removedInfo 14110 .removedChildPackages.get(deletedChildPkg.packageName); 14111 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14112 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14113 } 14114 } 14115 } 14116 14117 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14118 prepareAppDataAfterInstallLIF(newPackage); 14119 } 14120 } catch (PackageManagerException e) { 14121 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14122 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14123 } 14124 14125 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14126 // Re installation failed. Restore old information 14127 // Remove new pkg information 14128 if (newPackage != null) { 14129 removeInstalledPackageLI(newPackage, true); 14130 } 14131 // Add back the old system package 14132 try { 14133 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14134 } catch (PackageManagerException e) { 14135 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14136 } 14137 14138 synchronized (mPackages) { 14139 if (disabledSystem) { 14140 enableSystemPackageLPw(deletedPackage); 14141 } 14142 14143 // Ensure the installer package name up to date 14144 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14145 14146 // Update permissions for restored package 14147 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14148 14149 mSettings.writeLPr(); 14150 } 14151 14152 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14153 + " after failed upgrade"); 14154 } 14155 } 14156 14157 /** 14158 * Checks whether the parent or any of the child packages have a change shared 14159 * user. For a package to be a valid update the shred users of the parent and 14160 * the children should match. We may later support changing child shared users. 14161 * @param oldPkg The updated package. 14162 * @param newPkg The update package. 14163 * @return The shared user that change between the versions. 14164 */ 14165 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14166 PackageParser.Package newPkg) { 14167 // Check parent shared user 14168 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14169 return newPkg.packageName; 14170 } 14171 // Check child shared users 14172 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14173 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14174 for (int i = 0; i < newChildCount; i++) { 14175 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14176 // If this child was present, did it have the same shared user? 14177 for (int j = 0; j < oldChildCount; j++) { 14178 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14179 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14180 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14181 return newChildPkg.packageName; 14182 } 14183 } 14184 } 14185 return null; 14186 } 14187 14188 private void removeNativeBinariesLI(PackageSetting ps) { 14189 // Remove the lib path for the parent package 14190 if (ps != null) { 14191 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14192 // Remove the lib path for the child packages 14193 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14194 for (int i = 0; i < childCount; i++) { 14195 PackageSetting childPs = null; 14196 synchronized (mPackages) { 14197 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14198 } 14199 if (childPs != null) { 14200 NativeLibraryHelper.removeNativeBinariesLI(childPs 14201 .legacyNativeLibraryPathString); 14202 } 14203 } 14204 } 14205 } 14206 14207 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14208 // Enable the parent package 14209 mSettings.enableSystemPackageLPw(pkg.packageName); 14210 // Enable the child packages 14211 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14212 for (int i = 0; i < childCount; i++) { 14213 PackageParser.Package childPkg = pkg.childPackages.get(i); 14214 mSettings.enableSystemPackageLPw(childPkg.packageName); 14215 } 14216 } 14217 14218 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14219 PackageParser.Package newPkg) { 14220 // Disable the parent package (parent always replaced) 14221 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14222 // Disable the child packages 14223 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14224 for (int i = 0; i < childCount; i++) { 14225 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14226 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14227 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14228 } 14229 return disabled; 14230 } 14231 14232 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14233 String installerPackageName) { 14234 // Enable the parent package 14235 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14236 // Enable the child packages 14237 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14238 for (int i = 0; i < childCount; i++) { 14239 PackageParser.Package childPkg = pkg.childPackages.get(i); 14240 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14241 } 14242 } 14243 14244 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14245 // Collect all used permissions in the UID 14246 ArraySet<String> usedPermissions = new ArraySet<>(); 14247 final int packageCount = su.packages.size(); 14248 for (int i = 0; i < packageCount; i++) { 14249 PackageSetting ps = su.packages.valueAt(i); 14250 if (ps.pkg == null) { 14251 continue; 14252 } 14253 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14254 for (int j = 0; j < requestedPermCount; j++) { 14255 String permission = ps.pkg.requestedPermissions.get(j); 14256 BasePermission bp = mSettings.mPermissions.get(permission); 14257 if (bp != null) { 14258 usedPermissions.add(permission); 14259 } 14260 } 14261 } 14262 14263 PermissionsState permissionsState = su.getPermissionsState(); 14264 // Prune install permissions 14265 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14266 final int installPermCount = installPermStates.size(); 14267 for (int i = installPermCount - 1; i >= 0; i--) { 14268 PermissionState permissionState = installPermStates.get(i); 14269 if (!usedPermissions.contains(permissionState.getName())) { 14270 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14271 if (bp != null) { 14272 permissionsState.revokeInstallPermission(bp); 14273 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14274 PackageManager.MASK_PERMISSION_FLAGS, 0); 14275 } 14276 } 14277 } 14278 14279 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14280 14281 // Prune runtime permissions 14282 for (int userId : allUserIds) { 14283 List<PermissionState> runtimePermStates = permissionsState 14284 .getRuntimePermissionStates(userId); 14285 final int runtimePermCount = runtimePermStates.size(); 14286 for (int i = runtimePermCount - 1; i >= 0; i--) { 14287 PermissionState permissionState = runtimePermStates.get(i); 14288 if (!usedPermissions.contains(permissionState.getName())) { 14289 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14290 if (bp != null) { 14291 permissionsState.revokeRuntimePermission(bp, userId); 14292 permissionsState.updatePermissionFlags(bp, userId, 14293 PackageManager.MASK_PERMISSION_FLAGS, 0); 14294 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14295 runtimePermissionChangedUserIds, userId); 14296 } 14297 } 14298 } 14299 } 14300 14301 return runtimePermissionChangedUserIds; 14302 } 14303 14304 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14305 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14306 // Update the parent package setting 14307 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14308 res, user); 14309 // Update the child packages setting 14310 final int childCount = (newPackage.childPackages != null) 14311 ? newPackage.childPackages.size() : 0; 14312 for (int i = 0; i < childCount; i++) { 14313 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14314 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14315 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14316 childRes.origUsers, childRes, user); 14317 } 14318 } 14319 14320 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14321 String installerPackageName, int[] allUsers, int[] installedForUsers, 14322 PackageInstalledInfo res, UserHandle user) { 14323 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14324 14325 String pkgName = newPackage.packageName; 14326 synchronized (mPackages) { 14327 //write settings. the installStatus will be incomplete at this stage. 14328 //note that the new package setting would have already been 14329 //added to mPackages. It hasn't been persisted yet. 14330 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14331 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14332 mSettings.writeLPr(); 14333 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14334 } 14335 14336 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14337 synchronized (mPackages) { 14338 updatePermissionsLPw(newPackage.packageName, newPackage, 14339 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14340 ? UPDATE_PERMISSIONS_ALL : 0)); 14341 // For system-bundled packages, we assume that installing an upgraded version 14342 // of the package implies that the user actually wants to run that new code, 14343 // so we enable the package. 14344 PackageSetting ps = mSettings.mPackages.get(pkgName); 14345 final int userId = user.getIdentifier(); 14346 if (ps != null) { 14347 if (isSystemApp(newPackage)) { 14348 if (DEBUG_INSTALL) { 14349 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14350 } 14351 // Enable system package for requested users 14352 if (res.origUsers != null) { 14353 for (int origUserId : res.origUsers) { 14354 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14355 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14356 origUserId, installerPackageName); 14357 } 14358 } 14359 } 14360 // Also convey the prior install/uninstall state 14361 if (allUsers != null && installedForUsers != null) { 14362 for (int currentUserId : allUsers) { 14363 final boolean installed = ArrayUtils.contains( 14364 installedForUsers, currentUserId); 14365 if (DEBUG_INSTALL) { 14366 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14367 } 14368 ps.setInstalled(installed, currentUserId); 14369 } 14370 // these install state changes will be persisted in the 14371 // upcoming call to mSettings.writeLPr(). 14372 } 14373 } 14374 // It's implied that when a user requests installation, they want the app to be 14375 // installed and enabled. 14376 if (userId != UserHandle.USER_ALL) { 14377 ps.setInstalled(true, userId); 14378 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14379 } 14380 } 14381 res.name = pkgName; 14382 res.uid = newPackage.applicationInfo.uid; 14383 res.pkg = newPackage; 14384 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14385 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14386 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14387 //to update install status 14388 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14389 mSettings.writeLPr(); 14390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14391 } 14392 14393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14394 } 14395 14396 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14397 try { 14398 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14399 installPackageLI(args, res); 14400 } finally { 14401 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14402 } 14403 } 14404 14405 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14406 final int installFlags = args.installFlags; 14407 final String installerPackageName = args.installerPackageName; 14408 final String volumeUuid = args.volumeUuid; 14409 final File tmpPackageFile = new File(args.getCodePath()); 14410 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14411 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14412 || (args.volumeUuid != null)); 14413 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14414 boolean replace = false; 14415 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14416 if (args.move != null) { 14417 // moving a complete application; perform an initial scan on the new install location 14418 scanFlags |= SCAN_INITIAL; 14419 } 14420 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14421 scanFlags |= SCAN_DONT_KILL_APP; 14422 } 14423 14424 // Result object to be returned 14425 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14426 14427 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14428 14429 // Sanity check 14430 if (ephemeral && (forwardLocked || onExternal)) { 14431 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14432 + " external=" + onExternal); 14433 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14434 return; 14435 } 14436 14437 // Retrieve PackageSettings and parse package 14438 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14439 | PackageParser.PARSE_ENFORCE_CODE 14440 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14441 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14442 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14443 PackageParser pp = new PackageParser(); 14444 pp.setSeparateProcesses(mSeparateProcesses); 14445 pp.setDisplayMetrics(mMetrics); 14446 14447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14448 final PackageParser.Package pkg; 14449 try { 14450 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14451 } catch (PackageParserException e) { 14452 res.setError("Failed parse during installPackageLI", e); 14453 return; 14454 } finally { 14455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14456 } 14457 14458 // If we are installing a clustered package add results for the children 14459 if (pkg.childPackages != null) { 14460 synchronized (mPackages) { 14461 final int childCount = pkg.childPackages.size(); 14462 for (int i = 0; i < childCount; i++) { 14463 PackageParser.Package childPkg = pkg.childPackages.get(i); 14464 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14465 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14466 childRes.pkg = childPkg; 14467 childRes.name = childPkg.packageName; 14468 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14469 if (childPs != null) { 14470 childRes.origUsers = childPs.queryInstalledUsers( 14471 sUserManager.getUserIds(), true); 14472 } 14473 if ((mPackages.containsKey(childPkg.packageName))) { 14474 childRes.removedInfo = new PackageRemovedInfo(); 14475 childRes.removedInfo.removedPackage = childPkg.packageName; 14476 } 14477 if (res.addedChildPackages == null) { 14478 res.addedChildPackages = new ArrayMap<>(); 14479 } 14480 res.addedChildPackages.put(childPkg.packageName, childRes); 14481 } 14482 } 14483 } 14484 14485 // If package doesn't declare API override, mark that we have an install 14486 // time CPU ABI override. 14487 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14488 pkg.cpuAbiOverride = args.abiOverride; 14489 } 14490 14491 String pkgName = res.name = pkg.packageName; 14492 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14493 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14494 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14495 return; 14496 } 14497 } 14498 14499 try { 14500 // either use what we've been given or parse directly from the APK 14501 if (args.certificates != null) { 14502 try { 14503 PackageParser.populateCertificates(pkg, args.certificates); 14504 } catch (PackageParserException e) { 14505 // there was something wrong with the certificates we were given; 14506 // try to pull them from the APK 14507 PackageParser.collectCertificates(pkg, parseFlags); 14508 } 14509 } else { 14510 PackageParser.collectCertificates(pkg, parseFlags); 14511 } 14512 } catch (PackageParserException e) { 14513 res.setError("Failed collect during installPackageLI", e); 14514 return; 14515 } 14516 14517 // Get rid of all references to package scan path via parser. 14518 pp = null; 14519 String oldCodePath = null; 14520 boolean systemApp = false; 14521 synchronized (mPackages) { 14522 // Check if installing already existing package 14523 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14524 String oldName = mSettings.mRenamedPackages.get(pkgName); 14525 if (pkg.mOriginalPackages != null 14526 && pkg.mOriginalPackages.contains(oldName) 14527 && mPackages.containsKey(oldName)) { 14528 // This package is derived from an original package, 14529 // and this device has been updating from that original 14530 // name. We must continue using the original name, so 14531 // rename the new package here. 14532 pkg.setPackageName(oldName); 14533 pkgName = pkg.packageName; 14534 replace = true; 14535 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14536 + oldName + " pkgName=" + pkgName); 14537 } else if (mPackages.containsKey(pkgName)) { 14538 // This package, under its official name, already exists 14539 // on the device; we should replace it. 14540 replace = true; 14541 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14542 } 14543 14544 // Child packages are installed through the parent package 14545 if (pkg.parentPackage != null) { 14546 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14547 "Package " + pkg.packageName + " is child of package " 14548 + pkg.parentPackage.parentPackage + ". Child packages " 14549 + "can be updated only through the parent package."); 14550 return; 14551 } 14552 14553 if (replace) { 14554 // Prevent apps opting out from runtime permissions 14555 PackageParser.Package oldPackage = mPackages.get(pkgName); 14556 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14557 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14558 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14559 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14560 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14561 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14562 + " doesn't support runtime permissions but the old" 14563 + " target SDK " + oldTargetSdk + " does."); 14564 return; 14565 } 14566 14567 // Prevent installing of child packages 14568 if (oldPackage.parentPackage != null) { 14569 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14570 "Package " + pkg.packageName + " is child of package " 14571 + oldPackage.parentPackage + ". Child packages " 14572 + "can be updated only through the parent package."); 14573 return; 14574 } 14575 } 14576 } 14577 14578 PackageSetting ps = mSettings.mPackages.get(pkgName); 14579 if (ps != null) { 14580 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14581 14582 // Quick sanity check that we're signed correctly if updating; 14583 // we'll check this again later when scanning, but we want to 14584 // bail early here before tripping over redefined permissions. 14585 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14586 if (!checkUpgradeKeySetLP(ps, pkg)) { 14587 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14588 + pkg.packageName + " upgrade keys do not match the " 14589 + "previously installed version"); 14590 return; 14591 } 14592 } else { 14593 try { 14594 verifySignaturesLP(ps, pkg); 14595 } catch (PackageManagerException e) { 14596 res.setError(e.error, e.getMessage()); 14597 return; 14598 } 14599 } 14600 14601 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14602 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14603 systemApp = (ps.pkg.applicationInfo.flags & 14604 ApplicationInfo.FLAG_SYSTEM) != 0; 14605 } 14606 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14607 } 14608 14609 // Check whether the newly-scanned package wants to define an already-defined perm 14610 int N = pkg.permissions.size(); 14611 for (int i = N-1; i >= 0; i--) { 14612 PackageParser.Permission perm = pkg.permissions.get(i); 14613 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14614 if (bp != null) { 14615 // If the defining package is signed with our cert, it's okay. This 14616 // also includes the "updating the same package" case, of course. 14617 // "updating same package" could also involve key-rotation. 14618 final boolean sigsOk; 14619 if (bp.sourcePackage.equals(pkg.packageName) 14620 && (bp.packageSetting instanceof PackageSetting) 14621 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14622 scanFlags))) { 14623 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14624 } else { 14625 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14626 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14627 } 14628 if (!sigsOk) { 14629 // If the owning package is the system itself, we log but allow 14630 // install to proceed; we fail the install on all other permission 14631 // redefinitions. 14632 if (!bp.sourcePackage.equals("android")) { 14633 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14634 + pkg.packageName + " attempting to redeclare permission " 14635 + perm.info.name + " already owned by " + bp.sourcePackage); 14636 res.origPermission = perm.info.name; 14637 res.origPackage = bp.sourcePackage; 14638 return; 14639 } else { 14640 Slog.w(TAG, "Package " + pkg.packageName 14641 + " attempting to redeclare system permission " 14642 + perm.info.name + "; ignoring new declaration"); 14643 pkg.permissions.remove(i); 14644 } 14645 } 14646 } 14647 } 14648 } 14649 14650 if (systemApp) { 14651 if (onExternal) { 14652 // Abort update; system app can't be replaced with app on sdcard 14653 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14654 "Cannot install updates to system apps on sdcard"); 14655 return; 14656 } else if (ephemeral) { 14657 // Abort update; system app can't be replaced with an ephemeral app 14658 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14659 "Cannot update a system app with an ephemeral app"); 14660 return; 14661 } 14662 } 14663 14664 if (args.move != null) { 14665 // We did an in-place move, so dex is ready to roll 14666 scanFlags |= SCAN_NO_DEX; 14667 scanFlags |= SCAN_MOVE; 14668 14669 synchronized (mPackages) { 14670 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14671 if (ps == null) { 14672 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14673 "Missing settings for moved package " + pkgName); 14674 } 14675 14676 // We moved the entire application as-is, so bring over the 14677 // previously derived ABI information. 14678 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14679 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14680 } 14681 14682 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14683 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14684 scanFlags |= SCAN_NO_DEX; 14685 14686 try { 14687 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14688 args.abiOverride : pkg.cpuAbiOverride); 14689 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14690 true /* extract libs */); 14691 } catch (PackageManagerException pme) { 14692 Slog.e(TAG, "Error deriving application ABI", pme); 14693 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14694 return; 14695 } 14696 14697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14698 // Do not run PackageDexOptimizer through the local performDexOpt 14699 // method because `pkg` is not in `mPackages` yet. 14700 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14701 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14702 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14703 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14704 String msg = "Extracting package failed for " + pkgName; 14705 res.setError(INSTALL_FAILED_DEXOPT, msg); 14706 return; 14707 } 14708 14709 // Notify BackgroundDexOptService that the package has been changed. 14710 // If this is an update of a package which used to fail to compile, 14711 // BDOS will remove it from its blacklist. 14712 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14713 } 14714 14715 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14716 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14717 return; 14718 } 14719 14720 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14721 14722 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14723 "installPackageLI")) { 14724 if (replace) { 14725 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14726 installerPackageName, res); 14727 } else { 14728 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14729 args.user, installerPackageName, volumeUuid, res); 14730 } 14731 } 14732 synchronized (mPackages) { 14733 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14734 if (ps != null) { 14735 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14736 } 14737 14738 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14739 for (int i = 0; i < childCount; i++) { 14740 PackageParser.Package childPkg = pkg.childPackages.get(i); 14741 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14742 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14743 if (childPs != null) { 14744 childRes.newUsers = childPs.queryInstalledUsers( 14745 sUserManager.getUserIds(), true); 14746 } 14747 } 14748 } 14749 } 14750 14751 private void startIntentFilterVerifications(int userId, boolean replacing, 14752 PackageParser.Package pkg) { 14753 if (mIntentFilterVerifierComponent == null) { 14754 Slog.w(TAG, "No IntentFilter verification will not be done as " 14755 + "there is no IntentFilterVerifier available!"); 14756 return; 14757 } 14758 14759 final int verifierUid = getPackageUid( 14760 mIntentFilterVerifierComponent.getPackageName(), 14761 MATCH_DEBUG_TRIAGED_MISSING, 14762 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14763 14764 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14765 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14766 mHandler.sendMessage(msg); 14767 14768 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14769 for (int i = 0; i < childCount; i++) { 14770 PackageParser.Package childPkg = pkg.childPackages.get(i); 14771 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14772 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14773 mHandler.sendMessage(msg); 14774 } 14775 } 14776 14777 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14778 PackageParser.Package pkg) { 14779 int size = pkg.activities.size(); 14780 if (size == 0) { 14781 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14782 "No activity, so no need to verify any IntentFilter!"); 14783 return; 14784 } 14785 14786 final boolean hasDomainURLs = hasDomainURLs(pkg); 14787 if (!hasDomainURLs) { 14788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14789 "No domain URLs, so no need to verify any IntentFilter!"); 14790 return; 14791 } 14792 14793 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14794 + " if any IntentFilter from the " + size 14795 + " Activities needs verification ..."); 14796 14797 int count = 0; 14798 final String packageName = pkg.packageName; 14799 14800 synchronized (mPackages) { 14801 // If this is a new install and we see that we've already run verification for this 14802 // package, we have nothing to do: it means the state was restored from backup. 14803 if (!replacing) { 14804 IntentFilterVerificationInfo ivi = 14805 mSettings.getIntentFilterVerificationLPr(packageName); 14806 if (ivi != null) { 14807 if (DEBUG_DOMAIN_VERIFICATION) { 14808 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14809 + ivi.getStatusString()); 14810 } 14811 return; 14812 } 14813 } 14814 14815 // If any filters need to be verified, then all need to be. 14816 boolean needToVerify = false; 14817 for (PackageParser.Activity a : pkg.activities) { 14818 for (ActivityIntentInfo filter : a.intents) { 14819 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14820 if (DEBUG_DOMAIN_VERIFICATION) { 14821 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14822 } 14823 needToVerify = true; 14824 break; 14825 } 14826 } 14827 } 14828 14829 if (needToVerify) { 14830 final int verificationId = mIntentFilterVerificationToken++; 14831 for (PackageParser.Activity a : pkg.activities) { 14832 for (ActivityIntentInfo filter : a.intents) { 14833 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14835 "Verification needed for IntentFilter:" + filter.toString()); 14836 mIntentFilterVerifier.addOneIntentFilterVerification( 14837 verifierUid, userId, verificationId, filter, packageName); 14838 count++; 14839 } 14840 } 14841 } 14842 } 14843 } 14844 14845 if (count > 0) { 14846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14847 + " IntentFilter verification" + (count > 1 ? "s" : "") 14848 + " for userId:" + userId); 14849 mIntentFilterVerifier.startVerifications(userId); 14850 } else { 14851 if (DEBUG_DOMAIN_VERIFICATION) { 14852 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14853 } 14854 } 14855 } 14856 14857 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14858 final ComponentName cn = filter.activity.getComponentName(); 14859 final String packageName = cn.getPackageName(); 14860 14861 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14862 packageName); 14863 if (ivi == null) { 14864 return true; 14865 } 14866 int status = ivi.getStatus(); 14867 switch (status) { 14868 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14869 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14870 return true; 14871 14872 default: 14873 // Nothing to do 14874 return false; 14875 } 14876 } 14877 14878 private static boolean isMultiArch(ApplicationInfo info) { 14879 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14880 } 14881 14882 private static boolean isExternal(PackageParser.Package pkg) { 14883 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14884 } 14885 14886 private static boolean isExternal(PackageSetting ps) { 14887 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14888 } 14889 14890 private static boolean isEphemeral(PackageParser.Package pkg) { 14891 return pkg.applicationInfo.isEphemeralApp(); 14892 } 14893 14894 private static boolean isEphemeral(PackageSetting ps) { 14895 return ps.pkg != null && isEphemeral(ps.pkg); 14896 } 14897 14898 private static boolean isSystemApp(PackageParser.Package pkg) { 14899 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14900 } 14901 14902 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14903 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14904 } 14905 14906 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14907 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14908 } 14909 14910 private static boolean isSystemApp(PackageSetting ps) { 14911 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14912 } 14913 14914 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14915 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14916 } 14917 14918 private int packageFlagsToInstallFlags(PackageSetting ps) { 14919 int installFlags = 0; 14920 if (isEphemeral(ps)) { 14921 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14922 } 14923 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14924 // This existing package was an external ASEC install when we have 14925 // the external flag without a UUID 14926 installFlags |= PackageManager.INSTALL_EXTERNAL; 14927 } 14928 if (ps.isForwardLocked()) { 14929 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14930 } 14931 return installFlags; 14932 } 14933 14934 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14935 if (isExternal(pkg)) { 14936 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14937 return StorageManager.UUID_PRIMARY_PHYSICAL; 14938 } else { 14939 return pkg.volumeUuid; 14940 } 14941 } else { 14942 return StorageManager.UUID_PRIVATE_INTERNAL; 14943 } 14944 } 14945 14946 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14947 if (isExternal(pkg)) { 14948 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14949 return mSettings.getExternalVersion(); 14950 } else { 14951 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14952 } 14953 } else { 14954 return mSettings.getInternalVersion(); 14955 } 14956 } 14957 14958 private void deleteTempPackageFiles() { 14959 final FilenameFilter filter = new FilenameFilter() { 14960 public boolean accept(File dir, String name) { 14961 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14962 } 14963 }; 14964 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14965 file.delete(); 14966 } 14967 } 14968 14969 @Override 14970 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14971 int flags) { 14972 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14973 flags); 14974 } 14975 14976 @Override 14977 public void deletePackage(final String packageName, 14978 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14979 mContext.enforceCallingOrSelfPermission( 14980 android.Manifest.permission.DELETE_PACKAGES, null); 14981 Preconditions.checkNotNull(packageName); 14982 Preconditions.checkNotNull(observer); 14983 final int uid = Binder.getCallingUid(); 14984 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14985 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14986 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14987 mContext.enforceCallingOrSelfPermission( 14988 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14989 "deletePackage for user " + userId); 14990 } 14991 14992 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14993 try { 14994 observer.onPackageDeleted(packageName, 14995 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14996 } catch (RemoteException re) { 14997 } 14998 return; 14999 } 15000 15001 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15002 try { 15003 observer.onPackageDeleted(packageName, 15004 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15005 } catch (RemoteException re) { 15006 } 15007 return; 15008 } 15009 15010 if (DEBUG_REMOVE) { 15011 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15012 + " deleteAllUsers: " + deleteAllUsers ); 15013 } 15014 // Queue up an async operation since the package deletion may take a little while. 15015 mHandler.post(new Runnable() { 15016 public void run() { 15017 mHandler.removeCallbacks(this); 15018 int returnCode; 15019 if (!deleteAllUsers) { 15020 returnCode = deletePackageX(packageName, userId, deleteFlags); 15021 } else { 15022 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15023 // If nobody is blocking uninstall, proceed with delete for all users 15024 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15025 returnCode = deletePackageX(packageName, userId, deleteFlags); 15026 } else { 15027 // Otherwise uninstall individually for users with blockUninstalls=false 15028 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15029 for (int userId : users) { 15030 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15031 returnCode = deletePackageX(packageName, userId, userFlags); 15032 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15033 Slog.w(TAG, "Package delete failed for user " + userId 15034 + ", returnCode " + returnCode); 15035 } 15036 } 15037 } 15038 // The app has only been marked uninstalled for certain users. 15039 // We still need to report that delete was blocked 15040 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15041 } 15042 } 15043 try { 15044 observer.onPackageDeleted(packageName, returnCode, null); 15045 } catch (RemoteException e) { 15046 Log.i(TAG, "Observer no longer exists."); 15047 } //end catch 15048 } //end run 15049 }); 15050 } 15051 15052 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15053 int[] result = EMPTY_INT_ARRAY; 15054 for (int userId : userIds) { 15055 if (getBlockUninstallForUser(packageName, userId)) { 15056 result = ArrayUtils.appendInt(result, userId); 15057 } 15058 } 15059 return result; 15060 } 15061 15062 @Override 15063 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15064 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15065 } 15066 15067 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15068 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15069 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15070 try { 15071 if (dpm != null) { 15072 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15073 /* callingUserOnly =*/ false); 15074 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15075 : deviceOwnerComponentName.getPackageName(); 15076 // Does the package contains the device owner? 15077 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15078 // this check is probably not needed, since DO should be registered as a device 15079 // admin on some user too. (Original bug for this: b/17657954) 15080 if (packageName.equals(deviceOwnerPackageName)) { 15081 return true; 15082 } 15083 // Does it contain a device admin for any user? 15084 int[] users; 15085 if (userId == UserHandle.USER_ALL) { 15086 users = sUserManager.getUserIds(); 15087 } else { 15088 users = new int[]{userId}; 15089 } 15090 for (int i = 0; i < users.length; ++i) { 15091 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15092 return true; 15093 } 15094 } 15095 } 15096 } catch (RemoteException e) { 15097 } 15098 return false; 15099 } 15100 15101 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15102 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15103 } 15104 15105 /** 15106 * This method is an internal method that could be get invoked either 15107 * to delete an installed package or to clean up a failed installation. 15108 * After deleting an installed package, a broadcast is sent to notify any 15109 * listeners that the package has been removed. For cleaning up a failed 15110 * installation, the broadcast is not necessary since the package's 15111 * installation wouldn't have sent the initial broadcast either 15112 * The key steps in deleting a package are 15113 * deleting the package information in internal structures like mPackages, 15114 * deleting the packages base directories through installd 15115 * updating mSettings to reflect current status 15116 * persisting settings for later use 15117 * sending a broadcast if necessary 15118 */ 15119 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15120 final PackageRemovedInfo info = new PackageRemovedInfo(); 15121 final boolean res; 15122 15123 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15124 ? UserHandle.ALL : new UserHandle(userId); 15125 15126 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15127 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15128 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15129 } 15130 15131 PackageSetting uninstalledPs = null; 15132 15133 // for the uninstall-updates case and restricted profiles, remember the per- 15134 // user handle installed state 15135 int[] allUsers; 15136 synchronized (mPackages) { 15137 uninstalledPs = mSettings.mPackages.get(packageName); 15138 if (uninstalledPs == null) { 15139 Slog.w(TAG, "Not removing non-existent package " + packageName); 15140 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15141 } 15142 allUsers = sUserManager.getUserIds(); 15143 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15144 } 15145 15146 synchronized (mInstallLock) { 15147 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15148 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15149 "deletePackageX")) { 15150 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15151 deleteFlags | REMOVE_CHATTY, info, true, null); 15152 } 15153 synchronized (mPackages) { 15154 if (res) { 15155 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15156 } 15157 } 15158 } 15159 15160 if (res) { 15161 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15162 info.sendPackageRemovedBroadcasts(killApp); 15163 info.sendSystemPackageUpdatedBroadcasts(); 15164 info.sendSystemPackageAppearedBroadcasts(); 15165 } 15166 // Force a gc here. 15167 Runtime.getRuntime().gc(); 15168 // Delete the resources here after sending the broadcast to let 15169 // other processes clean up before deleting resources. 15170 if (info.args != null) { 15171 synchronized (mInstallLock) { 15172 info.args.doPostDeleteLI(true); 15173 } 15174 } 15175 15176 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15177 } 15178 15179 class PackageRemovedInfo { 15180 String removedPackage; 15181 int uid = -1; 15182 int removedAppId = -1; 15183 int[] origUsers; 15184 int[] removedUsers = null; 15185 boolean isRemovedPackageSystemUpdate = false; 15186 boolean isUpdate; 15187 boolean dataRemoved; 15188 boolean removedForAllUsers; 15189 // Clean up resources deleted packages. 15190 InstallArgs args = null; 15191 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15192 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15193 15194 void sendPackageRemovedBroadcasts(boolean killApp) { 15195 sendPackageRemovedBroadcastInternal(killApp); 15196 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15197 for (int i = 0; i < childCount; i++) { 15198 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15199 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15200 } 15201 } 15202 15203 void sendSystemPackageUpdatedBroadcasts() { 15204 if (isRemovedPackageSystemUpdate) { 15205 sendSystemPackageUpdatedBroadcastsInternal(); 15206 final int childCount = (removedChildPackages != null) 15207 ? removedChildPackages.size() : 0; 15208 for (int i = 0; i < childCount; i++) { 15209 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15210 if (childInfo.isRemovedPackageSystemUpdate) { 15211 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15212 } 15213 } 15214 } 15215 } 15216 15217 void sendSystemPackageAppearedBroadcasts() { 15218 final int packageCount = (appearedChildPackages != null) 15219 ? appearedChildPackages.size() : 0; 15220 for (int i = 0; i < packageCount; i++) { 15221 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15222 for (int userId : installedInfo.newUsers) { 15223 sendPackageAddedForUser(installedInfo.name, true, 15224 UserHandle.getAppId(installedInfo.uid), userId); 15225 } 15226 } 15227 } 15228 15229 private void sendSystemPackageUpdatedBroadcastsInternal() { 15230 Bundle extras = new Bundle(2); 15231 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15232 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15233 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15234 extras, 0, null, null, null); 15235 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15236 extras, 0, null, null, null); 15237 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15238 null, 0, removedPackage, null, null); 15239 } 15240 15241 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15242 Bundle extras = new Bundle(2); 15243 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15244 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15245 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15246 if (isUpdate || isRemovedPackageSystemUpdate) { 15247 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15248 } 15249 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15250 if (removedPackage != null) { 15251 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15252 extras, 0, null, null, removedUsers); 15253 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15254 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15255 removedPackage, extras, 0, null, null, removedUsers); 15256 } 15257 } 15258 if (removedAppId >= 0) { 15259 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15260 removedUsers); 15261 } 15262 } 15263 } 15264 15265 /* 15266 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15267 * flag is not set, the data directory is removed as well. 15268 * make sure this flag is set for partially installed apps. If not its meaningless to 15269 * delete a partially installed application. 15270 */ 15271 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15272 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15273 String packageName = ps.name; 15274 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15275 // Retrieve object to delete permissions for shared user later on 15276 final PackageParser.Package deletedPkg; 15277 final PackageSetting deletedPs; 15278 // reader 15279 synchronized (mPackages) { 15280 deletedPkg = mPackages.get(packageName); 15281 deletedPs = mSettings.mPackages.get(packageName); 15282 if (outInfo != null) { 15283 outInfo.removedPackage = packageName; 15284 outInfo.removedUsers = deletedPs != null 15285 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15286 : null; 15287 } 15288 } 15289 15290 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15291 15292 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15293 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15294 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15295 destroyAppProfilesLIF(deletedPkg); 15296 if (outInfo != null) { 15297 outInfo.dataRemoved = true; 15298 } 15299 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15300 } 15301 15302 // writer 15303 synchronized (mPackages) { 15304 if (deletedPs != null) { 15305 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15306 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15307 clearDefaultBrowserIfNeeded(packageName); 15308 if (outInfo != null) { 15309 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15310 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15311 } 15312 updatePermissionsLPw(deletedPs.name, null, 0); 15313 if (deletedPs.sharedUser != null) { 15314 // Remove permissions associated with package. Since runtime 15315 // permissions are per user we have to kill the removed package 15316 // or packages running under the shared user of the removed 15317 // package if revoking the permissions requested only by the removed 15318 // package is successful and this causes a change in gids. 15319 for (int userId : UserManagerService.getInstance().getUserIds()) { 15320 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15321 userId); 15322 if (userIdToKill == UserHandle.USER_ALL 15323 || userIdToKill >= UserHandle.USER_SYSTEM) { 15324 // If gids changed for this user, kill all affected packages. 15325 mHandler.post(new Runnable() { 15326 @Override 15327 public void run() { 15328 // This has to happen with no lock held. 15329 killApplication(deletedPs.name, deletedPs.appId, 15330 KILL_APP_REASON_GIDS_CHANGED); 15331 } 15332 }); 15333 break; 15334 } 15335 } 15336 } 15337 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15338 } 15339 // make sure to preserve per-user disabled state if this removal was just 15340 // a downgrade of a system app to the factory package 15341 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15342 if (DEBUG_REMOVE) { 15343 Slog.d(TAG, "Propagating install state across downgrade"); 15344 } 15345 for (int userId : allUserHandles) { 15346 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15347 if (DEBUG_REMOVE) { 15348 Slog.d(TAG, " user " + userId + " => " + installed); 15349 } 15350 ps.setInstalled(installed, userId); 15351 } 15352 } 15353 } 15354 // can downgrade to reader 15355 if (writeSettings) { 15356 // Save settings now 15357 mSettings.writeLPr(); 15358 } 15359 } 15360 if (outInfo != null) { 15361 // A user ID was deleted here. Go through all users and remove it 15362 // from KeyStore. 15363 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15364 } 15365 } 15366 15367 static boolean locationIsPrivileged(File path) { 15368 try { 15369 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15370 .getCanonicalPath(); 15371 return path.getCanonicalPath().startsWith(privilegedAppDir); 15372 } catch (IOException e) { 15373 Slog.e(TAG, "Unable to access code path " + path); 15374 } 15375 return false; 15376 } 15377 15378 /* 15379 * Tries to delete system package. 15380 */ 15381 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15382 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15383 boolean writeSettings) { 15384 if (deletedPs.parentPackageName != null) { 15385 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15386 return false; 15387 } 15388 15389 final boolean applyUserRestrictions 15390 = (allUserHandles != null) && (outInfo.origUsers != null); 15391 final PackageSetting disabledPs; 15392 // Confirm if the system package has been updated 15393 // An updated system app can be deleted. This will also have to restore 15394 // the system pkg from system partition 15395 // reader 15396 synchronized (mPackages) { 15397 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15398 } 15399 15400 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15401 + " disabledPs=" + disabledPs); 15402 15403 if (disabledPs == null) { 15404 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15405 return false; 15406 } else if (DEBUG_REMOVE) { 15407 Slog.d(TAG, "Deleting system pkg from data partition"); 15408 } 15409 15410 if (DEBUG_REMOVE) { 15411 if (applyUserRestrictions) { 15412 Slog.d(TAG, "Remembering install states:"); 15413 for (int userId : allUserHandles) { 15414 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15415 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15416 } 15417 } 15418 } 15419 15420 // Delete the updated package 15421 outInfo.isRemovedPackageSystemUpdate = true; 15422 if (outInfo.removedChildPackages != null) { 15423 final int childCount = (deletedPs.childPackageNames != null) 15424 ? deletedPs.childPackageNames.size() : 0; 15425 for (int i = 0; i < childCount; i++) { 15426 String childPackageName = deletedPs.childPackageNames.get(i); 15427 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15428 .contains(childPackageName)) { 15429 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15430 childPackageName); 15431 if (childInfo != null) { 15432 childInfo.isRemovedPackageSystemUpdate = true; 15433 } 15434 } 15435 } 15436 } 15437 15438 if (disabledPs.versionCode < deletedPs.versionCode) { 15439 // Delete data for downgrades 15440 flags &= ~PackageManager.DELETE_KEEP_DATA; 15441 } else { 15442 // Preserve data by setting flag 15443 flags |= PackageManager.DELETE_KEEP_DATA; 15444 } 15445 15446 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15447 outInfo, writeSettings, disabledPs.pkg); 15448 if (!ret) { 15449 return false; 15450 } 15451 15452 // writer 15453 synchronized (mPackages) { 15454 // Reinstate the old system package 15455 enableSystemPackageLPw(disabledPs.pkg); 15456 // Remove any native libraries from the upgraded package. 15457 removeNativeBinariesLI(deletedPs); 15458 } 15459 15460 // Install the system package 15461 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15462 int parseFlags = mDefParseFlags 15463 | PackageParser.PARSE_MUST_BE_APK 15464 | PackageParser.PARSE_IS_SYSTEM 15465 | PackageParser.PARSE_IS_SYSTEM_DIR; 15466 if (locationIsPrivileged(disabledPs.codePath)) { 15467 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15468 } 15469 15470 final PackageParser.Package newPkg; 15471 try { 15472 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15473 } catch (PackageManagerException e) { 15474 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15475 + e.getMessage()); 15476 return false; 15477 } 15478 15479 prepareAppDataAfterInstallLIF(newPkg); 15480 15481 // writer 15482 synchronized (mPackages) { 15483 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15484 15485 // Propagate the permissions state as we do not want to drop on the floor 15486 // runtime permissions. The update permissions method below will take 15487 // care of removing obsolete permissions and grant install permissions. 15488 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15489 updatePermissionsLPw(newPkg.packageName, newPkg, 15490 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15491 15492 if (applyUserRestrictions) { 15493 if (DEBUG_REMOVE) { 15494 Slog.d(TAG, "Propagating install state across reinstall"); 15495 } 15496 for (int userId : allUserHandles) { 15497 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15498 if (DEBUG_REMOVE) { 15499 Slog.d(TAG, " user " + userId + " => " + installed); 15500 } 15501 ps.setInstalled(installed, userId); 15502 15503 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15504 } 15505 // Regardless of writeSettings we need to ensure that this restriction 15506 // state propagation is persisted 15507 mSettings.writeAllUsersPackageRestrictionsLPr(); 15508 } 15509 // can downgrade to reader here 15510 if (writeSettings) { 15511 mSettings.writeLPr(); 15512 } 15513 } 15514 return true; 15515 } 15516 15517 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15518 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15519 PackageRemovedInfo outInfo, boolean writeSettings, 15520 PackageParser.Package replacingPackage) { 15521 synchronized (mPackages) { 15522 if (outInfo != null) { 15523 outInfo.uid = ps.appId; 15524 } 15525 15526 if (outInfo != null && outInfo.removedChildPackages != null) { 15527 final int childCount = (ps.childPackageNames != null) 15528 ? ps.childPackageNames.size() : 0; 15529 for (int i = 0; i < childCount; i++) { 15530 String childPackageName = ps.childPackageNames.get(i); 15531 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15532 if (childPs == null) { 15533 return false; 15534 } 15535 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15536 childPackageName); 15537 if (childInfo != null) { 15538 childInfo.uid = childPs.appId; 15539 } 15540 } 15541 } 15542 } 15543 15544 // Delete package data from internal structures and also remove data if flag is set 15545 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15546 15547 // Delete the child packages data 15548 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15549 for (int i = 0; i < childCount; i++) { 15550 PackageSetting childPs; 15551 synchronized (mPackages) { 15552 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15553 } 15554 if (childPs != null) { 15555 PackageRemovedInfo childOutInfo = (outInfo != null 15556 && outInfo.removedChildPackages != null) 15557 ? outInfo.removedChildPackages.get(childPs.name) : null; 15558 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15559 && (replacingPackage != null 15560 && !replacingPackage.hasChildPackage(childPs.name)) 15561 ? flags & ~DELETE_KEEP_DATA : flags; 15562 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15563 deleteFlags, writeSettings); 15564 } 15565 } 15566 15567 // Delete application code and resources only for parent packages 15568 if (ps.parentPackageName == null) { 15569 if (deleteCodeAndResources && (outInfo != null)) { 15570 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15571 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15572 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15573 } 15574 } 15575 15576 return true; 15577 } 15578 15579 @Override 15580 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15581 int userId) { 15582 mContext.enforceCallingOrSelfPermission( 15583 android.Manifest.permission.DELETE_PACKAGES, null); 15584 synchronized (mPackages) { 15585 PackageSetting ps = mSettings.mPackages.get(packageName); 15586 if (ps == null) { 15587 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15588 return false; 15589 } 15590 if (!ps.getInstalled(userId)) { 15591 // Can't block uninstall for an app that is not installed or enabled. 15592 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15593 return false; 15594 } 15595 ps.setBlockUninstall(blockUninstall, userId); 15596 mSettings.writePackageRestrictionsLPr(userId); 15597 } 15598 return true; 15599 } 15600 15601 @Override 15602 public boolean getBlockUninstallForUser(String packageName, int userId) { 15603 synchronized (mPackages) { 15604 PackageSetting ps = mSettings.mPackages.get(packageName); 15605 if (ps == null) { 15606 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15607 return false; 15608 } 15609 return ps.getBlockUninstall(userId); 15610 } 15611 } 15612 15613 @Override 15614 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15615 int callingUid = Binder.getCallingUid(); 15616 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15617 throw new SecurityException( 15618 "setRequiredForSystemUser can only be run by the system or root"); 15619 } 15620 synchronized (mPackages) { 15621 PackageSetting ps = mSettings.mPackages.get(packageName); 15622 if (ps == null) { 15623 Log.w(TAG, "Package doesn't exist: " + packageName); 15624 return false; 15625 } 15626 if (systemUserApp) { 15627 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15628 } else { 15629 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15630 } 15631 mSettings.writeLPr(); 15632 } 15633 return true; 15634 } 15635 15636 /* 15637 * This method handles package deletion in general 15638 */ 15639 private boolean deletePackageLIF(String packageName, UserHandle user, 15640 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15641 PackageRemovedInfo outInfo, boolean writeSettings, 15642 PackageParser.Package replacingPackage) { 15643 if (packageName == null) { 15644 Slog.w(TAG, "Attempt to delete null packageName."); 15645 return false; 15646 } 15647 15648 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15649 15650 PackageSetting ps; 15651 15652 synchronized (mPackages) { 15653 ps = mSettings.mPackages.get(packageName); 15654 if (ps == null) { 15655 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15656 return false; 15657 } 15658 15659 if (ps.parentPackageName != null && (!isSystemApp(ps) 15660 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15661 if (DEBUG_REMOVE) { 15662 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15663 + ((user == null) ? UserHandle.USER_ALL : user)); 15664 } 15665 final int removedUserId = (user != null) ? user.getIdentifier() 15666 : UserHandle.USER_ALL; 15667 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15668 return false; 15669 } 15670 markPackageUninstalledForUserLPw(ps, user); 15671 scheduleWritePackageRestrictionsLocked(user); 15672 return true; 15673 } 15674 } 15675 15676 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15677 && user.getIdentifier() != UserHandle.USER_ALL)) { 15678 // The caller is asking that the package only be deleted for a single 15679 // user. To do this, we just mark its uninstalled state and delete 15680 // its data. If this is a system app, we only allow this to happen if 15681 // they have set the special DELETE_SYSTEM_APP which requests different 15682 // semantics than normal for uninstalling system apps. 15683 markPackageUninstalledForUserLPw(ps, user); 15684 15685 if (!isSystemApp(ps)) { 15686 // Do not uninstall the APK if an app should be cached 15687 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15688 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15689 // Other user still have this package installed, so all 15690 // we need to do is clear this user's data and save that 15691 // it is uninstalled. 15692 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15693 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15694 return false; 15695 } 15696 scheduleWritePackageRestrictionsLocked(user); 15697 return true; 15698 } else { 15699 // We need to set it back to 'installed' so the uninstall 15700 // broadcasts will be sent correctly. 15701 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15702 ps.setInstalled(true, user.getIdentifier()); 15703 } 15704 } else { 15705 // This is a system app, so we assume that the 15706 // other users still have this package installed, so all 15707 // we need to do is clear this user's data and save that 15708 // it is uninstalled. 15709 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15710 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15711 return false; 15712 } 15713 scheduleWritePackageRestrictionsLocked(user); 15714 return true; 15715 } 15716 } 15717 15718 // If we are deleting a composite package for all users, keep track 15719 // of result for each child. 15720 if (ps.childPackageNames != null && outInfo != null) { 15721 synchronized (mPackages) { 15722 final int childCount = ps.childPackageNames.size(); 15723 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15724 for (int i = 0; i < childCount; i++) { 15725 String childPackageName = ps.childPackageNames.get(i); 15726 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15727 childInfo.removedPackage = childPackageName; 15728 outInfo.removedChildPackages.put(childPackageName, childInfo); 15729 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15730 if (childPs != null) { 15731 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15732 } 15733 } 15734 } 15735 } 15736 15737 boolean ret = false; 15738 if (isSystemApp(ps)) { 15739 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15740 // When an updated system application is deleted we delete the existing resources 15741 // as well and fall back to existing code in system partition 15742 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15743 } else { 15744 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15745 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15746 outInfo, writeSettings, replacingPackage); 15747 } 15748 15749 // Take a note whether we deleted the package for all users 15750 if (outInfo != null) { 15751 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15752 if (outInfo.removedChildPackages != null) { 15753 synchronized (mPackages) { 15754 final int childCount = outInfo.removedChildPackages.size(); 15755 for (int i = 0; i < childCount; i++) { 15756 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15757 if (childInfo != null) { 15758 childInfo.removedForAllUsers = mPackages.get( 15759 childInfo.removedPackage) == null; 15760 } 15761 } 15762 } 15763 } 15764 // If we uninstalled an update to a system app there may be some 15765 // child packages that appeared as they are declared in the system 15766 // app but were not declared in the update. 15767 if (isSystemApp(ps)) { 15768 synchronized (mPackages) { 15769 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15770 final int childCount = (updatedPs.childPackageNames != null) 15771 ? updatedPs.childPackageNames.size() : 0; 15772 for (int i = 0; i < childCount; i++) { 15773 String childPackageName = updatedPs.childPackageNames.get(i); 15774 if (outInfo.removedChildPackages == null 15775 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15776 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15777 if (childPs == null) { 15778 continue; 15779 } 15780 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15781 installRes.name = childPackageName; 15782 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15783 installRes.pkg = mPackages.get(childPackageName); 15784 installRes.uid = childPs.pkg.applicationInfo.uid; 15785 if (outInfo.appearedChildPackages == null) { 15786 outInfo.appearedChildPackages = new ArrayMap<>(); 15787 } 15788 outInfo.appearedChildPackages.put(childPackageName, installRes); 15789 } 15790 } 15791 } 15792 } 15793 } 15794 15795 return ret; 15796 } 15797 15798 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15799 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15800 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15801 for (int nextUserId : userIds) { 15802 if (DEBUG_REMOVE) { 15803 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15804 } 15805 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15806 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15807 false /*hidden*/, false /*suspended*/, null, null, null, 15808 false /*blockUninstall*/, 15809 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15810 } 15811 } 15812 15813 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15814 PackageRemovedInfo outInfo) { 15815 final PackageParser.Package pkg; 15816 synchronized (mPackages) { 15817 pkg = mPackages.get(ps.name); 15818 } 15819 15820 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15821 : new int[] {userId}; 15822 for (int nextUserId : userIds) { 15823 if (DEBUG_REMOVE) { 15824 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15825 + nextUserId); 15826 } 15827 15828 destroyAppDataLIF(pkg, userId, 15829 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15830 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15831 schedulePackageCleaning(ps.name, nextUserId, false); 15832 synchronized (mPackages) { 15833 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15834 scheduleWritePackageRestrictionsLocked(nextUserId); 15835 } 15836 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15837 } 15838 } 15839 15840 if (outInfo != null) { 15841 outInfo.removedPackage = ps.name; 15842 outInfo.removedAppId = ps.appId; 15843 outInfo.removedUsers = userIds; 15844 } 15845 15846 return true; 15847 } 15848 15849 private final class ClearStorageConnection implements ServiceConnection { 15850 IMediaContainerService mContainerService; 15851 15852 @Override 15853 public void onServiceConnected(ComponentName name, IBinder service) { 15854 synchronized (this) { 15855 mContainerService = IMediaContainerService.Stub.asInterface(service); 15856 notifyAll(); 15857 } 15858 } 15859 15860 @Override 15861 public void onServiceDisconnected(ComponentName name) { 15862 } 15863 } 15864 15865 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15866 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15867 15868 final boolean mounted; 15869 if (Environment.isExternalStorageEmulated()) { 15870 mounted = true; 15871 } else { 15872 final String status = Environment.getExternalStorageState(); 15873 15874 mounted = status.equals(Environment.MEDIA_MOUNTED) 15875 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15876 } 15877 15878 if (!mounted) { 15879 return; 15880 } 15881 15882 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15883 int[] users; 15884 if (userId == UserHandle.USER_ALL) { 15885 users = sUserManager.getUserIds(); 15886 } else { 15887 users = new int[] { userId }; 15888 } 15889 final ClearStorageConnection conn = new ClearStorageConnection(); 15890 if (mContext.bindServiceAsUser( 15891 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15892 try { 15893 for (int curUser : users) { 15894 long timeout = SystemClock.uptimeMillis() + 5000; 15895 synchronized (conn) { 15896 long now = SystemClock.uptimeMillis(); 15897 while (conn.mContainerService == null && now < timeout) { 15898 try { 15899 conn.wait(timeout - now); 15900 } catch (InterruptedException e) { 15901 } 15902 } 15903 } 15904 if (conn.mContainerService == null) { 15905 return; 15906 } 15907 15908 final UserEnvironment userEnv = new UserEnvironment(curUser); 15909 clearDirectory(conn.mContainerService, 15910 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15911 if (allData) { 15912 clearDirectory(conn.mContainerService, 15913 userEnv.buildExternalStorageAppDataDirs(packageName)); 15914 clearDirectory(conn.mContainerService, 15915 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15916 } 15917 } 15918 } finally { 15919 mContext.unbindService(conn); 15920 } 15921 } 15922 } 15923 15924 @Override 15925 public void clearApplicationProfileData(String packageName) { 15926 enforceSystemOrRoot("Only the system can clear all profile data"); 15927 15928 final PackageParser.Package pkg; 15929 synchronized (mPackages) { 15930 pkg = mPackages.get(packageName); 15931 } 15932 15933 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15934 synchronized (mInstallLock) { 15935 clearAppProfilesLIF(pkg); 15936 } 15937 } 15938 } 15939 15940 @Override 15941 public void clearApplicationUserData(final String packageName, 15942 final IPackageDataObserver observer, final int userId) { 15943 mContext.enforceCallingOrSelfPermission( 15944 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15945 15946 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15947 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15948 15949 final DevicePolicyManagerInternal dpmi = LocalServices 15950 .getService(DevicePolicyManagerInternal.class); 15951 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15952 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15953 } 15954 // Queue up an async operation since the package deletion may take a little while. 15955 mHandler.post(new Runnable() { 15956 public void run() { 15957 mHandler.removeCallbacks(this); 15958 final boolean succeeded; 15959 try (PackageFreezer freezer = freezePackage(packageName, 15960 "clearApplicationUserData")) { 15961 synchronized (mInstallLock) { 15962 succeeded = clearApplicationUserDataLIF(packageName, userId); 15963 } 15964 clearExternalStorageDataSync(packageName, userId, true); 15965 } 15966 if (succeeded) { 15967 // invoke DeviceStorageMonitor's update method to clear any notifications 15968 DeviceStorageMonitorInternal dsm = LocalServices 15969 .getService(DeviceStorageMonitorInternal.class); 15970 if (dsm != null) { 15971 dsm.checkMemory(); 15972 } 15973 } 15974 if(observer != null) { 15975 try { 15976 observer.onRemoveCompleted(packageName, succeeded); 15977 } catch (RemoteException e) { 15978 Log.i(TAG, "Observer no longer exists."); 15979 } 15980 } //end if observer 15981 } //end run 15982 }); 15983 } 15984 15985 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15986 if (packageName == null) { 15987 Slog.w(TAG, "Attempt to delete null packageName."); 15988 return false; 15989 } 15990 15991 // Try finding details about the requested package 15992 PackageParser.Package pkg; 15993 synchronized (mPackages) { 15994 pkg = mPackages.get(packageName); 15995 if (pkg == null) { 15996 final PackageSetting ps = mSettings.mPackages.get(packageName); 15997 if (ps != null) { 15998 pkg = ps.pkg; 15999 } 16000 } 16001 16002 if (pkg == null) { 16003 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16004 return false; 16005 } 16006 16007 PackageSetting ps = (PackageSetting) pkg.mExtras; 16008 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16009 } 16010 16011 clearAppDataLIF(pkg, userId, 16012 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16013 16014 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16015 removeKeystoreDataIfNeeded(userId, appId); 16016 16017 final UserManager um = mContext.getSystemService(UserManager.class); 16018 final int flags; 16019 if (um.isUserUnlocked(userId)) { 16020 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16021 } else if (um.isUserRunning(userId)) { 16022 flags = StorageManager.FLAG_STORAGE_DE; 16023 } else { 16024 flags = 0; 16025 } 16026 prepareAppDataContentsLIF(pkg, userId, flags); 16027 16028 return true; 16029 } 16030 16031 /** 16032 * Reverts user permission state changes (permissions and flags) in 16033 * all packages for a given user. 16034 * 16035 * @param userId The device user for which to do a reset. 16036 */ 16037 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16038 final int packageCount = mPackages.size(); 16039 for (int i = 0; i < packageCount; i++) { 16040 PackageParser.Package pkg = mPackages.valueAt(i); 16041 PackageSetting ps = (PackageSetting) pkg.mExtras; 16042 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16043 } 16044 } 16045 16046 /** 16047 * Reverts user permission state changes (permissions and flags). 16048 * 16049 * @param ps The package for which to reset. 16050 * @param userId The device user for which to do a reset. 16051 */ 16052 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16053 final PackageSetting ps, final int userId) { 16054 if (ps.pkg == null) { 16055 return; 16056 } 16057 16058 // These are flags that can change base on user actions. 16059 final int userSettableMask = FLAG_PERMISSION_USER_SET 16060 | FLAG_PERMISSION_USER_FIXED 16061 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16062 | FLAG_PERMISSION_REVIEW_REQUIRED; 16063 16064 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16065 | FLAG_PERMISSION_POLICY_FIXED; 16066 16067 boolean writeInstallPermissions = false; 16068 boolean writeRuntimePermissions = false; 16069 16070 final int permissionCount = ps.pkg.requestedPermissions.size(); 16071 for (int i = 0; i < permissionCount; i++) { 16072 String permission = ps.pkg.requestedPermissions.get(i); 16073 16074 BasePermission bp = mSettings.mPermissions.get(permission); 16075 if (bp == null) { 16076 continue; 16077 } 16078 16079 // If shared user we just reset the state to which only this app contributed. 16080 if (ps.sharedUser != null) { 16081 boolean used = false; 16082 final int packageCount = ps.sharedUser.packages.size(); 16083 for (int j = 0; j < packageCount; j++) { 16084 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16085 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16086 && pkg.pkg.requestedPermissions.contains(permission)) { 16087 used = true; 16088 break; 16089 } 16090 } 16091 if (used) { 16092 continue; 16093 } 16094 } 16095 16096 PermissionsState permissionsState = ps.getPermissionsState(); 16097 16098 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16099 16100 // Always clear the user settable flags. 16101 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16102 bp.name) != null; 16103 // If permission review is enabled and this is a legacy app, mark the 16104 // permission as requiring a review as this is the initial state. 16105 int flags = 0; 16106 if (Build.PERMISSIONS_REVIEW_REQUIRED 16107 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16108 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16109 } 16110 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16111 if (hasInstallState) { 16112 writeInstallPermissions = true; 16113 } else { 16114 writeRuntimePermissions = true; 16115 } 16116 } 16117 16118 // Below is only runtime permission handling. 16119 if (!bp.isRuntime()) { 16120 continue; 16121 } 16122 16123 // Never clobber system or policy. 16124 if ((oldFlags & policyOrSystemFlags) != 0) { 16125 continue; 16126 } 16127 16128 // If this permission was granted by default, make sure it is. 16129 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16130 if (permissionsState.grantRuntimePermission(bp, userId) 16131 != PERMISSION_OPERATION_FAILURE) { 16132 writeRuntimePermissions = true; 16133 } 16134 // If permission review is enabled the permissions for a legacy apps 16135 // are represented as constantly granted runtime ones, so don't revoke. 16136 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16137 // Otherwise, reset the permission. 16138 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16139 switch (revokeResult) { 16140 case PERMISSION_OPERATION_SUCCESS: 16141 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16142 writeRuntimePermissions = true; 16143 final int appId = ps.appId; 16144 mHandler.post(new Runnable() { 16145 @Override 16146 public void run() { 16147 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16148 } 16149 }); 16150 } break; 16151 } 16152 } 16153 } 16154 16155 // Synchronously write as we are taking permissions away. 16156 if (writeRuntimePermissions) { 16157 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16158 } 16159 16160 // Synchronously write as we are taking permissions away. 16161 if (writeInstallPermissions) { 16162 mSettings.writeLPr(); 16163 } 16164 } 16165 16166 /** 16167 * Remove entries from the keystore daemon. Will only remove it if the 16168 * {@code appId} is valid. 16169 */ 16170 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16171 if (appId < 0) { 16172 return; 16173 } 16174 16175 final KeyStore keyStore = KeyStore.getInstance(); 16176 if (keyStore != null) { 16177 if (userId == UserHandle.USER_ALL) { 16178 for (final int individual : sUserManager.getUserIds()) { 16179 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16180 } 16181 } else { 16182 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16183 } 16184 } else { 16185 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16186 } 16187 } 16188 16189 @Override 16190 public void deleteApplicationCacheFiles(final String packageName, 16191 final IPackageDataObserver observer) { 16192 final int userId = UserHandle.getCallingUserId(); 16193 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16194 } 16195 16196 @Override 16197 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16198 final IPackageDataObserver observer) { 16199 mContext.enforceCallingOrSelfPermission( 16200 android.Manifest.permission.DELETE_CACHE_FILES, null); 16201 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16202 /* requireFullPermission= */ true, /* checkShell= */ false, 16203 "delete application cache files"); 16204 16205 final PackageParser.Package pkg; 16206 synchronized (mPackages) { 16207 pkg = mPackages.get(packageName); 16208 } 16209 16210 // Queue up an async operation since the package deletion may take a little while. 16211 mHandler.post(new Runnable() { 16212 public void run() { 16213 synchronized (mInstallLock) { 16214 final int flags = StorageManager.FLAG_STORAGE_DE 16215 | StorageManager.FLAG_STORAGE_CE; 16216 // We're only clearing cache files, so we don't care if the 16217 // app is unfrozen and still able to run 16218 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16219 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16220 } 16221 clearExternalStorageDataSync(packageName, userId, false); 16222 if (observer != null) { 16223 try { 16224 observer.onRemoveCompleted(packageName, true); 16225 } catch (RemoteException e) { 16226 Log.i(TAG, "Observer no longer exists."); 16227 } 16228 } 16229 } 16230 }); 16231 } 16232 16233 @Override 16234 public void getPackageSizeInfo(final String packageName, int userHandle, 16235 final IPackageStatsObserver observer) { 16236 mContext.enforceCallingOrSelfPermission( 16237 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16238 if (packageName == null) { 16239 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16240 } 16241 16242 PackageStats stats = new PackageStats(packageName, userHandle); 16243 16244 /* 16245 * Queue up an async operation since the package measurement may take a 16246 * little while. 16247 */ 16248 Message msg = mHandler.obtainMessage(INIT_COPY); 16249 msg.obj = new MeasureParams(stats, observer); 16250 mHandler.sendMessage(msg); 16251 } 16252 16253 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16254 final PackageSetting ps; 16255 synchronized (mPackages) { 16256 ps = mSettings.mPackages.get(packageName); 16257 if (ps == null) { 16258 Slog.w(TAG, "Failed to find settings for " + packageName); 16259 return false; 16260 } 16261 } 16262 try { 16263 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16264 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16265 ps.getCeDataInode(userId), ps.codePathString, stats); 16266 } catch (InstallerException e) { 16267 Slog.w(TAG, String.valueOf(e)); 16268 return false; 16269 } 16270 16271 // For now, ignore code size of packages on system partition 16272 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16273 stats.codeSize = 0; 16274 } 16275 16276 return true; 16277 } 16278 16279 private int getUidTargetSdkVersionLockedLPr(int uid) { 16280 Object obj = mSettings.getUserIdLPr(uid); 16281 if (obj instanceof SharedUserSetting) { 16282 final SharedUserSetting sus = (SharedUserSetting) obj; 16283 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16284 final Iterator<PackageSetting> it = sus.packages.iterator(); 16285 while (it.hasNext()) { 16286 final PackageSetting ps = it.next(); 16287 if (ps.pkg != null) { 16288 int v = ps.pkg.applicationInfo.targetSdkVersion; 16289 if (v < vers) vers = v; 16290 } 16291 } 16292 return vers; 16293 } else if (obj instanceof PackageSetting) { 16294 final PackageSetting ps = (PackageSetting) obj; 16295 if (ps.pkg != null) { 16296 return ps.pkg.applicationInfo.targetSdkVersion; 16297 } 16298 } 16299 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16300 } 16301 16302 @Override 16303 public void addPreferredActivity(IntentFilter filter, int match, 16304 ComponentName[] set, ComponentName activity, int userId) { 16305 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16306 "Adding preferred"); 16307 } 16308 16309 private void addPreferredActivityInternal(IntentFilter filter, int match, 16310 ComponentName[] set, ComponentName activity, boolean always, int userId, 16311 String opname) { 16312 // writer 16313 int callingUid = Binder.getCallingUid(); 16314 enforceCrossUserPermission(callingUid, userId, 16315 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16316 if (filter.countActions() == 0) { 16317 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16318 return; 16319 } 16320 synchronized (mPackages) { 16321 if (mContext.checkCallingOrSelfPermission( 16322 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16323 != PackageManager.PERMISSION_GRANTED) { 16324 if (getUidTargetSdkVersionLockedLPr(callingUid) 16325 < Build.VERSION_CODES.FROYO) { 16326 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16327 + callingUid); 16328 return; 16329 } 16330 mContext.enforceCallingOrSelfPermission( 16331 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16332 } 16333 16334 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16335 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16336 + userId + ":"); 16337 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16338 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16339 scheduleWritePackageRestrictionsLocked(userId); 16340 } 16341 } 16342 16343 @Override 16344 public void replacePreferredActivity(IntentFilter filter, int match, 16345 ComponentName[] set, ComponentName activity, int userId) { 16346 if (filter.countActions() != 1) { 16347 throw new IllegalArgumentException( 16348 "replacePreferredActivity expects filter to have only 1 action."); 16349 } 16350 if (filter.countDataAuthorities() != 0 16351 || filter.countDataPaths() != 0 16352 || filter.countDataSchemes() > 1 16353 || filter.countDataTypes() != 0) { 16354 throw new IllegalArgumentException( 16355 "replacePreferredActivity expects filter to have no data authorities, " + 16356 "paths, or types; and at most one scheme."); 16357 } 16358 16359 final int callingUid = Binder.getCallingUid(); 16360 enforceCrossUserPermission(callingUid, userId, 16361 true /* requireFullPermission */, false /* checkShell */, 16362 "replace preferred activity"); 16363 synchronized (mPackages) { 16364 if (mContext.checkCallingOrSelfPermission( 16365 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16366 != PackageManager.PERMISSION_GRANTED) { 16367 if (getUidTargetSdkVersionLockedLPr(callingUid) 16368 < Build.VERSION_CODES.FROYO) { 16369 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16370 + Binder.getCallingUid()); 16371 return; 16372 } 16373 mContext.enforceCallingOrSelfPermission( 16374 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16375 } 16376 16377 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16378 if (pir != null) { 16379 // Get all of the existing entries that exactly match this filter. 16380 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16381 if (existing != null && existing.size() == 1) { 16382 PreferredActivity cur = existing.get(0); 16383 if (DEBUG_PREFERRED) { 16384 Slog.i(TAG, "Checking replace of preferred:"); 16385 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16386 if (!cur.mPref.mAlways) { 16387 Slog.i(TAG, " -- CUR; not mAlways!"); 16388 } else { 16389 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16390 Slog.i(TAG, " -- CUR: mSet=" 16391 + Arrays.toString(cur.mPref.mSetComponents)); 16392 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16393 Slog.i(TAG, " -- NEW: mMatch=" 16394 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16395 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16396 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16397 } 16398 } 16399 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16400 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16401 && cur.mPref.sameSet(set)) { 16402 // Setting the preferred activity to what it happens to be already 16403 if (DEBUG_PREFERRED) { 16404 Slog.i(TAG, "Replacing with same preferred activity " 16405 + cur.mPref.mShortComponent + " for user " 16406 + userId + ":"); 16407 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16408 } 16409 return; 16410 } 16411 } 16412 16413 if (existing != null) { 16414 if (DEBUG_PREFERRED) { 16415 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16416 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16417 } 16418 for (int i = 0; i < existing.size(); i++) { 16419 PreferredActivity pa = existing.get(i); 16420 if (DEBUG_PREFERRED) { 16421 Slog.i(TAG, "Removing existing preferred activity " 16422 + pa.mPref.mComponent + ":"); 16423 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16424 } 16425 pir.removeFilter(pa); 16426 } 16427 } 16428 } 16429 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16430 "Replacing preferred"); 16431 } 16432 } 16433 16434 @Override 16435 public void clearPackagePreferredActivities(String packageName) { 16436 final int uid = Binder.getCallingUid(); 16437 // writer 16438 synchronized (mPackages) { 16439 PackageParser.Package pkg = mPackages.get(packageName); 16440 if (pkg == null || pkg.applicationInfo.uid != uid) { 16441 if (mContext.checkCallingOrSelfPermission( 16442 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16443 != PackageManager.PERMISSION_GRANTED) { 16444 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16445 < Build.VERSION_CODES.FROYO) { 16446 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16447 + Binder.getCallingUid()); 16448 return; 16449 } 16450 mContext.enforceCallingOrSelfPermission( 16451 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16452 } 16453 } 16454 16455 int user = UserHandle.getCallingUserId(); 16456 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16457 scheduleWritePackageRestrictionsLocked(user); 16458 } 16459 } 16460 } 16461 16462 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16463 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16464 ArrayList<PreferredActivity> removed = null; 16465 boolean changed = false; 16466 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16467 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16468 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16469 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16470 continue; 16471 } 16472 Iterator<PreferredActivity> it = pir.filterIterator(); 16473 while (it.hasNext()) { 16474 PreferredActivity pa = it.next(); 16475 // Mark entry for removal only if it matches the package name 16476 // and the entry is of type "always". 16477 if (packageName == null || 16478 (pa.mPref.mComponent.getPackageName().equals(packageName) 16479 && pa.mPref.mAlways)) { 16480 if (removed == null) { 16481 removed = new ArrayList<PreferredActivity>(); 16482 } 16483 removed.add(pa); 16484 } 16485 } 16486 if (removed != null) { 16487 for (int j=0; j<removed.size(); j++) { 16488 PreferredActivity pa = removed.get(j); 16489 pir.removeFilter(pa); 16490 } 16491 changed = true; 16492 } 16493 } 16494 return changed; 16495 } 16496 16497 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16498 private void clearIntentFilterVerificationsLPw(int userId) { 16499 final int packageCount = mPackages.size(); 16500 for (int i = 0; i < packageCount; i++) { 16501 PackageParser.Package pkg = mPackages.valueAt(i); 16502 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16503 } 16504 } 16505 16506 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16507 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16508 if (userId == UserHandle.USER_ALL) { 16509 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16510 sUserManager.getUserIds())) { 16511 for (int oneUserId : sUserManager.getUserIds()) { 16512 scheduleWritePackageRestrictionsLocked(oneUserId); 16513 } 16514 } 16515 } else { 16516 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16517 scheduleWritePackageRestrictionsLocked(userId); 16518 } 16519 } 16520 } 16521 16522 void clearDefaultBrowserIfNeeded(String packageName) { 16523 for (int oneUserId : sUserManager.getUserIds()) { 16524 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16525 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16526 if (packageName.equals(defaultBrowserPackageName)) { 16527 setDefaultBrowserPackageName(null, oneUserId); 16528 } 16529 } 16530 } 16531 16532 @Override 16533 public void resetApplicationPreferences(int userId) { 16534 mContext.enforceCallingOrSelfPermission( 16535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16536 // writer 16537 synchronized (mPackages) { 16538 final long identity = Binder.clearCallingIdentity(); 16539 try { 16540 clearPackagePreferredActivitiesLPw(null, userId); 16541 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16542 // TODO: We have to reset the default SMS and Phone. This requires 16543 // significant refactoring to keep all default apps in the package 16544 // manager (cleaner but more work) or have the services provide 16545 // callbacks to the package manager to request a default app reset. 16546 applyFactoryDefaultBrowserLPw(userId); 16547 clearIntentFilterVerificationsLPw(userId); 16548 primeDomainVerificationsLPw(userId); 16549 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16550 scheduleWritePackageRestrictionsLocked(userId); 16551 } finally { 16552 Binder.restoreCallingIdentity(identity); 16553 } 16554 } 16555 } 16556 16557 @Override 16558 public int getPreferredActivities(List<IntentFilter> outFilters, 16559 List<ComponentName> outActivities, String packageName) { 16560 16561 int num = 0; 16562 final int userId = UserHandle.getCallingUserId(); 16563 // reader 16564 synchronized (mPackages) { 16565 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16566 if (pir != null) { 16567 final Iterator<PreferredActivity> it = pir.filterIterator(); 16568 while (it.hasNext()) { 16569 final PreferredActivity pa = it.next(); 16570 if (packageName == null 16571 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16572 && pa.mPref.mAlways)) { 16573 if (outFilters != null) { 16574 outFilters.add(new IntentFilter(pa)); 16575 } 16576 if (outActivities != null) { 16577 outActivities.add(pa.mPref.mComponent); 16578 } 16579 } 16580 } 16581 } 16582 } 16583 16584 return num; 16585 } 16586 16587 @Override 16588 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16589 int userId) { 16590 int callingUid = Binder.getCallingUid(); 16591 if (callingUid != Process.SYSTEM_UID) { 16592 throw new SecurityException( 16593 "addPersistentPreferredActivity can only be run by the system"); 16594 } 16595 if (filter.countActions() == 0) { 16596 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16597 return; 16598 } 16599 synchronized (mPackages) { 16600 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16601 ":"); 16602 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16603 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16604 new PersistentPreferredActivity(filter, activity)); 16605 scheduleWritePackageRestrictionsLocked(userId); 16606 } 16607 } 16608 16609 @Override 16610 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16611 int callingUid = Binder.getCallingUid(); 16612 if (callingUid != Process.SYSTEM_UID) { 16613 throw new SecurityException( 16614 "clearPackagePersistentPreferredActivities can only be run by the system"); 16615 } 16616 ArrayList<PersistentPreferredActivity> removed = null; 16617 boolean changed = false; 16618 synchronized (mPackages) { 16619 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16620 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16621 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16622 .valueAt(i); 16623 if (userId != thisUserId) { 16624 continue; 16625 } 16626 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16627 while (it.hasNext()) { 16628 PersistentPreferredActivity ppa = it.next(); 16629 // Mark entry for removal only if it matches the package name. 16630 if (ppa.mComponent.getPackageName().equals(packageName)) { 16631 if (removed == null) { 16632 removed = new ArrayList<PersistentPreferredActivity>(); 16633 } 16634 removed.add(ppa); 16635 } 16636 } 16637 if (removed != null) { 16638 for (int j=0; j<removed.size(); j++) { 16639 PersistentPreferredActivity ppa = removed.get(j); 16640 ppir.removeFilter(ppa); 16641 } 16642 changed = true; 16643 } 16644 } 16645 16646 if (changed) { 16647 scheduleWritePackageRestrictionsLocked(userId); 16648 } 16649 } 16650 } 16651 16652 /** 16653 * Common machinery for picking apart a restored XML blob and passing 16654 * it to a caller-supplied functor to be applied to the running system. 16655 */ 16656 private void restoreFromXml(XmlPullParser parser, int userId, 16657 String expectedStartTag, BlobXmlRestorer functor) 16658 throws IOException, XmlPullParserException { 16659 int type; 16660 while ((type = parser.next()) != XmlPullParser.START_TAG 16661 && type != XmlPullParser.END_DOCUMENT) { 16662 } 16663 if (type != XmlPullParser.START_TAG) { 16664 // oops didn't find a start tag?! 16665 if (DEBUG_BACKUP) { 16666 Slog.e(TAG, "Didn't find start tag during restore"); 16667 } 16668 return; 16669 } 16670Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16671 // this is supposed to be TAG_PREFERRED_BACKUP 16672 if (!expectedStartTag.equals(parser.getName())) { 16673 if (DEBUG_BACKUP) { 16674 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16675 } 16676 return; 16677 } 16678 16679 // skip interfering stuff, then we're aligned with the backing implementation 16680 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16681Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16682 functor.apply(parser, userId); 16683 } 16684 16685 private interface BlobXmlRestorer { 16686 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16687 } 16688 16689 /** 16690 * Non-Binder method, support for the backup/restore mechanism: write the 16691 * full set of preferred activities in its canonical XML format. Returns the 16692 * XML output as a byte array, or null if there is none. 16693 */ 16694 @Override 16695 public byte[] getPreferredActivityBackup(int userId) { 16696 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16697 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16698 } 16699 16700 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16701 try { 16702 final XmlSerializer serializer = new FastXmlSerializer(); 16703 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16704 serializer.startDocument(null, true); 16705 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16706 16707 synchronized (mPackages) { 16708 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16709 } 16710 16711 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16712 serializer.endDocument(); 16713 serializer.flush(); 16714 } catch (Exception e) { 16715 if (DEBUG_BACKUP) { 16716 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16717 } 16718 return null; 16719 } 16720 16721 return dataStream.toByteArray(); 16722 } 16723 16724 @Override 16725 public void restorePreferredActivities(byte[] backup, int userId) { 16726 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16727 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16728 } 16729 16730 try { 16731 final XmlPullParser parser = Xml.newPullParser(); 16732 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16733 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16734 new BlobXmlRestorer() { 16735 @Override 16736 public void apply(XmlPullParser parser, int userId) 16737 throws XmlPullParserException, IOException { 16738 synchronized (mPackages) { 16739 mSettings.readPreferredActivitiesLPw(parser, userId); 16740 } 16741 } 16742 } ); 16743 } catch (Exception e) { 16744 if (DEBUG_BACKUP) { 16745 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16746 } 16747 } 16748 } 16749 16750 /** 16751 * Non-Binder method, support for the backup/restore mechanism: write the 16752 * default browser (etc) settings in its canonical XML format. Returns the default 16753 * browser XML representation as a byte array, or null if there is none. 16754 */ 16755 @Override 16756 public byte[] getDefaultAppsBackup(int userId) { 16757 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16758 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16759 } 16760 16761 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16762 try { 16763 final XmlSerializer serializer = new FastXmlSerializer(); 16764 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16765 serializer.startDocument(null, true); 16766 serializer.startTag(null, TAG_DEFAULT_APPS); 16767 16768 synchronized (mPackages) { 16769 mSettings.writeDefaultAppsLPr(serializer, userId); 16770 } 16771 16772 serializer.endTag(null, TAG_DEFAULT_APPS); 16773 serializer.endDocument(); 16774 serializer.flush(); 16775 } catch (Exception e) { 16776 if (DEBUG_BACKUP) { 16777 Slog.e(TAG, "Unable to write default apps for backup", e); 16778 } 16779 return null; 16780 } 16781 16782 return dataStream.toByteArray(); 16783 } 16784 16785 @Override 16786 public void restoreDefaultApps(byte[] backup, int userId) { 16787 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16788 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16789 } 16790 16791 try { 16792 final XmlPullParser parser = Xml.newPullParser(); 16793 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16794 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16795 new BlobXmlRestorer() { 16796 @Override 16797 public void apply(XmlPullParser parser, int userId) 16798 throws XmlPullParserException, IOException { 16799 synchronized (mPackages) { 16800 mSettings.readDefaultAppsLPw(parser, userId); 16801 } 16802 } 16803 } ); 16804 } catch (Exception e) { 16805 if (DEBUG_BACKUP) { 16806 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16807 } 16808 } 16809 } 16810 16811 @Override 16812 public byte[] getIntentFilterVerificationBackup(int userId) { 16813 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16814 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16815 } 16816 16817 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16818 try { 16819 final XmlSerializer serializer = new FastXmlSerializer(); 16820 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16821 serializer.startDocument(null, true); 16822 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16823 16824 synchronized (mPackages) { 16825 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16826 } 16827 16828 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16829 serializer.endDocument(); 16830 serializer.flush(); 16831 } catch (Exception e) { 16832 if (DEBUG_BACKUP) { 16833 Slog.e(TAG, "Unable to write default apps for backup", e); 16834 } 16835 return null; 16836 } 16837 16838 return dataStream.toByteArray(); 16839 } 16840 16841 @Override 16842 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16843 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16844 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16845 } 16846 16847 try { 16848 final XmlPullParser parser = Xml.newPullParser(); 16849 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16850 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16851 new BlobXmlRestorer() { 16852 @Override 16853 public void apply(XmlPullParser parser, int userId) 16854 throws XmlPullParserException, IOException { 16855 synchronized (mPackages) { 16856 mSettings.readAllDomainVerificationsLPr(parser, userId); 16857 mSettings.writeLPr(); 16858 } 16859 } 16860 } ); 16861 } catch (Exception e) { 16862 if (DEBUG_BACKUP) { 16863 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16864 } 16865 } 16866 } 16867 16868 @Override 16869 public byte[] getPermissionGrantBackup(int userId) { 16870 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16871 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16872 } 16873 16874 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16875 try { 16876 final XmlSerializer serializer = new FastXmlSerializer(); 16877 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16878 serializer.startDocument(null, true); 16879 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16880 16881 synchronized (mPackages) { 16882 serializeRuntimePermissionGrantsLPr(serializer, userId); 16883 } 16884 16885 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16886 serializer.endDocument(); 16887 serializer.flush(); 16888 } catch (Exception e) { 16889 if (DEBUG_BACKUP) { 16890 Slog.e(TAG, "Unable to write default apps for backup", e); 16891 } 16892 return null; 16893 } 16894 16895 return dataStream.toByteArray(); 16896 } 16897 16898 @Override 16899 public void restorePermissionGrants(byte[] backup, int userId) { 16900 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16901 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16902 } 16903 16904 try { 16905 final XmlPullParser parser = Xml.newPullParser(); 16906 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16907 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16908 new BlobXmlRestorer() { 16909 @Override 16910 public void apply(XmlPullParser parser, int userId) 16911 throws XmlPullParserException, IOException { 16912 synchronized (mPackages) { 16913 processRestoredPermissionGrantsLPr(parser, userId); 16914 } 16915 } 16916 } ); 16917 } catch (Exception e) { 16918 if (DEBUG_BACKUP) { 16919 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16920 } 16921 } 16922 } 16923 16924 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16925 throws IOException { 16926 serializer.startTag(null, TAG_ALL_GRANTS); 16927 16928 final int N = mSettings.mPackages.size(); 16929 for (int i = 0; i < N; i++) { 16930 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16931 boolean pkgGrantsKnown = false; 16932 16933 PermissionsState packagePerms = ps.getPermissionsState(); 16934 16935 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16936 final int grantFlags = state.getFlags(); 16937 // only look at grants that are not system/policy fixed 16938 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16939 final boolean isGranted = state.isGranted(); 16940 // And only back up the user-twiddled state bits 16941 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16942 final String packageName = mSettings.mPackages.keyAt(i); 16943 if (!pkgGrantsKnown) { 16944 serializer.startTag(null, TAG_GRANT); 16945 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16946 pkgGrantsKnown = true; 16947 } 16948 16949 final boolean userSet = 16950 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16951 final boolean userFixed = 16952 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16953 final boolean revoke = 16954 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16955 16956 serializer.startTag(null, TAG_PERMISSION); 16957 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16958 if (isGranted) { 16959 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16960 } 16961 if (userSet) { 16962 serializer.attribute(null, ATTR_USER_SET, "true"); 16963 } 16964 if (userFixed) { 16965 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16966 } 16967 if (revoke) { 16968 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16969 } 16970 serializer.endTag(null, TAG_PERMISSION); 16971 } 16972 } 16973 } 16974 16975 if (pkgGrantsKnown) { 16976 serializer.endTag(null, TAG_GRANT); 16977 } 16978 } 16979 16980 serializer.endTag(null, TAG_ALL_GRANTS); 16981 } 16982 16983 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16984 throws XmlPullParserException, IOException { 16985 String pkgName = null; 16986 int outerDepth = parser.getDepth(); 16987 int type; 16988 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16989 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16990 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16991 continue; 16992 } 16993 16994 final String tagName = parser.getName(); 16995 if (tagName.equals(TAG_GRANT)) { 16996 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16997 if (DEBUG_BACKUP) { 16998 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16999 } 17000 } else if (tagName.equals(TAG_PERMISSION)) { 17001 17002 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17003 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17004 17005 int newFlagSet = 0; 17006 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17007 newFlagSet |= FLAG_PERMISSION_USER_SET; 17008 } 17009 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17010 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17011 } 17012 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17013 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17014 } 17015 if (DEBUG_BACKUP) { 17016 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17017 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17018 } 17019 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17020 if (ps != null) { 17021 // Already installed so we apply the grant immediately 17022 if (DEBUG_BACKUP) { 17023 Slog.v(TAG, " + already installed; applying"); 17024 } 17025 PermissionsState perms = ps.getPermissionsState(); 17026 BasePermission bp = mSettings.mPermissions.get(permName); 17027 if (bp != null) { 17028 if (isGranted) { 17029 perms.grantRuntimePermission(bp, userId); 17030 } 17031 if (newFlagSet != 0) { 17032 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17033 } 17034 } 17035 } else { 17036 // Need to wait for post-restore install to apply the grant 17037 if (DEBUG_BACKUP) { 17038 Slog.v(TAG, " - not yet installed; saving for later"); 17039 } 17040 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17041 isGranted, newFlagSet, userId); 17042 } 17043 } else { 17044 PackageManagerService.reportSettingsProblem(Log.WARN, 17045 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17046 XmlUtils.skipCurrentTag(parser); 17047 } 17048 } 17049 17050 scheduleWriteSettingsLocked(); 17051 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17052 } 17053 17054 @Override 17055 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17056 int sourceUserId, int targetUserId, int flags) { 17057 mContext.enforceCallingOrSelfPermission( 17058 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17059 int callingUid = Binder.getCallingUid(); 17060 enforceOwnerRights(ownerPackage, callingUid); 17061 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17062 if (intentFilter.countActions() == 0) { 17063 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17064 return; 17065 } 17066 synchronized (mPackages) { 17067 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17068 ownerPackage, targetUserId, flags); 17069 CrossProfileIntentResolver resolver = 17070 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17071 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17072 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17073 if (existing != null) { 17074 int size = existing.size(); 17075 for (int i = 0; i < size; i++) { 17076 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17077 return; 17078 } 17079 } 17080 } 17081 resolver.addFilter(newFilter); 17082 scheduleWritePackageRestrictionsLocked(sourceUserId); 17083 } 17084 } 17085 17086 @Override 17087 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17088 mContext.enforceCallingOrSelfPermission( 17089 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17090 int callingUid = Binder.getCallingUid(); 17091 enforceOwnerRights(ownerPackage, callingUid); 17092 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17093 synchronized (mPackages) { 17094 CrossProfileIntentResolver resolver = 17095 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17096 ArraySet<CrossProfileIntentFilter> set = 17097 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17098 for (CrossProfileIntentFilter filter : set) { 17099 if (filter.getOwnerPackage().equals(ownerPackage)) { 17100 resolver.removeFilter(filter); 17101 } 17102 } 17103 scheduleWritePackageRestrictionsLocked(sourceUserId); 17104 } 17105 } 17106 17107 // Enforcing that callingUid is owning pkg on userId 17108 private void enforceOwnerRights(String pkg, int callingUid) { 17109 // The system owns everything. 17110 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17111 return; 17112 } 17113 int callingUserId = UserHandle.getUserId(callingUid); 17114 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17115 if (pi == null) { 17116 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17117 + callingUserId); 17118 } 17119 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17120 throw new SecurityException("Calling uid " + callingUid 17121 + " does not own package " + pkg); 17122 } 17123 } 17124 17125 @Override 17126 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17127 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17128 } 17129 17130 private Intent getHomeIntent() { 17131 Intent intent = new Intent(Intent.ACTION_MAIN); 17132 intent.addCategory(Intent.CATEGORY_HOME); 17133 return intent; 17134 } 17135 17136 private IntentFilter getHomeFilter() { 17137 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17138 filter.addCategory(Intent.CATEGORY_HOME); 17139 filter.addCategory(Intent.CATEGORY_DEFAULT); 17140 return filter; 17141 } 17142 17143 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17144 int userId) { 17145 Intent intent = getHomeIntent(); 17146 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17147 PackageManager.GET_META_DATA, userId); 17148 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17149 true, false, false, userId); 17150 17151 allHomeCandidates.clear(); 17152 if (list != null) { 17153 for (ResolveInfo ri : list) { 17154 allHomeCandidates.add(ri); 17155 } 17156 } 17157 return (preferred == null || preferred.activityInfo == null) 17158 ? null 17159 : new ComponentName(preferred.activityInfo.packageName, 17160 preferred.activityInfo.name); 17161 } 17162 17163 @Override 17164 public void setHomeActivity(ComponentName comp, int userId) { 17165 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17166 getHomeActivitiesAsUser(homeActivities, userId); 17167 17168 boolean found = false; 17169 17170 final int size = homeActivities.size(); 17171 final ComponentName[] set = new ComponentName[size]; 17172 for (int i = 0; i < size; i++) { 17173 final ResolveInfo candidate = homeActivities.get(i); 17174 final ActivityInfo info = candidate.activityInfo; 17175 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17176 set[i] = activityName; 17177 if (!found && activityName.equals(comp)) { 17178 found = true; 17179 } 17180 } 17181 if (!found) { 17182 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17183 + userId); 17184 } 17185 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17186 set, comp, userId); 17187 } 17188 17189 private @Nullable String getSetupWizardPackageName() { 17190 final Intent intent = new Intent(Intent.ACTION_MAIN); 17191 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17192 17193 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17194 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17195 | MATCH_DISABLED_COMPONENTS, 17196 UserHandle.myUserId()); 17197 if (matches.size() == 1) { 17198 return matches.get(0).getComponentInfo().packageName; 17199 } else { 17200 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17201 + ": matches=" + matches); 17202 return null; 17203 } 17204 } 17205 17206 @Override 17207 public void setApplicationEnabledSetting(String appPackageName, 17208 int newState, int flags, int userId, String callingPackage) { 17209 if (!sUserManager.exists(userId)) return; 17210 if (callingPackage == null) { 17211 callingPackage = Integer.toString(Binder.getCallingUid()); 17212 } 17213 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17214 } 17215 17216 @Override 17217 public void setComponentEnabledSetting(ComponentName componentName, 17218 int newState, int flags, int userId) { 17219 if (!sUserManager.exists(userId)) return; 17220 setEnabledSetting(componentName.getPackageName(), 17221 componentName.getClassName(), newState, flags, userId, null); 17222 } 17223 17224 private void setEnabledSetting(final String packageName, String className, int newState, 17225 final int flags, int userId, String callingPackage) { 17226 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17227 || newState == COMPONENT_ENABLED_STATE_ENABLED 17228 || newState == COMPONENT_ENABLED_STATE_DISABLED 17229 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17230 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17231 throw new IllegalArgumentException("Invalid new component state: " 17232 + newState); 17233 } 17234 PackageSetting pkgSetting; 17235 final int uid = Binder.getCallingUid(); 17236 final int permission; 17237 if (uid == Process.SYSTEM_UID) { 17238 permission = PackageManager.PERMISSION_GRANTED; 17239 } else { 17240 permission = mContext.checkCallingOrSelfPermission( 17241 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17242 } 17243 enforceCrossUserPermission(uid, userId, 17244 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17245 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17246 boolean sendNow = false; 17247 boolean isApp = (className == null); 17248 String componentName = isApp ? packageName : className; 17249 int packageUid = -1; 17250 ArrayList<String> components; 17251 17252 // writer 17253 synchronized (mPackages) { 17254 pkgSetting = mSettings.mPackages.get(packageName); 17255 if (pkgSetting == null) { 17256 if (className == null) { 17257 throw new IllegalArgumentException("Unknown package: " + packageName); 17258 } 17259 throw new IllegalArgumentException( 17260 "Unknown component: " + packageName + "/" + className); 17261 } 17262 // Allow root and verify that userId is not being specified by a different user 17263 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17264 throw new SecurityException( 17265 "Permission Denial: attempt to change component state from pid=" 17266 + Binder.getCallingPid() 17267 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17268 } 17269 if (className == null) { 17270 // We're dealing with an application/package level state change 17271 if (pkgSetting.getEnabled(userId) == newState) { 17272 // Nothing to do 17273 return; 17274 } 17275 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17276 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17277 // Don't care about who enables an app. 17278 callingPackage = null; 17279 } 17280 pkgSetting.setEnabled(newState, userId, callingPackage); 17281 // pkgSetting.pkg.mSetEnabled = newState; 17282 } else { 17283 // We're dealing with a component level state change 17284 // First, verify that this is a valid class name. 17285 PackageParser.Package pkg = pkgSetting.pkg; 17286 if (pkg == null || !pkg.hasComponentClassName(className)) { 17287 if (pkg != null && 17288 pkg.applicationInfo.targetSdkVersion >= 17289 Build.VERSION_CODES.JELLY_BEAN) { 17290 throw new IllegalArgumentException("Component class " + className 17291 + " does not exist in " + packageName); 17292 } else { 17293 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17294 + className + " does not exist in " + packageName); 17295 } 17296 } 17297 switch (newState) { 17298 case COMPONENT_ENABLED_STATE_ENABLED: 17299 if (!pkgSetting.enableComponentLPw(className, userId)) { 17300 return; 17301 } 17302 break; 17303 case COMPONENT_ENABLED_STATE_DISABLED: 17304 if (!pkgSetting.disableComponentLPw(className, userId)) { 17305 return; 17306 } 17307 break; 17308 case COMPONENT_ENABLED_STATE_DEFAULT: 17309 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17310 return; 17311 } 17312 break; 17313 default: 17314 Slog.e(TAG, "Invalid new component state: " + newState); 17315 return; 17316 } 17317 } 17318 scheduleWritePackageRestrictionsLocked(userId); 17319 components = mPendingBroadcasts.get(userId, packageName); 17320 final boolean newPackage = components == null; 17321 if (newPackage) { 17322 components = new ArrayList<String>(); 17323 } 17324 if (!components.contains(componentName)) { 17325 components.add(componentName); 17326 } 17327 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17328 sendNow = true; 17329 // Purge entry from pending broadcast list if another one exists already 17330 // since we are sending one right away. 17331 mPendingBroadcasts.remove(userId, packageName); 17332 } else { 17333 if (newPackage) { 17334 mPendingBroadcasts.put(userId, packageName, components); 17335 } 17336 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17337 // Schedule a message 17338 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17339 } 17340 } 17341 } 17342 17343 long callingId = Binder.clearCallingIdentity(); 17344 try { 17345 if (sendNow) { 17346 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17347 sendPackageChangedBroadcast(packageName, 17348 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17349 } 17350 } finally { 17351 Binder.restoreCallingIdentity(callingId); 17352 } 17353 } 17354 17355 @Override 17356 public void flushPackageRestrictionsAsUser(int userId) { 17357 if (!sUserManager.exists(userId)) { 17358 return; 17359 } 17360 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17361 false /* checkShell */, "flushPackageRestrictions"); 17362 synchronized (mPackages) { 17363 mSettings.writePackageRestrictionsLPr(userId); 17364 mDirtyUsers.remove(userId); 17365 if (mDirtyUsers.isEmpty()) { 17366 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17367 } 17368 } 17369 } 17370 17371 private void sendPackageChangedBroadcast(String packageName, 17372 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17373 if (DEBUG_INSTALL) 17374 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17375 + componentNames); 17376 Bundle extras = new Bundle(4); 17377 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17378 String nameList[] = new String[componentNames.size()]; 17379 componentNames.toArray(nameList); 17380 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17381 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17382 extras.putInt(Intent.EXTRA_UID, packageUid); 17383 // If this is not reporting a change of the overall package, then only send it 17384 // to registered receivers. We don't want to launch a swath of apps for every 17385 // little component state change. 17386 final int flags = !componentNames.contains(packageName) 17387 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17388 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17389 new int[] {UserHandle.getUserId(packageUid)}); 17390 } 17391 17392 @Override 17393 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17394 if (!sUserManager.exists(userId)) return; 17395 final int uid = Binder.getCallingUid(); 17396 final int permission = mContext.checkCallingOrSelfPermission( 17397 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17398 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17399 enforceCrossUserPermission(uid, userId, 17400 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17401 // writer 17402 synchronized (mPackages) { 17403 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17404 allowedByPermission, uid, userId)) { 17405 scheduleWritePackageRestrictionsLocked(userId); 17406 } 17407 } 17408 } 17409 17410 @Override 17411 public String getInstallerPackageName(String packageName) { 17412 // reader 17413 synchronized (mPackages) { 17414 return mSettings.getInstallerPackageNameLPr(packageName); 17415 } 17416 } 17417 17418 @Override 17419 public int getApplicationEnabledSetting(String packageName, int userId) { 17420 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17421 int uid = Binder.getCallingUid(); 17422 enforceCrossUserPermission(uid, userId, 17423 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17424 // reader 17425 synchronized (mPackages) { 17426 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17427 } 17428 } 17429 17430 @Override 17431 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17432 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17433 int uid = Binder.getCallingUid(); 17434 enforceCrossUserPermission(uid, userId, 17435 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17436 // reader 17437 synchronized (mPackages) { 17438 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17439 } 17440 } 17441 17442 @Override 17443 public void enterSafeMode() { 17444 enforceSystemOrRoot("Only the system can request entering safe mode"); 17445 17446 if (!mSystemReady) { 17447 mSafeMode = true; 17448 } 17449 } 17450 17451 @Override 17452 public void systemReady() { 17453 mSystemReady = true; 17454 17455 // Read the compatibilty setting when the system is ready. 17456 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17457 mContext.getContentResolver(), 17458 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17459 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17460 if (DEBUG_SETTINGS) { 17461 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17462 } 17463 17464 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17465 17466 synchronized (mPackages) { 17467 // Verify that all of the preferred activity components actually 17468 // exist. It is possible for applications to be updated and at 17469 // that point remove a previously declared activity component that 17470 // had been set as a preferred activity. We try to clean this up 17471 // the next time we encounter that preferred activity, but it is 17472 // possible for the user flow to never be able to return to that 17473 // situation so here we do a sanity check to make sure we haven't 17474 // left any junk around. 17475 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17476 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17477 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17478 removed.clear(); 17479 for (PreferredActivity pa : pir.filterSet()) { 17480 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17481 removed.add(pa); 17482 } 17483 } 17484 if (removed.size() > 0) { 17485 for (int r=0; r<removed.size(); r++) { 17486 PreferredActivity pa = removed.get(r); 17487 Slog.w(TAG, "Removing dangling preferred activity: " 17488 + pa.mPref.mComponent); 17489 pir.removeFilter(pa); 17490 } 17491 mSettings.writePackageRestrictionsLPr( 17492 mSettings.mPreferredActivities.keyAt(i)); 17493 } 17494 } 17495 17496 for (int userId : UserManagerService.getInstance().getUserIds()) { 17497 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17498 grantPermissionsUserIds = ArrayUtils.appendInt( 17499 grantPermissionsUserIds, userId); 17500 } 17501 } 17502 } 17503 sUserManager.systemReady(); 17504 17505 // If we upgraded grant all default permissions before kicking off. 17506 for (int userId : grantPermissionsUserIds) { 17507 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17508 } 17509 17510 // Kick off any messages waiting for system ready 17511 if (mPostSystemReadyMessages != null) { 17512 for (Message msg : mPostSystemReadyMessages) { 17513 msg.sendToTarget(); 17514 } 17515 mPostSystemReadyMessages = null; 17516 } 17517 17518 // Watch for external volumes that come and go over time 17519 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17520 storage.registerListener(mStorageListener); 17521 17522 mInstallerService.systemReady(); 17523 mPackageDexOptimizer.systemReady(); 17524 17525 MountServiceInternal mountServiceInternal = LocalServices.getService( 17526 MountServiceInternal.class); 17527 mountServiceInternal.addExternalStoragePolicy( 17528 new MountServiceInternal.ExternalStorageMountPolicy() { 17529 @Override 17530 public int getMountMode(int uid, String packageName) { 17531 if (Process.isIsolated(uid)) { 17532 return Zygote.MOUNT_EXTERNAL_NONE; 17533 } 17534 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17535 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17536 } 17537 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17538 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17539 } 17540 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17541 return Zygote.MOUNT_EXTERNAL_READ; 17542 } 17543 return Zygote.MOUNT_EXTERNAL_WRITE; 17544 } 17545 17546 @Override 17547 public boolean hasExternalStorage(int uid, String packageName) { 17548 return true; 17549 } 17550 }); 17551 17552 // Now that we're mostly running, clean up stale users and apps 17553 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17554 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17555 } 17556 17557 @Override 17558 public boolean isSafeMode() { 17559 return mSafeMode; 17560 } 17561 17562 @Override 17563 public boolean hasSystemUidErrors() { 17564 return mHasSystemUidErrors; 17565 } 17566 17567 static String arrayToString(int[] array) { 17568 StringBuffer buf = new StringBuffer(128); 17569 buf.append('['); 17570 if (array != null) { 17571 for (int i=0; i<array.length; i++) { 17572 if (i > 0) buf.append(", "); 17573 buf.append(array[i]); 17574 } 17575 } 17576 buf.append(']'); 17577 return buf.toString(); 17578 } 17579 17580 static class DumpState { 17581 public static final int DUMP_LIBS = 1 << 0; 17582 public static final int DUMP_FEATURES = 1 << 1; 17583 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17584 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17585 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17586 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17587 public static final int DUMP_PERMISSIONS = 1 << 6; 17588 public static final int DUMP_PACKAGES = 1 << 7; 17589 public static final int DUMP_SHARED_USERS = 1 << 8; 17590 public static final int DUMP_MESSAGES = 1 << 9; 17591 public static final int DUMP_PROVIDERS = 1 << 10; 17592 public static final int DUMP_VERIFIERS = 1 << 11; 17593 public static final int DUMP_PREFERRED = 1 << 12; 17594 public static final int DUMP_PREFERRED_XML = 1 << 13; 17595 public static final int DUMP_KEYSETS = 1 << 14; 17596 public static final int DUMP_VERSION = 1 << 15; 17597 public static final int DUMP_INSTALLS = 1 << 16; 17598 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17599 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17600 public static final int DUMP_FROZEN = 1 << 19; 17601 17602 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17603 17604 private int mTypes; 17605 17606 private int mOptions; 17607 17608 private boolean mTitlePrinted; 17609 17610 private SharedUserSetting mSharedUser; 17611 17612 public boolean isDumping(int type) { 17613 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17614 return true; 17615 } 17616 17617 return (mTypes & type) != 0; 17618 } 17619 17620 public void setDump(int type) { 17621 mTypes |= type; 17622 } 17623 17624 public boolean isOptionEnabled(int option) { 17625 return (mOptions & option) != 0; 17626 } 17627 17628 public void setOptionEnabled(int option) { 17629 mOptions |= option; 17630 } 17631 17632 public boolean onTitlePrinted() { 17633 final boolean printed = mTitlePrinted; 17634 mTitlePrinted = true; 17635 return printed; 17636 } 17637 17638 public boolean getTitlePrinted() { 17639 return mTitlePrinted; 17640 } 17641 17642 public void setTitlePrinted(boolean enabled) { 17643 mTitlePrinted = enabled; 17644 } 17645 17646 public SharedUserSetting getSharedUser() { 17647 return mSharedUser; 17648 } 17649 17650 public void setSharedUser(SharedUserSetting user) { 17651 mSharedUser = user; 17652 } 17653 } 17654 17655 @Override 17656 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17657 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17658 (new PackageManagerShellCommand(this)).exec( 17659 this, in, out, err, args, resultReceiver); 17660 } 17661 17662 @Override 17663 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17664 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17665 != PackageManager.PERMISSION_GRANTED) { 17666 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17667 + Binder.getCallingPid() 17668 + ", uid=" + Binder.getCallingUid() 17669 + " without permission " 17670 + android.Manifest.permission.DUMP); 17671 return; 17672 } 17673 17674 DumpState dumpState = new DumpState(); 17675 boolean fullPreferred = false; 17676 boolean checkin = false; 17677 17678 String packageName = null; 17679 ArraySet<String> permissionNames = null; 17680 17681 int opti = 0; 17682 while (opti < args.length) { 17683 String opt = args[opti]; 17684 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17685 break; 17686 } 17687 opti++; 17688 17689 if ("-a".equals(opt)) { 17690 // Right now we only know how to print all. 17691 } else if ("-h".equals(opt)) { 17692 pw.println("Package manager dump options:"); 17693 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17694 pw.println(" --checkin: dump for a checkin"); 17695 pw.println(" -f: print details of intent filters"); 17696 pw.println(" -h: print this help"); 17697 pw.println(" cmd may be one of:"); 17698 pw.println(" l[ibraries]: list known shared libraries"); 17699 pw.println(" f[eatures]: list device features"); 17700 pw.println(" k[eysets]: print known keysets"); 17701 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17702 pw.println(" perm[issions]: dump permissions"); 17703 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17704 pw.println(" pref[erred]: print preferred package settings"); 17705 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17706 pw.println(" prov[iders]: dump content providers"); 17707 pw.println(" p[ackages]: dump installed packages"); 17708 pw.println(" s[hared-users]: dump shared user IDs"); 17709 pw.println(" m[essages]: print collected runtime messages"); 17710 pw.println(" v[erifiers]: print package verifier info"); 17711 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17712 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17713 pw.println(" version: print database version info"); 17714 pw.println(" write: write current settings now"); 17715 pw.println(" installs: details about install sessions"); 17716 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17717 pw.println(" <package.name>: info about given package"); 17718 return; 17719 } else if ("--checkin".equals(opt)) { 17720 checkin = true; 17721 } else if ("-f".equals(opt)) { 17722 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17723 } else { 17724 pw.println("Unknown argument: " + opt + "; use -h for help"); 17725 } 17726 } 17727 17728 // Is the caller requesting to dump a particular piece of data? 17729 if (opti < args.length) { 17730 String cmd = args[opti]; 17731 opti++; 17732 // Is this a package name? 17733 if ("android".equals(cmd) || cmd.contains(".")) { 17734 packageName = cmd; 17735 // When dumping a single package, we always dump all of its 17736 // filter information since the amount of data will be reasonable. 17737 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17738 } else if ("check-permission".equals(cmd)) { 17739 if (opti >= args.length) { 17740 pw.println("Error: check-permission missing permission argument"); 17741 return; 17742 } 17743 String perm = args[opti]; 17744 opti++; 17745 if (opti >= args.length) { 17746 pw.println("Error: check-permission missing package argument"); 17747 return; 17748 } 17749 String pkg = args[opti]; 17750 opti++; 17751 int user = UserHandle.getUserId(Binder.getCallingUid()); 17752 if (opti < args.length) { 17753 try { 17754 user = Integer.parseInt(args[opti]); 17755 } catch (NumberFormatException e) { 17756 pw.println("Error: check-permission user argument is not a number: " 17757 + args[opti]); 17758 return; 17759 } 17760 } 17761 pw.println(checkPermission(perm, pkg, user)); 17762 return; 17763 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17764 dumpState.setDump(DumpState.DUMP_LIBS); 17765 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17766 dumpState.setDump(DumpState.DUMP_FEATURES); 17767 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17768 if (opti >= args.length) { 17769 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17770 | DumpState.DUMP_SERVICE_RESOLVERS 17771 | DumpState.DUMP_RECEIVER_RESOLVERS 17772 | DumpState.DUMP_CONTENT_RESOLVERS); 17773 } else { 17774 while (opti < args.length) { 17775 String name = args[opti]; 17776 if ("a".equals(name) || "activity".equals(name)) { 17777 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17778 } else if ("s".equals(name) || "service".equals(name)) { 17779 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17780 } else if ("r".equals(name) || "receiver".equals(name)) { 17781 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17782 } else if ("c".equals(name) || "content".equals(name)) { 17783 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17784 } else { 17785 pw.println("Error: unknown resolver table type: " + name); 17786 return; 17787 } 17788 opti++; 17789 } 17790 } 17791 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17792 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17793 } else if ("permission".equals(cmd)) { 17794 if (opti >= args.length) { 17795 pw.println("Error: permission requires permission name"); 17796 return; 17797 } 17798 permissionNames = new ArraySet<>(); 17799 while (opti < args.length) { 17800 permissionNames.add(args[opti]); 17801 opti++; 17802 } 17803 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17804 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17805 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17806 dumpState.setDump(DumpState.DUMP_PREFERRED); 17807 } else if ("preferred-xml".equals(cmd)) { 17808 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17809 if (opti < args.length && "--full".equals(args[opti])) { 17810 fullPreferred = true; 17811 opti++; 17812 } 17813 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17814 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17815 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17816 dumpState.setDump(DumpState.DUMP_PACKAGES); 17817 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17818 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17819 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17820 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17821 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17822 dumpState.setDump(DumpState.DUMP_MESSAGES); 17823 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17824 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17825 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17826 || "intent-filter-verifiers".equals(cmd)) { 17827 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17828 } else if ("version".equals(cmd)) { 17829 dumpState.setDump(DumpState.DUMP_VERSION); 17830 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17831 dumpState.setDump(DumpState.DUMP_KEYSETS); 17832 } else if ("installs".equals(cmd)) { 17833 dumpState.setDump(DumpState.DUMP_INSTALLS); 17834 } else if ("frozen".equals(cmd)) { 17835 dumpState.setDump(DumpState.DUMP_FROZEN); 17836 } else if ("write".equals(cmd)) { 17837 synchronized (mPackages) { 17838 mSettings.writeLPr(); 17839 pw.println("Settings written."); 17840 return; 17841 } 17842 } 17843 } 17844 17845 if (checkin) { 17846 pw.println("vers,1"); 17847 } 17848 17849 // reader 17850 synchronized (mPackages) { 17851 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17852 if (!checkin) { 17853 if (dumpState.onTitlePrinted()) 17854 pw.println(); 17855 pw.println("Database versions:"); 17856 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17857 } 17858 } 17859 17860 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17861 if (!checkin) { 17862 if (dumpState.onTitlePrinted()) 17863 pw.println(); 17864 pw.println("Verifiers:"); 17865 pw.print(" Required: "); 17866 pw.print(mRequiredVerifierPackage); 17867 pw.print(" (uid="); 17868 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17869 UserHandle.USER_SYSTEM)); 17870 pw.println(")"); 17871 } else if (mRequiredVerifierPackage != null) { 17872 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17873 pw.print(","); 17874 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17875 UserHandle.USER_SYSTEM)); 17876 } 17877 } 17878 17879 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17880 packageName == null) { 17881 if (mIntentFilterVerifierComponent != null) { 17882 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17883 if (!checkin) { 17884 if (dumpState.onTitlePrinted()) 17885 pw.println(); 17886 pw.println("Intent Filter Verifier:"); 17887 pw.print(" Using: "); 17888 pw.print(verifierPackageName); 17889 pw.print(" (uid="); 17890 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17891 UserHandle.USER_SYSTEM)); 17892 pw.println(")"); 17893 } else if (verifierPackageName != null) { 17894 pw.print("ifv,"); pw.print(verifierPackageName); 17895 pw.print(","); 17896 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17897 UserHandle.USER_SYSTEM)); 17898 } 17899 } else { 17900 pw.println(); 17901 pw.println("No Intent Filter Verifier available!"); 17902 } 17903 } 17904 17905 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17906 boolean printedHeader = false; 17907 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17908 while (it.hasNext()) { 17909 String name = it.next(); 17910 SharedLibraryEntry ent = mSharedLibraries.get(name); 17911 if (!checkin) { 17912 if (!printedHeader) { 17913 if (dumpState.onTitlePrinted()) 17914 pw.println(); 17915 pw.println("Libraries:"); 17916 printedHeader = true; 17917 } 17918 pw.print(" "); 17919 } else { 17920 pw.print("lib,"); 17921 } 17922 pw.print(name); 17923 if (!checkin) { 17924 pw.print(" -> "); 17925 } 17926 if (ent.path != null) { 17927 if (!checkin) { 17928 pw.print("(jar) "); 17929 pw.print(ent.path); 17930 } else { 17931 pw.print(",jar,"); 17932 pw.print(ent.path); 17933 } 17934 } else { 17935 if (!checkin) { 17936 pw.print("(apk) "); 17937 pw.print(ent.apk); 17938 } else { 17939 pw.print(",apk,"); 17940 pw.print(ent.apk); 17941 } 17942 } 17943 pw.println(); 17944 } 17945 } 17946 17947 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17948 if (dumpState.onTitlePrinted()) 17949 pw.println(); 17950 if (!checkin) { 17951 pw.println("Features:"); 17952 } 17953 17954 for (FeatureInfo feat : mAvailableFeatures.values()) { 17955 if (checkin) { 17956 pw.print("feat,"); 17957 pw.print(feat.name); 17958 pw.print(","); 17959 pw.println(feat.version); 17960 } else { 17961 pw.print(" "); 17962 pw.print(feat.name); 17963 if (feat.version > 0) { 17964 pw.print(" version="); 17965 pw.print(feat.version); 17966 } 17967 pw.println(); 17968 } 17969 } 17970 } 17971 17972 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17973 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17974 : "Activity Resolver Table:", " ", packageName, 17975 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17976 dumpState.setTitlePrinted(true); 17977 } 17978 } 17979 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17980 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17981 : "Receiver Resolver Table:", " ", packageName, 17982 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17983 dumpState.setTitlePrinted(true); 17984 } 17985 } 17986 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17987 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17988 : "Service Resolver Table:", " ", packageName, 17989 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17990 dumpState.setTitlePrinted(true); 17991 } 17992 } 17993 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17994 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17995 : "Provider Resolver Table:", " ", packageName, 17996 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17997 dumpState.setTitlePrinted(true); 17998 } 17999 } 18000 18001 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18002 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18003 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18004 int user = mSettings.mPreferredActivities.keyAt(i); 18005 if (pir.dump(pw, 18006 dumpState.getTitlePrinted() 18007 ? "\nPreferred Activities User " + user + ":" 18008 : "Preferred Activities User " + user + ":", " ", 18009 packageName, true, false)) { 18010 dumpState.setTitlePrinted(true); 18011 } 18012 } 18013 } 18014 18015 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18016 pw.flush(); 18017 FileOutputStream fout = new FileOutputStream(fd); 18018 BufferedOutputStream str = new BufferedOutputStream(fout); 18019 XmlSerializer serializer = new FastXmlSerializer(); 18020 try { 18021 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18022 serializer.startDocument(null, true); 18023 serializer.setFeature( 18024 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18025 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18026 serializer.endDocument(); 18027 serializer.flush(); 18028 } catch (IllegalArgumentException e) { 18029 pw.println("Failed writing: " + e); 18030 } catch (IllegalStateException e) { 18031 pw.println("Failed writing: " + e); 18032 } catch (IOException e) { 18033 pw.println("Failed writing: " + e); 18034 } 18035 } 18036 18037 if (!checkin 18038 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18039 && packageName == null) { 18040 pw.println(); 18041 int count = mSettings.mPackages.size(); 18042 if (count == 0) { 18043 pw.println("No applications!"); 18044 pw.println(); 18045 } else { 18046 final String prefix = " "; 18047 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18048 if (allPackageSettings.size() == 0) { 18049 pw.println("No domain preferred apps!"); 18050 pw.println(); 18051 } else { 18052 pw.println("App verification status:"); 18053 pw.println(); 18054 count = 0; 18055 for (PackageSetting ps : allPackageSettings) { 18056 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18057 if (ivi == null || ivi.getPackageName() == null) continue; 18058 pw.println(prefix + "Package: " + ivi.getPackageName()); 18059 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18060 pw.println(prefix + "Status: " + ivi.getStatusString()); 18061 pw.println(); 18062 count++; 18063 } 18064 if (count == 0) { 18065 pw.println(prefix + "No app verification established."); 18066 pw.println(); 18067 } 18068 for (int userId : sUserManager.getUserIds()) { 18069 pw.println("App linkages for user " + userId + ":"); 18070 pw.println(); 18071 count = 0; 18072 for (PackageSetting ps : allPackageSettings) { 18073 final long status = ps.getDomainVerificationStatusForUser(userId); 18074 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18075 continue; 18076 } 18077 pw.println(prefix + "Package: " + ps.name); 18078 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18079 String statusStr = IntentFilterVerificationInfo. 18080 getStatusStringFromValue(status); 18081 pw.println(prefix + "Status: " + statusStr); 18082 pw.println(); 18083 count++; 18084 } 18085 if (count == 0) { 18086 pw.println(prefix + "No configured app linkages."); 18087 pw.println(); 18088 } 18089 } 18090 } 18091 } 18092 } 18093 18094 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18095 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18096 if (packageName == null && permissionNames == null) { 18097 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18098 if (iperm == 0) { 18099 if (dumpState.onTitlePrinted()) 18100 pw.println(); 18101 pw.println("AppOp Permissions:"); 18102 } 18103 pw.print(" AppOp Permission "); 18104 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18105 pw.println(":"); 18106 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18107 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18108 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18109 } 18110 } 18111 } 18112 } 18113 18114 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18115 boolean printedSomething = false; 18116 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18117 if (packageName != null && !packageName.equals(p.info.packageName)) { 18118 continue; 18119 } 18120 if (!printedSomething) { 18121 if (dumpState.onTitlePrinted()) 18122 pw.println(); 18123 pw.println("Registered ContentProviders:"); 18124 printedSomething = true; 18125 } 18126 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18127 pw.print(" "); pw.println(p.toString()); 18128 } 18129 printedSomething = false; 18130 for (Map.Entry<String, PackageParser.Provider> entry : 18131 mProvidersByAuthority.entrySet()) { 18132 PackageParser.Provider p = entry.getValue(); 18133 if (packageName != null && !packageName.equals(p.info.packageName)) { 18134 continue; 18135 } 18136 if (!printedSomething) { 18137 if (dumpState.onTitlePrinted()) 18138 pw.println(); 18139 pw.println("ContentProvider Authorities:"); 18140 printedSomething = true; 18141 } 18142 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18143 pw.print(" "); pw.println(p.toString()); 18144 if (p.info != null && p.info.applicationInfo != null) { 18145 final String appInfo = p.info.applicationInfo.toString(); 18146 pw.print(" applicationInfo="); pw.println(appInfo); 18147 } 18148 } 18149 } 18150 18151 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18152 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18153 } 18154 18155 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18156 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18157 } 18158 18159 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18160 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18161 } 18162 18163 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18164 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18165 } 18166 18167 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18168 // XXX should handle packageName != null by dumping only install data that 18169 // the given package is involved with. 18170 if (dumpState.onTitlePrinted()) pw.println(); 18171 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18172 } 18173 18174 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18175 // XXX should handle packageName != null by dumping only install data that 18176 // the given package is involved with. 18177 if (dumpState.onTitlePrinted()) pw.println(); 18178 18179 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18180 ipw.println(); 18181 ipw.println("Frozen packages:"); 18182 ipw.increaseIndent(); 18183 if (mFrozenPackages.size() == 0) { 18184 ipw.println("(none)"); 18185 } else { 18186 for (int i = 0; i < mFrozenPackages.size(); i++) { 18187 ipw.println(mFrozenPackages.valueAt(i)); 18188 } 18189 } 18190 ipw.decreaseIndent(); 18191 } 18192 18193 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18194 if (dumpState.onTitlePrinted()) pw.println(); 18195 mSettings.dumpReadMessagesLPr(pw, dumpState); 18196 18197 pw.println(); 18198 pw.println("Package warning messages:"); 18199 BufferedReader in = null; 18200 String line = null; 18201 try { 18202 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18203 while ((line = in.readLine()) != null) { 18204 if (line.contains("ignored: updated version")) continue; 18205 pw.println(line); 18206 } 18207 } catch (IOException ignored) { 18208 } finally { 18209 IoUtils.closeQuietly(in); 18210 } 18211 } 18212 18213 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18214 BufferedReader in = null; 18215 String line = null; 18216 try { 18217 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18218 while ((line = in.readLine()) != null) { 18219 if (line.contains("ignored: updated version")) continue; 18220 pw.print("msg,"); 18221 pw.println(line); 18222 } 18223 } catch (IOException ignored) { 18224 } finally { 18225 IoUtils.closeQuietly(in); 18226 } 18227 } 18228 } 18229 } 18230 18231 private String dumpDomainString(String packageName) { 18232 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18233 .getList(); 18234 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18235 18236 ArraySet<String> result = new ArraySet<>(); 18237 if (iviList.size() > 0) { 18238 for (IntentFilterVerificationInfo ivi : iviList) { 18239 for (String host : ivi.getDomains()) { 18240 result.add(host); 18241 } 18242 } 18243 } 18244 if (filters != null && filters.size() > 0) { 18245 for (IntentFilter filter : filters) { 18246 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18247 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18248 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18249 result.addAll(filter.getHostsList()); 18250 } 18251 } 18252 } 18253 18254 StringBuilder sb = new StringBuilder(result.size() * 16); 18255 for (String domain : result) { 18256 if (sb.length() > 0) sb.append(" "); 18257 sb.append(domain); 18258 } 18259 return sb.toString(); 18260 } 18261 18262 // ------- apps on sdcard specific code ------- 18263 static final boolean DEBUG_SD_INSTALL = false; 18264 18265 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18266 18267 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18268 18269 private boolean mMediaMounted = false; 18270 18271 static String getEncryptKey() { 18272 try { 18273 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18274 SD_ENCRYPTION_KEYSTORE_NAME); 18275 if (sdEncKey == null) { 18276 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18277 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18278 if (sdEncKey == null) { 18279 Slog.e(TAG, "Failed to create encryption keys"); 18280 return null; 18281 } 18282 } 18283 return sdEncKey; 18284 } catch (NoSuchAlgorithmException nsae) { 18285 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18286 return null; 18287 } catch (IOException ioe) { 18288 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18289 return null; 18290 } 18291 } 18292 18293 /* 18294 * Update media status on PackageManager. 18295 */ 18296 @Override 18297 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18298 int callingUid = Binder.getCallingUid(); 18299 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18300 throw new SecurityException("Media status can only be updated by the system"); 18301 } 18302 // reader; this apparently protects mMediaMounted, but should probably 18303 // be a different lock in that case. 18304 synchronized (mPackages) { 18305 Log.i(TAG, "Updating external media status from " 18306 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18307 + (mediaStatus ? "mounted" : "unmounted")); 18308 if (DEBUG_SD_INSTALL) 18309 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18310 + ", mMediaMounted=" + mMediaMounted); 18311 if (mediaStatus == mMediaMounted) { 18312 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18313 : 0, -1); 18314 mHandler.sendMessage(msg); 18315 return; 18316 } 18317 mMediaMounted = mediaStatus; 18318 } 18319 // Queue up an async operation since the package installation may take a 18320 // little while. 18321 mHandler.post(new Runnable() { 18322 public void run() { 18323 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18324 } 18325 }); 18326 } 18327 18328 /** 18329 * Called by MountService when the initial ASECs to scan are available. 18330 * Should block until all the ASEC containers are finished being scanned. 18331 */ 18332 public void scanAvailableAsecs() { 18333 updateExternalMediaStatusInner(true, false, false); 18334 } 18335 18336 /* 18337 * Collect information of applications on external media, map them against 18338 * existing containers and update information based on current mount status. 18339 * Please note that we always have to report status if reportStatus has been 18340 * set to true especially when unloading packages. 18341 */ 18342 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18343 boolean externalStorage) { 18344 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18345 int[] uidArr = EmptyArray.INT; 18346 18347 final String[] list = PackageHelper.getSecureContainerList(); 18348 if (ArrayUtils.isEmpty(list)) { 18349 Log.i(TAG, "No secure containers found"); 18350 } else { 18351 // Process list of secure containers and categorize them 18352 // as active or stale based on their package internal state. 18353 18354 // reader 18355 synchronized (mPackages) { 18356 for (String cid : list) { 18357 // Leave stages untouched for now; installer service owns them 18358 if (PackageInstallerService.isStageName(cid)) continue; 18359 18360 if (DEBUG_SD_INSTALL) 18361 Log.i(TAG, "Processing container " + cid); 18362 String pkgName = getAsecPackageName(cid); 18363 if (pkgName == null) { 18364 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18365 continue; 18366 } 18367 if (DEBUG_SD_INSTALL) 18368 Log.i(TAG, "Looking for pkg : " + pkgName); 18369 18370 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18371 if (ps == null) { 18372 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18373 continue; 18374 } 18375 18376 /* 18377 * Skip packages that are not external if we're unmounting 18378 * external storage. 18379 */ 18380 if (externalStorage && !isMounted && !isExternal(ps)) { 18381 continue; 18382 } 18383 18384 final AsecInstallArgs args = new AsecInstallArgs(cid, 18385 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18386 // The package status is changed only if the code path 18387 // matches between settings and the container id. 18388 if (ps.codePathString != null 18389 && ps.codePathString.startsWith(args.getCodePath())) { 18390 if (DEBUG_SD_INSTALL) { 18391 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18392 + " at code path: " + ps.codePathString); 18393 } 18394 18395 // We do have a valid package installed on sdcard 18396 processCids.put(args, ps.codePathString); 18397 final int uid = ps.appId; 18398 if (uid != -1) { 18399 uidArr = ArrayUtils.appendInt(uidArr, uid); 18400 } 18401 } else { 18402 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18403 + ps.codePathString); 18404 } 18405 } 18406 } 18407 18408 Arrays.sort(uidArr); 18409 } 18410 18411 // Process packages with valid entries. 18412 if (isMounted) { 18413 if (DEBUG_SD_INSTALL) 18414 Log.i(TAG, "Loading packages"); 18415 loadMediaPackages(processCids, uidArr, externalStorage); 18416 startCleaningPackages(); 18417 mInstallerService.onSecureContainersAvailable(); 18418 } else { 18419 if (DEBUG_SD_INSTALL) 18420 Log.i(TAG, "Unloading packages"); 18421 unloadMediaPackages(processCids, uidArr, reportStatus); 18422 } 18423 } 18424 18425 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18426 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18427 final int size = infos.size(); 18428 final String[] packageNames = new String[size]; 18429 final int[] packageUids = new int[size]; 18430 for (int i = 0; i < size; i++) { 18431 final ApplicationInfo info = infos.get(i); 18432 packageNames[i] = info.packageName; 18433 packageUids[i] = info.uid; 18434 } 18435 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18436 finishedReceiver); 18437 } 18438 18439 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18440 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18441 sendResourcesChangedBroadcast(mediaStatus, replacing, 18442 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18443 } 18444 18445 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18446 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18447 int size = pkgList.length; 18448 if (size > 0) { 18449 // Send broadcasts here 18450 Bundle extras = new Bundle(); 18451 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18452 if (uidArr != null) { 18453 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18454 } 18455 if (replacing) { 18456 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18457 } 18458 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18459 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18460 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18461 } 18462 } 18463 18464 /* 18465 * Look at potentially valid container ids from processCids If package 18466 * information doesn't match the one on record or package scanning fails, 18467 * the cid is added to list of removeCids. We currently don't delete stale 18468 * containers. 18469 */ 18470 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18471 boolean externalStorage) { 18472 ArrayList<String> pkgList = new ArrayList<String>(); 18473 Set<AsecInstallArgs> keys = processCids.keySet(); 18474 18475 for (AsecInstallArgs args : keys) { 18476 String codePath = processCids.get(args); 18477 if (DEBUG_SD_INSTALL) 18478 Log.i(TAG, "Loading container : " + args.cid); 18479 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18480 try { 18481 // Make sure there are no container errors first. 18482 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18483 Slog.e(TAG, "Failed to mount cid : " + args.cid 18484 + " when installing from sdcard"); 18485 continue; 18486 } 18487 // Check code path here. 18488 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18489 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18490 + " does not match one in settings " + codePath); 18491 continue; 18492 } 18493 // Parse package 18494 int parseFlags = mDefParseFlags; 18495 if (args.isExternalAsec()) { 18496 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18497 } 18498 if (args.isFwdLocked()) { 18499 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18500 } 18501 18502 synchronized (mInstallLock) { 18503 PackageParser.Package pkg = null; 18504 try { 18505 // Sadly we don't know the package name yet to freeze it 18506 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18507 SCAN_IGNORE_FROZEN, 0, null); 18508 } catch (PackageManagerException e) { 18509 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18510 } 18511 // Scan the package 18512 if (pkg != null) { 18513 /* 18514 * TODO why is the lock being held? doPostInstall is 18515 * called in other places without the lock. This needs 18516 * to be straightened out. 18517 */ 18518 // writer 18519 synchronized (mPackages) { 18520 retCode = PackageManager.INSTALL_SUCCEEDED; 18521 pkgList.add(pkg.packageName); 18522 // Post process args 18523 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18524 pkg.applicationInfo.uid); 18525 } 18526 } else { 18527 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18528 } 18529 } 18530 18531 } finally { 18532 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18533 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18534 } 18535 } 18536 } 18537 // writer 18538 synchronized (mPackages) { 18539 // If the platform SDK has changed since the last time we booted, 18540 // we need to re-grant app permission to catch any new ones that 18541 // appear. This is really a hack, and means that apps can in some 18542 // cases get permissions that the user didn't initially explicitly 18543 // allow... it would be nice to have some better way to handle 18544 // this situation. 18545 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18546 : mSettings.getInternalVersion(); 18547 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18548 : StorageManager.UUID_PRIVATE_INTERNAL; 18549 18550 int updateFlags = UPDATE_PERMISSIONS_ALL; 18551 if (ver.sdkVersion != mSdkVersion) { 18552 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18553 + mSdkVersion + "; regranting permissions for external"); 18554 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18555 } 18556 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18557 18558 // Yay, everything is now upgraded 18559 ver.forceCurrent(); 18560 18561 // can downgrade to reader 18562 // Persist settings 18563 mSettings.writeLPr(); 18564 } 18565 // Send a broadcast to let everyone know we are done processing 18566 if (pkgList.size() > 0) { 18567 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18568 } 18569 } 18570 18571 /* 18572 * Utility method to unload a list of specified containers 18573 */ 18574 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18575 // Just unmount all valid containers. 18576 for (AsecInstallArgs arg : cidArgs) { 18577 synchronized (mInstallLock) { 18578 arg.doPostDeleteLI(false); 18579 } 18580 } 18581 } 18582 18583 /* 18584 * Unload packages mounted on external media. This involves deleting package 18585 * data from internal structures, sending broadcasts about disabled packages, 18586 * gc'ing to free up references, unmounting all secure containers 18587 * corresponding to packages on external media, and posting a 18588 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18589 * that we always have to post this message if status has been requested no 18590 * matter what. 18591 */ 18592 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18593 final boolean reportStatus) { 18594 if (DEBUG_SD_INSTALL) 18595 Log.i(TAG, "unloading media packages"); 18596 ArrayList<String> pkgList = new ArrayList<String>(); 18597 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18598 final Set<AsecInstallArgs> keys = processCids.keySet(); 18599 for (AsecInstallArgs args : keys) { 18600 String pkgName = args.getPackageName(); 18601 if (DEBUG_SD_INSTALL) 18602 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18603 // Delete package internally 18604 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18605 synchronized (mInstallLock) { 18606 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18607 final boolean res; 18608 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18609 "unloadMediaPackages")) { 18610 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18611 null); 18612 } 18613 if (res) { 18614 pkgList.add(pkgName); 18615 } else { 18616 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18617 failedList.add(args); 18618 } 18619 } 18620 } 18621 18622 // reader 18623 synchronized (mPackages) { 18624 // We didn't update the settings after removing each package; 18625 // write them now for all packages. 18626 mSettings.writeLPr(); 18627 } 18628 18629 // We have to absolutely send UPDATED_MEDIA_STATUS only 18630 // after confirming that all the receivers processed the ordered 18631 // broadcast when packages get disabled, force a gc to clean things up. 18632 // and unload all the containers. 18633 if (pkgList.size() > 0) { 18634 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18635 new IIntentReceiver.Stub() { 18636 public void performReceive(Intent intent, int resultCode, String data, 18637 Bundle extras, boolean ordered, boolean sticky, 18638 int sendingUser) throws RemoteException { 18639 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18640 reportStatus ? 1 : 0, 1, keys); 18641 mHandler.sendMessage(msg); 18642 } 18643 }); 18644 } else { 18645 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18646 keys); 18647 mHandler.sendMessage(msg); 18648 } 18649 } 18650 18651 private void loadPrivatePackages(final VolumeInfo vol) { 18652 mHandler.post(new Runnable() { 18653 @Override 18654 public void run() { 18655 loadPrivatePackagesInner(vol); 18656 } 18657 }); 18658 } 18659 18660 private void loadPrivatePackagesInner(VolumeInfo vol) { 18661 final String volumeUuid = vol.fsUuid; 18662 if (TextUtils.isEmpty(volumeUuid)) { 18663 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18664 return; 18665 } 18666 18667 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18668 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18669 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18670 18671 final VersionInfo ver; 18672 final List<PackageSetting> packages; 18673 synchronized (mPackages) { 18674 ver = mSettings.findOrCreateVersion(volumeUuid); 18675 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18676 } 18677 18678 for (PackageSetting ps : packages) { 18679 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18680 synchronized (mInstallLock) { 18681 final PackageParser.Package pkg; 18682 try { 18683 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18684 loaded.add(pkg.applicationInfo); 18685 18686 } catch (PackageManagerException e) { 18687 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18688 } 18689 18690 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18691 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18692 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18693 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18694 } 18695 } 18696 } 18697 18698 // Reconcile app data for all started/unlocked users 18699 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18700 final UserManager um = mContext.getSystemService(UserManager.class); 18701 for (UserInfo user : um.getUsers()) { 18702 final int flags; 18703 if (um.isUserUnlocked(user.id)) { 18704 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18705 } else if (um.isUserRunning(user.id)) { 18706 flags = StorageManager.FLAG_STORAGE_DE; 18707 } else { 18708 continue; 18709 } 18710 18711 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18712 synchronized (mInstallLock) { 18713 reconcileAppsDataLI(volumeUuid, user.id, flags); 18714 } 18715 } 18716 18717 synchronized (mPackages) { 18718 int updateFlags = UPDATE_PERMISSIONS_ALL; 18719 if (ver.sdkVersion != mSdkVersion) { 18720 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18721 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18722 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18723 } 18724 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18725 18726 // Yay, everything is now upgraded 18727 ver.forceCurrent(); 18728 18729 mSettings.writeLPr(); 18730 } 18731 18732 for (PackageFreezer freezer : freezers) { 18733 freezer.close(); 18734 } 18735 18736 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18737 sendResourcesChangedBroadcast(true, false, loaded, null); 18738 } 18739 18740 private void unloadPrivatePackages(final VolumeInfo vol) { 18741 mHandler.post(new Runnable() { 18742 @Override 18743 public void run() { 18744 unloadPrivatePackagesInner(vol); 18745 } 18746 }); 18747 } 18748 18749 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18750 final String volumeUuid = vol.fsUuid; 18751 if (TextUtils.isEmpty(volumeUuid)) { 18752 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18753 return; 18754 } 18755 18756 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18757 synchronized (mInstallLock) { 18758 synchronized (mPackages) { 18759 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18760 for (PackageSetting ps : packages) { 18761 if (ps.pkg == null) continue; 18762 18763 final ApplicationInfo info = ps.pkg.applicationInfo; 18764 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18765 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18766 18767 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18768 "unloadPrivatePackagesInner")) { 18769 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18770 false, null)) { 18771 unloaded.add(info); 18772 } else { 18773 Slog.w(TAG, "Failed to unload " + ps.codePath); 18774 } 18775 } 18776 } 18777 18778 mSettings.writeLPr(); 18779 } 18780 } 18781 18782 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18783 sendResourcesChangedBroadcast(false, false, unloaded, null); 18784 } 18785 18786 /** 18787 * Prepare storage areas for given user on all mounted devices. 18788 */ 18789 void prepareUserData(int userId, int userSerial, int flags) { 18790 synchronized (mInstallLock) { 18791 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18792 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18793 final String volumeUuid = vol.getFsUuid(); 18794 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18795 } 18796 } 18797 } 18798 18799 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18800 boolean allowRecover) { 18801 // Prepare storage and verify that serial numbers are consistent; if 18802 // there's a mismatch we need to destroy to avoid leaking data 18803 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18804 try { 18805 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18806 18807 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18808 UserManagerService.enforceSerialNumber( 18809 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18810 } 18811 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18812 UserManagerService.enforceSerialNumber( 18813 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18814 } 18815 18816 synchronized (mInstallLock) { 18817 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18818 } 18819 } catch (Exception e) { 18820 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18821 + " because we failed to prepare: " + e); 18822 destroyUserDataLI(volumeUuid, userId, 18823 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18824 18825 if (allowRecover) { 18826 // Try one last time; if we fail again we're really in trouble 18827 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18828 } 18829 } 18830 } 18831 18832 /** 18833 * Destroy storage areas for given user on all mounted devices. 18834 */ 18835 void destroyUserData(int userId, int flags) { 18836 synchronized (mInstallLock) { 18837 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18838 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18839 final String volumeUuid = vol.getFsUuid(); 18840 destroyUserDataLI(volumeUuid, userId, flags); 18841 } 18842 } 18843 } 18844 18845 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18846 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18847 try { 18848 // Clean up app data, profile data, and media data 18849 mInstaller.destroyUserData(volumeUuid, userId, flags); 18850 18851 // Clean up system data 18852 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18853 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18854 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18855 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18856 } 18857 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18858 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18859 } 18860 } 18861 18862 // Data with special labels is now gone, so finish the job 18863 storage.destroyUserStorage(volumeUuid, userId, flags); 18864 18865 } catch (Exception e) { 18866 logCriticalInfo(Log.WARN, 18867 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18868 } 18869 } 18870 18871 /** 18872 * Examine all users present on given mounted volume, and destroy data 18873 * belonging to users that are no longer valid, or whose user ID has been 18874 * recycled. 18875 */ 18876 private void reconcileUsers(String volumeUuid) { 18877 final List<File> files = new ArrayList<>(); 18878 Collections.addAll(files, FileUtils 18879 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18880 Collections.addAll(files, FileUtils 18881 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18882 for (File file : files) { 18883 if (!file.isDirectory()) continue; 18884 18885 final int userId; 18886 final UserInfo info; 18887 try { 18888 userId = Integer.parseInt(file.getName()); 18889 info = sUserManager.getUserInfo(userId); 18890 } catch (NumberFormatException e) { 18891 Slog.w(TAG, "Invalid user directory " + file); 18892 continue; 18893 } 18894 18895 boolean destroyUser = false; 18896 if (info == null) { 18897 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18898 + " because no matching user was found"); 18899 destroyUser = true; 18900 } else if (!mOnlyCore) { 18901 try { 18902 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18903 } catch (IOException e) { 18904 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18905 + " because we failed to enforce serial number: " + e); 18906 destroyUser = true; 18907 } 18908 } 18909 18910 if (destroyUser) { 18911 synchronized (mInstallLock) { 18912 destroyUserDataLI(volumeUuid, userId, 18913 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18914 } 18915 } 18916 } 18917 } 18918 18919 private void assertPackageKnown(String volumeUuid, String packageName) 18920 throws PackageManagerException { 18921 synchronized (mPackages) { 18922 final PackageSetting ps = mSettings.mPackages.get(packageName); 18923 if (ps == null) { 18924 throw new PackageManagerException("Package " + packageName + " is unknown"); 18925 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18926 throw new PackageManagerException( 18927 "Package " + packageName + " found on unknown volume " + volumeUuid 18928 + "; expected volume " + ps.volumeUuid); 18929 } 18930 } 18931 } 18932 18933 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18934 throws PackageManagerException { 18935 synchronized (mPackages) { 18936 final PackageSetting ps = mSettings.mPackages.get(packageName); 18937 if (ps == null) { 18938 throw new PackageManagerException("Package " + packageName + " is unknown"); 18939 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18940 throw new PackageManagerException( 18941 "Package " + packageName + " found on unknown volume " + volumeUuid 18942 + "; expected volume " + ps.volumeUuid); 18943 } else if (!ps.getInstalled(userId)) { 18944 throw new PackageManagerException( 18945 "Package " + packageName + " not installed for user " + userId); 18946 } 18947 } 18948 } 18949 18950 /** 18951 * Examine all apps present on given mounted volume, and destroy apps that 18952 * aren't expected, either due to uninstallation or reinstallation on 18953 * another volume. 18954 */ 18955 private void reconcileApps(String volumeUuid) { 18956 final File[] files = FileUtils 18957 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18958 for (File file : files) { 18959 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18960 && !PackageInstallerService.isStageName(file.getName()); 18961 if (!isPackage) { 18962 // Ignore entries which are not packages 18963 continue; 18964 } 18965 18966 try { 18967 final PackageLite pkg = PackageParser.parsePackageLite(file, 18968 PackageParser.PARSE_MUST_BE_APK); 18969 assertPackageKnown(volumeUuid, pkg.packageName); 18970 18971 } catch (PackageParserException | PackageManagerException e) { 18972 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18973 synchronized (mInstallLock) { 18974 removeCodePathLI(file); 18975 } 18976 } 18977 } 18978 } 18979 18980 /** 18981 * Reconcile all app data for the given user. 18982 * <p> 18983 * Verifies that directories exist and that ownership and labeling is 18984 * correct for all installed apps on all mounted volumes. 18985 */ 18986 void reconcileAppsData(int userId, int flags) { 18987 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18988 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18989 final String volumeUuid = vol.getFsUuid(); 18990 synchronized (mInstallLock) { 18991 reconcileAppsDataLI(volumeUuid, userId, flags); 18992 } 18993 } 18994 } 18995 18996 /** 18997 * Reconcile all app data on given mounted volume. 18998 * <p> 18999 * Destroys app data that isn't expected, either due to uninstallation or 19000 * reinstallation on another volume. 19001 * <p> 19002 * Verifies that directories exist and that ownership and labeling is 19003 * correct for all installed apps. 19004 */ 19005 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19006 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19007 + Integer.toHexString(flags)); 19008 19009 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19010 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19011 19012 boolean restoreconNeeded = false; 19013 19014 // First look for stale data that doesn't belong, and check if things 19015 // have changed since we did our last restorecon 19016 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19017 if (!isUserKeyUnlocked(userId)) { 19018 throw new RuntimeException( 19019 "Yikes, someone asked us to reconcile CE storage while " + userId 19020 + " was still locked; this would have caused massive data loss!"); 19021 } 19022 19023 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19024 19025 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19026 for (File file : files) { 19027 final String packageName = file.getName(); 19028 try { 19029 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19030 } catch (PackageManagerException e) { 19031 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19032 try { 19033 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19034 StorageManager.FLAG_STORAGE_CE, 0); 19035 } catch (InstallerException e2) { 19036 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19037 } 19038 } 19039 } 19040 } 19041 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19042 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19043 19044 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19045 for (File file : files) { 19046 final String packageName = file.getName(); 19047 try { 19048 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19049 } catch (PackageManagerException e) { 19050 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19051 try { 19052 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19053 StorageManager.FLAG_STORAGE_DE, 0); 19054 } catch (InstallerException e2) { 19055 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19056 } 19057 } 19058 } 19059 } 19060 19061 // Ensure that data directories are ready to roll for all packages 19062 // installed for this volume and user 19063 final List<PackageSetting> packages; 19064 synchronized (mPackages) { 19065 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19066 } 19067 int preparedCount = 0; 19068 for (PackageSetting ps : packages) { 19069 final String packageName = ps.name; 19070 if (ps.pkg == null) { 19071 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19072 // TODO: might be due to legacy ASEC apps; we should circle back 19073 // and reconcile again once they're scanned 19074 continue; 19075 } 19076 19077 if (ps.getInstalled(userId)) { 19078 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19079 19080 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19081 // We may have just shuffled around app data directories, so 19082 // prepare them one more time 19083 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19084 } 19085 19086 preparedCount++; 19087 } 19088 } 19089 19090 if (restoreconNeeded) { 19091 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19092 SELinuxMMAC.setRestoreconDone(ceDir); 19093 } 19094 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19095 SELinuxMMAC.setRestoreconDone(deDir); 19096 } 19097 } 19098 19099 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19100 + " packages; restoreconNeeded was " + restoreconNeeded); 19101 } 19102 19103 /** 19104 * Prepare app data for the given app just after it was installed or 19105 * upgraded. This method carefully only touches users that it's installed 19106 * for, and it forces a restorecon to handle any seinfo changes. 19107 * <p> 19108 * Verifies that directories exist and that ownership and labeling is 19109 * correct for all installed apps. If there is an ownership mismatch, it 19110 * will try recovering system apps by wiping data; third-party app data is 19111 * left intact. 19112 * <p> 19113 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19114 */ 19115 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19116 final PackageSetting ps; 19117 synchronized (mPackages) { 19118 ps = mSettings.mPackages.get(pkg.packageName); 19119 mSettings.writeKernelMappingLPr(ps); 19120 } 19121 19122 final UserManager um = mContext.getSystemService(UserManager.class); 19123 for (UserInfo user : um.getUsers()) { 19124 final int flags; 19125 if (um.isUserUnlocked(user.id)) { 19126 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19127 } else if (um.isUserRunning(user.id)) { 19128 flags = StorageManager.FLAG_STORAGE_DE; 19129 } else { 19130 continue; 19131 } 19132 19133 if (ps.getInstalled(user.id)) { 19134 // Whenever an app changes, force a restorecon of its data 19135 // TODO: when user data is locked, mark that we're still dirty 19136 prepareAppDataLIF(pkg, user.id, flags, true); 19137 } 19138 } 19139 } 19140 19141 /** 19142 * Prepare app data for the given app. 19143 * <p> 19144 * Verifies that directories exist and that ownership and labeling is 19145 * correct for all installed apps. If there is an ownership mismatch, this 19146 * will try recovering system apps by wiping data; third-party app data is 19147 * left intact. 19148 */ 19149 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19150 boolean restoreconNeeded) { 19151 if (pkg == null) { 19152 Slog.wtf(TAG, "Package was null!", new Throwable()); 19153 return; 19154 } 19155 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19156 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19157 for (int i = 0; i < childCount; i++) { 19158 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19159 } 19160 } 19161 19162 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19163 boolean restoreconNeeded) { 19164 if (DEBUG_APP_DATA) { 19165 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19166 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19167 } 19168 19169 final String volumeUuid = pkg.volumeUuid; 19170 final String packageName = pkg.packageName; 19171 final ApplicationInfo app = pkg.applicationInfo; 19172 final int appId = UserHandle.getAppId(app.uid); 19173 19174 Preconditions.checkNotNull(app.seinfo); 19175 19176 try { 19177 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19178 appId, app.seinfo, app.targetSdkVersion); 19179 } catch (InstallerException e) { 19180 if (app.isSystemApp()) { 19181 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19182 + ", but trying to recover: " + e); 19183 destroyAppDataLeafLIF(pkg, userId, flags); 19184 try { 19185 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19186 appId, app.seinfo, app.targetSdkVersion); 19187 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19188 } catch (InstallerException e2) { 19189 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19190 } 19191 } else { 19192 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19193 } 19194 } 19195 19196 if (restoreconNeeded) { 19197 try { 19198 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19199 app.seinfo); 19200 } catch (InstallerException e) { 19201 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19202 } 19203 } 19204 19205 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19206 try { 19207 // CE storage is unlocked right now, so read out the inode and 19208 // remember for use later when it's locked 19209 // TODO: mark this structure as dirty so we persist it! 19210 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19211 StorageManager.FLAG_STORAGE_CE); 19212 synchronized (mPackages) { 19213 final PackageSetting ps = mSettings.mPackages.get(packageName); 19214 if (ps != null) { 19215 ps.setCeDataInode(ceDataInode, userId); 19216 } 19217 } 19218 } catch (InstallerException e) { 19219 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19220 } 19221 } 19222 19223 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19224 } 19225 19226 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19227 if (pkg == null) { 19228 Slog.wtf(TAG, "Package was null!", new Throwable()); 19229 return; 19230 } 19231 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19232 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19233 for (int i = 0; i < childCount; i++) { 19234 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19235 } 19236 } 19237 19238 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19239 final String volumeUuid = pkg.volumeUuid; 19240 final String packageName = pkg.packageName; 19241 final ApplicationInfo app = pkg.applicationInfo; 19242 19243 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19244 // Create a native library symlink only if we have native libraries 19245 // and if the native libraries are 32 bit libraries. We do not provide 19246 // this symlink for 64 bit libraries. 19247 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19248 final String nativeLibPath = app.nativeLibraryDir; 19249 try { 19250 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19251 nativeLibPath, userId); 19252 } catch (InstallerException e) { 19253 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19254 } 19255 } 19256 } 19257 } 19258 19259 /** 19260 * For system apps on non-FBE devices, this method migrates any existing 19261 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19262 * requested by the app. 19263 */ 19264 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19265 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19266 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19267 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19268 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19269 try { 19270 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19271 storageTarget); 19272 } catch (InstallerException e) { 19273 logCriticalInfo(Log.WARN, 19274 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19275 } 19276 return true; 19277 } else { 19278 return false; 19279 } 19280 } 19281 19282 public PackageFreezer freezePackage(String packageName, String killReason) { 19283 return new PackageFreezer(packageName, killReason); 19284 } 19285 19286 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19287 String killReason) { 19288 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19289 return new PackageFreezer(); 19290 } else { 19291 return freezePackage(packageName, killReason); 19292 } 19293 } 19294 19295 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19296 String killReason) { 19297 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19298 return new PackageFreezer(); 19299 } else { 19300 return freezePackage(packageName, killReason); 19301 } 19302 } 19303 19304 /** 19305 * Class that freezes and kills the given package upon creation, and 19306 * unfreezes it upon closing. This is typically used when doing surgery on 19307 * app code/data to prevent the app from running while you're working. 19308 */ 19309 private class PackageFreezer implements AutoCloseable { 19310 private final String mPackageName; 19311 private final PackageFreezer[] mChildren; 19312 19313 private final boolean mWeFroze; 19314 19315 private final AtomicBoolean mClosed = new AtomicBoolean(); 19316 private final CloseGuard mCloseGuard = CloseGuard.get(); 19317 19318 /** 19319 * Create and return a stub freezer that doesn't actually do anything, 19320 * typically used when someone requested 19321 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19322 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19323 */ 19324 public PackageFreezer() { 19325 mPackageName = null; 19326 mChildren = null; 19327 mWeFroze = false; 19328 mCloseGuard.open("close"); 19329 } 19330 19331 public PackageFreezer(String packageName, String killReason) { 19332 synchronized (mPackages) { 19333 mPackageName = packageName; 19334 mWeFroze = mFrozenPackages.add(mPackageName); 19335 19336 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19337 if (ps != null) { 19338 killApplication(ps.name, ps.appId, killReason); 19339 } 19340 19341 final PackageParser.Package p = mPackages.get(packageName); 19342 if (p != null && p.childPackages != null) { 19343 final int N = p.childPackages.size(); 19344 mChildren = new PackageFreezer[N]; 19345 for (int i = 0; i < N; i++) { 19346 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19347 killReason); 19348 } 19349 } else { 19350 mChildren = null; 19351 } 19352 } 19353 mCloseGuard.open("close"); 19354 } 19355 19356 @Override 19357 protected void finalize() throws Throwable { 19358 try { 19359 mCloseGuard.warnIfOpen(); 19360 close(); 19361 } finally { 19362 super.finalize(); 19363 } 19364 } 19365 19366 @Override 19367 public void close() { 19368 mCloseGuard.close(); 19369 if (mClosed.compareAndSet(false, true)) { 19370 synchronized (mPackages) { 19371 if (mWeFroze) { 19372 mFrozenPackages.remove(mPackageName); 19373 } 19374 19375 if (mChildren != null) { 19376 for (PackageFreezer freezer : mChildren) { 19377 freezer.close(); 19378 } 19379 } 19380 } 19381 } 19382 } 19383 } 19384 19385 /** 19386 * Verify that given package is currently frozen. 19387 */ 19388 private void checkPackageFrozen(String packageName) { 19389 synchronized (mPackages) { 19390 if (!mFrozenPackages.contains(packageName)) { 19391 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19392 } 19393 } 19394 } 19395 19396 @Override 19397 public int movePackage(final String packageName, final String volumeUuid) { 19398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19399 19400 final int moveId = mNextMoveId.getAndIncrement(); 19401 mHandler.post(new Runnable() { 19402 @Override 19403 public void run() { 19404 try { 19405 movePackageInternal(packageName, volumeUuid, moveId); 19406 } catch (PackageManagerException e) { 19407 Slog.w(TAG, "Failed to move " + packageName, e); 19408 mMoveCallbacks.notifyStatusChanged(moveId, 19409 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19410 } 19411 } 19412 }); 19413 return moveId; 19414 } 19415 19416 private void movePackageInternal(final String packageName, final String volumeUuid, 19417 final int moveId) throws PackageManagerException { 19418 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19419 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19420 final PackageManager pm = mContext.getPackageManager(); 19421 19422 final boolean currentAsec; 19423 final String currentVolumeUuid; 19424 final File codeFile; 19425 final String installerPackageName; 19426 final String packageAbiOverride; 19427 final int appId; 19428 final String seinfo; 19429 final String label; 19430 final int targetSdkVersion; 19431 final PackageFreezer freezer; 19432 19433 // reader 19434 synchronized (mPackages) { 19435 final PackageParser.Package pkg = mPackages.get(packageName); 19436 final PackageSetting ps = mSettings.mPackages.get(packageName); 19437 if (pkg == null || ps == null) { 19438 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19439 } 19440 19441 if (pkg.applicationInfo.isSystemApp()) { 19442 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19443 "Cannot move system application"); 19444 } 19445 19446 if (pkg.applicationInfo.isExternalAsec()) { 19447 currentAsec = true; 19448 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19449 } else if (pkg.applicationInfo.isForwardLocked()) { 19450 currentAsec = true; 19451 currentVolumeUuid = "forward_locked"; 19452 } else { 19453 currentAsec = false; 19454 currentVolumeUuid = ps.volumeUuid; 19455 19456 final File probe = new File(pkg.codePath); 19457 final File probeOat = new File(probe, "oat"); 19458 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19459 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19460 "Move only supported for modern cluster style installs"); 19461 } 19462 } 19463 19464 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19465 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19466 "Package already moved to " + volumeUuid); 19467 } 19468 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19469 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19470 "Device admin cannot be moved"); 19471 } 19472 19473 if (mFrozenPackages.contains(packageName)) { 19474 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19475 "Failed to move already frozen package"); 19476 } 19477 19478 codeFile = new File(pkg.codePath); 19479 installerPackageName = ps.installerPackageName; 19480 packageAbiOverride = ps.cpuAbiOverrideString; 19481 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19482 seinfo = pkg.applicationInfo.seinfo; 19483 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19484 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19485 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19486 } 19487 19488 final Bundle extras = new Bundle(); 19489 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19490 extras.putString(Intent.EXTRA_TITLE, label); 19491 mMoveCallbacks.notifyCreated(moveId, extras); 19492 19493 int installFlags; 19494 final boolean moveCompleteApp; 19495 final File measurePath; 19496 19497 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19498 installFlags = INSTALL_INTERNAL; 19499 moveCompleteApp = !currentAsec; 19500 measurePath = Environment.getDataAppDirectory(volumeUuid); 19501 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19502 installFlags = INSTALL_EXTERNAL; 19503 moveCompleteApp = false; 19504 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19505 } else { 19506 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19507 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19508 || !volume.isMountedWritable()) { 19509 freezer.close(); 19510 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19511 "Move location not mounted private volume"); 19512 } 19513 19514 Preconditions.checkState(!currentAsec); 19515 19516 installFlags = INSTALL_INTERNAL; 19517 moveCompleteApp = true; 19518 measurePath = Environment.getDataAppDirectory(volumeUuid); 19519 } 19520 19521 final PackageStats stats = new PackageStats(null, -1); 19522 synchronized (mInstaller) { 19523 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19524 freezer.close(); 19525 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19526 "Failed to measure package size"); 19527 } 19528 } 19529 19530 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19531 + stats.dataSize); 19532 19533 final long startFreeBytes = measurePath.getFreeSpace(); 19534 final long sizeBytes; 19535 if (moveCompleteApp) { 19536 sizeBytes = stats.codeSize + stats.dataSize; 19537 } else { 19538 sizeBytes = stats.codeSize; 19539 } 19540 19541 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19542 freezer.close(); 19543 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19544 "Not enough free space to move"); 19545 } 19546 19547 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19548 19549 final CountDownLatch installedLatch = new CountDownLatch(1); 19550 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19551 @Override 19552 public void onUserActionRequired(Intent intent) throws RemoteException { 19553 throw new IllegalStateException(); 19554 } 19555 19556 @Override 19557 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19558 Bundle extras) throws RemoteException { 19559 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19560 + PackageManager.installStatusToString(returnCode, msg)); 19561 19562 installedLatch.countDown(); 19563 freezer.close(); 19564 19565 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19566 switch (status) { 19567 case PackageInstaller.STATUS_SUCCESS: 19568 mMoveCallbacks.notifyStatusChanged(moveId, 19569 PackageManager.MOVE_SUCCEEDED); 19570 break; 19571 case PackageInstaller.STATUS_FAILURE_STORAGE: 19572 mMoveCallbacks.notifyStatusChanged(moveId, 19573 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19574 break; 19575 default: 19576 mMoveCallbacks.notifyStatusChanged(moveId, 19577 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19578 break; 19579 } 19580 } 19581 }; 19582 19583 final MoveInfo move; 19584 if (moveCompleteApp) { 19585 // Kick off a thread to report progress estimates 19586 new Thread() { 19587 @Override 19588 public void run() { 19589 while (true) { 19590 try { 19591 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19592 break; 19593 } 19594 } catch (InterruptedException ignored) { 19595 } 19596 19597 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19598 final int progress = 10 + (int) MathUtils.constrain( 19599 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19600 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19601 } 19602 } 19603 }.start(); 19604 19605 final String dataAppName = codeFile.getName(); 19606 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19607 dataAppName, appId, seinfo, targetSdkVersion); 19608 } else { 19609 move = null; 19610 } 19611 19612 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19613 19614 final Message msg = mHandler.obtainMessage(INIT_COPY); 19615 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19616 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19617 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19618 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19619 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19620 msg.obj = params; 19621 19622 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19623 System.identityHashCode(msg.obj)); 19624 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19625 System.identityHashCode(msg.obj)); 19626 19627 mHandler.sendMessage(msg); 19628 } 19629 19630 @Override 19631 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19632 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19633 19634 final int realMoveId = mNextMoveId.getAndIncrement(); 19635 final Bundle extras = new Bundle(); 19636 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19637 mMoveCallbacks.notifyCreated(realMoveId, extras); 19638 19639 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19640 @Override 19641 public void onCreated(int moveId, Bundle extras) { 19642 // Ignored 19643 } 19644 19645 @Override 19646 public void onStatusChanged(int moveId, int status, long estMillis) { 19647 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19648 } 19649 }; 19650 19651 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19652 storage.setPrimaryStorageUuid(volumeUuid, callback); 19653 return realMoveId; 19654 } 19655 19656 @Override 19657 public int getMoveStatus(int moveId) { 19658 mContext.enforceCallingOrSelfPermission( 19659 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19660 return mMoveCallbacks.mLastStatus.get(moveId); 19661 } 19662 19663 @Override 19664 public void registerMoveCallback(IPackageMoveObserver callback) { 19665 mContext.enforceCallingOrSelfPermission( 19666 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19667 mMoveCallbacks.register(callback); 19668 } 19669 19670 @Override 19671 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19672 mContext.enforceCallingOrSelfPermission( 19673 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19674 mMoveCallbacks.unregister(callback); 19675 } 19676 19677 @Override 19678 public boolean setInstallLocation(int loc) { 19679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19680 null); 19681 if (getInstallLocation() == loc) { 19682 return true; 19683 } 19684 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19685 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19686 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19687 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19688 return true; 19689 } 19690 return false; 19691 } 19692 19693 @Override 19694 public int getInstallLocation() { 19695 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19696 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19697 PackageHelper.APP_INSTALL_AUTO); 19698 } 19699 19700 /** Called by UserManagerService */ 19701 void cleanUpUser(UserManagerService userManager, int userHandle) { 19702 synchronized (mPackages) { 19703 mDirtyUsers.remove(userHandle); 19704 mUserNeedsBadging.delete(userHandle); 19705 mSettings.removeUserLPw(userHandle); 19706 mPendingBroadcasts.remove(userHandle); 19707 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19708 removeUnusedPackagesLPw(userManager, userHandle); 19709 } 19710 } 19711 19712 /** 19713 * We're removing userHandle and would like to remove any downloaded packages 19714 * that are no longer in use by any other user. 19715 * @param userHandle the user being removed 19716 */ 19717 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19718 final boolean DEBUG_CLEAN_APKS = false; 19719 int [] users = userManager.getUserIds(); 19720 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19721 while (psit.hasNext()) { 19722 PackageSetting ps = psit.next(); 19723 if (ps.pkg == null) { 19724 continue; 19725 } 19726 final String packageName = ps.pkg.packageName; 19727 // Skip over if system app 19728 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19729 continue; 19730 } 19731 if (DEBUG_CLEAN_APKS) { 19732 Slog.i(TAG, "Checking package " + packageName); 19733 } 19734 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19735 if (keep) { 19736 if (DEBUG_CLEAN_APKS) { 19737 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19738 } 19739 } else { 19740 for (int i = 0; i < users.length; i++) { 19741 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19742 keep = true; 19743 if (DEBUG_CLEAN_APKS) { 19744 Slog.i(TAG, " Keeping package " + packageName + " for user " 19745 + users[i]); 19746 } 19747 break; 19748 } 19749 } 19750 } 19751 if (!keep) { 19752 if (DEBUG_CLEAN_APKS) { 19753 Slog.i(TAG, " Removing package " + packageName); 19754 } 19755 mHandler.post(new Runnable() { 19756 public void run() { 19757 deletePackageX(packageName, userHandle, 0); 19758 } //end run 19759 }); 19760 } 19761 } 19762 } 19763 19764 /** Called by UserManagerService */ 19765 void createNewUser(int userHandle) { 19766 synchronized (mInstallLock) { 19767 mSettings.createNewUserLI(this, mInstaller, userHandle); 19768 } 19769 synchronized (mPackages) { 19770 applyFactoryDefaultBrowserLPw(userHandle); 19771 primeDomainVerificationsLPw(userHandle); 19772 } 19773 } 19774 19775 void newUserCreated(final int userHandle) { 19776 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19777 // If permission review for legacy apps is required, we represent 19778 // dagerous permissions for such apps as always granted runtime 19779 // permissions to keep per user flag state whether review is needed. 19780 // Hence, if a new user is added we have to propagate dangerous 19781 // permission grants for these legacy apps. 19782 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19783 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19784 | UPDATE_PERMISSIONS_REPLACE_ALL); 19785 } 19786 } 19787 19788 @Override 19789 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19790 mContext.enforceCallingOrSelfPermission( 19791 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19792 "Only package verification agents can read the verifier device identity"); 19793 19794 synchronized (mPackages) { 19795 return mSettings.getVerifierDeviceIdentityLPw(); 19796 } 19797 } 19798 19799 @Override 19800 public void setPermissionEnforced(String permission, boolean enforced) { 19801 // TODO: Now that we no longer change GID for storage, this should to away. 19802 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19803 "setPermissionEnforced"); 19804 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19805 synchronized (mPackages) { 19806 if (mSettings.mReadExternalStorageEnforced == null 19807 || mSettings.mReadExternalStorageEnforced != enforced) { 19808 mSettings.mReadExternalStorageEnforced = enforced; 19809 mSettings.writeLPr(); 19810 } 19811 } 19812 // kill any non-foreground processes so we restart them and 19813 // grant/revoke the GID. 19814 final IActivityManager am = ActivityManagerNative.getDefault(); 19815 if (am != null) { 19816 final long token = Binder.clearCallingIdentity(); 19817 try { 19818 am.killProcessesBelowForeground("setPermissionEnforcement"); 19819 } catch (RemoteException e) { 19820 } finally { 19821 Binder.restoreCallingIdentity(token); 19822 } 19823 } 19824 } else { 19825 throw new IllegalArgumentException("No selective enforcement for " + permission); 19826 } 19827 } 19828 19829 @Override 19830 @Deprecated 19831 public boolean isPermissionEnforced(String permission) { 19832 return true; 19833 } 19834 19835 @Override 19836 public boolean isStorageLow() { 19837 final long token = Binder.clearCallingIdentity(); 19838 try { 19839 final DeviceStorageMonitorInternal 19840 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19841 if (dsm != null) { 19842 return dsm.isMemoryLow(); 19843 } else { 19844 return false; 19845 } 19846 } finally { 19847 Binder.restoreCallingIdentity(token); 19848 } 19849 } 19850 19851 @Override 19852 public IPackageInstaller getPackageInstaller() { 19853 return mInstallerService; 19854 } 19855 19856 private boolean userNeedsBadging(int userId) { 19857 int index = mUserNeedsBadging.indexOfKey(userId); 19858 if (index < 0) { 19859 final UserInfo userInfo; 19860 final long token = Binder.clearCallingIdentity(); 19861 try { 19862 userInfo = sUserManager.getUserInfo(userId); 19863 } finally { 19864 Binder.restoreCallingIdentity(token); 19865 } 19866 final boolean b; 19867 if (userInfo != null && userInfo.isManagedProfile()) { 19868 b = true; 19869 } else { 19870 b = false; 19871 } 19872 mUserNeedsBadging.put(userId, b); 19873 return b; 19874 } 19875 return mUserNeedsBadging.valueAt(index); 19876 } 19877 19878 @Override 19879 public KeySet getKeySetByAlias(String packageName, String alias) { 19880 if (packageName == null || alias == null) { 19881 return null; 19882 } 19883 synchronized(mPackages) { 19884 final PackageParser.Package pkg = mPackages.get(packageName); 19885 if (pkg == null) { 19886 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19887 throw new IllegalArgumentException("Unknown package: " + packageName); 19888 } 19889 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19890 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19891 } 19892 } 19893 19894 @Override 19895 public KeySet getSigningKeySet(String packageName) { 19896 if (packageName == null) { 19897 return null; 19898 } 19899 synchronized(mPackages) { 19900 final PackageParser.Package pkg = mPackages.get(packageName); 19901 if (pkg == null) { 19902 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19903 throw new IllegalArgumentException("Unknown package: " + packageName); 19904 } 19905 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19906 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19907 throw new SecurityException("May not access signing KeySet of other apps."); 19908 } 19909 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19910 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19911 } 19912 } 19913 19914 @Override 19915 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19916 if (packageName == null || ks == null) { 19917 return false; 19918 } 19919 synchronized(mPackages) { 19920 final PackageParser.Package pkg = mPackages.get(packageName); 19921 if (pkg == null) { 19922 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19923 throw new IllegalArgumentException("Unknown package: " + packageName); 19924 } 19925 IBinder ksh = ks.getToken(); 19926 if (ksh instanceof KeySetHandle) { 19927 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19928 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19929 } 19930 return false; 19931 } 19932 } 19933 19934 @Override 19935 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19936 if (packageName == null || ks == null) { 19937 return false; 19938 } 19939 synchronized(mPackages) { 19940 final PackageParser.Package pkg = mPackages.get(packageName); 19941 if (pkg == null) { 19942 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19943 throw new IllegalArgumentException("Unknown package: " + packageName); 19944 } 19945 IBinder ksh = ks.getToken(); 19946 if (ksh instanceof KeySetHandle) { 19947 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19948 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19949 } 19950 return false; 19951 } 19952 } 19953 19954 private void deletePackageIfUnusedLPr(final String packageName) { 19955 PackageSetting ps = mSettings.mPackages.get(packageName); 19956 if (ps == null) { 19957 return; 19958 } 19959 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19960 // TODO Implement atomic delete if package is unused 19961 // It is currently possible that the package will be deleted even if it is installed 19962 // after this method returns. 19963 mHandler.post(new Runnable() { 19964 public void run() { 19965 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19966 } 19967 }); 19968 } 19969 } 19970 19971 /** 19972 * Check and throw if the given before/after packages would be considered a 19973 * downgrade. 19974 */ 19975 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19976 throws PackageManagerException { 19977 if (after.versionCode < before.mVersionCode) { 19978 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19979 "Update version code " + after.versionCode + " is older than current " 19980 + before.mVersionCode); 19981 } else if (after.versionCode == before.mVersionCode) { 19982 if (after.baseRevisionCode < before.baseRevisionCode) { 19983 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19984 "Update base revision code " + after.baseRevisionCode 19985 + " is older than current " + before.baseRevisionCode); 19986 } 19987 19988 if (!ArrayUtils.isEmpty(after.splitNames)) { 19989 for (int i = 0; i < after.splitNames.length; i++) { 19990 final String splitName = after.splitNames[i]; 19991 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19992 if (j != -1) { 19993 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19994 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19995 "Update split " + splitName + " revision code " 19996 + after.splitRevisionCodes[i] + " is older than current " 19997 + before.splitRevisionCodes[j]); 19998 } 19999 } 20000 } 20001 } 20002 } 20003 } 20004 20005 private static class MoveCallbacks extends Handler { 20006 private static final int MSG_CREATED = 1; 20007 private static final int MSG_STATUS_CHANGED = 2; 20008 20009 private final RemoteCallbackList<IPackageMoveObserver> 20010 mCallbacks = new RemoteCallbackList<>(); 20011 20012 private final SparseIntArray mLastStatus = new SparseIntArray(); 20013 20014 public MoveCallbacks(Looper looper) { 20015 super(looper); 20016 } 20017 20018 public void register(IPackageMoveObserver callback) { 20019 mCallbacks.register(callback); 20020 } 20021 20022 public void unregister(IPackageMoveObserver callback) { 20023 mCallbacks.unregister(callback); 20024 } 20025 20026 @Override 20027 public void handleMessage(Message msg) { 20028 final SomeArgs args = (SomeArgs) msg.obj; 20029 final int n = mCallbacks.beginBroadcast(); 20030 for (int i = 0; i < n; i++) { 20031 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20032 try { 20033 invokeCallback(callback, msg.what, args); 20034 } catch (RemoteException ignored) { 20035 } 20036 } 20037 mCallbacks.finishBroadcast(); 20038 args.recycle(); 20039 } 20040 20041 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20042 throws RemoteException { 20043 switch (what) { 20044 case MSG_CREATED: { 20045 callback.onCreated(args.argi1, (Bundle) args.arg2); 20046 break; 20047 } 20048 case MSG_STATUS_CHANGED: { 20049 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20050 break; 20051 } 20052 } 20053 } 20054 20055 private void notifyCreated(int moveId, Bundle extras) { 20056 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20057 20058 final SomeArgs args = SomeArgs.obtain(); 20059 args.argi1 = moveId; 20060 args.arg2 = extras; 20061 obtainMessage(MSG_CREATED, args).sendToTarget(); 20062 } 20063 20064 private void notifyStatusChanged(int moveId, int status) { 20065 notifyStatusChanged(moveId, status, -1); 20066 } 20067 20068 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20069 Slog.v(TAG, "Move " + moveId + " status " + status); 20070 20071 final SomeArgs args = SomeArgs.obtain(); 20072 args.argi1 = moveId; 20073 args.argi2 = status; 20074 args.arg3 = estMillis; 20075 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20076 20077 synchronized (mLastStatus) { 20078 mLastStatus.put(moveId, status); 20079 } 20080 } 20081 } 20082 20083 private final static class OnPermissionChangeListeners extends Handler { 20084 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20085 20086 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20087 new RemoteCallbackList<>(); 20088 20089 public OnPermissionChangeListeners(Looper looper) { 20090 super(looper); 20091 } 20092 20093 @Override 20094 public void handleMessage(Message msg) { 20095 switch (msg.what) { 20096 case MSG_ON_PERMISSIONS_CHANGED: { 20097 final int uid = msg.arg1; 20098 handleOnPermissionsChanged(uid); 20099 } break; 20100 } 20101 } 20102 20103 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20104 mPermissionListeners.register(listener); 20105 20106 } 20107 20108 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20109 mPermissionListeners.unregister(listener); 20110 } 20111 20112 public void onPermissionsChanged(int uid) { 20113 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20114 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20115 } 20116 } 20117 20118 private void handleOnPermissionsChanged(int uid) { 20119 final int count = mPermissionListeners.beginBroadcast(); 20120 try { 20121 for (int i = 0; i < count; i++) { 20122 IOnPermissionsChangeListener callback = mPermissionListeners 20123 .getBroadcastItem(i); 20124 try { 20125 callback.onPermissionsChanged(uid); 20126 } catch (RemoteException e) { 20127 Log.e(TAG, "Permission listener is dead", e); 20128 } 20129 } 20130 } finally { 20131 mPermissionListeners.finishBroadcast(); 20132 } 20133 } 20134 } 20135 20136 private class PackageManagerInternalImpl extends PackageManagerInternal { 20137 @Override 20138 public void setLocationPackagesProvider(PackagesProvider provider) { 20139 synchronized (mPackages) { 20140 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20141 } 20142 } 20143 20144 @Override 20145 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20146 synchronized (mPackages) { 20147 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20148 } 20149 } 20150 20151 @Override 20152 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20153 synchronized (mPackages) { 20154 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20155 } 20156 } 20157 20158 @Override 20159 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20160 synchronized (mPackages) { 20161 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20162 } 20163 } 20164 20165 @Override 20166 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20167 synchronized (mPackages) { 20168 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20169 } 20170 } 20171 20172 @Override 20173 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20174 synchronized (mPackages) { 20175 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20176 } 20177 } 20178 20179 @Override 20180 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20181 synchronized (mPackages) { 20182 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20183 packageName, userId); 20184 } 20185 } 20186 20187 @Override 20188 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20189 synchronized (mPackages) { 20190 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20191 packageName, userId); 20192 } 20193 } 20194 20195 @Override 20196 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20197 synchronized (mPackages) { 20198 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20199 packageName, userId); 20200 } 20201 } 20202 20203 @Override 20204 public void setKeepUninstalledPackages(final List<String> packageList) { 20205 Preconditions.checkNotNull(packageList); 20206 List<String> removedFromList = null; 20207 synchronized (mPackages) { 20208 if (mKeepUninstalledPackages != null) { 20209 final int packagesCount = mKeepUninstalledPackages.size(); 20210 for (int i = 0; i < packagesCount; i++) { 20211 String oldPackage = mKeepUninstalledPackages.get(i); 20212 if (packageList != null && packageList.contains(oldPackage)) { 20213 continue; 20214 } 20215 if (removedFromList == null) { 20216 removedFromList = new ArrayList<>(); 20217 } 20218 removedFromList.add(oldPackage); 20219 } 20220 } 20221 mKeepUninstalledPackages = new ArrayList<>(packageList); 20222 if (removedFromList != null) { 20223 final int removedCount = removedFromList.size(); 20224 for (int i = 0; i < removedCount; i++) { 20225 deletePackageIfUnusedLPr(removedFromList.get(i)); 20226 } 20227 } 20228 } 20229 } 20230 20231 @Override 20232 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20233 synchronized (mPackages) { 20234 // If we do not support permission review, done. 20235 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20236 return false; 20237 } 20238 20239 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20240 if (packageSetting == null) { 20241 return false; 20242 } 20243 20244 // Permission review applies only to apps not supporting the new permission model. 20245 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20246 return false; 20247 } 20248 20249 // Legacy apps have the permission and get user consent on launch. 20250 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20251 return permissionsState.isPermissionReviewRequired(userId); 20252 } 20253 } 20254 20255 @Override 20256 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20257 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20258 } 20259 20260 @Override 20261 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20262 int userId) { 20263 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20264 } 20265 } 20266 20267 @Override 20268 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20269 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20270 synchronized (mPackages) { 20271 final long identity = Binder.clearCallingIdentity(); 20272 try { 20273 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20274 packageNames, userId); 20275 } finally { 20276 Binder.restoreCallingIdentity(identity); 20277 } 20278 } 20279 } 20280 20281 private static void enforceSystemOrPhoneCaller(String tag) { 20282 int callingUid = Binder.getCallingUid(); 20283 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20284 throw new SecurityException( 20285 "Cannot call " + tag + " from UID " + callingUid); 20286 } 20287 } 20288 20289 boolean isHistoricalPackageUsageAvailable() { 20290 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20291 } 20292 20293 /** 20294 * Return a <b>copy</b> of the collection of packages known to the package manager. 20295 * @return A copy of the values of mPackages. 20296 */ 20297 Collection<PackageParser.Package> getPackages() { 20298 synchronized (mPackages) { 20299 return new ArrayList<>(mPackages.values()); 20300 } 20301 } 20302 20303 /** 20304 * Logs process start information (including base APK hash) to the security log. 20305 * @hide 20306 */ 20307 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20308 String apkFile, int pid) { 20309 if (!SecurityLog.isLoggingEnabled()) { 20310 return; 20311 } 20312 Bundle data = new Bundle(); 20313 data.putLong("startTimestamp", System.currentTimeMillis()); 20314 data.putString("processName", processName); 20315 data.putInt("uid", uid); 20316 data.putString("seinfo", seinfo); 20317 data.putString("apkFile", apkFile); 20318 data.putInt("pid", pid); 20319 Message msg = mProcessLoggingHandler.obtainMessage( 20320 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20321 msg.setData(data); 20322 mProcessLoggingHandler.sendMessage(msg); 20323 } 20324} 20325