PackageManagerService.java revision 599de361cb7832fec18a51a62cbf44af4df27020
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.FileInputStream; 270import java.io.FileNotFoundException; 271import java.io.FileOutputStream; 272import java.io.FileReader; 273import java.io.FilenameFilter; 274import java.io.IOException; 275import java.io.InputStream; 276import java.io.PrintWriter; 277import java.nio.charset.StandardCharsets; 278import java.security.DigestInputStream; 279import java.security.MessageDigest; 280import java.security.NoSuchAlgorithmException; 281import java.security.PublicKey; 282import java.security.cert.Certificate; 283import java.security.cert.CertificateEncodingException; 284import java.security.cert.CertificateException; 285import java.text.SimpleDateFormat; 286import java.util.ArrayList; 287import java.util.Arrays; 288import java.util.Collection; 289import java.util.Collections; 290import java.util.Comparator; 291import java.util.Date; 292import java.util.HashSet; 293import java.util.Iterator; 294import java.util.List; 295import java.util.Map; 296import java.util.Objects; 297import java.util.Set; 298import java.util.concurrent.CountDownLatch; 299import java.util.concurrent.TimeUnit; 300import java.util.concurrent.atomic.AtomicBoolean; 301import java.util.concurrent.atomic.AtomicInteger; 302import java.util.concurrent.atomic.AtomicLong; 303 304/** 305 * Keep track of all those APKs everywhere. 306 * <p> 307 * Internally there are two important locks: 308 * <ul> 309 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 310 * and other related state. It is a fine-grained lock that should only be held 311 * momentarily, as it's one of the most contended locks in the system. 312 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 313 * operations typically involve heavy lifting of application data on disk. Since 314 * {@code installd} is single-threaded, and it's operations can often be slow, 315 * this lock should never be acquired while already holding {@link #mPackages}. 316 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 317 * holding {@link #mInstallLock}. 318 * </ul> 319 * Many internal methods rely on the caller to hold the appropriate locks, and 320 * this contract is expressed through method name suffixes: 321 * <ul> 322 * <li>fooLI(): the caller must hold {@link #mInstallLock} 323 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 324 * being modified must be frozen 325 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 326 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 327 * </ul> 328 * <p> 329 * Because this class is very central to the platform's security; please run all 330 * CTS and unit tests whenever making modifications: 331 * 332 * <pre> 333 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 334 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 335 * </pre> 336 */ 337public class PackageManagerService extends IPackageManager.Stub { 338 static final String TAG = "PackageManager"; 339 static final boolean DEBUG_SETTINGS = false; 340 static final boolean DEBUG_PREFERRED = false; 341 static final boolean DEBUG_UPGRADE = false; 342 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 343 private static final boolean DEBUG_BACKUP = false; 344 private static final boolean DEBUG_INSTALL = false; 345 private static final boolean DEBUG_REMOVE = false; 346 private static final boolean DEBUG_BROADCASTS = false; 347 private static final boolean DEBUG_SHOW_INFO = false; 348 private static final boolean DEBUG_PACKAGE_INFO = false; 349 private static final boolean DEBUG_INTENT_MATCHING = false; 350 private static final boolean DEBUG_PACKAGE_SCANNING = false; 351 private static final boolean DEBUG_VERIFY = false; 352 private static final boolean DEBUG_FILTERS = false; 353 354 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 355 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 356 // user, but by default initialize to this. 357 static final boolean DEBUG_DEXOPT = false; 358 359 private static final boolean DEBUG_ABI_SELECTION = false; 360 private static final boolean DEBUG_EPHEMERAL = false; 361 private static final boolean DEBUG_TRIAGED_MISSING = false; 362 private static final boolean DEBUG_APP_DATA = false; 363 364 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 365 366 private static final boolean DISABLE_EPHEMERAL_APPS = true; 367 368 private static final int RADIO_UID = Process.PHONE_UID; 369 private static final int LOG_UID = Process.LOG_UID; 370 private static final int NFC_UID = Process.NFC_UID; 371 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 372 private static final int SHELL_UID = Process.SHELL_UID; 373 374 // Cap the size of permission trees that 3rd party apps can define 375 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 376 377 // Suffix used during package installation when copying/moving 378 // package apks to install directory. 379 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 380 381 static final int SCAN_NO_DEX = 1<<1; 382 static final int SCAN_FORCE_DEX = 1<<2; 383 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 384 static final int SCAN_NEW_INSTALL = 1<<4; 385 static final int SCAN_NO_PATHS = 1<<5; 386 static final int SCAN_UPDATE_TIME = 1<<6; 387 static final int SCAN_DEFER_DEX = 1<<7; 388 static final int SCAN_BOOTING = 1<<8; 389 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 390 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 391 static final int SCAN_REPLACING = 1<<11; 392 static final int SCAN_REQUIRE_KNOWN = 1<<12; 393 static final int SCAN_MOVE = 1<<13; 394 static final int SCAN_INITIAL = 1<<14; 395 static final int SCAN_CHECK_ONLY = 1<<15; 396 static final int SCAN_DONT_KILL_APP = 1<<17; 397 static final int SCAN_IGNORE_FROZEN = 1<<18; 398 399 static final int REMOVE_CHATTY = 1<<16; 400 401 private static final int[] EMPTY_INT_ARRAY = new int[0]; 402 403 /** 404 * Timeout (in milliseconds) after which the watchdog should declare that 405 * our handler thread is wedged. The usual default for such things is one 406 * minute but we sometimes do very lengthy I/O operations on this thread, 407 * such as installing multi-gigabyte applications, so ours needs to be longer. 408 */ 409 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 410 411 /** 412 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 413 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 414 * settings entry if available, otherwise we use the hardcoded default. If it's been 415 * more than this long since the last fstrim, we force one during the boot sequence. 416 * 417 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 418 * one gets run at the next available charging+idle time. This final mandatory 419 * no-fstrim check kicks in only of the other scheduling criteria is never met. 420 */ 421 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 422 423 /** 424 * Whether verification is enabled by default. 425 */ 426 private static final boolean DEFAULT_VERIFY_ENABLE = true; 427 428 /** 429 * The default maximum time to wait for the verification agent to return in 430 * milliseconds. 431 */ 432 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 433 434 /** 435 * The default response for package verification timeout. 436 * 437 * This can be either PackageManager.VERIFICATION_ALLOW or 438 * PackageManager.VERIFICATION_REJECT. 439 */ 440 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 441 442 static final String PLATFORM_PACKAGE_NAME = "android"; 443 444 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 445 446 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 447 DEFAULT_CONTAINER_PACKAGE, 448 "com.android.defcontainer.DefaultContainerService"); 449 450 private static final String KILL_APP_REASON_GIDS_CHANGED = 451 "permission grant or revoke changed gids"; 452 453 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 454 "permissions revoked"; 455 456 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 457 458 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 459 460 /** Permission grant: not grant the permission. */ 461 private static final int GRANT_DENIED = 1; 462 463 /** Permission grant: grant the permission as an install permission. */ 464 private static final int GRANT_INSTALL = 2; 465 466 /** Permission grant: grant the permission as a runtime one. */ 467 private static final int GRANT_RUNTIME = 3; 468 469 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 470 private static final int GRANT_UPGRADE = 4; 471 472 /** Canonical intent used to identify what counts as a "web browser" app */ 473 private static final Intent sBrowserIntent; 474 static { 475 sBrowserIntent = new Intent(); 476 sBrowserIntent.setAction(Intent.ACTION_VIEW); 477 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 478 sBrowserIntent.setData(Uri.parse("http:")); 479 } 480 481 /** 482 * The set of all protected actions [i.e. those actions for which a high priority 483 * intent filter is disallowed]. 484 */ 485 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 486 static { 487 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 488 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 489 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 490 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 491 } 492 493 // Compilation reasons. 494 public static final int REASON_FIRST_BOOT = 0; 495 public static final int REASON_BOOT = 1; 496 public static final int REASON_INSTALL = 2; 497 public static final int REASON_BACKGROUND_DEXOPT = 3; 498 public static final int REASON_AB_OTA = 4; 499 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 500 public static final int REASON_SHARED_APK = 6; 501 public static final int REASON_FORCED_DEXOPT = 7; 502 503 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 504 505 /** Special library name that skips shared libraries check during compilation. */ 506 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 507 508 final ServiceThread mHandlerThread; 509 510 final PackageHandler mHandler; 511 512 private final ProcessLoggingHandler mProcessLoggingHandler; 513 514 /** 515 * Messages for {@link #mHandler} that need to wait for system ready before 516 * being dispatched. 517 */ 518 private ArrayList<Message> mPostSystemReadyMessages; 519 520 final int mSdkVersion = Build.VERSION.SDK_INT; 521 522 final Context mContext; 523 final boolean mFactoryTest; 524 final boolean mOnlyCore; 525 final DisplayMetrics mMetrics; 526 final int mDefParseFlags; 527 final String[] mSeparateProcesses; 528 final boolean mIsUpgrade; 529 final boolean mIsPreNUpgrade; 530 531 /** The location for ASEC container files on internal storage. */ 532 final String mAsecInternalPath; 533 534 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 535 // LOCK HELD. Can be called with mInstallLock held. 536 @GuardedBy("mInstallLock") 537 final Installer mInstaller; 538 539 /** Directory where installed third-party apps stored */ 540 final File mAppInstallDir; 541 final File mEphemeralInstallDir; 542 543 /** 544 * Directory to which applications installed internally have their 545 * 32 bit native libraries copied. 546 */ 547 private File mAppLib32InstallDir; 548 549 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 550 // apps. 551 final File mDrmAppPrivateInstallDir; 552 553 // ---------------------------------------------------------------- 554 555 // Lock for state used when installing and doing other long running 556 // operations. Methods that must be called with this lock held have 557 // the suffix "LI". 558 final Object mInstallLock = new Object(); 559 560 // ---------------------------------------------------------------- 561 562 // Keys are String (package name), values are Package. This also serves 563 // as the lock for the global state. Methods that must be called with 564 // this lock held have the prefix "LP". 565 @GuardedBy("mPackages") 566 final ArrayMap<String, PackageParser.Package> mPackages = 567 new ArrayMap<String, PackageParser.Package>(); 568 569 final ArrayMap<String, Set<String>> mKnownCodebase = 570 new ArrayMap<String, Set<String>>(); 571 572 // Tracks available target package names -> overlay package paths. 573 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 574 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 575 576 /** 577 * Tracks new system packages [received in an OTA] that we expect to 578 * find updated user-installed versions. Keys are package name, values 579 * are package location. 580 */ 581 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 582 /** 583 * Tracks high priority intent filters for protected actions. During boot, certain 584 * filter actions are protected and should never be allowed to have a high priority 585 * intent filter for them. However, there is one, and only one exception -- the 586 * setup wizard. It must be able to define a high priority intent filter for these 587 * actions to ensure there are no escapes from the wizard. We need to delay processing 588 * of these during boot as we need to look at all of the system packages in order 589 * to know which component is the setup wizard. 590 */ 591 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 592 /** 593 * Whether or not processing protected filters should be deferred. 594 */ 595 private boolean mDeferProtectedFilters = true; 596 597 /** 598 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 599 */ 600 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 601 /** 602 * Whether or not system app permissions should be promoted from install to runtime. 603 */ 604 boolean mPromoteSystemApps; 605 606 @GuardedBy("mPackages") 607 final Settings mSettings; 608 609 /** 610 * Set of package names that are currently "frozen", which means active 611 * surgery is being done on the code/data for that package. The platform 612 * will refuse to launch frozen packages to avoid race conditions. 613 * 614 * @see PackageFreezer 615 */ 616 @GuardedBy("mPackages") 617 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 618 619 boolean mRestoredSettings; 620 621 // System configuration read by SystemConfig. 622 final int[] mGlobalGids; 623 final SparseArray<ArraySet<String>> mSystemPermissions; 624 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 625 626 // If mac_permissions.xml was found for seinfo labeling. 627 boolean mFoundPolicyFile; 628 629 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 630 631 public static final class SharedLibraryEntry { 632 public final String path; 633 public final String apk; 634 635 SharedLibraryEntry(String _path, String _apk) { 636 path = _path; 637 apk = _apk; 638 } 639 } 640 641 // Currently known shared libraries. 642 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 643 new ArrayMap<String, SharedLibraryEntry>(); 644 645 // All available activities, for your resolving pleasure. 646 final ActivityIntentResolver mActivities = 647 new ActivityIntentResolver(); 648 649 // All available receivers, for your resolving pleasure. 650 final ActivityIntentResolver mReceivers = 651 new ActivityIntentResolver(); 652 653 // All available services, for your resolving pleasure. 654 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 655 656 // All available providers, for your resolving pleasure. 657 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 658 659 // Mapping from provider base names (first directory in content URI codePath) 660 // to the provider information. 661 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 662 new ArrayMap<String, PackageParser.Provider>(); 663 664 // Mapping from instrumentation class names to info about them. 665 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 666 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 667 668 // Mapping from permission names to info about them. 669 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 670 new ArrayMap<String, PackageParser.PermissionGroup>(); 671 672 // Packages whose data we have transfered into another package, thus 673 // should no longer exist. 674 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 675 676 // Broadcast actions that are only available to the system. 677 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 678 679 /** List of packages waiting for verification. */ 680 final SparseArray<PackageVerificationState> mPendingVerification 681 = new SparseArray<PackageVerificationState>(); 682 683 /** Set of packages associated with each app op permission. */ 684 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 685 686 final PackageInstallerService mInstallerService; 687 688 private final PackageDexOptimizer mPackageDexOptimizer; 689 690 private AtomicInteger mNextMoveId = new AtomicInteger(); 691 private final MoveCallbacks mMoveCallbacks; 692 693 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 694 695 // Cache of users who need badging. 696 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 697 698 /** Token for keys in mPendingVerification. */ 699 private int mPendingVerificationToken = 0; 700 701 volatile boolean mSystemReady; 702 volatile boolean mSafeMode; 703 volatile boolean mHasSystemUidErrors; 704 705 ApplicationInfo mAndroidApplication; 706 final ActivityInfo mResolveActivity = new ActivityInfo(); 707 final ResolveInfo mResolveInfo = new ResolveInfo(); 708 ComponentName mResolveComponentName; 709 PackageParser.Package mPlatformPackage; 710 ComponentName mCustomResolverComponentName; 711 712 boolean mResolverReplaced = false; 713 714 private final @Nullable ComponentName mIntentFilterVerifierComponent; 715 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 716 717 private int mIntentFilterVerificationToken = 0; 718 719 /** Component that knows whether or not an ephemeral application exists */ 720 final ComponentName mEphemeralResolverComponent; 721 /** The service connection to the ephemeral resolver */ 722 final EphemeralResolverConnection mEphemeralResolverConnection; 723 724 /** Component used to install ephemeral applications */ 725 final ComponentName mEphemeralInstallerComponent; 726 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 727 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 728 729 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 730 = new SparseArray<IntentFilterVerificationState>(); 731 732 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 733 new DefaultPermissionGrantPolicy(this); 734 735 // List of packages names to keep cached, even if they are uninstalled for all users 736 private List<String> mKeepUninstalledPackages; 737 738 private static class IFVerificationParams { 739 PackageParser.Package pkg; 740 boolean replacing; 741 int userId; 742 int verifierUid; 743 744 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 745 int _userId, int _verifierUid) { 746 pkg = _pkg; 747 replacing = _replacing; 748 userId = _userId; 749 replacing = _replacing; 750 verifierUid = _verifierUid; 751 } 752 } 753 754 private interface IntentFilterVerifier<T extends IntentFilter> { 755 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 756 T filter, String packageName); 757 void startVerifications(int userId); 758 void receiveVerificationResponse(int verificationId); 759 } 760 761 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 762 private Context mContext; 763 private ComponentName mIntentFilterVerifierComponent; 764 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 765 766 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 767 mContext = context; 768 mIntentFilterVerifierComponent = verifierComponent; 769 } 770 771 private String getDefaultScheme() { 772 return IntentFilter.SCHEME_HTTPS; 773 } 774 775 @Override 776 public void startVerifications(int userId) { 777 // Launch verifications requests 778 int count = mCurrentIntentFilterVerifications.size(); 779 for (int n=0; n<count; n++) { 780 int verificationId = mCurrentIntentFilterVerifications.get(n); 781 final IntentFilterVerificationState ivs = 782 mIntentFilterVerificationStates.get(verificationId); 783 784 String packageName = ivs.getPackageName(); 785 786 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 787 final int filterCount = filters.size(); 788 ArraySet<String> domainsSet = new ArraySet<>(); 789 for (int m=0; m<filterCount; m++) { 790 PackageParser.ActivityIntentInfo filter = filters.get(m); 791 domainsSet.addAll(filter.getHostsList()); 792 } 793 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 794 synchronized (mPackages) { 795 if (mSettings.createIntentFilterVerificationIfNeededLPw( 796 packageName, domainsList) != null) { 797 scheduleWriteSettingsLocked(); 798 } 799 } 800 sendVerificationRequest(userId, verificationId, ivs); 801 } 802 mCurrentIntentFilterVerifications.clear(); 803 } 804 805 private void sendVerificationRequest(int userId, int verificationId, 806 IntentFilterVerificationState ivs) { 807 808 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 809 verificationIntent.putExtra( 810 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 811 verificationId); 812 verificationIntent.putExtra( 813 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 814 getDefaultScheme()); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 817 ivs.getHostsString()); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 820 ivs.getPackageName()); 821 verificationIntent.setComponent(mIntentFilterVerifierComponent); 822 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 823 824 UserHandle user = new UserHandle(userId); 825 mContext.sendBroadcastAsUser(verificationIntent, user); 826 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 827 "Sending IntentFilter verification broadcast"); 828 } 829 830 public void receiveVerificationResponse(int verificationId) { 831 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 832 833 final boolean verified = ivs.isVerified(); 834 835 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 836 final int count = filters.size(); 837 if (DEBUG_DOMAIN_VERIFICATION) { 838 Slog.i(TAG, "Received verification response " + verificationId 839 + " for " + count + " filters, verified=" + verified); 840 } 841 for (int n=0; n<count; n++) { 842 PackageParser.ActivityIntentInfo filter = filters.get(n); 843 filter.setVerified(verified); 844 845 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 846 + " verified with result:" + verified + " and hosts:" 847 + ivs.getHostsString()); 848 } 849 850 mIntentFilterVerificationStates.remove(verificationId); 851 852 final String packageName = ivs.getPackageName(); 853 IntentFilterVerificationInfo ivi = null; 854 855 synchronized (mPackages) { 856 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 857 } 858 if (ivi == null) { 859 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 860 + verificationId + " packageName:" + packageName); 861 return; 862 } 863 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 864 "Updating IntentFilterVerificationInfo for package " + packageName 865 +" verificationId:" + verificationId); 866 867 synchronized (mPackages) { 868 if (verified) { 869 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 870 } else { 871 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 872 } 873 scheduleWriteSettingsLocked(); 874 875 final int userId = ivs.getUserId(); 876 if (userId != UserHandle.USER_ALL) { 877 final int userStatus = 878 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 879 880 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 881 boolean needUpdate = false; 882 883 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 884 // already been set by the User thru the Disambiguation dialog 885 switch (userStatus) { 886 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 887 if (verified) { 888 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 889 } else { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 891 } 892 needUpdate = true; 893 break; 894 895 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 896 if (verified) { 897 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 898 needUpdate = true; 899 } 900 break; 901 902 default: 903 // Nothing to do 904 } 905 906 if (needUpdate) { 907 mSettings.updateIntentFilterVerificationStatusLPw( 908 packageName, updatedStatus, userId); 909 scheduleWritePackageRestrictionsLocked(userId); 910 } 911 } 912 } 913 } 914 915 @Override 916 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 917 ActivityIntentInfo filter, String packageName) { 918 if (!hasValidDomains(filter)) { 919 return false; 920 } 921 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 922 if (ivs == null) { 923 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 924 packageName); 925 } 926 if (DEBUG_DOMAIN_VERIFICATION) { 927 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 928 } 929 ivs.addFilter(filter); 930 return true; 931 } 932 933 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 934 int userId, int verificationId, String packageName) { 935 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 936 verifierUid, userId, packageName); 937 ivs.setPendingState(); 938 synchronized (mPackages) { 939 mIntentFilterVerificationStates.append(verificationId, ivs); 940 mCurrentIntentFilterVerifications.add(verificationId); 941 } 942 return ivs; 943 } 944 } 945 946 private static boolean hasValidDomains(ActivityIntentInfo filter) { 947 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 948 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 949 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 950 } 951 952 // Set of pending broadcasts for aggregating enable/disable of components. 953 static class PendingPackageBroadcasts { 954 // for each user id, a map of <package name -> components within that package> 955 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 956 957 public PendingPackageBroadcasts() { 958 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 959 } 960 961 public ArrayList<String> get(int userId, String packageName) { 962 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 963 return packages.get(packageName); 964 } 965 966 public void put(int userId, String packageName, ArrayList<String> components) { 967 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 968 packages.put(packageName, components); 969 } 970 971 public void remove(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 973 if (packages != null) { 974 packages.remove(packageName); 975 } 976 } 977 978 public void remove(int userId) { 979 mUidMap.remove(userId); 980 } 981 982 public int userIdCount() { 983 return mUidMap.size(); 984 } 985 986 public int userIdAt(int n) { 987 return mUidMap.keyAt(n); 988 } 989 990 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 991 return mUidMap.get(userId); 992 } 993 994 public int size() { 995 // total number of pending broadcast entries across all userIds 996 int num = 0; 997 for (int i = 0; i< mUidMap.size(); i++) { 998 num += mUidMap.valueAt(i).size(); 999 } 1000 return num; 1001 } 1002 1003 public void clear() { 1004 mUidMap.clear(); 1005 } 1006 1007 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1008 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1009 if (map == null) { 1010 map = new ArrayMap<String, ArrayList<String>>(); 1011 mUidMap.put(userId, map); 1012 } 1013 return map; 1014 } 1015 } 1016 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1017 1018 // Service Connection to remote media container service to copy 1019 // package uri's from external media onto secure containers 1020 // or internal storage. 1021 private IMediaContainerService mContainerService = null; 1022 1023 static final int SEND_PENDING_BROADCAST = 1; 1024 static final int MCS_BOUND = 3; 1025 static final int END_COPY = 4; 1026 static final int INIT_COPY = 5; 1027 static final int MCS_UNBIND = 6; 1028 static final int START_CLEANING_PACKAGE = 7; 1029 static final int FIND_INSTALL_LOC = 8; 1030 static final int POST_INSTALL = 9; 1031 static final int MCS_RECONNECT = 10; 1032 static final int MCS_GIVE_UP = 11; 1033 static final int UPDATED_MEDIA_STATUS = 12; 1034 static final int WRITE_SETTINGS = 13; 1035 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1036 static final int PACKAGE_VERIFIED = 15; 1037 static final int CHECK_PENDING_VERIFICATION = 16; 1038 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1039 static final int INTENT_FILTER_VERIFIED = 18; 1040 1041 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1042 1043 // Delay time in millisecs 1044 static final int BROADCAST_DELAY = 10 * 1000; 1045 1046 static UserManagerService sUserManager; 1047 1048 // Stores a list of users whose package restrictions file needs to be updated 1049 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1050 1051 final private DefaultContainerConnection mDefContainerConn = 1052 new DefaultContainerConnection(); 1053 class DefaultContainerConnection implements ServiceConnection { 1054 public void onServiceConnected(ComponentName name, IBinder service) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1056 IMediaContainerService imcs = 1057 IMediaContainerService.Stub.asInterface(service); 1058 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1059 } 1060 1061 public void onServiceDisconnected(ComponentName name) { 1062 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1063 } 1064 } 1065 1066 // Recordkeeping of restore-after-install operations that are currently in flight 1067 // between the Package Manager and the Backup Manager 1068 static class PostInstallData { 1069 public InstallArgs args; 1070 public PackageInstalledInfo res; 1071 1072 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1073 args = _a; 1074 res = _r; 1075 } 1076 } 1077 1078 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1079 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1080 1081 // XML tags for backup/restore of various bits of state 1082 private static final String TAG_PREFERRED_BACKUP = "pa"; 1083 private static final String TAG_DEFAULT_APPS = "da"; 1084 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1085 1086 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1087 private static final String TAG_ALL_GRANTS = "rt-grants"; 1088 private static final String TAG_GRANT = "grant"; 1089 private static final String ATTR_PACKAGE_NAME = "pkg"; 1090 1091 private static final String TAG_PERMISSION = "perm"; 1092 private static final String ATTR_PERMISSION_NAME = "name"; 1093 private static final String ATTR_IS_GRANTED = "g"; 1094 private static final String ATTR_USER_SET = "set"; 1095 private static final String ATTR_USER_FIXED = "fixed"; 1096 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1097 1098 // System/policy permission grants are not backed up 1099 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1100 FLAG_PERMISSION_POLICY_FIXED 1101 | FLAG_PERMISSION_SYSTEM_FIXED 1102 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1103 1104 // And we back up these user-adjusted states 1105 private static final int USER_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_USER_SET 1107 | FLAG_PERMISSION_USER_FIXED 1108 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1109 1110 final @Nullable String mRequiredVerifierPackage; 1111 final @NonNull String mRequiredInstallerPackage; 1112 final @Nullable String mSetupWizardPackage; 1113 final @NonNull String mServicesSystemSharedLibraryPackageName; 1114 final @NonNull String mSharedSystemSharedLibraryPackageName; 1115 1116 private final PackageUsage mPackageUsage = new PackageUsage(); 1117 1118 private class PackageUsage { 1119 private static final int WRITE_INTERVAL 1120 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1121 1122 private final Object mFileLock = new Object(); 1123 private final AtomicLong mLastWritten = new AtomicLong(0); 1124 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1125 1126 private boolean mIsHistoricalPackageUsageAvailable = true; 1127 1128 boolean isHistoricalPackageUsageAvailable() { 1129 return mIsHistoricalPackageUsageAvailable; 1130 } 1131 1132 void write(boolean force) { 1133 if (force) { 1134 writeInternal(); 1135 return; 1136 } 1137 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1138 && !DEBUG_DEXOPT) { 1139 return; 1140 } 1141 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1142 new Thread("PackageUsage_DiskWriter") { 1143 @Override 1144 public void run() { 1145 try { 1146 writeInternal(); 1147 } finally { 1148 mBackgroundWriteRunning.set(false); 1149 } 1150 } 1151 }.start(); 1152 } 1153 } 1154 1155 private void writeInternal() { 1156 synchronized (mPackages) { 1157 synchronized (mFileLock) { 1158 AtomicFile file = getFile(); 1159 FileOutputStream f = null; 1160 try { 1161 f = file.startWrite(); 1162 BufferedOutputStream out = new BufferedOutputStream(f); 1163 FileUtils.setPermissions(file.getBaseFile().getPath(), 1164 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1165 StringBuilder sb = new StringBuilder(); 1166 1167 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1168 sb.append('\n'); 1169 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1170 1171 for (PackageParser.Package pkg : mPackages.values()) { 1172 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1173 continue; 1174 } 1175 sb.setLength(0); 1176 sb.append(pkg.packageName); 1177 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1178 sb.append(' '); 1179 sb.append(usageTimeInMillis); 1180 } 1181 sb.append('\n'); 1182 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1183 } 1184 out.flush(); 1185 file.finishWrite(f); 1186 } catch (IOException e) { 1187 if (f != null) { 1188 file.failWrite(f); 1189 } 1190 Log.e(TAG, "Failed to write package usage times", e); 1191 } 1192 } 1193 } 1194 mLastWritten.set(SystemClock.elapsedRealtime()); 1195 } 1196 1197 void readLP() { 1198 synchronized (mFileLock) { 1199 AtomicFile file = getFile(); 1200 BufferedInputStream in = null; 1201 try { 1202 in = new BufferedInputStream(file.openRead()); 1203 StringBuffer sb = new StringBuffer(); 1204 1205 String firstLine = readLine(in, sb); 1206 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1207 readVersion1LP(in, sb); 1208 } else { 1209 readVersion0LP(in, sb, firstLine); 1210 } 1211 } catch (FileNotFoundException expected) { 1212 mIsHistoricalPackageUsageAvailable = false; 1213 } catch (IOException e) { 1214 Log.w(TAG, "Failed to read package usage times", e); 1215 } finally { 1216 IoUtils.closeQuietly(in); 1217 } 1218 } 1219 mLastWritten.set(SystemClock.elapsedRealtime()); 1220 } 1221 1222 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1223 throws IOException { 1224 // Initial version of the file had no version number and stored one 1225 // package-timestamp pair per line. 1226 // Note that the first line has already been read from the InputStream. 1227 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1228 String[] tokens = line.split(" "); 1229 if (tokens.length != 2) { 1230 throw new IOException("Failed to parse " + line + 1231 " as package-timestamp pair."); 1232 } 1233 1234 String packageName = tokens[0]; 1235 PackageParser.Package pkg = mPackages.get(packageName); 1236 if (pkg == null) { 1237 continue; 1238 } 1239 1240 long timestamp = parseAsLong(tokens[1]); 1241 for (int reason = 0; 1242 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1243 reason++) { 1244 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1245 } 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 final boolean didRestore = (msg.arg2 != 0); 1578 mRunningInstalls.delete(msg.arg1); 1579 1580 if (data != null) { 1581 InstallArgs args = data.args; 1582 PackageInstalledInfo parentRes = data.res; 1583 1584 final boolean grantPermissions = (args.installFlags 1585 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1586 final boolean killApp = (args.installFlags 1587 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1588 final String[] grantedPermissions = args.installGrantPermissions; 1589 1590 // Handle the parent package 1591 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1592 grantedPermissions, didRestore, args.installerPackageName, 1593 args.observer); 1594 1595 // Handle the child packages 1596 final int childCount = (parentRes.addedChildPackages != null) 1597 ? parentRes.addedChildPackages.size() : 0; 1598 for (int i = 0; i < childCount; i++) { 1599 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1600 handlePackagePostInstall(childRes, grantPermissions, killApp, 1601 grantedPermissions, false, args.installerPackageName, 1602 args.observer); 1603 } 1604 1605 // Log tracing if needed 1606 if (args.traceMethod != null) { 1607 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1608 args.traceCookie); 1609 } 1610 } else { 1611 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1612 } 1613 1614 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1615 } break; 1616 case UPDATED_MEDIA_STATUS: { 1617 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1618 boolean reportStatus = msg.arg1 == 1; 1619 boolean doGc = msg.arg2 == 1; 1620 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1621 if (doGc) { 1622 // Force a gc to clear up stale containers. 1623 Runtime.getRuntime().gc(); 1624 } 1625 if (msg.obj != null) { 1626 @SuppressWarnings("unchecked") 1627 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1628 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1629 // Unload containers 1630 unloadAllContainers(args); 1631 } 1632 if (reportStatus) { 1633 try { 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1635 PackageHelper.getMountService().finishMediaUpdate(); 1636 } catch (RemoteException e) { 1637 Log.e(TAG, "MountService not running?"); 1638 } 1639 } 1640 } break; 1641 case WRITE_SETTINGS: { 1642 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1643 synchronized (mPackages) { 1644 removeMessages(WRITE_SETTINGS); 1645 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1646 mSettings.writeLPr(); 1647 mDirtyUsers.clear(); 1648 } 1649 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1650 } break; 1651 case WRITE_PACKAGE_RESTRICTIONS: { 1652 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1653 synchronized (mPackages) { 1654 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1655 for (int userId : mDirtyUsers) { 1656 mSettings.writePackageRestrictionsLPr(userId); 1657 } 1658 mDirtyUsers.clear(); 1659 } 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1661 } break; 1662 case CHECK_PENDING_VERIFICATION: { 1663 final int verificationId = msg.arg1; 1664 final PackageVerificationState state = mPendingVerification.get(verificationId); 1665 1666 if ((state != null) && !state.timeoutExtended()) { 1667 final InstallArgs args = state.getInstallArgs(); 1668 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1669 1670 Slog.i(TAG, "Verification timed out for " + originUri); 1671 mPendingVerification.remove(verificationId); 1672 1673 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1674 1675 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1676 Slog.i(TAG, "Continuing with installation of " + originUri); 1677 state.setVerifierResponse(Binder.getCallingUid(), 1678 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1679 broadcastPackageVerified(verificationId, originUri, 1680 PackageManager.VERIFICATION_ALLOW, 1681 state.getInstallArgs().getUser()); 1682 try { 1683 ret = args.copyApk(mContainerService, true); 1684 } catch (RemoteException e) { 1685 Slog.e(TAG, "Could not contact the ContainerService"); 1686 } 1687 } else { 1688 broadcastPackageVerified(verificationId, originUri, 1689 PackageManager.VERIFICATION_REJECT, 1690 state.getInstallArgs().getUser()); 1691 } 1692 1693 Trace.asyncTraceEnd( 1694 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1695 1696 processPendingInstall(args, ret); 1697 mHandler.sendEmptyMessage(MCS_UNBIND); 1698 } 1699 break; 1700 } 1701 case PACKAGE_VERIFIED: { 1702 final int verificationId = msg.arg1; 1703 1704 final PackageVerificationState state = mPendingVerification.get(verificationId); 1705 if (state == null) { 1706 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1707 break; 1708 } 1709 1710 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1711 1712 state.setVerifierResponse(response.callerUid, response.code); 1713 1714 if (state.isVerificationComplete()) { 1715 mPendingVerification.remove(verificationId); 1716 1717 final InstallArgs args = state.getInstallArgs(); 1718 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1719 1720 int ret; 1721 if (state.isInstallAllowed()) { 1722 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1723 broadcastPackageVerified(verificationId, originUri, 1724 response.code, state.getInstallArgs().getUser()); 1725 try { 1726 ret = args.copyApk(mContainerService, true); 1727 } catch (RemoteException e) { 1728 Slog.e(TAG, "Could not contact the ContainerService"); 1729 } 1730 } else { 1731 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1732 } 1733 1734 Trace.asyncTraceEnd( 1735 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1736 1737 processPendingInstall(args, ret); 1738 mHandler.sendEmptyMessage(MCS_UNBIND); 1739 } 1740 1741 break; 1742 } 1743 case START_INTENT_FILTER_VERIFICATIONS: { 1744 IFVerificationParams params = (IFVerificationParams) msg.obj; 1745 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1746 params.replacing, params.pkg); 1747 break; 1748 } 1749 case INTENT_FILTER_VERIFIED: { 1750 final int verificationId = msg.arg1; 1751 1752 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1753 verificationId); 1754 if (state == null) { 1755 Slog.w(TAG, "Invalid IntentFilter verification token " 1756 + verificationId + " received"); 1757 break; 1758 } 1759 1760 final int userId = state.getUserId(); 1761 1762 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1763 "Processing IntentFilter verification with token:" 1764 + verificationId + " and userId:" + userId); 1765 1766 final IntentFilterVerificationResponse response = 1767 (IntentFilterVerificationResponse) msg.obj; 1768 1769 state.setVerifierResponse(response.callerUid, response.code); 1770 1771 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1772 "IntentFilter verification with token:" + verificationId 1773 + " and userId:" + userId 1774 + " is settings verifier response with response code:" 1775 + response.code); 1776 1777 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1778 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1779 + response.getFailedDomainsString()); 1780 } 1781 1782 if (state.isVerificationComplete()) { 1783 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1784 } else { 1785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1786 "IntentFilter verification with token:" + verificationId 1787 + " was not said to be complete"); 1788 } 1789 1790 break; 1791 } 1792 } 1793 } 1794 } 1795 1796 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1797 boolean killApp, String[] grantedPermissions, 1798 boolean launchedForRestore, String installerPackage, 1799 IPackageInstallObserver2 installObserver) { 1800 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1801 // Send the removed broadcasts 1802 if (res.removedInfo != null) { 1803 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1804 } 1805 1806 // Now that we successfully installed the package, grant runtime 1807 // permissions if requested before broadcasting the install. 1808 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1809 >= Build.VERSION_CODES.M) { 1810 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1811 } 1812 1813 final boolean update = res.removedInfo != null 1814 && res.removedInfo.removedPackage != null; 1815 1816 // If this is the first time we have child packages for a disabled privileged 1817 // app that had no children, we grant requested runtime permissions to the new 1818 // children if the parent on the system image had them already granted. 1819 if (res.pkg.parentPackage != null) { 1820 synchronized (mPackages) { 1821 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1822 } 1823 } 1824 1825 synchronized (mPackages) { 1826 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1827 } 1828 1829 final String packageName = res.pkg.applicationInfo.packageName; 1830 Bundle extras = new Bundle(1); 1831 extras.putInt(Intent.EXTRA_UID, res.uid); 1832 1833 // Determine the set of users who are adding this package for 1834 // the first time vs. those who are seeing an update. 1835 int[] firstUsers = EMPTY_INT_ARRAY; 1836 int[] updateUsers = EMPTY_INT_ARRAY; 1837 if (res.origUsers == null || res.origUsers.length == 0) { 1838 firstUsers = res.newUsers; 1839 } else { 1840 for (int newUser : res.newUsers) { 1841 boolean isNew = true; 1842 for (int origUser : res.origUsers) { 1843 if (origUser == newUser) { 1844 isNew = false; 1845 break; 1846 } 1847 } 1848 if (isNew) { 1849 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1850 } else { 1851 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1852 } 1853 } 1854 } 1855 1856 // Send installed broadcasts if the install/update is not ephemeral 1857 if (!isEphemeral(res.pkg)) { 1858 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1859 1860 // Send added for users that see the package for the first time 1861 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1862 extras, 0 /*flags*/, null /*targetPackage*/, 1863 null /*finishedReceiver*/, firstUsers); 1864 1865 // Send added for users that don't see the package for the first time 1866 if (update) { 1867 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1868 } 1869 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1870 extras, 0 /*flags*/, null /*targetPackage*/, 1871 null /*finishedReceiver*/, updateUsers); 1872 1873 // Send replaced for users that don't see the package for the first time 1874 if (update) { 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1876 packageName, extras, 0 /*flags*/, 1877 null /*targetPackage*/, null /*finishedReceiver*/, 1878 updateUsers); 1879 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1880 null /*package*/, null /*extras*/, 0 /*flags*/, 1881 packageName /*targetPackage*/, 1882 null /*finishedReceiver*/, updateUsers); 1883 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1884 // First-install and we did a restore, so we're responsible for the 1885 // first-launch broadcast. 1886 if (DEBUG_BACKUP) { 1887 Slog.i(TAG, "Post-restore of " + packageName 1888 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1889 } 1890 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1891 } 1892 1893 // Send broadcast package appeared if forward locked/external for all users 1894 // treat asec-hosted packages like removable media on upgrade 1895 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1896 if (DEBUG_INSTALL) { 1897 Slog.i(TAG, "upgrading pkg " + res.pkg 1898 + " is ASEC-hosted -> AVAILABLE"); 1899 } 1900 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1901 ArrayList<String> pkgList = new ArrayList<>(1); 1902 pkgList.add(packageName); 1903 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1904 } 1905 } 1906 1907 // Work that needs to happen on first install within each user 1908 if (firstUsers != null && firstUsers.length > 0) { 1909 synchronized (mPackages) { 1910 for (int userId : firstUsers) { 1911 // If this app is a browser and it's newly-installed for some 1912 // users, clear any default-browser state in those users. The 1913 // app's nature doesn't depend on the user, so we can just check 1914 // its browser nature in any user and generalize. 1915 if (packageIsBrowser(packageName, userId)) { 1916 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1917 } 1918 1919 // We may also need to apply pending (restored) runtime 1920 // permission grants within these users. 1921 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1922 } 1923 } 1924 } 1925 1926 // Log current value of "unknown sources" setting 1927 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1928 getUnknownSourcesSettings()); 1929 1930 // Force a gc to clear up things 1931 Runtime.getRuntime().gc(); 1932 1933 // Remove the replaced package's older resources safely now 1934 // We delete after a gc for applications on sdcard. 1935 if (res.removedInfo != null && res.removedInfo.args != null) { 1936 synchronized (mInstallLock) { 1937 res.removedInfo.args.doPostDeleteLI(true); 1938 } 1939 } 1940 } 1941 1942 // If someone is watching installs - notify them 1943 if (installObserver != null) { 1944 try { 1945 Bundle extras = extrasForInstallResult(res); 1946 installObserver.onPackageInstalled(res.name, res.returnCode, 1947 res.returnMsg, extras); 1948 } catch (RemoteException e) { 1949 Slog.i(TAG, "Observer no longer exists."); 1950 } 1951 } 1952 } 1953 1954 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1955 PackageParser.Package pkg) { 1956 if (pkg.parentPackage == null) { 1957 return; 1958 } 1959 if (pkg.requestedPermissions == null) { 1960 return; 1961 } 1962 final PackageSetting disabledSysParentPs = mSettings 1963 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1964 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1965 || !disabledSysParentPs.isPrivileged() 1966 || (disabledSysParentPs.childPackageNames != null 1967 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1968 return; 1969 } 1970 final int[] allUserIds = sUserManager.getUserIds(); 1971 final int permCount = pkg.requestedPermissions.size(); 1972 for (int i = 0; i < permCount; i++) { 1973 String permission = pkg.requestedPermissions.get(i); 1974 BasePermission bp = mSettings.mPermissions.get(permission); 1975 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1976 continue; 1977 } 1978 for (int userId : allUserIds) { 1979 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1980 permission, userId)) { 1981 grantRuntimePermission(pkg.packageName, permission, userId); 1982 } 1983 } 1984 } 1985 } 1986 1987 private StorageEventListener mStorageListener = new StorageEventListener() { 1988 @Override 1989 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1990 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1991 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1992 final String volumeUuid = vol.getFsUuid(); 1993 1994 // Clean up any users or apps that were removed or recreated 1995 // while this volume was missing 1996 reconcileUsers(volumeUuid); 1997 reconcileApps(volumeUuid); 1998 1999 // Clean up any install sessions that expired or were 2000 // cancelled while this volume was missing 2001 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2002 2003 loadPrivatePackages(vol); 2004 2005 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2006 unloadPrivatePackages(vol); 2007 } 2008 } 2009 2010 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2011 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2012 updateExternalMediaStatus(true, false); 2013 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2014 updateExternalMediaStatus(false, false); 2015 } 2016 } 2017 } 2018 2019 @Override 2020 public void onVolumeForgotten(String fsUuid) { 2021 if (TextUtils.isEmpty(fsUuid)) { 2022 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2023 return; 2024 } 2025 2026 // Remove any apps installed on the forgotten volume 2027 synchronized (mPackages) { 2028 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2029 for (PackageSetting ps : packages) { 2030 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2031 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2032 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2033 } 2034 2035 mSettings.onVolumeForgotten(fsUuid); 2036 mSettings.writeLPr(); 2037 } 2038 } 2039 }; 2040 2041 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2042 String[] grantedPermissions) { 2043 for (int userId : userIds) { 2044 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2045 } 2046 2047 // We could have touched GID membership, so flush out packages.list 2048 synchronized (mPackages) { 2049 mSettings.writePackageListLPr(); 2050 } 2051 } 2052 2053 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2054 String[] grantedPermissions) { 2055 SettingBase sb = (SettingBase) pkg.mExtras; 2056 if (sb == null) { 2057 return; 2058 } 2059 2060 PermissionsState permissionsState = sb.getPermissionsState(); 2061 2062 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2063 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2064 2065 for (String permission : pkg.requestedPermissions) { 2066 final BasePermission bp; 2067 synchronized (mPackages) { 2068 bp = mSettings.mPermissions.get(permission); 2069 } 2070 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2071 && (grantedPermissions == null 2072 || ArrayUtils.contains(grantedPermissions, permission))) { 2073 final int flags = permissionsState.getPermissionFlags(permission, userId); 2074 // Installer cannot change immutable permissions. 2075 if ((flags & immutableFlags) == 0) { 2076 grantRuntimePermission(pkg.packageName, permission, userId); 2077 } 2078 } 2079 } 2080 } 2081 2082 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2083 Bundle extras = null; 2084 switch (res.returnCode) { 2085 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2086 extras = new Bundle(); 2087 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2088 res.origPermission); 2089 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2090 res.origPackage); 2091 break; 2092 } 2093 case PackageManager.INSTALL_SUCCEEDED: { 2094 extras = new Bundle(); 2095 extras.putBoolean(Intent.EXTRA_REPLACING, 2096 res.removedInfo != null && res.removedInfo.removedPackage != null); 2097 break; 2098 } 2099 } 2100 return extras; 2101 } 2102 2103 void scheduleWriteSettingsLocked() { 2104 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2105 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2106 } 2107 } 2108 2109 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2110 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2111 scheduleWritePackageRestrictionsLocked(userId); 2112 } 2113 2114 void scheduleWritePackageRestrictionsLocked(int userId) { 2115 final int[] userIds = (userId == UserHandle.USER_ALL) 2116 ? sUserManager.getUserIds() : new int[]{userId}; 2117 for (int nextUserId : userIds) { 2118 if (!sUserManager.exists(nextUserId)) return; 2119 mDirtyUsers.add(nextUserId); 2120 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2121 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2122 } 2123 } 2124 } 2125 2126 public static PackageManagerService main(Context context, Installer installer, 2127 boolean factoryTest, boolean onlyCore) { 2128 // Self-check for initial settings. 2129 PackageManagerServiceCompilerMapping.checkProperties(); 2130 2131 PackageManagerService m = new PackageManagerService(context, installer, 2132 factoryTest, onlyCore); 2133 m.enableSystemUserPackages(); 2134 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2135 // disabled after already being started. 2136 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2137 UserHandle.USER_SYSTEM); 2138 ServiceManager.addService("package", m); 2139 return m; 2140 } 2141 2142 private void enableSystemUserPackages() { 2143 if (!UserManager.isSplitSystemUser()) { 2144 return; 2145 } 2146 // For system user, enable apps based on the following conditions: 2147 // - app is whitelisted or belong to one of these groups: 2148 // -- system app which has no launcher icons 2149 // -- system app which has INTERACT_ACROSS_USERS permission 2150 // -- system IME app 2151 // - app is not in the blacklist 2152 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2153 Set<String> enableApps = new ArraySet<>(); 2154 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2155 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2156 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2157 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2158 enableApps.addAll(wlApps); 2159 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2160 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2161 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2162 enableApps.removeAll(blApps); 2163 Log.i(TAG, "Applications installed for system user: " + enableApps); 2164 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2165 UserHandle.SYSTEM); 2166 final int allAppsSize = allAps.size(); 2167 synchronized (mPackages) { 2168 for (int i = 0; i < allAppsSize; i++) { 2169 String pName = allAps.get(i); 2170 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2171 // Should not happen, but we shouldn't be failing if it does 2172 if (pkgSetting == null) { 2173 continue; 2174 } 2175 boolean install = enableApps.contains(pName); 2176 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2177 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2178 + " for system user"); 2179 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2180 } 2181 } 2182 } 2183 } 2184 2185 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2186 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2187 Context.DISPLAY_SERVICE); 2188 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2189 } 2190 2191 public PackageManagerService(Context context, Installer installer, 2192 boolean factoryTest, boolean onlyCore) { 2193 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2194 SystemClock.uptimeMillis()); 2195 2196 if (mSdkVersion <= 0) { 2197 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2198 } 2199 2200 mContext = context; 2201 mFactoryTest = factoryTest; 2202 mOnlyCore = onlyCore; 2203 mMetrics = new DisplayMetrics(); 2204 mSettings = new Settings(mPackages); 2205 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2206 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2207 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2208 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2209 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 2218 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2219 if (separateProcesses != null && separateProcesses.length() > 0) { 2220 if ("*".equals(separateProcesses)) { 2221 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2222 mSeparateProcesses = null; 2223 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2224 } else { 2225 mDefParseFlags = 0; 2226 mSeparateProcesses = separateProcesses.split(","); 2227 Slog.w(TAG, "Running with debug.separate_processes: " 2228 + separateProcesses); 2229 } 2230 } else { 2231 mDefParseFlags = 0; 2232 mSeparateProcesses = null; 2233 } 2234 2235 mInstaller = installer; 2236 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2237 "*dexopt*"); 2238 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2239 2240 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2241 FgThread.get().getLooper()); 2242 2243 getDefaultDisplayMetrics(context, mMetrics); 2244 2245 SystemConfig systemConfig = SystemConfig.getInstance(); 2246 mGlobalGids = systemConfig.getGlobalGids(); 2247 mSystemPermissions = systemConfig.getSystemPermissions(); 2248 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2249 2250 synchronized (mInstallLock) { 2251 // writer 2252 synchronized (mPackages) { 2253 mHandlerThread = new ServiceThread(TAG, 2254 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2255 mHandlerThread.start(); 2256 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2257 mProcessLoggingHandler = new ProcessLoggingHandler(); 2258 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2259 2260 File dataDir = Environment.getDataDirectory(); 2261 mAppInstallDir = new File(dataDir, "app"); 2262 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2263 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2264 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2265 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2266 2267 sUserManager = new UserManagerService(context, this, mPackages); 2268 2269 // Propagate permission configuration in to package manager. 2270 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2271 = systemConfig.getPermissions(); 2272 for (int i=0; i<permConfig.size(); i++) { 2273 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2274 BasePermission bp = mSettings.mPermissions.get(perm.name); 2275 if (bp == null) { 2276 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2277 mSettings.mPermissions.put(perm.name, bp); 2278 } 2279 if (perm.gids != null) { 2280 bp.setGids(perm.gids, perm.perUser); 2281 } 2282 } 2283 2284 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2285 for (int i=0; i<libConfig.size(); i++) { 2286 mSharedLibraries.put(libConfig.keyAt(i), 2287 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2288 } 2289 2290 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2291 2292 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2293 2294 String customResolverActivity = Resources.getSystem().getString( 2295 R.string.config_customResolverActivity); 2296 if (TextUtils.isEmpty(customResolverActivity)) { 2297 customResolverActivity = null; 2298 } else { 2299 mCustomResolverComponentName = ComponentName.unflattenFromString( 2300 customResolverActivity); 2301 } 2302 2303 long startTime = SystemClock.uptimeMillis(); 2304 2305 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2306 startTime); 2307 2308 // Set flag to monitor and not change apk file paths when 2309 // scanning install directories. 2310 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2311 2312 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2313 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2314 2315 if (bootClassPath == null) { 2316 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2317 } 2318 2319 if (systemServerClassPath == null) { 2320 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2321 } 2322 2323 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2324 final String[] dexCodeInstructionSets = 2325 getDexCodeInstructionSets( 2326 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2327 2328 /** 2329 * Ensure all external libraries have had dexopt run on them. 2330 */ 2331 if (mSharedLibraries.size() > 0) { 2332 // NOTE: For now, we're compiling these system "shared libraries" 2333 // (and framework jars) into all available architectures. It's possible 2334 // to compile them only when we come across an app that uses them (there's 2335 // already logic for that in scanPackageLI) but that adds some complexity. 2336 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2337 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2338 final String lib = libEntry.path; 2339 if (lib == null) { 2340 continue; 2341 } 2342 2343 try { 2344 // Shared libraries do not have profiles so we perform a full 2345 // AOT compilation (if needed). 2346 int dexoptNeeded = DexFile.getDexOptNeeded( 2347 lib, dexCodeInstructionSet, 2348 getCompilerFilterForReason(REASON_SHARED_APK), 2349 false /* newProfile */); 2350 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2351 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2352 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2353 getCompilerFilterForReason(REASON_SHARED_APK), 2354 StorageManager.UUID_PRIVATE_INTERNAL, 2355 SKIP_SHARED_LIBRARY_CHECK); 2356 } 2357 } catch (FileNotFoundException e) { 2358 Slog.w(TAG, "Library not found: " + lib); 2359 } catch (IOException | InstallerException e) { 2360 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2361 + e.getMessage()); 2362 } 2363 } 2364 } 2365 } 2366 2367 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2368 2369 final VersionInfo ver = mSettings.getInternalVersion(); 2370 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2371 2372 // when upgrading from pre-M, promote system app permissions from install to runtime 2373 mPromoteSystemApps = 2374 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2375 2376 // save off the names of pre-existing system packages prior to scanning; we don't 2377 // want to automatically grant runtime permissions for new system apps 2378 if (mPromoteSystemApps) { 2379 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2380 while (pkgSettingIter.hasNext()) { 2381 PackageSetting ps = pkgSettingIter.next(); 2382 if (isSystemApp(ps)) { 2383 mExistingSystemPackages.add(ps.name); 2384 } 2385 } 2386 } 2387 2388 // When upgrading from pre-N, we need to handle package extraction like first boot, 2389 // as there is no profiling data available. 2390 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2391 mSettings.setNWorkDone(); 2392 2393 // Collect vendor overlay packages. 2394 // (Do this before scanning any apps.) 2395 // For security and version matching reason, only consider 2396 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2397 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2398 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2399 | PackageParser.PARSE_IS_SYSTEM 2400 | PackageParser.PARSE_IS_SYSTEM_DIR 2401 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2402 2403 // Find base frameworks (resource packages without code). 2404 scanDirTracedLI(frameworkDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR 2407 | PackageParser.PARSE_IS_PRIVILEGED, 2408 scanFlags | SCAN_NO_DEX, 0); 2409 2410 // Collected privileged system packages. 2411 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2412 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2413 | PackageParser.PARSE_IS_SYSTEM 2414 | PackageParser.PARSE_IS_SYSTEM_DIR 2415 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2416 2417 // Collect ordinary system packages. 2418 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2419 scanDirTracedLI(systemAppDir, mDefParseFlags 2420 | PackageParser.PARSE_IS_SYSTEM 2421 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2422 2423 // Collect all vendor packages. 2424 File vendorAppDir = new File("/vendor/app"); 2425 try { 2426 vendorAppDir = vendorAppDir.getCanonicalFile(); 2427 } catch (IOException e) { 2428 // failed to look up canonical path, continue with original one 2429 } 2430 scanDirTracedLI(vendorAppDir, mDefParseFlags 2431 | PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2433 2434 // Collect all OEM packages. 2435 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2436 scanDirTracedLI(oemAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2439 2440 // Prune any system packages that no longer exist. 2441 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2442 if (!mOnlyCore) { 2443 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2444 while (psit.hasNext()) { 2445 PackageSetting ps = psit.next(); 2446 2447 /* 2448 * If this is not a system app, it can't be a 2449 * disable system app. 2450 */ 2451 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2452 continue; 2453 } 2454 2455 /* 2456 * If the package is scanned, it's not erased. 2457 */ 2458 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2459 if (scannedPkg != null) { 2460 /* 2461 * If the system app is both scanned and in the 2462 * disabled packages list, then it must have been 2463 * added via OTA. Remove it from the currently 2464 * scanned package so the previously user-installed 2465 * application can be scanned. 2466 */ 2467 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2468 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2469 + ps.name + "; removing system app. Last known codePath=" 2470 + ps.codePathString + ", installStatus=" + ps.installStatus 2471 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2472 + scannedPkg.mVersionCode); 2473 removePackageLI(scannedPkg, true); 2474 mExpectingBetter.put(ps.name, ps.codePath); 2475 } 2476 2477 continue; 2478 } 2479 2480 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2481 psit.remove(); 2482 logCriticalInfo(Log.WARN, "System package " + ps.name 2483 + " no longer exists; it's data will be wiped"); 2484 // Actual deletion of code and data will be handled by later 2485 // reconciliation step 2486 } else { 2487 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2488 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2489 possiblyDeletedUpdatedSystemApps.add(ps.name); 2490 } 2491 } 2492 } 2493 } 2494 2495 //look for any incomplete package installations 2496 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2497 for (int i = 0; i < deletePkgsList.size(); i++) { 2498 // Actual deletion of code and data will be handled by later 2499 // reconciliation step 2500 final String packageName = deletePkgsList.get(i).name; 2501 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2502 synchronized (mPackages) { 2503 mSettings.removePackageLPw(packageName); 2504 } 2505 } 2506 2507 //delete tmp files 2508 deleteTempPackageFiles(); 2509 2510 // Remove any shared userIDs that have no associated packages 2511 mSettings.pruneSharedUsersLPw(); 2512 2513 if (!mOnlyCore) { 2514 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2515 SystemClock.uptimeMillis()); 2516 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2517 2518 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2519 | PackageParser.PARSE_FORWARD_LOCK, 2520 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2521 2522 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2523 | PackageParser.PARSE_IS_EPHEMERAL, 2524 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2525 2526 /** 2527 * Remove disable package settings for any updated system 2528 * apps that were removed via an OTA. If they're not a 2529 * previously-updated app, remove them completely. 2530 * Otherwise, just revoke their system-level permissions. 2531 */ 2532 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2533 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2534 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2535 2536 String msg; 2537 if (deletedPkg == null) { 2538 msg = "Updated system package " + deletedAppName 2539 + " no longer exists; it's data will be wiped"; 2540 // Actual deletion of code and data will be handled by later 2541 // reconciliation step 2542 } else { 2543 msg = "Updated system app + " + deletedAppName 2544 + " no longer present; removing system privileges for " 2545 + deletedAppName; 2546 2547 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2548 2549 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2550 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2551 } 2552 logCriticalInfo(Log.WARN, msg); 2553 } 2554 2555 /** 2556 * Make sure all system apps that we expected to appear on 2557 * the userdata partition actually showed up. If they never 2558 * appeared, crawl back and revive the system version. 2559 */ 2560 for (int i = 0; i < mExpectingBetter.size(); i++) { 2561 final String packageName = mExpectingBetter.keyAt(i); 2562 if (!mPackages.containsKey(packageName)) { 2563 final File scanFile = mExpectingBetter.valueAt(i); 2564 2565 logCriticalInfo(Log.WARN, "Expected better " + packageName 2566 + " but never showed up; reverting to system"); 2567 2568 int reparseFlags = mDefParseFlags; 2569 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2570 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2571 | PackageParser.PARSE_IS_SYSTEM_DIR 2572 | PackageParser.PARSE_IS_PRIVILEGED; 2573 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2574 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2575 | PackageParser.PARSE_IS_SYSTEM_DIR; 2576 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2577 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2578 | PackageParser.PARSE_IS_SYSTEM_DIR; 2579 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else { 2583 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2584 continue; 2585 } 2586 2587 mSettings.enableSystemPackageLPw(packageName); 2588 2589 try { 2590 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2591 } catch (PackageManagerException e) { 2592 Slog.e(TAG, "Failed to parse original system package: " 2593 + e.getMessage()); 2594 } 2595 } 2596 } 2597 } 2598 mExpectingBetter.clear(); 2599 2600 // Resolve protected action filters. Only the setup wizard is allowed to 2601 // have a high priority filter for these actions. 2602 mSetupWizardPackage = getSetupWizardPackageName(); 2603 if (mProtectedFilters.size() > 0) { 2604 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2605 Slog.i(TAG, "No setup wizard;" 2606 + " All protected intents capped to priority 0"); 2607 } 2608 for (ActivityIntentInfo filter : mProtectedFilters) { 2609 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2610 if (DEBUG_FILTERS) { 2611 Slog.i(TAG, "Found setup wizard;" 2612 + " allow priority " + filter.getPriority() + ";" 2613 + " package: " + filter.activity.info.packageName 2614 + " activity: " + filter.activity.className 2615 + " priority: " + filter.getPriority()); 2616 } 2617 // skip setup wizard; allow it to keep the high priority filter 2618 continue; 2619 } 2620 Slog.w(TAG, "Protected action; cap priority to 0;" 2621 + " package: " + filter.activity.info.packageName 2622 + " activity: " + filter.activity.className 2623 + " origPrio: " + filter.getPriority()); 2624 filter.setPriority(0); 2625 } 2626 } 2627 mDeferProtectedFilters = false; 2628 mProtectedFilters.clear(); 2629 2630 // Now that we know all of the shared libraries, update all clients to have 2631 // the correct library paths. 2632 updateAllSharedLibrariesLPw(); 2633 2634 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2635 // NOTE: We ignore potential failures here during a system scan (like 2636 // the rest of the commands above) because there's precious little we 2637 // can do about it. A settings error is reported, though. 2638 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2639 false /* boot complete */); 2640 } 2641 2642 // Now that we know all the packages we are keeping, 2643 // read and update their last usage times. 2644 mPackageUsage.readLP(); 2645 2646 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2647 SystemClock.uptimeMillis()); 2648 Slog.i(TAG, "Time to scan packages: " 2649 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2650 + " seconds"); 2651 2652 // If the platform SDK has changed since the last time we booted, 2653 // we need to re-grant app permission to catch any new ones that 2654 // appear. This is really a hack, and means that apps can in some 2655 // cases get permissions that the user didn't initially explicitly 2656 // allow... it would be nice to have some better way to handle 2657 // this situation. 2658 int updateFlags = UPDATE_PERMISSIONS_ALL; 2659 if (ver.sdkVersion != mSdkVersion) { 2660 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2661 + mSdkVersion + "; regranting permissions for internal storage"); 2662 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2663 } 2664 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2665 ver.sdkVersion = mSdkVersion; 2666 2667 // If this is the first boot or an update from pre-M, and it is a normal 2668 // boot, then we need to initialize the default preferred apps across 2669 // all defined users. 2670 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2671 for (UserInfo user : sUserManager.getUsers(true)) { 2672 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2673 applyFactoryDefaultBrowserLPw(user.id); 2674 primeDomainVerificationsLPw(user.id); 2675 } 2676 } 2677 2678 // Prepare storage for system user really early during boot, 2679 // since core system apps like SettingsProvider and SystemUI 2680 // can't wait for user to start 2681 final int storageFlags; 2682 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2683 storageFlags = StorageManager.FLAG_STORAGE_DE; 2684 } else { 2685 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2686 } 2687 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2688 storageFlags); 2689 2690 // If this is first boot after an OTA, and a normal boot, then 2691 // we need to clear code cache directories. 2692 if (mIsUpgrade && !onlyCore) { 2693 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2694 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2695 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2696 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2697 // No apps are running this early, so no need to freeze 2698 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2699 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2700 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2701 } 2702 clearAppProfilesLIF(ps.pkg); 2703 } 2704 ver.fingerprint = Build.FINGERPRINT; 2705 } 2706 2707 checkDefaultBrowser(); 2708 2709 // clear only after permissions and other defaults have been updated 2710 mExistingSystemPackages.clear(); 2711 mPromoteSystemApps = false; 2712 2713 // All the changes are done during package scanning. 2714 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2715 2716 // can downgrade to reader 2717 mSettings.writeLPr(); 2718 2719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2720 SystemClock.uptimeMillis()); 2721 2722 if (!mOnlyCore) { 2723 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2724 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2725 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2726 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2727 mIntentFilterVerifierComponent); 2728 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2729 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2730 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2731 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2732 } else { 2733 mRequiredVerifierPackage = null; 2734 mRequiredInstallerPackage = null; 2735 mIntentFilterVerifierComponent = null; 2736 mIntentFilterVerifier = null; 2737 mServicesSystemSharedLibraryPackageName = null; 2738 mSharedSystemSharedLibraryPackageName = null; 2739 } 2740 2741 mInstallerService = new PackageInstallerService(context, this); 2742 2743 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2744 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2745 // both the installer and resolver must be present to enable ephemeral 2746 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2747 if (DEBUG_EPHEMERAL) { 2748 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2749 + " installer:" + ephemeralInstallerComponent); 2750 } 2751 mEphemeralResolverComponent = ephemeralResolverComponent; 2752 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2753 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2754 mEphemeralResolverConnection = 2755 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2756 } else { 2757 if (DEBUG_EPHEMERAL) { 2758 final String missingComponent = 2759 (ephemeralResolverComponent == null) 2760 ? (ephemeralInstallerComponent == null) 2761 ? "resolver and installer" 2762 : "resolver" 2763 : "installer"; 2764 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2765 } 2766 mEphemeralResolverComponent = null; 2767 mEphemeralInstallerComponent = null; 2768 mEphemeralResolverConnection = null; 2769 } 2770 2771 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2772 } // synchronized (mPackages) 2773 } // synchronized (mInstallLock) 2774 2775 // Now after opening every single application zip, make sure they 2776 // are all flushed. Not really needed, but keeps things nice and 2777 // tidy. 2778 Runtime.getRuntime().gc(); 2779 2780 // The initial scanning above does many calls into installd while 2781 // holding the mPackages lock, but we're mostly interested in yelling 2782 // once we have a booted system. 2783 mInstaller.setWarnIfHeld(mPackages); 2784 2785 // Expose private service for system components to use. 2786 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2787 } 2788 2789 @Override 2790 public boolean isFirstBoot() { 2791 return !mRestoredSettings; 2792 } 2793 2794 @Override 2795 public boolean isOnlyCoreApps() { 2796 return mOnlyCore; 2797 } 2798 2799 @Override 2800 public boolean isUpgrade() { 2801 return mIsUpgrade; 2802 } 2803 2804 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2805 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2806 2807 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2808 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2809 UserHandle.USER_SYSTEM); 2810 if (matches.size() == 1) { 2811 return matches.get(0).getComponentInfo().packageName; 2812 } else { 2813 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2814 return null; 2815 } 2816 } 2817 2818 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2819 synchronized (mPackages) { 2820 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2821 if (libraryEntry == null) { 2822 throw new IllegalStateException("Missing required shared library:" + libraryName); 2823 } 2824 return libraryEntry.apk; 2825 } 2826 } 2827 2828 private @NonNull String getRequiredInstallerLPr() { 2829 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2830 intent.addCategory(Intent.CATEGORY_DEFAULT); 2831 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2832 2833 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2834 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2835 UserHandle.USER_SYSTEM); 2836 if (matches.size() == 1) { 2837 ResolveInfo resolveInfo = matches.get(0); 2838 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2839 throw new RuntimeException("The installer must be a privileged app"); 2840 } 2841 return matches.get(0).getComponentInfo().packageName; 2842 } else { 2843 throw new RuntimeException("There must be exactly one installer; found " + matches); 2844 } 2845 } 2846 2847 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2848 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2849 2850 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2851 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2852 UserHandle.USER_SYSTEM); 2853 ResolveInfo best = null; 2854 final int N = matches.size(); 2855 for (int i = 0; i < N; i++) { 2856 final ResolveInfo cur = matches.get(i); 2857 final String packageName = cur.getComponentInfo().packageName; 2858 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2859 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2860 continue; 2861 } 2862 2863 if (best == null || cur.priority > best.priority) { 2864 best = cur; 2865 } 2866 } 2867 2868 if (best != null) { 2869 return best.getComponentInfo().getComponentName(); 2870 } else { 2871 throw new RuntimeException("There must be at least one intent filter verifier"); 2872 } 2873 } 2874 2875 private @Nullable ComponentName getEphemeralResolverLPr() { 2876 final String[] packageArray = 2877 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2878 if (packageArray.length == 0) { 2879 if (DEBUG_EPHEMERAL) { 2880 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2881 } 2882 return null; 2883 } 2884 2885 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2886 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2887 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2888 UserHandle.USER_SYSTEM); 2889 2890 final int N = resolvers.size(); 2891 if (N == 0) { 2892 if (DEBUG_EPHEMERAL) { 2893 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2894 } 2895 return null; 2896 } 2897 2898 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2899 for (int i = 0; i < N; i++) { 2900 final ResolveInfo info = resolvers.get(i); 2901 2902 if (info.serviceInfo == null) { 2903 continue; 2904 } 2905 2906 final String packageName = info.serviceInfo.packageName; 2907 if (!possiblePackages.contains(packageName)) { 2908 if (DEBUG_EPHEMERAL) { 2909 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2910 + " pkg: " + packageName + ", info:" + info); 2911 } 2912 continue; 2913 } 2914 2915 if (DEBUG_EPHEMERAL) { 2916 Slog.v(TAG, "Ephemeral resolver found;" 2917 + " pkg: " + packageName + ", info:" + info); 2918 } 2919 return new ComponentName(packageName, info.serviceInfo.name); 2920 } 2921 if (DEBUG_EPHEMERAL) { 2922 Slog.v(TAG, "Ephemeral resolver NOT found"); 2923 } 2924 return null; 2925 } 2926 2927 private @Nullable ComponentName getEphemeralInstallerLPr() { 2928 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2929 intent.addCategory(Intent.CATEGORY_DEFAULT); 2930 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2931 2932 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2933 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2934 UserHandle.USER_SYSTEM); 2935 if (matches.size() == 0) { 2936 return null; 2937 } else if (matches.size() == 1) { 2938 return matches.get(0).getComponentInfo().getComponentName(); 2939 } else { 2940 throw new RuntimeException( 2941 "There must be at most one ephemeral installer; found " + matches); 2942 } 2943 } 2944 2945 private void primeDomainVerificationsLPw(int userId) { 2946 if (DEBUG_DOMAIN_VERIFICATION) { 2947 Slog.d(TAG, "Priming domain verifications in user " + userId); 2948 } 2949 2950 SystemConfig systemConfig = SystemConfig.getInstance(); 2951 ArraySet<String> packages = systemConfig.getLinkedApps(); 2952 ArraySet<String> domains = new ArraySet<String>(); 2953 2954 for (String packageName : packages) { 2955 PackageParser.Package pkg = mPackages.get(packageName); 2956 if (pkg != null) { 2957 if (!pkg.isSystemApp()) { 2958 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2959 continue; 2960 } 2961 2962 domains.clear(); 2963 for (PackageParser.Activity a : pkg.activities) { 2964 for (ActivityIntentInfo filter : a.intents) { 2965 if (hasValidDomains(filter)) { 2966 domains.addAll(filter.getHostsList()); 2967 } 2968 } 2969 } 2970 2971 if (domains.size() > 0) { 2972 if (DEBUG_DOMAIN_VERIFICATION) { 2973 Slog.v(TAG, " + " + packageName); 2974 } 2975 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2976 // state w.r.t. the formal app-linkage "no verification attempted" state; 2977 // and then 'always' in the per-user state actually used for intent resolution. 2978 final IntentFilterVerificationInfo ivi; 2979 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2980 new ArrayList<String>(domains)); 2981 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2982 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2983 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2984 } else { 2985 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2986 + "' does not handle web links"); 2987 } 2988 } else { 2989 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2990 } 2991 } 2992 2993 scheduleWritePackageRestrictionsLocked(userId); 2994 scheduleWriteSettingsLocked(); 2995 } 2996 2997 private void applyFactoryDefaultBrowserLPw(int userId) { 2998 // The default browser app's package name is stored in a string resource, 2999 // with a product-specific overlay used for vendor customization. 3000 String browserPkg = mContext.getResources().getString( 3001 com.android.internal.R.string.default_browser); 3002 if (!TextUtils.isEmpty(browserPkg)) { 3003 // non-empty string => required to be a known package 3004 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3005 if (ps == null) { 3006 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3007 browserPkg = null; 3008 } else { 3009 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3010 } 3011 } 3012 3013 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3014 // default. If there's more than one, just leave everything alone. 3015 if (browserPkg == null) { 3016 calculateDefaultBrowserLPw(userId); 3017 } 3018 } 3019 3020 private void calculateDefaultBrowserLPw(int userId) { 3021 List<String> allBrowsers = resolveAllBrowserApps(userId); 3022 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3023 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3024 } 3025 3026 private List<String> resolveAllBrowserApps(int userId) { 3027 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3028 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3029 PackageManager.MATCH_ALL, userId); 3030 3031 final int count = list.size(); 3032 List<String> result = new ArrayList<String>(count); 3033 for (int i=0; i<count; i++) { 3034 ResolveInfo info = list.get(i); 3035 if (info.activityInfo == null 3036 || !info.handleAllWebDataURI 3037 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3038 || result.contains(info.activityInfo.packageName)) { 3039 continue; 3040 } 3041 result.add(info.activityInfo.packageName); 3042 } 3043 3044 return result; 3045 } 3046 3047 private boolean packageIsBrowser(String packageName, int userId) { 3048 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3049 PackageManager.MATCH_ALL, userId); 3050 final int N = list.size(); 3051 for (int i = 0; i < N; i++) { 3052 ResolveInfo info = list.get(i); 3053 if (packageName.equals(info.activityInfo.packageName)) { 3054 return true; 3055 } 3056 } 3057 return false; 3058 } 3059 3060 private void checkDefaultBrowser() { 3061 final int myUserId = UserHandle.myUserId(); 3062 final String packageName = getDefaultBrowserPackageName(myUserId); 3063 if (packageName != null) { 3064 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3065 if (info == null) { 3066 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3067 synchronized (mPackages) { 3068 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3069 } 3070 } 3071 } 3072 } 3073 3074 @Override 3075 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3076 throws RemoteException { 3077 try { 3078 return super.onTransact(code, data, reply, flags); 3079 } catch (RuntimeException e) { 3080 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3081 Slog.wtf(TAG, "Package Manager Crash", e); 3082 } 3083 throw e; 3084 } 3085 } 3086 3087 static int[] appendInts(int[] cur, int[] add) { 3088 if (add == null) return cur; 3089 if (cur == null) return add; 3090 final int N = add.length; 3091 for (int i=0; i<N; i++) { 3092 cur = appendInt(cur, add[i]); 3093 } 3094 return cur; 3095 } 3096 3097 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3098 if (!sUserManager.exists(userId)) return null; 3099 if (ps == null) { 3100 return null; 3101 } 3102 final PackageParser.Package p = ps.pkg; 3103 if (p == null) { 3104 return null; 3105 } 3106 3107 final PermissionsState permissionsState = ps.getPermissionsState(); 3108 3109 final int[] gids = permissionsState.computeGids(userId); 3110 final Set<String> permissions = permissionsState.getPermissions(userId); 3111 final PackageUserState state = ps.readUserState(userId); 3112 3113 return PackageParser.generatePackageInfo(p, gids, flags, 3114 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3115 } 3116 3117 @Override 3118 public void checkPackageStartable(String packageName, int userId) { 3119 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3120 3121 synchronized (mPackages) { 3122 final PackageSetting ps = mSettings.mPackages.get(packageName); 3123 if (ps == null) { 3124 throw new SecurityException("Package " + packageName + " was not found!"); 3125 } 3126 3127 if (!ps.getInstalled(userId)) { 3128 throw new SecurityException( 3129 "Package " + packageName + " was not installed for user " + userId + "!"); 3130 } 3131 3132 if (mSafeMode && !ps.isSystem()) { 3133 throw new SecurityException("Package " + packageName + " not a system app!"); 3134 } 3135 3136 if (mFrozenPackages.contains(packageName)) { 3137 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3138 } 3139 3140 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3141 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3142 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3143 } 3144 } 3145 } 3146 3147 @Override 3148 public boolean isPackageAvailable(String packageName, int userId) { 3149 if (!sUserManager.exists(userId)) return false; 3150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3151 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3152 synchronized (mPackages) { 3153 PackageParser.Package p = mPackages.get(packageName); 3154 if (p != null) { 3155 final PackageSetting ps = (PackageSetting) p.mExtras; 3156 if (ps != null) { 3157 final PackageUserState state = ps.readUserState(userId); 3158 if (state != null) { 3159 return PackageParser.isAvailable(state); 3160 } 3161 } 3162 } 3163 } 3164 return false; 3165 } 3166 3167 @Override 3168 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3169 if (!sUserManager.exists(userId)) return null; 3170 flags = updateFlagsForPackage(flags, userId, packageName); 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3172 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3173 // reader 3174 synchronized (mPackages) { 3175 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3176 PackageParser.Package p = null; 3177 if (matchFactoryOnly) { 3178 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3179 if (ps != null) { 3180 return generatePackageInfo(ps, flags, userId); 3181 } 3182 } 3183 if (p == null) { 3184 p = mPackages.get(packageName); 3185 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3186 return null; 3187 } 3188 } 3189 if (DEBUG_PACKAGE_INFO) 3190 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3191 if (p != null) { 3192 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3193 } 3194 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3195 final PackageSetting ps = mSettings.mPackages.get(packageName); 3196 return generatePackageInfo(ps, flags, userId); 3197 } 3198 } 3199 return null; 3200 } 3201 3202 @Override 3203 public String[] currentToCanonicalPackageNames(String[] names) { 3204 String[] out = new String[names.length]; 3205 // reader 3206 synchronized (mPackages) { 3207 for (int i=names.length-1; i>=0; i--) { 3208 PackageSetting ps = mSettings.mPackages.get(names[i]); 3209 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3210 } 3211 } 3212 return out; 3213 } 3214 3215 @Override 3216 public String[] canonicalToCurrentPackageNames(String[] names) { 3217 String[] out = new String[names.length]; 3218 // reader 3219 synchronized (mPackages) { 3220 for (int i=names.length-1; i>=0; i--) { 3221 String cur = mSettings.mRenamedPackages.get(names[i]); 3222 out[i] = cur != null ? cur : names[i]; 3223 } 3224 } 3225 return out; 3226 } 3227 3228 @Override 3229 public int getPackageUid(String packageName, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return -1; 3231 flags = updateFlagsForPackage(flags, userId, packageName); 3232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3233 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3234 3235 // reader 3236 synchronized (mPackages) { 3237 final PackageParser.Package p = mPackages.get(packageName); 3238 if (p != null && p.isMatch(flags)) { 3239 return UserHandle.getUid(userId, p.applicationInfo.uid); 3240 } 3241 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3242 final PackageSetting ps = mSettings.mPackages.get(packageName); 3243 if (ps != null && ps.isMatch(flags)) { 3244 return UserHandle.getUid(userId, ps.appId); 3245 } 3246 } 3247 } 3248 3249 return -1; 3250 } 3251 3252 @Override 3253 public int[] getPackageGids(String packageName, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return null; 3255 flags = updateFlagsForPackage(flags, userId, packageName); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3257 false /* requireFullPermission */, false /* checkShell */, 3258 "getPackageGids"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 PackageSetting ps = (PackageSetting) p.mExtras; 3265 return ps.getPermissionsState().computeGids(userId); 3266 } 3267 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3268 final PackageSetting ps = mSettings.mPackages.get(packageName); 3269 if (ps != null && ps.isMatch(flags)) { 3270 return ps.getPermissionsState().computeGids(userId); 3271 } 3272 } 3273 } 3274 3275 return null; 3276 } 3277 3278 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3279 if (bp.perm != null) { 3280 return PackageParser.generatePermissionInfo(bp.perm, flags); 3281 } 3282 PermissionInfo pi = new PermissionInfo(); 3283 pi.name = bp.name; 3284 pi.packageName = bp.sourcePackage; 3285 pi.nonLocalizedLabel = bp.name; 3286 pi.protectionLevel = bp.protectionLevel; 3287 return pi; 3288 } 3289 3290 @Override 3291 public PermissionInfo getPermissionInfo(String name, int flags) { 3292 // reader 3293 synchronized (mPackages) { 3294 final BasePermission p = mSettings.mPermissions.get(name); 3295 if (p != null) { 3296 return generatePermissionInfo(p, flags); 3297 } 3298 return null; 3299 } 3300 } 3301 3302 @Override 3303 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3304 int flags) { 3305 // reader 3306 synchronized (mPackages) { 3307 if (group != null && !mPermissionGroups.containsKey(group)) { 3308 // This is thrown as NameNotFoundException 3309 return null; 3310 } 3311 3312 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3313 for (BasePermission p : mSettings.mPermissions.values()) { 3314 if (group == null) { 3315 if (p.perm == null || p.perm.info.group == null) { 3316 out.add(generatePermissionInfo(p, flags)); 3317 } 3318 } else { 3319 if (p.perm != null && group.equals(p.perm.info.group)) { 3320 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3321 } 3322 } 3323 } 3324 return new ParceledListSlice<>(out); 3325 } 3326 } 3327 3328 @Override 3329 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 return PackageParser.generatePermissionGroupInfo( 3333 mPermissionGroups.get(name), flags); 3334 } 3335 } 3336 3337 @Override 3338 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3339 // reader 3340 synchronized (mPackages) { 3341 final int N = mPermissionGroups.size(); 3342 ArrayList<PermissionGroupInfo> out 3343 = new ArrayList<PermissionGroupInfo>(N); 3344 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3345 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3346 } 3347 return new ParceledListSlice<>(out); 3348 } 3349 } 3350 3351 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3352 int userId) { 3353 if (!sUserManager.exists(userId)) return null; 3354 PackageSetting ps = mSettings.mPackages.get(packageName); 3355 if (ps != null) { 3356 if (ps.pkg == null) { 3357 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3358 if (pInfo != null) { 3359 return pInfo.applicationInfo; 3360 } 3361 return null; 3362 } 3363 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3364 ps.readUserState(userId), userId); 3365 } 3366 return null; 3367 } 3368 3369 @Override 3370 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3371 if (!sUserManager.exists(userId)) return null; 3372 flags = updateFlagsForApplication(flags, userId, packageName); 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3374 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3375 // writer 3376 synchronized (mPackages) { 3377 PackageParser.Package p = mPackages.get(packageName); 3378 if (DEBUG_PACKAGE_INFO) Log.v( 3379 TAG, "getApplicationInfo " + packageName 3380 + ": " + p); 3381 if (p != null) { 3382 PackageSetting ps = mSettings.mPackages.get(packageName); 3383 if (ps == null) return null; 3384 // Note: isEnabledLP() does not apply here - always return info 3385 return PackageParser.generateApplicationInfo( 3386 p, flags, ps.readUserState(userId), userId); 3387 } 3388 if ("android".equals(packageName)||"system".equals(packageName)) { 3389 return mAndroidApplication; 3390 } 3391 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3392 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3393 } 3394 } 3395 return null; 3396 } 3397 3398 @Override 3399 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3400 final IPackageDataObserver observer) { 3401 mContext.enforceCallingOrSelfPermission( 3402 android.Manifest.permission.CLEAR_APP_CACHE, null); 3403 // Queue up an async operation since clearing cache may take a little while. 3404 mHandler.post(new Runnable() { 3405 public void run() { 3406 mHandler.removeCallbacks(this); 3407 boolean success = true; 3408 synchronized (mInstallLock) { 3409 try { 3410 mInstaller.freeCache(volumeUuid, freeStorageSize); 3411 } catch (InstallerException e) { 3412 Slog.w(TAG, "Couldn't clear application caches: " + e); 3413 success = false; 3414 } 3415 } 3416 if (observer != null) { 3417 try { 3418 observer.onRemoveCompleted(null, success); 3419 } catch (RemoteException e) { 3420 Slog.w(TAG, "RemoveException when invoking call back"); 3421 } 3422 } 3423 } 3424 }); 3425 } 3426 3427 @Override 3428 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3429 final IntentSender pi) { 3430 mContext.enforceCallingOrSelfPermission( 3431 android.Manifest.permission.CLEAR_APP_CACHE, null); 3432 // Queue up an async operation since clearing cache may take a little while. 3433 mHandler.post(new Runnable() { 3434 public void run() { 3435 mHandler.removeCallbacks(this); 3436 boolean success = true; 3437 synchronized (mInstallLock) { 3438 try { 3439 mInstaller.freeCache(volumeUuid, freeStorageSize); 3440 } catch (InstallerException e) { 3441 Slog.w(TAG, "Couldn't clear application caches: " + e); 3442 success = false; 3443 } 3444 } 3445 if(pi != null) { 3446 try { 3447 // Callback via pending intent 3448 int code = success ? 1 : 0; 3449 pi.sendIntent(null, code, null, 3450 null, null); 3451 } catch (SendIntentException e1) { 3452 Slog.i(TAG, "Failed to send pending intent"); 3453 } 3454 } 3455 } 3456 }); 3457 } 3458 3459 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3460 synchronized (mInstallLock) { 3461 try { 3462 mInstaller.freeCache(volumeUuid, freeStorageSize); 3463 } catch (InstallerException e) { 3464 throw new IOException("Failed to free enough space", e); 3465 } 3466 } 3467 } 3468 3469 /** 3470 * Update given flags based on encryption status of current user. 3471 */ 3472 private int updateFlags(int flags, int userId) { 3473 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3474 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3475 // Caller expressed an explicit opinion about what encryption 3476 // aware/unaware components they want to see, so fall through and 3477 // give them what they want 3478 } else { 3479 // Caller expressed no opinion, so match based on user state 3480 if (StorageManager.isUserKeyUnlocked(userId)) { 3481 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3482 } else { 3483 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3484 } 3485 } 3486 return flags; 3487 } 3488 3489 /** 3490 * Update given flags when being used to request {@link PackageInfo}. 3491 */ 3492 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3493 boolean triaged = true; 3494 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3495 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3496 // Caller is asking for component details, so they'd better be 3497 // asking for specific encryption matching behavior, or be triaged 3498 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3499 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3500 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3501 triaged = false; 3502 } 3503 } 3504 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3505 | PackageManager.MATCH_SYSTEM_ONLY 3506 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3507 triaged = false; 3508 } 3509 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3510 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3511 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3512 } 3513 return updateFlags(flags, userId); 3514 } 3515 3516 /** 3517 * Update given flags when being used to request {@link ApplicationInfo}. 3518 */ 3519 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3520 return updateFlagsForPackage(flags, userId, cookie); 3521 } 3522 3523 /** 3524 * Update given flags when being used to request {@link ComponentInfo}. 3525 */ 3526 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3527 if (cookie instanceof Intent) { 3528 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3529 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3530 } 3531 } 3532 3533 boolean triaged = true; 3534 // Caller is asking for component details, so they'd better be 3535 // asking for specific encryption matching behavior, or be triaged 3536 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3537 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3538 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3539 triaged = false; 3540 } 3541 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3542 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3543 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3544 } 3545 3546 return updateFlags(flags, userId); 3547 } 3548 3549 /** 3550 * Update given flags when being used to request {@link ResolveInfo}. 3551 */ 3552 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3553 // Safe mode means we shouldn't match any third-party components 3554 if (mSafeMode) { 3555 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3556 } 3557 3558 return updateFlagsForComponent(flags, userId, cookie); 3559 } 3560 3561 @Override 3562 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3563 if (!sUserManager.exists(userId)) return null; 3564 flags = updateFlagsForComponent(flags, userId, component); 3565 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3566 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3567 synchronized (mPackages) { 3568 PackageParser.Activity a = mActivities.mActivities.get(component); 3569 3570 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3571 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3572 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3573 if (ps == null) return null; 3574 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3575 userId); 3576 } 3577 if (mResolveComponentName.equals(component)) { 3578 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3579 new PackageUserState(), userId); 3580 } 3581 } 3582 return null; 3583 } 3584 3585 @Override 3586 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3587 String resolvedType) { 3588 synchronized (mPackages) { 3589 if (component.equals(mResolveComponentName)) { 3590 // The resolver supports EVERYTHING! 3591 return true; 3592 } 3593 PackageParser.Activity a = mActivities.mActivities.get(component); 3594 if (a == null) { 3595 return false; 3596 } 3597 for (int i=0; i<a.intents.size(); i++) { 3598 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3599 intent.getData(), intent.getCategories(), TAG) >= 0) { 3600 return true; 3601 } 3602 } 3603 return false; 3604 } 3605 } 3606 3607 @Override 3608 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3609 if (!sUserManager.exists(userId)) return null; 3610 flags = updateFlagsForComponent(flags, userId, component); 3611 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3612 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3613 synchronized (mPackages) { 3614 PackageParser.Activity a = mReceivers.mActivities.get(component); 3615 if (DEBUG_PACKAGE_INFO) Log.v( 3616 TAG, "getReceiverInfo " + component + ": " + a); 3617 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3618 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3619 if (ps == null) return null; 3620 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3621 userId); 3622 } 3623 } 3624 return null; 3625 } 3626 3627 @Override 3628 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3629 if (!sUserManager.exists(userId)) return null; 3630 flags = updateFlagsForComponent(flags, userId, component); 3631 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3632 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3633 synchronized (mPackages) { 3634 PackageParser.Service s = mServices.mServices.get(component); 3635 if (DEBUG_PACKAGE_INFO) Log.v( 3636 TAG, "getServiceInfo " + component + ": " + s); 3637 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3638 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3639 if (ps == null) return null; 3640 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3641 userId); 3642 } 3643 } 3644 return null; 3645 } 3646 3647 @Override 3648 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3649 if (!sUserManager.exists(userId)) return null; 3650 flags = updateFlagsForComponent(flags, userId, component); 3651 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3652 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3653 synchronized (mPackages) { 3654 PackageParser.Provider p = mProviders.mProviders.get(component); 3655 if (DEBUG_PACKAGE_INFO) Log.v( 3656 TAG, "getProviderInfo " + component + ": " + p); 3657 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3658 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3659 if (ps == null) return null; 3660 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3661 userId); 3662 } 3663 } 3664 return null; 3665 } 3666 3667 @Override 3668 public String[] getSystemSharedLibraryNames() { 3669 Set<String> libSet; 3670 synchronized (mPackages) { 3671 libSet = mSharedLibraries.keySet(); 3672 int size = libSet.size(); 3673 if (size > 0) { 3674 String[] libs = new String[size]; 3675 libSet.toArray(libs); 3676 return libs; 3677 } 3678 } 3679 return null; 3680 } 3681 3682 @Override 3683 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3684 synchronized (mPackages) { 3685 return mServicesSystemSharedLibraryPackageName; 3686 } 3687 } 3688 3689 @Override 3690 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3691 synchronized (mPackages) { 3692 return mSharedSystemSharedLibraryPackageName; 3693 } 3694 } 3695 3696 @Override 3697 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3698 synchronized (mPackages) { 3699 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3700 3701 final FeatureInfo fi = new FeatureInfo(); 3702 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3703 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3704 res.add(fi); 3705 3706 return new ParceledListSlice<>(res); 3707 } 3708 } 3709 3710 @Override 3711 public boolean hasSystemFeature(String name, int version) { 3712 synchronized (mPackages) { 3713 final FeatureInfo feat = mAvailableFeatures.get(name); 3714 if (feat == null) { 3715 return false; 3716 } else { 3717 return feat.version >= version; 3718 } 3719 } 3720 } 3721 3722 @Override 3723 public int checkPermission(String permName, String pkgName, int userId) { 3724 if (!sUserManager.exists(userId)) { 3725 return PackageManager.PERMISSION_DENIED; 3726 } 3727 3728 synchronized (mPackages) { 3729 final PackageParser.Package p = mPackages.get(pkgName); 3730 if (p != null && p.mExtras != null) { 3731 final PackageSetting ps = (PackageSetting) p.mExtras; 3732 final PermissionsState permissionsState = ps.getPermissionsState(); 3733 if (permissionsState.hasPermission(permName, userId)) { 3734 return PackageManager.PERMISSION_GRANTED; 3735 } 3736 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3737 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3738 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3739 return PackageManager.PERMISSION_GRANTED; 3740 } 3741 } 3742 } 3743 3744 return PackageManager.PERMISSION_DENIED; 3745 } 3746 3747 @Override 3748 public int checkUidPermission(String permName, int uid) { 3749 final int userId = UserHandle.getUserId(uid); 3750 3751 if (!sUserManager.exists(userId)) { 3752 return PackageManager.PERMISSION_DENIED; 3753 } 3754 3755 synchronized (mPackages) { 3756 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3757 if (obj != null) { 3758 final SettingBase ps = (SettingBase) obj; 3759 final PermissionsState permissionsState = ps.getPermissionsState(); 3760 if (permissionsState.hasPermission(permName, userId)) { 3761 return PackageManager.PERMISSION_GRANTED; 3762 } 3763 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3764 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3765 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3766 return PackageManager.PERMISSION_GRANTED; 3767 } 3768 } else { 3769 ArraySet<String> perms = mSystemPermissions.get(uid); 3770 if (perms != null) { 3771 if (perms.contains(permName)) { 3772 return PackageManager.PERMISSION_GRANTED; 3773 } 3774 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3775 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3776 return PackageManager.PERMISSION_GRANTED; 3777 } 3778 } 3779 } 3780 } 3781 3782 return PackageManager.PERMISSION_DENIED; 3783 } 3784 3785 @Override 3786 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3787 if (UserHandle.getCallingUserId() != userId) { 3788 mContext.enforceCallingPermission( 3789 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3790 "isPermissionRevokedByPolicy for user " + userId); 3791 } 3792 3793 if (checkPermission(permission, packageName, userId) 3794 == PackageManager.PERMISSION_GRANTED) { 3795 return false; 3796 } 3797 3798 final long identity = Binder.clearCallingIdentity(); 3799 try { 3800 final int flags = getPermissionFlags(permission, packageName, userId); 3801 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3802 } finally { 3803 Binder.restoreCallingIdentity(identity); 3804 } 3805 } 3806 3807 @Override 3808 public String getPermissionControllerPackageName() { 3809 synchronized (mPackages) { 3810 return mRequiredInstallerPackage; 3811 } 3812 } 3813 3814 /** 3815 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3816 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3817 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3818 * @param message the message to log on security exception 3819 */ 3820 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3821 boolean checkShell, String message) { 3822 if (userId < 0) { 3823 throw new IllegalArgumentException("Invalid userId " + userId); 3824 } 3825 if (checkShell) { 3826 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3827 } 3828 if (userId == UserHandle.getUserId(callingUid)) return; 3829 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3830 if (requireFullPermission) { 3831 mContext.enforceCallingOrSelfPermission( 3832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3833 } else { 3834 try { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3837 } catch (SecurityException se) { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3840 } 3841 } 3842 } 3843 } 3844 3845 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3846 if (callingUid == Process.SHELL_UID) { 3847 if (userHandle >= 0 3848 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3849 throw new SecurityException("Shell does not have permission to access user " 3850 + userHandle); 3851 } else if (userHandle < 0) { 3852 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3853 + Debug.getCallers(3)); 3854 } 3855 } 3856 } 3857 3858 private BasePermission findPermissionTreeLP(String permName) { 3859 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3860 if (permName.startsWith(bp.name) && 3861 permName.length() > bp.name.length() && 3862 permName.charAt(bp.name.length()) == '.') { 3863 return bp; 3864 } 3865 } 3866 return null; 3867 } 3868 3869 private BasePermission checkPermissionTreeLP(String permName) { 3870 if (permName != null) { 3871 BasePermission bp = findPermissionTreeLP(permName); 3872 if (bp != null) { 3873 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3874 return bp; 3875 } 3876 throw new SecurityException("Calling uid " 3877 + Binder.getCallingUid() 3878 + " is not allowed to add to permission tree " 3879 + bp.name + " owned by uid " + bp.uid); 3880 } 3881 } 3882 throw new SecurityException("No permission tree found for " + permName); 3883 } 3884 3885 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3886 if (s1 == null) { 3887 return s2 == null; 3888 } 3889 if (s2 == null) { 3890 return false; 3891 } 3892 if (s1.getClass() != s2.getClass()) { 3893 return false; 3894 } 3895 return s1.equals(s2); 3896 } 3897 3898 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3899 if (pi1.icon != pi2.icon) return false; 3900 if (pi1.logo != pi2.logo) return false; 3901 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3902 if (!compareStrings(pi1.name, pi2.name)) return false; 3903 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3904 // We'll take care of setting this one. 3905 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3906 // These are not currently stored in settings. 3907 //if (!compareStrings(pi1.group, pi2.group)) return false; 3908 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3909 //if (pi1.labelRes != pi2.labelRes) return false; 3910 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3911 return true; 3912 } 3913 3914 int permissionInfoFootprint(PermissionInfo info) { 3915 int size = info.name.length(); 3916 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3917 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3918 return size; 3919 } 3920 3921 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3922 int size = 0; 3923 for (BasePermission perm : mSettings.mPermissions.values()) { 3924 if (perm.uid == tree.uid) { 3925 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3926 } 3927 } 3928 return size; 3929 } 3930 3931 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3932 // We calculate the max size of permissions defined by this uid and throw 3933 // if that plus the size of 'info' would exceed our stated maximum. 3934 if (tree.uid != Process.SYSTEM_UID) { 3935 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3936 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3937 throw new SecurityException("Permission tree size cap exceeded"); 3938 } 3939 } 3940 } 3941 3942 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3943 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3944 throw new SecurityException("Label must be specified in permission"); 3945 } 3946 BasePermission tree = checkPermissionTreeLP(info.name); 3947 BasePermission bp = mSettings.mPermissions.get(info.name); 3948 boolean added = bp == null; 3949 boolean changed = true; 3950 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3951 if (added) { 3952 enforcePermissionCapLocked(info, tree); 3953 bp = new BasePermission(info.name, tree.sourcePackage, 3954 BasePermission.TYPE_DYNAMIC); 3955 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3956 throw new SecurityException( 3957 "Not allowed to modify non-dynamic permission " 3958 + info.name); 3959 } else { 3960 if (bp.protectionLevel == fixedLevel 3961 && bp.perm.owner.equals(tree.perm.owner) 3962 && bp.uid == tree.uid 3963 && comparePermissionInfos(bp.perm.info, info)) { 3964 changed = false; 3965 } 3966 } 3967 bp.protectionLevel = fixedLevel; 3968 info = new PermissionInfo(info); 3969 info.protectionLevel = fixedLevel; 3970 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3971 bp.perm.info.packageName = tree.perm.info.packageName; 3972 bp.uid = tree.uid; 3973 if (added) { 3974 mSettings.mPermissions.put(info.name, bp); 3975 } 3976 if (changed) { 3977 if (!async) { 3978 mSettings.writeLPr(); 3979 } else { 3980 scheduleWriteSettingsLocked(); 3981 } 3982 } 3983 return added; 3984 } 3985 3986 @Override 3987 public boolean addPermission(PermissionInfo info) { 3988 synchronized (mPackages) { 3989 return addPermissionLocked(info, false); 3990 } 3991 } 3992 3993 @Override 3994 public boolean addPermissionAsync(PermissionInfo info) { 3995 synchronized (mPackages) { 3996 return addPermissionLocked(info, true); 3997 } 3998 } 3999 4000 @Override 4001 public void removePermission(String name) { 4002 synchronized (mPackages) { 4003 checkPermissionTreeLP(name); 4004 BasePermission bp = mSettings.mPermissions.get(name); 4005 if (bp != null) { 4006 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4007 throw new SecurityException( 4008 "Not allowed to modify non-dynamic permission " 4009 + name); 4010 } 4011 mSettings.mPermissions.remove(name); 4012 mSettings.writeLPr(); 4013 } 4014 } 4015 } 4016 4017 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4018 BasePermission bp) { 4019 int index = pkg.requestedPermissions.indexOf(bp.name); 4020 if (index == -1) { 4021 throw new SecurityException("Package " + pkg.packageName 4022 + " has not requested permission " + bp.name); 4023 } 4024 if (!bp.isRuntime() && !bp.isDevelopment()) { 4025 throw new SecurityException("Permission " + bp.name 4026 + " is not a changeable permission type"); 4027 } 4028 } 4029 4030 @Override 4031 public void grantRuntimePermission(String packageName, String name, final int userId) { 4032 if (!sUserManager.exists(userId)) { 4033 Log.e(TAG, "No such user:" + userId); 4034 return; 4035 } 4036 4037 mContext.enforceCallingOrSelfPermission( 4038 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4039 "grantRuntimePermission"); 4040 4041 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4042 true /* requireFullPermission */, true /* checkShell */, 4043 "grantRuntimePermission"); 4044 4045 final int uid; 4046 final SettingBase sb; 4047 4048 synchronized (mPackages) { 4049 final PackageParser.Package pkg = mPackages.get(packageName); 4050 if (pkg == null) { 4051 throw new IllegalArgumentException("Unknown package: " + packageName); 4052 } 4053 4054 final BasePermission bp = mSettings.mPermissions.get(name); 4055 if (bp == null) { 4056 throw new IllegalArgumentException("Unknown permission: " + name); 4057 } 4058 4059 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4060 4061 // If a permission review is required for legacy apps we represent 4062 // their permissions as always granted runtime ones since we need 4063 // to keep the review required permission flag per user while an 4064 // install permission's state is shared across all users. 4065 if (Build.PERMISSIONS_REVIEW_REQUIRED 4066 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4067 && bp.isRuntime()) { 4068 return; 4069 } 4070 4071 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4072 sb = (SettingBase) pkg.mExtras; 4073 if (sb == null) { 4074 throw new IllegalArgumentException("Unknown package: " + packageName); 4075 } 4076 4077 final PermissionsState permissionsState = sb.getPermissionsState(); 4078 4079 final int flags = permissionsState.getPermissionFlags(name, userId); 4080 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4081 throw new SecurityException("Cannot grant system fixed permission " 4082 + name + " for package " + packageName); 4083 } 4084 4085 if (bp.isDevelopment()) { 4086 // Development permissions must be handled specially, since they are not 4087 // normal runtime permissions. For now they apply to all users. 4088 if (permissionsState.grantInstallPermission(bp) != 4089 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4090 scheduleWriteSettingsLocked(); 4091 } 4092 return; 4093 } 4094 4095 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4096 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4097 return; 4098 } 4099 4100 final int result = permissionsState.grantRuntimePermission(bp, userId); 4101 switch (result) { 4102 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4103 return; 4104 } 4105 4106 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4107 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4108 mHandler.post(new Runnable() { 4109 @Override 4110 public void run() { 4111 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4112 } 4113 }); 4114 } 4115 break; 4116 } 4117 4118 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4119 4120 // Not critical if that is lost - app has to request again. 4121 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4122 } 4123 4124 // Only need to do this if user is initialized. Otherwise it's a new user 4125 // and there are no processes running as the user yet and there's no need 4126 // to make an expensive call to remount processes for the changed permissions. 4127 if (READ_EXTERNAL_STORAGE.equals(name) 4128 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4129 final long token = Binder.clearCallingIdentity(); 4130 try { 4131 if (sUserManager.isInitialized(userId)) { 4132 MountServiceInternal mountServiceInternal = LocalServices.getService( 4133 MountServiceInternal.class); 4134 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4135 } 4136 } finally { 4137 Binder.restoreCallingIdentity(token); 4138 } 4139 } 4140 } 4141 4142 @Override 4143 public void revokeRuntimePermission(String packageName, String name, int userId) { 4144 if (!sUserManager.exists(userId)) { 4145 Log.e(TAG, "No such user:" + userId); 4146 return; 4147 } 4148 4149 mContext.enforceCallingOrSelfPermission( 4150 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4151 "revokeRuntimePermission"); 4152 4153 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4154 true /* requireFullPermission */, true /* checkShell */, 4155 "revokeRuntimePermission"); 4156 4157 final int appId; 4158 4159 synchronized (mPackages) { 4160 final PackageParser.Package pkg = mPackages.get(packageName); 4161 if (pkg == null) { 4162 throw new IllegalArgumentException("Unknown package: " + packageName); 4163 } 4164 4165 final BasePermission bp = mSettings.mPermissions.get(name); 4166 if (bp == null) { 4167 throw new IllegalArgumentException("Unknown permission: " + name); 4168 } 4169 4170 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4171 4172 // If a permission review is required for legacy apps we represent 4173 // their permissions as always granted runtime ones since we need 4174 // to keep the review required permission flag per user while an 4175 // install permission's state is shared across all users. 4176 if (Build.PERMISSIONS_REVIEW_REQUIRED 4177 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4178 && bp.isRuntime()) { 4179 return; 4180 } 4181 4182 SettingBase sb = (SettingBase) pkg.mExtras; 4183 if (sb == null) { 4184 throw new IllegalArgumentException("Unknown package: " + packageName); 4185 } 4186 4187 final PermissionsState permissionsState = sb.getPermissionsState(); 4188 4189 final int flags = permissionsState.getPermissionFlags(name, userId); 4190 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4191 throw new SecurityException("Cannot revoke system fixed permission " 4192 + name + " for package " + packageName); 4193 } 4194 4195 if (bp.isDevelopment()) { 4196 // Development permissions must be handled specially, since they are not 4197 // normal runtime permissions. For now they apply to all users. 4198 if (permissionsState.revokeInstallPermission(bp) != 4199 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4200 scheduleWriteSettingsLocked(); 4201 } 4202 return; 4203 } 4204 4205 if (permissionsState.revokeRuntimePermission(bp, userId) == 4206 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4207 return; 4208 } 4209 4210 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4211 4212 // Critical, after this call app should never have the permission. 4213 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4214 4215 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4216 } 4217 4218 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4219 } 4220 4221 @Override 4222 public void resetRuntimePermissions() { 4223 mContext.enforceCallingOrSelfPermission( 4224 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4225 "revokeRuntimePermission"); 4226 4227 int callingUid = Binder.getCallingUid(); 4228 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4229 mContext.enforceCallingOrSelfPermission( 4230 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4231 "resetRuntimePermissions"); 4232 } 4233 4234 synchronized (mPackages) { 4235 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4236 for (int userId : UserManagerService.getInstance().getUserIds()) { 4237 final int packageCount = mPackages.size(); 4238 for (int i = 0; i < packageCount; i++) { 4239 PackageParser.Package pkg = mPackages.valueAt(i); 4240 if (!(pkg.mExtras instanceof PackageSetting)) { 4241 continue; 4242 } 4243 PackageSetting ps = (PackageSetting) pkg.mExtras; 4244 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4245 } 4246 } 4247 } 4248 } 4249 4250 @Override 4251 public int getPermissionFlags(String name, String packageName, int userId) { 4252 if (!sUserManager.exists(userId)) { 4253 return 0; 4254 } 4255 4256 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4257 4258 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4259 true /* requireFullPermission */, false /* checkShell */, 4260 "getPermissionFlags"); 4261 4262 synchronized (mPackages) { 4263 final PackageParser.Package pkg = mPackages.get(packageName); 4264 if (pkg == null) { 4265 throw new IllegalArgumentException("Unknown package: " + packageName); 4266 } 4267 4268 final BasePermission bp = mSettings.mPermissions.get(name); 4269 if (bp == null) { 4270 throw new IllegalArgumentException("Unknown permission: " + name); 4271 } 4272 4273 SettingBase sb = (SettingBase) pkg.mExtras; 4274 if (sb == null) { 4275 throw new IllegalArgumentException("Unknown package: " + packageName); 4276 } 4277 4278 PermissionsState permissionsState = sb.getPermissionsState(); 4279 return permissionsState.getPermissionFlags(name, userId); 4280 } 4281 } 4282 4283 @Override 4284 public void updatePermissionFlags(String name, String packageName, int flagMask, 4285 int flagValues, int userId) { 4286 if (!sUserManager.exists(userId)) { 4287 return; 4288 } 4289 4290 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4291 4292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4293 true /* requireFullPermission */, true /* checkShell */, 4294 "updatePermissionFlags"); 4295 4296 // Only the system can change these flags and nothing else. 4297 if (getCallingUid() != Process.SYSTEM_UID) { 4298 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4299 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4300 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4301 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4302 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4303 } 4304 4305 synchronized (mPackages) { 4306 final PackageParser.Package pkg = mPackages.get(packageName); 4307 if (pkg == null) { 4308 throw new IllegalArgumentException("Unknown package: " + packageName); 4309 } 4310 4311 final BasePermission bp = mSettings.mPermissions.get(name); 4312 if (bp == null) { 4313 throw new IllegalArgumentException("Unknown permission: " + name); 4314 } 4315 4316 SettingBase sb = (SettingBase) pkg.mExtras; 4317 if (sb == null) { 4318 throw new IllegalArgumentException("Unknown package: " + packageName); 4319 } 4320 4321 PermissionsState permissionsState = sb.getPermissionsState(); 4322 4323 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4324 4325 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4326 // Install and runtime permissions are stored in different places, 4327 // so figure out what permission changed and persist the change. 4328 if (permissionsState.getInstallPermissionState(name) != null) { 4329 scheduleWriteSettingsLocked(); 4330 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4331 || hadState) { 4332 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4333 } 4334 } 4335 } 4336 } 4337 4338 /** 4339 * Update the permission flags for all packages and runtime permissions of a user in order 4340 * to allow device or profile owner to remove POLICY_FIXED. 4341 */ 4342 @Override 4343 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4344 if (!sUserManager.exists(userId)) { 4345 return; 4346 } 4347 4348 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4349 4350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4351 true /* requireFullPermission */, true /* checkShell */, 4352 "updatePermissionFlagsForAllApps"); 4353 4354 // Only the system can change system fixed flags. 4355 if (getCallingUid() != Process.SYSTEM_UID) { 4356 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4357 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4358 } 4359 4360 synchronized (mPackages) { 4361 boolean changed = false; 4362 final int packageCount = mPackages.size(); 4363 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4364 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4365 SettingBase sb = (SettingBase) pkg.mExtras; 4366 if (sb == null) { 4367 continue; 4368 } 4369 PermissionsState permissionsState = sb.getPermissionsState(); 4370 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4371 userId, flagMask, flagValues); 4372 } 4373 if (changed) { 4374 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4375 } 4376 } 4377 } 4378 4379 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4380 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4381 != PackageManager.PERMISSION_GRANTED 4382 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4383 != PackageManager.PERMISSION_GRANTED) { 4384 throw new SecurityException(message + " requires " 4385 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4386 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4387 } 4388 } 4389 4390 @Override 4391 public boolean shouldShowRequestPermissionRationale(String permissionName, 4392 String packageName, int userId) { 4393 if (UserHandle.getCallingUserId() != userId) { 4394 mContext.enforceCallingPermission( 4395 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4396 "canShowRequestPermissionRationale for user " + userId); 4397 } 4398 4399 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4400 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4401 return false; 4402 } 4403 4404 if (checkPermission(permissionName, packageName, userId) 4405 == PackageManager.PERMISSION_GRANTED) { 4406 return false; 4407 } 4408 4409 final int flags; 4410 4411 final long identity = Binder.clearCallingIdentity(); 4412 try { 4413 flags = getPermissionFlags(permissionName, 4414 packageName, userId); 4415 } finally { 4416 Binder.restoreCallingIdentity(identity); 4417 } 4418 4419 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4420 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4421 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4422 4423 if ((flags & fixedFlags) != 0) { 4424 return false; 4425 } 4426 4427 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4428 } 4429 4430 @Override 4431 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4432 mContext.enforceCallingOrSelfPermission( 4433 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4434 "addOnPermissionsChangeListener"); 4435 4436 synchronized (mPackages) { 4437 mOnPermissionChangeListeners.addListenerLocked(listener); 4438 } 4439 } 4440 4441 @Override 4442 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4443 synchronized (mPackages) { 4444 mOnPermissionChangeListeners.removeListenerLocked(listener); 4445 } 4446 } 4447 4448 @Override 4449 public boolean isProtectedBroadcast(String actionName) { 4450 synchronized (mPackages) { 4451 if (mProtectedBroadcasts.contains(actionName)) { 4452 return true; 4453 } else if (actionName != null) { 4454 // TODO: remove these terrible hacks 4455 if (actionName.startsWith("android.net.netmon.lingerExpired") 4456 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4457 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4458 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4459 return true; 4460 } 4461 } 4462 } 4463 return false; 4464 } 4465 4466 @Override 4467 public int checkSignatures(String pkg1, String pkg2) { 4468 synchronized (mPackages) { 4469 final PackageParser.Package p1 = mPackages.get(pkg1); 4470 final PackageParser.Package p2 = mPackages.get(pkg2); 4471 if (p1 == null || p1.mExtras == null 4472 || p2 == null || p2.mExtras == null) { 4473 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4474 } 4475 return compareSignatures(p1.mSignatures, p2.mSignatures); 4476 } 4477 } 4478 4479 @Override 4480 public int checkUidSignatures(int uid1, int uid2) { 4481 // Map to base uids. 4482 uid1 = UserHandle.getAppId(uid1); 4483 uid2 = UserHandle.getAppId(uid2); 4484 // reader 4485 synchronized (mPackages) { 4486 Signature[] s1; 4487 Signature[] s2; 4488 Object obj = mSettings.getUserIdLPr(uid1); 4489 if (obj != null) { 4490 if (obj instanceof SharedUserSetting) { 4491 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4492 } else if (obj instanceof PackageSetting) { 4493 s1 = ((PackageSetting)obj).signatures.mSignatures; 4494 } else { 4495 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4496 } 4497 } else { 4498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4499 } 4500 obj = mSettings.getUserIdLPr(uid2); 4501 if (obj != null) { 4502 if (obj instanceof SharedUserSetting) { 4503 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4504 } else if (obj instanceof PackageSetting) { 4505 s2 = ((PackageSetting)obj).signatures.mSignatures; 4506 } else { 4507 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4508 } 4509 } else { 4510 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4511 } 4512 return compareSignatures(s1, s2); 4513 } 4514 } 4515 4516 /** 4517 * This method should typically only be used when granting or revoking 4518 * permissions, since the app may immediately restart after this call. 4519 * <p> 4520 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4521 * guard your work against the app being relaunched. 4522 */ 4523 private void killUid(int appId, int userId, String reason) { 4524 final long identity = Binder.clearCallingIdentity(); 4525 try { 4526 IActivityManager am = ActivityManagerNative.getDefault(); 4527 if (am != null) { 4528 try { 4529 am.killUid(appId, userId, reason); 4530 } catch (RemoteException e) { 4531 /* ignore - same process */ 4532 } 4533 } 4534 } finally { 4535 Binder.restoreCallingIdentity(identity); 4536 } 4537 } 4538 4539 /** 4540 * Compares two sets of signatures. Returns: 4541 * <br /> 4542 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4543 * <br /> 4544 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4551 */ 4552 static int compareSignatures(Signature[] s1, Signature[] s2) { 4553 if (s1 == null) { 4554 return s2 == null 4555 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4556 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4557 } 4558 4559 if (s2 == null) { 4560 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4561 } 4562 4563 if (s1.length != s2.length) { 4564 return PackageManager.SIGNATURE_NO_MATCH; 4565 } 4566 4567 // Since both signature sets are of size 1, we can compare without HashSets. 4568 if (s1.length == 1) { 4569 return s1[0].equals(s2[0]) ? 4570 PackageManager.SIGNATURE_MATCH : 4571 PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4575 for (Signature sig : s1) { 4576 set1.add(sig); 4577 } 4578 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4579 for (Signature sig : s2) { 4580 set2.add(sig); 4581 } 4582 // Make sure s2 contains all signatures in s1. 4583 if (set1.equals(set2)) { 4584 return PackageManager.SIGNATURE_MATCH; 4585 } 4586 return PackageManager.SIGNATURE_NO_MATCH; 4587 } 4588 4589 /** 4590 * If the database version for this type of package (internal storage or 4591 * external storage) is less than the version where package signatures 4592 * were updated, return true. 4593 */ 4594 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4595 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4596 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4597 } 4598 4599 /** 4600 * Used for backward compatibility to make sure any packages with 4601 * certificate chains get upgraded to the new style. {@code existingSigs} 4602 * will be in the old format (since they were stored on disk from before the 4603 * system upgrade) and {@code scannedSigs} will be in the newer format. 4604 */ 4605 private int compareSignaturesCompat(PackageSignatures existingSigs, 4606 PackageParser.Package scannedPkg) { 4607 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4608 return PackageManager.SIGNATURE_NO_MATCH; 4609 } 4610 4611 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4612 for (Signature sig : existingSigs.mSignatures) { 4613 existingSet.add(sig); 4614 } 4615 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4616 for (Signature sig : scannedPkg.mSignatures) { 4617 try { 4618 Signature[] chainSignatures = sig.getChainSignatures(); 4619 for (Signature chainSig : chainSignatures) { 4620 scannedCompatSet.add(chainSig); 4621 } 4622 } catch (CertificateEncodingException e) { 4623 scannedCompatSet.add(sig); 4624 } 4625 } 4626 /* 4627 * Make sure the expanded scanned set contains all signatures in the 4628 * existing one. 4629 */ 4630 if (scannedCompatSet.equals(existingSet)) { 4631 // Migrate the old signatures to the new scheme. 4632 existingSigs.assignSignatures(scannedPkg.mSignatures); 4633 // The new KeySets will be re-added later in the scanning process. 4634 synchronized (mPackages) { 4635 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4636 } 4637 return PackageManager.SIGNATURE_MATCH; 4638 } 4639 return PackageManager.SIGNATURE_NO_MATCH; 4640 } 4641 4642 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4643 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4644 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4645 } 4646 4647 private int compareSignaturesRecover(PackageSignatures existingSigs, 4648 PackageParser.Package scannedPkg) { 4649 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4650 return PackageManager.SIGNATURE_NO_MATCH; 4651 } 4652 4653 String msg = null; 4654 try { 4655 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4656 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4657 + scannedPkg.packageName); 4658 return PackageManager.SIGNATURE_MATCH; 4659 } 4660 } catch (CertificateException e) { 4661 msg = e.getMessage(); 4662 } 4663 4664 logCriticalInfo(Log.INFO, 4665 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4666 return PackageManager.SIGNATURE_NO_MATCH; 4667 } 4668 4669 @Override 4670 public List<String> getAllPackages() { 4671 synchronized (mPackages) { 4672 return new ArrayList<String>(mPackages.keySet()); 4673 } 4674 } 4675 4676 @Override 4677 public String[] getPackagesForUid(int uid) { 4678 uid = UserHandle.getAppId(uid); 4679 // reader 4680 synchronized (mPackages) { 4681 Object obj = mSettings.getUserIdLPr(uid); 4682 if (obj instanceof SharedUserSetting) { 4683 final SharedUserSetting sus = (SharedUserSetting) obj; 4684 final int N = sus.packages.size(); 4685 final String[] res = new String[N]; 4686 final Iterator<PackageSetting> it = sus.packages.iterator(); 4687 int i = 0; 4688 while (it.hasNext()) { 4689 res[i++] = it.next().name; 4690 } 4691 return res; 4692 } else if (obj instanceof PackageSetting) { 4693 final PackageSetting ps = (PackageSetting) obj; 4694 return new String[] { ps.name }; 4695 } 4696 } 4697 return null; 4698 } 4699 4700 @Override 4701 public String getNameForUid(int uid) { 4702 // reader 4703 synchronized (mPackages) { 4704 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4705 if (obj instanceof SharedUserSetting) { 4706 final SharedUserSetting sus = (SharedUserSetting) obj; 4707 return sus.name + ":" + sus.userId; 4708 } else if (obj instanceof PackageSetting) { 4709 final PackageSetting ps = (PackageSetting) obj; 4710 return ps.name; 4711 } 4712 } 4713 return null; 4714 } 4715 4716 @Override 4717 public int getUidForSharedUser(String sharedUserName) { 4718 if(sharedUserName == null) { 4719 return -1; 4720 } 4721 // reader 4722 synchronized (mPackages) { 4723 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4724 if (suid == null) { 4725 return -1; 4726 } 4727 return suid.userId; 4728 } 4729 } 4730 4731 @Override 4732 public int getFlagsForUid(int uid) { 4733 synchronized (mPackages) { 4734 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4735 if (obj instanceof SharedUserSetting) { 4736 final SharedUserSetting sus = (SharedUserSetting) obj; 4737 return sus.pkgFlags; 4738 } else if (obj instanceof PackageSetting) { 4739 final PackageSetting ps = (PackageSetting) obj; 4740 return ps.pkgFlags; 4741 } 4742 } 4743 return 0; 4744 } 4745 4746 @Override 4747 public int getPrivateFlagsForUid(int uid) { 4748 synchronized (mPackages) { 4749 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4750 if (obj instanceof SharedUserSetting) { 4751 final SharedUserSetting sus = (SharedUserSetting) obj; 4752 return sus.pkgPrivateFlags; 4753 } else if (obj instanceof PackageSetting) { 4754 final PackageSetting ps = (PackageSetting) obj; 4755 return ps.pkgPrivateFlags; 4756 } 4757 } 4758 return 0; 4759 } 4760 4761 @Override 4762 public boolean isUidPrivileged(int uid) { 4763 uid = UserHandle.getAppId(uid); 4764 // reader 4765 synchronized (mPackages) { 4766 Object obj = mSettings.getUserIdLPr(uid); 4767 if (obj instanceof SharedUserSetting) { 4768 final SharedUserSetting sus = (SharedUserSetting) obj; 4769 final Iterator<PackageSetting> it = sus.packages.iterator(); 4770 while (it.hasNext()) { 4771 if (it.next().isPrivileged()) { 4772 return true; 4773 } 4774 } 4775 } else if (obj instanceof PackageSetting) { 4776 final PackageSetting ps = (PackageSetting) obj; 4777 return ps.isPrivileged(); 4778 } 4779 } 4780 return false; 4781 } 4782 4783 @Override 4784 public String[] getAppOpPermissionPackages(String permissionName) { 4785 synchronized (mPackages) { 4786 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4787 if (pkgs == null) { 4788 return null; 4789 } 4790 return pkgs.toArray(new String[pkgs.size()]); 4791 } 4792 } 4793 4794 @Override 4795 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4796 int flags, int userId) { 4797 try { 4798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4799 4800 if (!sUserManager.exists(userId)) return null; 4801 flags = updateFlagsForResolve(flags, userId, intent); 4802 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4803 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4804 4805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4806 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4807 flags, userId); 4808 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4809 4810 final ResolveInfo bestChoice = 4811 chooseBestActivity(intent, resolvedType, flags, query, userId); 4812 4813 if (isEphemeralAllowed(intent, query, userId)) { 4814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4815 final EphemeralResolveInfo ai = 4816 getEphemeralResolveInfo(intent, resolvedType, userId); 4817 if (ai != null) { 4818 if (DEBUG_EPHEMERAL) { 4819 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4820 } 4821 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4822 bestChoice.ephemeralResolveInfo = ai; 4823 } 4824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4825 } 4826 return bestChoice; 4827 } finally { 4828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4829 } 4830 } 4831 4832 @Override 4833 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4834 IntentFilter filter, int match, ComponentName activity) { 4835 final int userId = UserHandle.getCallingUserId(); 4836 if (DEBUG_PREFERRED) { 4837 Log.v(TAG, "setLastChosenActivity intent=" + intent 4838 + " resolvedType=" + resolvedType 4839 + " flags=" + flags 4840 + " filter=" + filter 4841 + " match=" + match 4842 + " activity=" + activity); 4843 filter.dump(new PrintStreamPrinter(System.out), " "); 4844 } 4845 intent.setComponent(null); 4846 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4847 userId); 4848 // Find any earlier preferred or last chosen entries and nuke them 4849 findPreferredActivity(intent, resolvedType, 4850 flags, query, 0, false, true, false, userId); 4851 // Add the new activity as the last chosen for this filter 4852 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4853 "Setting last chosen"); 4854 } 4855 4856 @Override 4857 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4858 final int userId = UserHandle.getCallingUserId(); 4859 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4860 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4861 userId); 4862 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4863 false, false, false, userId); 4864 } 4865 4866 4867 private boolean isEphemeralAllowed( 4868 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4869 // Short circuit and return early if possible. 4870 if (DISABLE_EPHEMERAL_APPS) { 4871 return false; 4872 } 4873 final int callingUser = UserHandle.getCallingUserId(); 4874 if (callingUser != UserHandle.USER_SYSTEM) { 4875 return false; 4876 } 4877 if (mEphemeralResolverConnection == null) { 4878 return false; 4879 } 4880 if (intent.getComponent() != null) { 4881 return false; 4882 } 4883 if (intent.getPackage() != null) { 4884 return false; 4885 } 4886 final boolean isWebUri = hasWebURI(intent); 4887 if (!isWebUri) { 4888 return false; 4889 } 4890 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4891 synchronized (mPackages) { 4892 final int count = resolvedActivites.size(); 4893 for (int n = 0; n < count; n++) { 4894 ResolveInfo info = resolvedActivites.get(n); 4895 String packageName = info.activityInfo.packageName; 4896 PackageSetting ps = mSettings.mPackages.get(packageName); 4897 if (ps != null) { 4898 // Try to get the status from User settings first 4899 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4900 int status = (int) (packedStatus >> 32); 4901 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4902 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4903 if (DEBUG_EPHEMERAL) { 4904 Slog.v(TAG, "DENY ephemeral apps;" 4905 + " pkg: " + packageName + ", status: " + status); 4906 } 4907 return false; 4908 } 4909 } 4910 } 4911 } 4912 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4913 return true; 4914 } 4915 4916 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4917 int userId) { 4918 MessageDigest digest = null; 4919 try { 4920 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4921 } catch (NoSuchAlgorithmException e) { 4922 // If we can't create a digest, ignore ephemeral apps. 4923 return null; 4924 } 4925 4926 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4927 final byte[] digestBytes = digest.digest(hostBytes); 4928 int shaPrefix = 4929 digestBytes[0] << 24 4930 | digestBytes[1] << 16 4931 | digestBytes[2] << 8 4932 | digestBytes[3] << 0; 4933 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4934 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4935 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4936 // No hash prefix match; there are no ephemeral apps for this domain. 4937 return null; 4938 } 4939 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4940 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4941 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4942 continue; 4943 } 4944 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4945 // No filters; this should never happen. 4946 if (filters.isEmpty()) { 4947 continue; 4948 } 4949 // We have a domain match; resolve the filters to see if anything matches. 4950 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4951 for (int j = filters.size() - 1; j >= 0; --j) { 4952 final EphemeralResolveIntentInfo intentInfo = 4953 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4954 ephemeralResolver.addFilter(intentInfo); 4955 } 4956 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4957 intent, resolvedType, false /*defaultOnly*/, userId); 4958 if (!matchedResolveInfoList.isEmpty()) { 4959 return matchedResolveInfoList.get(0); 4960 } 4961 } 4962 // Hash or filter mis-match; no ephemeral apps for this domain. 4963 return null; 4964 } 4965 4966 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4967 int flags, List<ResolveInfo> query, int userId) { 4968 if (query != null) { 4969 final int N = query.size(); 4970 if (N == 1) { 4971 return query.get(0); 4972 } else if (N > 1) { 4973 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4974 // If there is more than one activity with the same priority, 4975 // then let the user decide between them. 4976 ResolveInfo r0 = query.get(0); 4977 ResolveInfo r1 = query.get(1); 4978 if (DEBUG_INTENT_MATCHING || debug) { 4979 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4980 + r1.activityInfo.name + "=" + r1.priority); 4981 } 4982 // If the first activity has a higher priority, or a different 4983 // default, then it is always desirable to pick it. 4984 if (r0.priority != r1.priority 4985 || r0.preferredOrder != r1.preferredOrder 4986 || r0.isDefault != r1.isDefault) { 4987 return query.get(0); 4988 } 4989 // If we have saved a preference for a preferred activity for 4990 // this Intent, use that. 4991 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4992 flags, query, r0.priority, true, false, debug, userId); 4993 if (ri != null) { 4994 return ri; 4995 } 4996 ri = new ResolveInfo(mResolveInfo); 4997 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4998 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4999 ri.activityInfo.applicationInfo = new ApplicationInfo( 5000 ri.activityInfo.applicationInfo); 5001 if (userId != 0) { 5002 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5003 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5004 } 5005 // Make sure that the resolver is displayable in car mode 5006 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5007 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5008 return ri; 5009 } 5010 } 5011 return null; 5012 } 5013 5014 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5015 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5016 final int N = query.size(); 5017 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5018 .get(userId); 5019 // Get the list of persistent preferred activities that handle the intent 5020 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5021 List<PersistentPreferredActivity> pprefs = ppir != null 5022 ? ppir.queryIntent(intent, resolvedType, 5023 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5024 : null; 5025 if (pprefs != null && pprefs.size() > 0) { 5026 final int M = pprefs.size(); 5027 for (int i=0; i<M; i++) { 5028 final PersistentPreferredActivity ppa = pprefs.get(i); 5029 if (DEBUG_PREFERRED || debug) { 5030 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5031 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5032 + "\n component=" + ppa.mComponent); 5033 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5034 } 5035 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5036 flags | MATCH_DISABLED_COMPONENTS, userId); 5037 if (DEBUG_PREFERRED || debug) { 5038 Slog.v(TAG, "Found persistent preferred activity:"); 5039 if (ai != null) { 5040 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5041 } else { 5042 Slog.v(TAG, " null"); 5043 } 5044 } 5045 if (ai == null) { 5046 // This previously registered persistent preferred activity 5047 // component is no longer known. Ignore it and do NOT remove it. 5048 continue; 5049 } 5050 for (int j=0; j<N; j++) { 5051 final ResolveInfo ri = query.get(j); 5052 if (!ri.activityInfo.applicationInfo.packageName 5053 .equals(ai.applicationInfo.packageName)) { 5054 continue; 5055 } 5056 if (!ri.activityInfo.name.equals(ai.name)) { 5057 continue; 5058 } 5059 // Found a persistent preference that can handle the intent. 5060 if (DEBUG_PREFERRED || debug) { 5061 Slog.v(TAG, "Returning persistent preferred activity: " + 5062 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5063 } 5064 return ri; 5065 } 5066 } 5067 } 5068 return null; 5069 } 5070 5071 // TODO: handle preferred activities missing while user has amnesia 5072 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5073 List<ResolveInfo> query, int priority, boolean always, 5074 boolean removeMatches, boolean debug, int userId) { 5075 if (!sUserManager.exists(userId)) return null; 5076 flags = updateFlagsForResolve(flags, userId, intent); 5077 // writer 5078 synchronized (mPackages) { 5079 if (intent.getSelector() != null) { 5080 intent = intent.getSelector(); 5081 } 5082 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5083 5084 // Try to find a matching persistent preferred activity. 5085 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5086 debug, userId); 5087 5088 // If a persistent preferred activity matched, use it. 5089 if (pri != null) { 5090 return pri; 5091 } 5092 5093 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5094 // Get the list of preferred activities that handle the intent 5095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5096 List<PreferredActivity> prefs = pir != null 5097 ? pir.queryIntent(intent, resolvedType, 5098 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5099 : null; 5100 if (prefs != null && prefs.size() > 0) { 5101 boolean changed = false; 5102 try { 5103 // First figure out how good the original match set is. 5104 // We will only allow preferred activities that came 5105 // from the same match quality. 5106 int match = 0; 5107 5108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5109 5110 final int N = query.size(); 5111 for (int j=0; j<N; j++) { 5112 final ResolveInfo ri = query.get(j); 5113 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5114 + ": 0x" + Integer.toHexString(match)); 5115 if (ri.match > match) { 5116 match = ri.match; 5117 } 5118 } 5119 5120 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5121 + Integer.toHexString(match)); 5122 5123 match &= IntentFilter.MATCH_CATEGORY_MASK; 5124 final int M = prefs.size(); 5125 for (int i=0; i<M; i++) { 5126 final PreferredActivity pa = prefs.get(i); 5127 if (DEBUG_PREFERRED || debug) { 5128 Slog.v(TAG, "Checking PreferredActivity ds=" 5129 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5130 + "\n component=" + pa.mPref.mComponent); 5131 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5132 } 5133 if (pa.mPref.mMatch != match) { 5134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5135 + Integer.toHexString(pa.mPref.mMatch)); 5136 continue; 5137 } 5138 // If it's not an "always" type preferred activity and that's what we're 5139 // looking for, skip it. 5140 if (always && !pa.mPref.mAlways) { 5141 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5142 continue; 5143 } 5144 final ActivityInfo ai = getActivityInfo( 5145 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5146 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5147 userId); 5148 if (DEBUG_PREFERRED || debug) { 5149 Slog.v(TAG, "Found preferred activity:"); 5150 if (ai != null) { 5151 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5152 } else { 5153 Slog.v(TAG, " null"); 5154 } 5155 } 5156 if (ai == null) { 5157 // This previously registered preferred activity 5158 // component is no longer known. Most likely an update 5159 // to the app was installed and in the new version this 5160 // component no longer exists. Clean it up by removing 5161 // it from the preferred activities list, and skip it. 5162 Slog.w(TAG, "Removing dangling preferred activity: " 5163 + pa.mPref.mComponent); 5164 pir.removeFilter(pa); 5165 changed = true; 5166 continue; 5167 } 5168 for (int j=0; j<N; j++) { 5169 final ResolveInfo ri = query.get(j); 5170 if (!ri.activityInfo.applicationInfo.packageName 5171 .equals(ai.applicationInfo.packageName)) { 5172 continue; 5173 } 5174 if (!ri.activityInfo.name.equals(ai.name)) { 5175 continue; 5176 } 5177 5178 if (removeMatches) { 5179 pir.removeFilter(pa); 5180 changed = true; 5181 if (DEBUG_PREFERRED) { 5182 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5183 } 5184 break; 5185 } 5186 5187 // Okay we found a previously set preferred or last chosen app. 5188 // If the result set is different from when this 5189 // was created, we need to clear it and re-ask the 5190 // user their preference, if we're looking for an "always" type entry. 5191 if (always && !pa.mPref.sameSet(query)) { 5192 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5193 + intent + " type " + resolvedType); 5194 if (DEBUG_PREFERRED) { 5195 Slog.v(TAG, "Removing preferred activity since set changed " 5196 + pa.mPref.mComponent); 5197 } 5198 pir.removeFilter(pa); 5199 // Re-add the filter as a "last chosen" entry (!always) 5200 PreferredActivity lastChosen = new PreferredActivity( 5201 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5202 pir.addFilter(lastChosen); 5203 changed = true; 5204 return null; 5205 } 5206 5207 // Yay! Either the set matched or we're looking for the last chosen 5208 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5209 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5210 return ri; 5211 } 5212 } 5213 } finally { 5214 if (changed) { 5215 if (DEBUG_PREFERRED) { 5216 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5217 } 5218 scheduleWritePackageRestrictionsLocked(userId); 5219 } 5220 } 5221 } 5222 } 5223 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5224 return null; 5225 } 5226 5227 /* 5228 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5229 */ 5230 @Override 5231 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5232 int targetUserId) { 5233 mContext.enforceCallingOrSelfPermission( 5234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5235 List<CrossProfileIntentFilter> matches = 5236 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5237 if (matches != null) { 5238 int size = matches.size(); 5239 for (int i = 0; i < size; i++) { 5240 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5241 } 5242 } 5243 if (hasWebURI(intent)) { 5244 // cross-profile app linking works only towards the parent. 5245 final UserInfo parent = getProfileParent(sourceUserId); 5246 synchronized(mPackages) { 5247 int flags = updateFlagsForResolve(0, parent.id, intent); 5248 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5249 intent, resolvedType, flags, sourceUserId, parent.id); 5250 return xpDomainInfo != null; 5251 } 5252 } 5253 return false; 5254 } 5255 5256 private UserInfo getProfileParent(int userId) { 5257 final long identity = Binder.clearCallingIdentity(); 5258 try { 5259 return sUserManager.getProfileParent(userId); 5260 } finally { 5261 Binder.restoreCallingIdentity(identity); 5262 } 5263 } 5264 5265 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5266 String resolvedType, int userId) { 5267 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5268 if (resolver != null) { 5269 return resolver.queryIntent(intent, resolvedType, false, userId); 5270 } 5271 return null; 5272 } 5273 5274 @Override 5275 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5276 String resolvedType, int flags, int userId) { 5277 try { 5278 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5279 5280 return new ParceledListSlice<>( 5281 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5282 } finally { 5283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5284 } 5285 } 5286 5287 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5288 String resolvedType, int flags, int userId) { 5289 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5290 flags = updateFlagsForResolve(flags, userId, intent); 5291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5292 false /* requireFullPermission */, false /* checkShell */, 5293 "query intent activities"); 5294 ComponentName comp = intent.getComponent(); 5295 if (comp == null) { 5296 if (intent.getSelector() != null) { 5297 intent = intent.getSelector(); 5298 comp = intent.getComponent(); 5299 } 5300 } 5301 5302 if (comp != null) { 5303 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5304 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5305 if (ai != null) { 5306 final ResolveInfo ri = new ResolveInfo(); 5307 ri.activityInfo = ai; 5308 list.add(ri); 5309 } 5310 return list; 5311 } 5312 5313 // reader 5314 synchronized (mPackages) { 5315 final String pkgName = intent.getPackage(); 5316 if (pkgName == null) { 5317 List<CrossProfileIntentFilter> matchingFilters = 5318 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5319 // Check for results that need to skip the current profile. 5320 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5321 resolvedType, flags, userId); 5322 if (xpResolveInfo != null) { 5323 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5324 result.add(xpResolveInfo); 5325 return filterIfNotSystemUser(result, userId); 5326 } 5327 5328 // Check for results in the current profile. 5329 List<ResolveInfo> result = mActivities.queryIntent( 5330 intent, resolvedType, flags, userId); 5331 result = filterIfNotSystemUser(result, userId); 5332 5333 // Check for cross profile results. 5334 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5335 xpResolveInfo = queryCrossProfileIntents( 5336 matchingFilters, intent, resolvedType, flags, userId, 5337 hasNonNegativePriorityResult); 5338 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5339 boolean isVisibleToUser = filterIfNotSystemUser( 5340 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5341 if (isVisibleToUser) { 5342 result.add(xpResolveInfo); 5343 Collections.sort(result, mResolvePrioritySorter); 5344 } 5345 } 5346 if (hasWebURI(intent)) { 5347 CrossProfileDomainInfo xpDomainInfo = null; 5348 final UserInfo parent = getProfileParent(userId); 5349 if (parent != null) { 5350 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5351 flags, userId, parent.id); 5352 } 5353 if (xpDomainInfo != null) { 5354 if (xpResolveInfo != null) { 5355 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5356 // in the result. 5357 result.remove(xpResolveInfo); 5358 } 5359 if (result.size() == 0) { 5360 result.add(xpDomainInfo.resolveInfo); 5361 return result; 5362 } 5363 } else if (result.size() <= 1) { 5364 return result; 5365 } 5366 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5367 xpDomainInfo, userId); 5368 Collections.sort(result, mResolvePrioritySorter); 5369 } 5370 return result; 5371 } 5372 final PackageParser.Package pkg = mPackages.get(pkgName); 5373 if (pkg != null) { 5374 return filterIfNotSystemUser( 5375 mActivities.queryIntentForPackage( 5376 intent, resolvedType, flags, pkg.activities, userId), 5377 userId); 5378 } 5379 return new ArrayList<ResolveInfo>(); 5380 } 5381 } 5382 5383 private static class CrossProfileDomainInfo { 5384 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5385 ResolveInfo resolveInfo; 5386 /* Best domain verification status of the activities found in the other profile */ 5387 int bestDomainVerificationStatus; 5388 } 5389 5390 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5391 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5392 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5393 sourceUserId)) { 5394 return null; 5395 } 5396 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5397 resolvedType, flags, parentUserId); 5398 5399 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5400 return null; 5401 } 5402 CrossProfileDomainInfo result = null; 5403 int size = resultTargetUser.size(); 5404 for (int i = 0; i < size; i++) { 5405 ResolveInfo riTargetUser = resultTargetUser.get(i); 5406 // Intent filter verification is only for filters that specify a host. So don't return 5407 // those that handle all web uris. 5408 if (riTargetUser.handleAllWebDataURI) { 5409 continue; 5410 } 5411 String packageName = riTargetUser.activityInfo.packageName; 5412 PackageSetting ps = mSettings.mPackages.get(packageName); 5413 if (ps == null) { 5414 continue; 5415 } 5416 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5417 int status = (int)(verificationState >> 32); 5418 if (result == null) { 5419 result = new CrossProfileDomainInfo(); 5420 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5421 sourceUserId, parentUserId); 5422 result.bestDomainVerificationStatus = status; 5423 } else { 5424 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5425 result.bestDomainVerificationStatus); 5426 } 5427 } 5428 // Don't consider matches with status NEVER across profiles. 5429 if (result != null && result.bestDomainVerificationStatus 5430 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5431 return null; 5432 } 5433 return result; 5434 } 5435 5436 /** 5437 * Verification statuses are ordered from the worse to the best, except for 5438 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5439 */ 5440 private int bestDomainVerificationStatus(int status1, int status2) { 5441 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5442 return status2; 5443 } 5444 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5445 return status1; 5446 } 5447 return (int) MathUtils.max(status1, status2); 5448 } 5449 5450 private boolean isUserEnabled(int userId) { 5451 long callingId = Binder.clearCallingIdentity(); 5452 try { 5453 UserInfo userInfo = sUserManager.getUserInfo(userId); 5454 return userInfo != null && userInfo.isEnabled(); 5455 } finally { 5456 Binder.restoreCallingIdentity(callingId); 5457 } 5458 } 5459 5460 /** 5461 * Filter out activities with systemUserOnly flag set, when current user is not System. 5462 * 5463 * @return filtered list 5464 */ 5465 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5466 if (userId == UserHandle.USER_SYSTEM) { 5467 return resolveInfos; 5468 } 5469 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5470 ResolveInfo info = resolveInfos.get(i); 5471 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5472 resolveInfos.remove(i); 5473 } 5474 } 5475 return resolveInfos; 5476 } 5477 5478 /** 5479 * @param resolveInfos list of resolve infos in descending priority order 5480 * @return if the list contains a resolve info with non-negative priority 5481 */ 5482 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5483 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5484 } 5485 5486 private static boolean hasWebURI(Intent intent) { 5487 if (intent.getData() == null) { 5488 return false; 5489 } 5490 final String scheme = intent.getScheme(); 5491 if (TextUtils.isEmpty(scheme)) { 5492 return false; 5493 } 5494 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5495 } 5496 5497 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5498 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5499 int userId) { 5500 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5501 5502 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5503 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5504 candidates.size()); 5505 } 5506 5507 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5508 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5509 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5510 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5511 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5513 5514 synchronized (mPackages) { 5515 final int count = candidates.size(); 5516 // First, try to use linked apps. Partition the candidates into four lists: 5517 // one for the final results, one for the "do not use ever", one for "undefined status" 5518 // and finally one for "browser app type". 5519 for (int n=0; n<count; n++) { 5520 ResolveInfo info = candidates.get(n); 5521 String packageName = info.activityInfo.packageName; 5522 PackageSetting ps = mSettings.mPackages.get(packageName); 5523 if (ps != null) { 5524 // Add to the special match all list (Browser use case) 5525 if (info.handleAllWebDataURI) { 5526 matchAllList.add(info); 5527 continue; 5528 } 5529 // Try to get the status from User settings first 5530 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5531 int status = (int)(packedStatus >> 32); 5532 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5533 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5534 if (DEBUG_DOMAIN_VERIFICATION) { 5535 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5536 + " : linkgen=" + linkGeneration); 5537 } 5538 // Use link-enabled generation as preferredOrder, i.e. 5539 // prefer newly-enabled over earlier-enabled. 5540 info.preferredOrder = linkGeneration; 5541 alwaysList.add(info); 5542 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5543 if (DEBUG_DOMAIN_VERIFICATION) { 5544 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5545 } 5546 neverList.add(info); 5547 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5548 if (DEBUG_DOMAIN_VERIFICATION) { 5549 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5550 } 5551 alwaysAskList.add(info); 5552 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5553 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5554 if (DEBUG_DOMAIN_VERIFICATION) { 5555 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5556 } 5557 undefinedList.add(info); 5558 } 5559 } 5560 } 5561 5562 // We'll want to include browser possibilities in a few cases 5563 boolean includeBrowser = false; 5564 5565 // First try to add the "always" resolution(s) for the current user, if any 5566 if (alwaysList.size() > 0) { 5567 result.addAll(alwaysList); 5568 } else { 5569 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5570 result.addAll(undefinedList); 5571 // Maybe add one for the other profile. 5572 if (xpDomainInfo != null && ( 5573 xpDomainInfo.bestDomainVerificationStatus 5574 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5575 result.add(xpDomainInfo.resolveInfo); 5576 } 5577 includeBrowser = true; 5578 } 5579 5580 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5581 // If there were 'always' entries their preferred order has been set, so we also 5582 // back that off to make the alternatives equivalent 5583 if (alwaysAskList.size() > 0) { 5584 for (ResolveInfo i : result) { 5585 i.preferredOrder = 0; 5586 } 5587 result.addAll(alwaysAskList); 5588 includeBrowser = true; 5589 } 5590 5591 if (includeBrowser) { 5592 // Also add browsers (all of them or only the default one) 5593 if (DEBUG_DOMAIN_VERIFICATION) { 5594 Slog.v(TAG, " ...including browsers in candidate set"); 5595 } 5596 if ((matchFlags & MATCH_ALL) != 0) { 5597 result.addAll(matchAllList); 5598 } else { 5599 // Browser/generic handling case. If there's a default browser, go straight 5600 // to that (but only if there is no other higher-priority match). 5601 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5602 int maxMatchPrio = 0; 5603 ResolveInfo defaultBrowserMatch = null; 5604 final int numCandidates = matchAllList.size(); 5605 for (int n = 0; n < numCandidates; n++) { 5606 ResolveInfo info = matchAllList.get(n); 5607 // track the highest overall match priority... 5608 if (info.priority > maxMatchPrio) { 5609 maxMatchPrio = info.priority; 5610 } 5611 // ...and the highest-priority default browser match 5612 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5613 if (defaultBrowserMatch == null 5614 || (defaultBrowserMatch.priority < info.priority)) { 5615 if (debug) { 5616 Slog.v(TAG, "Considering default browser match " + info); 5617 } 5618 defaultBrowserMatch = info; 5619 } 5620 } 5621 } 5622 if (defaultBrowserMatch != null 5623 && defaultBrowserMatch.priority >= maxMatchPrio 5624 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5625 { 5626 if (debug) { 5627 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5628 } 5629 result.add(defaultBrowserMatch); 5630 } else { 5631 result.addAll(matchAllList); 5632 } 5633 } 5634 5635 // If there is nothing selected, add all candidates and remove the ones that the user 5636 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5637 if (result.size() == 0) { 5638 result.addAll(candidates); 5639 result.removeAll(neverList); 5640 } 5641 } 5642 } 5643 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5644 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5645 result.size()); 5646 for (ResolveInfo info : result) { 5647 Slog.v(TAG, " + " + info.activityInfo); 5648 } 5649 } 5650 return result; 5651 } 5652 5653 // Returns a packed value as a long: 5654 // 5655 // high 'int'-sized word: link status: undefined/ask/never/always. 5656 // low 'int'-sized word: relative priority among 'always' results. 5657 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5658 long result = ps.getDomainVerificationStatusForUser(userId); 5659 // if none available, get the master status 5660 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5661 if (ps.getIntentFilterVerificationInfo() != null) { 5662 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5663 } 5664 } 5665 return result; 5666 } 5667 5668 private ResolveInfo querySkipCurrentProfileIntents( 5669 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5670 int flags, int sourceUserId) { 5671 if (matchingFilters != null) { 5672 int size = matchingFilters.size(); 5673 for (int i = 0; i < size; i ++) { 5674 CrossProfileIntentFilter filter = matchingFilters.get(i); 5675 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5676 // Checking if there are activities in the target user that can handle the 5677 // intent. 5678 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5679 resolvedType, flags, sourceUserId); 5680 if (resolveInfo != null) { 5681 return resolveInfo; 5682 } 5683 } 5684 } 5685 } 5686 return null; 5687 } 5688 5689 // Return matching ResolveInfo in target user if any. 5690 private ResolveInfo queryCrossProfileIntents( 5691 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5692 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5693 if (matchingFilters != null) { 5694 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5695 // match the same intent. For performance reasons, it is better not to 5696 // run queryIntent twice for the same userId 5697 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5698 int size = matchingFilters.size(); 5699 for (int i = 0; i < size; i++) { 5700 CrossProfileIntentFilter filter = matchingFilters.get(i); 5701 int targetUserId = filter.getTargetUserId(); 5702 boolean skipCurrentProfile = 5703 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5704 boolean skipCurrentProfileIfNoMatchFound = 5705 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5706 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5707 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5708 // Checking if there are activities in the target user that can handle the 5709 // intent. 5710 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5711 resolvedType, flags, sourceUserId); 5712 if (resolveInfo != null) return resolveInfo; 5713 alreadyTriedUserIds.put(targetUserId, true); 5714 } 5715 } 5716 } 5717 return null; 5718 } 5719 5720 /** 5721 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5722 * will forward the intent to the filter's target user. 5723 * Otherwise, returns null. 5724 */ 5725 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5726 String resolvedType, int flags, int sourceUserId) { 5727 int targetUserId = filter.getTargetUserId(); 5728 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5729 resolvedType, flags, targetUserId); 5730 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5731 // If all the matches in the target profile are suspended, return null. 5732 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5733 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5734 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5735 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5736 targetUserId); 5737 } 5738 } 5739 } 5740 return null; 5741 } 5742 5743 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5744 int sourceUserId, int targetUserId) { 5745 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5746 long ident = Binder.clearCallingIdentity(); 5747 boolean targetIsProfile; 5748 try { 5749 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5750 } finally { 5751 Binder.restoreCallingIdentity(ident); 5752 } 5753 String className; 5754 if (targetIsProfile) { 5755 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5756 } else { 5757 className = FORWARD_INTENT_TO_PARENT; 5758 } 5759 ComponentName forwardingActivityComponentName = new ComponentName( 5760 mAndroidApplication.packageName, className); 5761 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5762 sourceUserId); 5763 if (!targetIsProfile) { 5764 forwardingActivityInfo.showUserIcon = targetUserId; 5765 forwardingResolveInfo.noResourceId = true; 5766 } 5767 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5768 forwardingResolveInfo.priority = 0; 5769 forwardingResolveInfo.preferredOrder = 0; 5770 forwardingResolveInfo.match = 0; 5771 forwardingResolveInfo.isDefault = true; 5772 forwardingResolveInfo.filter = filter; 5773 forwardingResolveInfo.targetUserId = targetUserId; 5774 return forwardingResolveInfo; 5775 } 5776 5777 @Override 5778 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5779 Intent[] specifics, String[] specificTypes, Intent intent, 5780 String resolvedType, int flags, int userId) { 5781 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5782 specificTypes, intent, resolvedType, flags, userId)); 5783 } 5784 5785 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5786 Intent[] specifics, String[] specificTypes, Intent intent, 5787 String resolvedType, int flags, int userId) { 5788 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5789 flags = updateFlagsForResolve(flags, userId, intent); 5790 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5791 false /* requireFullPermission */, false /* checkShell */, 5792 "query intent activity options"); 5793 final String resultsAction = intent.getAction(); 5794 5795 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5796 | PackageManager.GET_RESOLVED_FILTER, userId); 5797 5798 if (DEBUG_INTENT_MATCHING) { 5799 Log.v(TAG, "Query " + intent + ": " + results); 5800 } 5801 5802 int specificsPos = 0; 5803 int N; 5804 5805 // todo: note that the algorithm used here is O(N^2). This 5806 // isn't a problem in our current environment, but if we start running 5807 // into situations where we have more than 5 or 10 matches then this 5808 // should probably be changed to something smarter... 5809 5810 // First we go through and resolve each of the specific items 5811 // that were supplied, taking care of removing any corresponding 5812 // duplicate items in the generic resolve list. 5813 if (specifics != null) { 5814 for (int i=0; i<specifics.length; i++) { 5815 final Intent sintent = specifics[i]; 5816 if (sintent == null) { 5817 continue; 5818 } 5819 5820 if (DEBUG_INTENT_MATCHING) { 5821 Log.v(TAG, "Specific #" + i + ": " + sintent); 5822 } 5823 5824 String action = sintent.getAction(); 5825 if (resultsAction != null && resultsAction.equals(action)) { 5826 // If this action was explicitly requested, then don't 5827 // remove things that have it. 5828 action = null; 5829 } 5830 5831 ResolveInfo ri = null; 5832 ActivityInfo ai = null; 5833 5834 ComponentName comp = sintent.getComponent(); 5835 if (comp == null) { 5836 ri = resolveIntent( 5837 sintent, 5838 specificTypes != null ? specificTypes[i] : null, 5839 flags, userId); 5840 if (ri == null) { 5841 continue; 5842 } 5843 if (ri == mResolveInfo) { 5844 // ACK! Must do something better with this. 5845 } 5846 ai = ri.activityInfo; 5847 comp = new ComponentName(ai.applicationInfo.packageName, 5848 ai.name); 5849 } else { 5850 ai = getActivityInfo(comp, flags, userId); 5851 if (ai == null) { 5852 continue; 5853 } 5854 } 5855 5856 // Look for any generic query activities that are duplicates 5857 // of this specific one, and remove them from the results. 5858 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5859 N = results.size(); 5860 int j; 5861 for (j=specificsPos; j<N; j++) { 5862 ResolveInfo sri = results.get(j); 5863 if ((sri.activityInfo.name.equals(comp.getClassName()) 5864 && sri.activityInfo.applicationInfo.packageName.equals( 5865 comp.getPackageName())) 5866 || (action != null && sri.filter.matchAction(action))) { 5867 results.remove(j); 5868 if (DEBUG_INTENT_MATCHING) Log.v( 5869 TAG, "Removing duplicate item from " + j 5870 + " due to specific " + specificsPos); 5871 if (ri == null) { 5872 ri = sri; 5873 } 5874 j--; 5875 N--; 5876 } 5877 } 5878 5879 // Add this specific item to its proper place. 5880 if (ri == null) { 5881 ri = new ResolveInfo(); 5882 ri.activityInfo = ai; 5883 } 5884 results.add(specificsPos, ri); 5885 ri.specificIndex = i; 5886 specificsPos++; 5887 } 5888 } 5889 5890 // Now we go through the remaining generic results and remove any 5891 // duplicate actions that are found here. 5892 N = results.size(); 5893 for (int i=specificsPos; i<N-1; i++) { 5894 final ResolveInfo rii = results.get(i); 5895 if (rii.filter == null) { 5896 continue; 5897 } 5898 5899 // Iterate over all of the actions of this result's intent 5900 // filter... typically this should be just one. 5901 final Iterator<String> it = rii.filter.actionsIterator(); 5902 if (it == null) { 5903 continue; 5904 } 5905 while (it.hasNext()) { 5906 final String action = it.next(); 5907 if (resultsAction != null && resultsAction.equals(action)) { 5908 // If this action was explicitly requested, then don't 5909 // remove things that have it. 5910 continue; 5911 } 5912 for (int j=i+1; j<N; j++) { 5913 final ResolveInfo rij = results.get(j); 5914 if (rij.filter != null && rij.filter.hasAction(action)) { 5915 results.remove(j); 5916 if (DEBUG_INTENT_MATCHING) Log.v( 5917 TAG, "Removing duplicate item from " + j 5918 + " due to action " + action + " at " + i); 5919 j--; 5920 N--; 5921 } 5922 } 5923 } 5924 5925 // If the caller didn't request filter information, drop it now 5926 // so we don't have to marshall/unmarshall it. 5927 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5928 rii.filter = null; 5929 } 5930 } 5931 5932 // Filter out the caller activity if so requested. 5933 if (caller != null) { 5934 N = results.size(); 5935 for (int i=0; i<N; i++) { 5936 ActivityInfo ainfo = results.get(i).activityInfo; 5937 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5938 && caller.getClassName().equals(ainfo.name)) { 5939 results.remove(i); 5940 break; 5941 } 5942 } 5943 } 5944 5945 // If the caller didn't request filter information, 5946 // drop them now so we don't have to 5947 // marshall/unmarshall it. 5948 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5949 N = results.size(); 5950 for (int i=0; i<N; i++) { 5951 results.get(i).filter = null; 5952 } 5953 } 5954 5955 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5956 return results; 5957 } 5958 5959 @Override 5960 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5961 String resolvedType, int flags, int userId) { 5962 return new ParceledListSlice<>( 5963 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5964 } 5965 5966 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5967 String resolvedType, int flags, int userId) { 5968 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5969 flags = updateFlagsForResolve(flags, userId, intent); 5970 ComponentName comp = intent.getComponent(); 5971 if (comp == null) { 5972 if (intent.getSelector() != null) { 5973 intent = intent.getSelector(); 5974 comp = intent.getComponent(); 5975 } 5976 } 5977 if (comp != null) { 5978 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5979 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5980 if (ai != null) { 5981 ResolveInfo ri = new ResolveInfo(); 5982 ri.activityInfo = ai; 5983 list.add(ri); 5984 } 5985 return list; 5986 } 5987 5988 // reader 5989 synchronized (mPackages) { 5990 String pkgName = intent.getPackage(); 5991 if (pkgName == null) { 5992 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5993 } 5994 final PackageParser.Package pkg = mPackages.get(pkgName); 5995 if (pkg != null) { 5996 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5997 userId); 5998 } 5999 return Collections.emptyList(); 6000 } 6001 } 6002 6003 @Override 6004 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6005 if (!sUserManager.exists(userId)) return null; 6006 flags = updateFlagsForResolve(flags, userId, intent); 6007 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6008 if (query != null) { 6009 if (query.size() >= 1) { 6010 // If there is more than one service with the same priority, 6011 // just arbitrarily pick the first one. 6012 return query.get(0); 6013 } 6014 } 6015 return null; 6016 } 6017 6018 @Override 6019 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6020 String resolvedType, int flags, int userId) { 6021 return new ParceledListSlice<>( 6022 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6023 } 6024 6025 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6026 String resolvedType, int flags, int userId) { 6027 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6028 flags = updateFlagsForResolve(flags, userId, intent); 6029 ComponentName comp = intent.getComponent(); 6030 if (comp == null) { 6031 if (intent.getSelector() != null) { 6032 intent = intent.getSelector(); 6033 comp = intent.getComponent(); 6034 } 6035 } 6036 if (comp != null) { 6037 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6038 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6039 if (si != null) { 6040 final ResolveInfo ri = new ResolveInfo(); 6041 ri.serviceInfo = si; 6042 list.add(ri); 6043 } 6044 return list; 6045 } 6046 6047 // reader 6048 synchronized (mPackages) { 6049 String pkgName = intent.getPackage(); 6050 if (pkgName == null) { 6051 return mServices.queryIntent(intent, resolvedType, flags, userId); 6052 } 6053 final PackageParser.Package pkg = mPackages.get(pkgName); 6054 if (pkg != null) { 6055 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6056 userId); 6057 } 6058 return Collections.emptyList(); 6059 } 6060 } 6061 6062 @Override 6063 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6064 String resolvedType, int flags, int userId) { 6065 return new ParceledListSlice<>( 6066 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6067 } 6068 6069 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6070 Intent intent, String resolvedType, int flags, int userId) { 6071 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6072 flags = updateFlagsForResolve(flags, userId, intent); 6073 ComponentName comp = intent.getComponent(); 6074 if (comp == null) { 6075 if (intent.getSelector() != null) { 6076 intent = intent.getSelector(); 6077 comp = intent.getComponent(); 6078 } 6079 } 6080 if (comp != null) { 6081 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6082 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6083 if (pi != null) { 6084 final ResolveInfo ri = new ResolveInfo(); 6085 ri.providerInfo = pi; 6086 list.add(ri); 6087 } 6088 return list; 6089 } 6090 6091 // reader 6092 synchronized (mPackages) { 6093 String pkgName = intent.getPackage(); 6094 if (pkgName == null) { 6095 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6096 } 6097 final PackageParser.Package pkg = mPackages.get(pkgName); 6098 if (pkg != null) { 6099 return mProviders.queryIntentForPackage( 6100 intent, resolvedType, flags, pkg.providers, userId); 6101 } 6102 return Collections.emptyList(); 6103 } 6104 } 6105 6106 @Override 6107 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6108 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6109 flags = updateFlagsForPackage(flags, userId, null); 6110 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6111 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6112 true /* requireFullPermission */, false /* checkShell */, 6113 "get installed packages"); 6114 6115 // writer 6116 synchronized (mPackages) { 6117 ArrayList<PackageInfo> list; 6118 if (listUninstalled) { 6119 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6120 for (PackageSetting ps : mSettings.mPackages.values()) { 6121 final PackageInfo pi; 6122 if (ps.pkg != null) { 6123 pi = generatePackageInfo(ps, flags, userId); 6124 } else { 6125 pi = generatePackageInfo(ps, flags, userId); 6126 } 6127 if (pi != null) { 6128 list.add(pi); 6129 } 6130 } 6131 } else { 6132 list = new ArrayList<PackageInfo>(mPackages.size()); 6133 for (PackageParser.Package p : mPackages.values()) { 6134 final PackageInfo pi = 6135 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6136 if (pi != null) { 6137 list.add(pi); 6138 } 6139 } 6140 } 6141 6142 return new ParceledListSlice<PackageInfo>(list); 6143 } 6144 } 6145 6146 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6147 String[] permissions, boolean[] tmp, int flags, int userId) { 6148 int numMatch = 0; 6149 final PermissionsState permissionsState = ps.getPermissionsState(); 6150 for (int i=0; i<permissions.length; i++) { 6151 final String permission = permissions[i]; 6152 if (permissionsState.hasPermission(permission, userId)) { 6153 tmp[i] = true; 6154 numMatch++; 6155 } else { 6156 tmp[i] = false; 6157 } 6158 } 6159 if (numMatch == 0) { 6160 return; 6161 } 6162 final PackageInfo pi; 6163 if (ps.pkg != null) { 6164 pi = generatePackageInfo(ps, flags, userId); 6165 } else { 6166 pi = generatePackageInfo(ps, flags, userId); 6167 } 6168 // The above might return null in cases of uninstalled apps or install-state 6169 // skew across users/profiles. 6170 if (pi != null) { 6171 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6172 if (numMatch == permissions.length) { 6173 pi.requestedPermissions = permissions; 6174 } else { 6175 pi.requestedPermissions = new String[numMatch]; 6176 numMatch = 0; 6177 for (int i=0; i<permissions.length; i++) { 6178 if (tmp[i]) { 6179 pi.requestedPermissions[numMatch] = permissions[i]; 6180 numMatch++; 6181 } 6182 } 6183 } 6184 } 6185 list.add(pi); 6186 } 6187 } 6188 6189 @Override 6190 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6191 String[] permissions, int flags, int userId) { 6192 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6193 flags = updateFlagsForPackage(flags, userId, permissions); 6194 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6195 6196 // writer 6197 synchronized (mPackages) { 6198 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6199 boolean[] tmpBools = new boolean[permissions.length]; 6200 if (listUninstalled) { 6201 for (PackageSetting ps : mSettings.mPackages.values()) { 6202 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6203 } 6204 } else { 6205 for (PackageParser.Package pkg : mPackages.values()) { 6206 PackageSetting ps = (PackageSetting)pkg.mExtras; 6207 if (ps != null) { 6208 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6209 userId); 6210 } 6211 } 6212 } 6213 6214 return new ParceledListSlice<PackageInfo>(list); 6215 } 6216 } 6217 6218 @Override 6219 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6220 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6221 flags = updateFlagsForApplication(flags, userId, null); 6222 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6223 6224 // writer 6225 synchronized (mPackages) { 6226 ArrayList<ApplicationInfo> list; 6227 if (listUninstalled) { 6228 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6229 for (PackageSetting ps : mSettings.mPackages.values()) { 6230 ApplicationInfo ai; 6231 if (ps.pkg != null) { 6232 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6233 ps.readUserState(userId), userId); 6234 } else { 6235 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6236 } 6237 if (ai != null) { 6238 list.add(ai); 6239 } 6240 } 6241 } else { 6242 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6243 for (PackageParser.Package p : mPackages.values()) { 6244 if (p.mExtras != null) { 6245 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6246 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6247 if (ai != null) { 6248 list.add(ai); 6249 } 6250 } 6251 } 6252 } 6253 6254 return new ParceledListSlice<ApplicationInfo>(list); 6255 } 6256 } 6257 6258 @Override 6259 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6260 if (DISABLE_EPHEMERAL_APPS) { 6261 return null; 6262 } 6263 6264 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6265 "getEphemeralApplications"); 6266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6267 true /* requireFullPermission */, false /* checkShell */, 6268 "getEphemeralApplications"); 6269 synchronized (mPackages) { 6270 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6271 .getEphemeralApplicationsLPw(userId); 6272 if (ephemeralApps != null) { 6273 return new ParceledListSlice<>(ephemeralApps); 6274 } 6275 } 6276 return null; 6277 } 6278 6279 @Override 6280 public boolean isEphemeralApplication(String packageName, int userId) { 6281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6282 true /* requireFullPermission */, false /* checkShell */, 6283 "isEphemeral"); 6284 if (DISABLE_EPHEMERAL_APPS) { 6285 return false; 6286 } 6287 6288 if (!isCallerSameApp(packageName)) { 6289 return false; 6290 } 6291 synchronized (mPackages) { 6292 PackageParser.Package pkg = mPackages.get(packageName); 6293 if (pkg != null) { 6294 return pkg.applicationInfo.isEphemeralApp(); 6295 } 6296 } 6297 return false; 6298 } 6299 6300 @Override 6301 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6302 if (DISABLE_EPHEMERAL_APPS) { 6303 return null; 6304 } 6305 6306 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6307 true /* requireFullPermission */, false /* checkShell */, 6308 "getCookie"); 6309 if (!isCallerSameApp(packageName)) { 6310 return null; 6311 } 6312 synchronized (mPackages) { 6313 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6314 packageName, userId); 6315 } 6316 } 6317 6318 @Override 6319 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6320 if (DISABLE_EPHEMERAL_APPS) { 6321 return true; 6322 } 6323 6324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6325 true /* requireFullPermission */, true /* checkShell */, 6326 "setCookie"); 6327 if (!isCallerSameApp(packageName)) { 6328 return false; 6329 } 6330 synchronized (mPackages) { 6331 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6332 packageName, cookie, userId); 6333 } 6334 } 6335 6336 @Override 6337 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6338 if (DISABLE_EPHEMERAL_APPS) { 6339 return null; 6340 } 6341 6342 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6343 "getEphemeralApplicationIcon"); 6344 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6345 true /* requireFullPermission */, false /* checkShell */, 6346 "getEphemeralApplicationIcon"); 6347 synchronized (mPackages) { 6348 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6349 packageName, userId); 6350 } 6351 } 6352 6353 private boolean isCallerSameApp(String packageName) { 6354 PackageParser.Package pkg = mPackages.get(packageName); 6355 return pkg != null 6356 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6357 } 6358 6359 @Override 6360 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6361 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6362 } 6363 6364 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6365 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6366 6367 // reader 6368 synchronized (mPackages) { 6369 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6370 final int userId = UserHandle.getCallingUserId(); 6371 while (i.hasNext()) { 6372 final PackageParser.Package p = i.next(); 6373 if (p.applicationInfo == null) continue; 6374 6375 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6376 && !p.applicationInfo.isDirectBootAware(); 6377 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6378 && p.applicationInfo.isDirectBootAware(); 6379 6380 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6381 && (!mSafeMode || isSystemApp(p)) 6382 && (matchesUnaware || matchesAware)) { 6383 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6384 if (ps != null) { 6385 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6386 ps.readUserState(userId), userId); 6387 if (ai != null) { 6388 finalList.add(ai); 6389 } 6390 } 6391 } 6392 } 6393 } 6394 6395 return finalList; 6396 } 6397 6398 @Override 6399 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6400 if (!sUserManager.exists(userId)) return null; 6401 flags = updateFlagsForComponent(flags, userId, name); 6402 // reader 6403 synchronized (mPackages) { 6404 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6405 PackageSetting ps = provider != null 6406 ? mSettings.mPackages.get(provider.owner.packageName) 6407 : null; 6408 return ps != null 6409 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6410 ? PackageParser.generateProviderInfo(provider, flags, 6411 ps.readUserState(userId), userId) 6412 : null; 6413 } 6414 } 6415 6416 /** 6417 * @deprecated 6418 */ 6419 @Deprecated 6420 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6421 // reader 6422 synchronized (mPackages) { 6423 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6424 .entrySet().iterator(); 6425 final int userId = UserHandle.getCallingUserId(); 6426 while (i.hasNext()) { 6427 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6428 PackageParser.Provider p = entry.getValue(); 6429 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6430 6431 if (ps != null && p.syncable 6432 && (!mSafeMode || (p.info.applicationInfo.flags 6433 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6434 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6435 ps.readUserState(userId), userId); 6436 if (info != null) { 6437 outNames.add(entry.getKey()); 6438 outInfo.add(info); 6439 } 6440 } 6441 } 6442 } 6443 } 6444 6445 @Override 6446 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6447 int uid, int flags) { 6448 final int userId = processName != null ? UserHandle.getUserId(uid) 6449 : UserHandle.getCallingUserId(); 6450 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6451 flags = updateFlagsForComponent(flags, userId, processName); 6452 6453 ArrayList<ProviderInfo> finalList = null; 6454 // reader 6455 synchronized (mPackages) { 6456 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6457 while (i.hasNext()) { 6458 final PackageParser.Provider p = i.next(); 6459 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6460 if (ps != null && p.info.authority != null 6461 && (processName == null 6462 || (p.info.processName.equals(processName) 6463 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6464 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6465 if (finalList == null) { 6466 finalList = new ArrayList<ProviderInfo>(3); 6467 } 6468 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6469 ps.readUserState(userId), userId); 6470 if (info != null) { 6471 finalList.add(info); 6472 } 6473 } 6474 } 6475 } 6476 6477 if (finalList != null) { 6478 Collections.sort(finalList, mProviderInitOrderSorter); 6479 return new ParceledListSlice<ProviderInfo>(finalList); 6480 } 6481 6482 return ParceledListSlice.emptyList(); 6483 } 6484 6485 @Override 6486 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6487 // reader 6488 synchronized (mPackages) { 6489 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6490 return PackageParser.generateInstrumentationInfo(i, flags); 6491 } 6492 } 6493 6494 @Override 6495 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6496 String targetPackage, int flags) { 6497 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6498 } 6499 6500 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6501 int flags) { 6502 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6503 6504 // reader 6505 synchronized (mPackages) { 6506 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6507 while (i.hasNext()) { 6508 final PackageParser.Instrumentation p = i.next(); 6509 if (targetPackage == null 6510 || targetPackage.equals(p.info.targetPackage)) { 6511 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6512 flags); 6513 if (ii != null) { 6514 finalList.add(ii); 6515 } 6516 } 6517 } 6518 } 6519 6520 return finalList; 6521 } 6522 6523 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6524 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6525 if (overlays == null) { 6526 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6527 return; 6528 } 6529 for (PackageParser.Package opkg : overlays.values()) { 6530 // Not much to do if idmap fails: we already logged the error 6531 // and we certainly don't want to abort installation of pkg simply 6532 // because an overlay didn't fit properly. For these reasons, 6533 // ignore the return value of createIdmapForPackagePairLI. 6534 createIdmapForPackagePairLI(pkg, opkg); 6535 } 6536 } 6537 6538 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6539 PackageParser.Package opkg) { 6540 if (!opkg.mTrustedOverlay) { 6541 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6542 opkg.baseCodePath + ": overlay not trusted"); 6543 return false; 6544 } 6545 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6546 if (overlaySet == null) { 6547 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6548 opkg.baseCodePath + " but target package has no known overlays"); 6549 return false; 6550 } 6551 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6552 // TODO: generate idmap for split APKs 6553 try { 6554 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6555 } catch (InstallerException e) { 6556 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6557 + opkg.baseCodePath); 6558 return false; 6559 } 6560 PackageParser.Package[] overlayArray = 6561 overlaySet.values().toArray(new PackageParser.Package[0]); 6562 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6563 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6564 return p1.mOverlayPriority - p2.mOverlayPriority; 6565 } 6566 }; 6567 Arrays.sort(overlayArray, cmp); 6568 6569 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6570 int i = 0; 6571 for (PackageParser.Package p : overlayArray) { 6572 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6573 } 6574 return true; 6575 } 6576 6577 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6578 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6579 try { 6580 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6581 } finally { 6582 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6583 } 6584 } 6585 6586 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6587 final File[] files = dir.listFiles(); 6588 if (ArrayUtils.isEmpty(files)) { 6589 Log.d(TAG, "No files in app dir " + dir); 6590 return; 6591 } 6592 6593 if (DEBUG_PACKAGE_SCANNING) { 6594 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6595 + " flags=0x" + Integer.toHexString(parseFlags)); 6596 } 6597 6598 for (File file : files) { 6599 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6600 && !PackageInstallerService.isStageName(file.getName()); 6601 if (!isPackage) { 6602 // Ignore entries which are not packages 6603 continue; 6604 } 6605 try { 6606 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6607 scanFlags, currentTime, null); 6608 } catch (PackageManagerException e) { 6609 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6610 6611 // Delete invalid userdata apps 6612 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6613 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6614 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6615 removeCodePathLI(file); 6616 } 6617 } 6618 } 6619 } 6620 6621 private static File getSettingsProblemFile() { 6622 File dataDir = Environment.getDataDirectory(); 6623 File systemDir = new File(dataDir, "system"); 6624 File fname = new File(systemDir, "uiderrors.txt"); 6625 return fname; 6626 } 6627 6628 static void reportSettingsProblem(int priority, String msg) { 6629 logCriticalInfo(priority, msg); 6630 } 6631 6632 static void logCriticalInfo(int priority, String msg) { 6633 Slog.println(priority, TAG, msg); 6634 EventLogTags.writePmCriticalInfo(msg); 6635 try { 6636 File fname = getSettingsProblemFile(); 6637 FileOutputStream out = new FileOutputStream(fname, true); 6638 PrintWriter pw = new FastPrintWriter(out); 6639 SimpleDateFormat formatter = new SimpleDateFormat(); 6640 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6641 pw.println(dateString + ": " + msg); 6642 pw.close(); 6643 FileUtils.setPermissions( 6644 fname.toString(), 6645 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6646 -1, -1); 6647 } catch (java.io.IOException e) { 6648 } 6649 } 6650 6651 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6652 final int policyFlags) throws PackageManagerException { 6653 if (ps != null 6654 && ps.codePath.equals(srcFile) 6655 && ps.timeStamp == srcFile.lastModified() 6656 && !isCompatSignatureUpdateNeeded(pkg) 6657 && !isRecoverSignatureUpdateNeeded(pkg)) { 6658 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6659 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6660 ArraySet<PublicKey> signingKs; 6661 synchronized (mPackages) { 6662 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6663 } 6664 if (ps.signatures.mSignatures != null 6665 && ps.signatures.mSignatures.length != 0 6666 && signingKs != null) { 6667 // Optimization: reuse the existing cached certificates 6668 // if the package appears to be unchanged. 6669 pkg.mSignatures = ps.signatures.mSignatures; 6670 pkg.mSigningKeys = signingKs; 6671 return; 6672 } 6673 6674 Slog.w(TAG, "PackageSetting for " + ps.name 6675 + " is missing signatures. Collecting certs again to recover them."); 6676 } else { 6677 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6678 } 6679 6680 try { 6681 PackageParser.collectCertificates(pkg, policyFlags); 6682 } catch (PackageParserException e) { 6683 throw PackageManagerException.from(e); 6684 } 6685 } 6686 6687 /** 6688 * Traces a package scan. 6689 * @see #scanPackageLI(File, int, int, long, UserHandle) 6690 */ 6691 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6692 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6693 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6694 try { 6695 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6696 } finally { 6697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6698 } 6699 } 6700 6701 /** 6702 * Scans a package and returns the newly parsed package. 6703 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6704 */ 6705 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6706 long currentTime, UserHandle user) throws PackageManagerException { 6707 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6708 PackageParser pp = new PackageParser(); 6709 pp.setSeparateProcesses(mSeparateProcesses); 6710 pp.setOnlyCoreApps(mOnlyCore); 6711 pp.setDisplayMetrics(mMetrics); 6712 6713 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6714 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6715 } 6716 6717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6718 final PackageParser.Package pkg; 6719 try { 6720 pkg = pp.parsePackage(scanFile, parseFlags); 6721 } catch (PackageParserException e) { 6722 throw PackageManagerException.from(e); 6723 } finally { 6724 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6725 } 6726 6727 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6728 } 6729 6730 /** 6731 * Scans a package and returns the newly parsed package. 6732 * @throws PackageManagerException on a parse error. 6733 */ 6734 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6735 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6736 throws PackageManagerException { 6737 // If the package has children and this is the first dive in the function 6738 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6739 // packages (parent and children) would be successfully scanned before the 6740 // actual scan since scanning mutates internal state and we want to atomically 6741 // install the package and its children. 6742 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6743 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6744 scanFlags |= SCAN_CHECK_ONLY; 6745 } 6746 } else { 6747 scanFlags &= ~SCAN_CHECK_ONLY; 6748 } 6749 6750 // Scan the parent 6751 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6752 scanFlags, currentTime, user); 6753 6754 // Scan the children 6755 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6756 for (int i = 0; i < childCount; i++) { 6757 PackageParser.Package childPackage = pkg.childPackages.get(i); 6758 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6759 currentTime, user); 6760 } 6761 6762 6763 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6764 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6765 } 6766 6767 return scannedPkg; 6768 } 6769 6770 /** 6771 * Scans a package and returns the newly parsed package. 6772 * @throws PackageManagerException on a parse error. 6773 */ 6774 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6775 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6776 throws PackageManagerException { 6777 PackageSetting ps = null; 6778 PackageSetting updatedPkg; 6779 // reader 6780 synchronized (mPackages) { 6781 // Look to see if we already know about this package. 6782 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6783 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6784 // This package has been renamed to its original name. Let's 6785 // use that. 6786 ps = mSettings.peekPackageLPr(oldName); 6787 } 6788 // If there was no original package, see one for the real package name. 6789 if (ps == null) { 6790 ps = mSettings.peekPackageLPr(pkg.packageName); 6791 } 6792 // Check to see if this package could be hiding/updating a system 6793 // package. Must look for it either under the original or real 6794 // package name depending on our state. 6795 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6796 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6797 6798 // If this is a package we don't know about on the system partition, we 6799 // may need to remove disabled child packages on the system partition 6800 // or may need to not add child packages if the parent apk is updated 6801 // on the data partition and no longer defines this child package. 6802 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6803 // If this is a parent package for an updated system app and this system 6804 // app got an OTA update which no longer defines some of the child packages 6805 // we have to prune them from the disabled system packages. 6806 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6807 if (disabledPs != null) { 6808 final int scannedChildCount = (pkg.childPackages != null) 6809 ? pkg.childPackages.size() : 0; 6810 final int disabledChildCount = disabledPs.childPackageNames != null 6811 ? disabledPs.childPackageNames.size() : 0; 6812 for (int i = 0; i < disabledChildCount; i++) { 6813 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6814 boolean disabledPackageAvailable = false; 6815 for (int j = 0; j < scannedChildCount; j++) { 6816 PackageParser.Package childPkg = pkg.childPackages.get(j); 6817 if (childPkg.packageName.equals(disabledChildPackageName)) { 6818 disabledPackageAvailable = true; 6819 break; 6820 } 6821 } 6822 if (!disabledPackageAvailable) { 6823 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6824 } 6825 } 6826 } 6827 } 6828 } 6829 6830 boolean updatedPkgBetter = false; 6831 // First check if this is a system package that may involve an update 6832 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6833 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6834 // it needs to drop FLAG_PRIVILEGED. 6835 if (locationIsPrivileged(scanFile)) { 6836 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6837 } else { 6838 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6839 } 6840 6841 if (ps != null && !ps.codePath.equals(scanFile)) { 6842 // The path has changed from what was last scanned... check the 6843 // version of the new path against what we have stored to determine 6844 // what to do. 6845 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6846 if (pkg.mVersionCode <= ps.versionCode) { 6847 // The system package has been updated and the code path does not match 6848 // Ignore entry. Skip it. 6849 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6850 + " ignored: updated version " + ps.versionCode 6851 + " better than this " + pkg.mVersionCode); 6852 if (!updatedPkg.codePath.equals(scanFile)) { 6853 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6854 + ps.name + " changing from " + updatedPkg.codePathString 6855 + " to " + scanFile); 6856 updatedPkg.codePath = scanFile; 6857 updatedPkg.codePathString = scanFile.toString(); 6858 updatedPkg.resourcePath = scanFile; 6859 updatedPkg.resourcePathString = scanFile.toString(); 6860 } 6861 updatedPkg.pkg = pkg; 6862 updatedPkg.versionCode = pkg.mVersionCode; 6863 6864 // Update the disabled system child packages to point to the package too. 6865 final int childCount = updatedPkg.childPackageNames != null 6866 ? updatedPkg.childPackageNames.size() : 0; 6867 for (int i = 0; i < childCount; i++) { 6868 String childPackageName = updatedPkg.childPackageNames.get(i); 6869 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6870 childPackageName); 6871 if (updatedChildPkg != null) { 6872 updatedChildPkg.pkg = pkg; 6873 updatedChildPkg.versionCode = pkg.mVersionCode; 6874 } 6875 } 6876 6877 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6878 + scanFile + " ignored: updated version " + ps.versionCode 6879 + " better than this " + pkg.mVersionCode); 6880 } else { 6881 // The current app on the system partition is better than 6882 // what we have updated to on the data partition; switch 6883 // back to the system partition version. 6884 // At this point, its safely assumed that package installation for 6885 // apps in system partition will go through. If not there won't be a working 6886 // version of the app 6887 // writer 6888 synchronized (mPackages) { 6889 // Just remove the loaded entries from package lists. 6890 mPackages.remove(ps.name); 6891 } 6892 6893 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6894 + " reverting from " + ps.codePathString 6895 + ": new version " + pkg.mVersionCode 6896 + " better than installed " + ps.versionCode); 6897 6898 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6899 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6900 synchronized (mInstallLock) { 6901 args.cleanUpResourcesLI(); 6902 } 6903 synchronized (mPackages) { 6904 mSettings.enableSystemPackageLPw(ps.name); 6905 } 6906 updatedPkgBetter = true; 6907 } 6908 } 6909 } 6910 6911 if (updatedPkg != null) { 6912 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6913 // initially 6914 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6915 6916 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6917 // flag set initially 6918 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6919 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6920 } 6921 } 6922 6923 // Verify certificates against what was last scanned 6924 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6925 6926 /* 6927 * A new system app appeared, but we already had a non-system one of the 6928 * same name installed earlier. 6929 */ 6930 boolean shouldHideSystemApp = false; 6931 if (updatedPkg == null && ps != null 6932 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6933 /* 6934 * Check to make sure the signatures match first. If they don't, 6935 * wipe the installed application and its data. 6936 */ 6937 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6938 != PackageManager.SIGNATURE_MATCH) { 6939 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6940 + " signatures don't match existing userdata copy; removing"); 6941 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6942 "scanPackageInternalLI")) { 6943 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6944 } 6945 ps = null; 6946 } else { 6947 /* 6948 * If the newly-added system app is an older version than the 6949 * already installed version, hide it. It will be scanned later 6950 * and re-added like an update. 6951 */ 6952 if (pkg.mVersionCode <= ps.versionCode) { 6953 shouldHideSystemApp = true; 6954 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6955 + " but new version " + pkg.mVersionCode + " better than installed " 6956 + ps.versionCode + "; hiding system"); 6957 } else { 6958 /* 6959 * The newly found system app is a newer version that the 6960 * one previously installed. Simply remove the 6961 * already-installed application and replace it with our own 6962 * while keeping the application data. 6963 */ 6964 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6965 + " reverting from " + ps.codePathString + ": new version " 6966 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6967 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6968 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6969 synchronized (mInstallLock) { 6970 args.cleanUpResourcesLI(); 6971 } 6972 } 6973 } 6974 } 6975 6976 // The apk is forward locked (not public) if its code and resources 6977 // are kept in different files. (except for app in either system or 6978 // vendor path). 6979 // TODO grab this value from PackageSettings 6980 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6981 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6982 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6983 } 6984 } 6985 6986 // TODO: extend to support forward-locked splits 6987 String resourcePath = null; 6988 String baseResourcePath = null; 6989 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6990 if (ps != null && ps.resourcePathString != null) { 6991 resourcePath = ps.resourcePathString; 6992 baseResourcePath = ps.resourcePathString; 6993 } else { 6994 // Should not happen at all. Just log an error. 6995 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6996 } 6997 } else { 6998 resourcePath = pkg.codePath; 6999 baseResourcePath = pkg.baseCodePath; 7000 } 7001 7002 // Set application objects path explicitly. 7003 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7004 pkg.setApplicationInfoCodePath(pkg.codePath); 7005 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7006 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7007 pkg.setApplicationInfoResourcePath(resourcePath); 7008 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7009 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7010 7011 // Note that we invoke the following method only if we are about to unpack an application 7012 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7013 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7014 7015 /* 7016 * If the system app should be overridden by a previously installed 7017 * data, hide the system app now and let the /data/app scan pick it up 7018 * again. 7019 */ 7020 if (shouldHideSystemApp) { 7021 synchronized (mPackages) { 7022 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7023 } 7024 } 7025 7026 return scannedPkg; 7027 } 7028 7029 private static String fixProcessName(String defProcessName, 7030 String processName, int uid) { 7031 if (processName == null) { 7032 return defProcessName; 7033 } 7034 return processName; 7035 } 7036 7037 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7038 throws PackageManagerException { 7039 if (pkgSetting.signatures.mSignatures != null) { 7040 // Already existing package. Make sure signatures match 7041 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7042 == PackageManager.SIGNATURE_MATCH; 7043 if (!match) { 7044 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7045 == PackageManager.SIGNATURE_MATCH; 7046 } 7047 if (!match) { 7048 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7049 == PackageManager.SIGNATURE_MATCH; 7050 } 7051 if (!match) { 7052 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7053 + pkg.packageName + " signatures do not match the " 7054 + "previously installed version; ignoring!"); 7055 } 7056 } 7057 7058 // Check for shared user signatures 7059 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7060 // Already existing package. Make sure signatures match 7061 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7062 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7063 if (!match) { 7064 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7065 == PackageManager.SIGNATURE_MATCH; 7066 } 7067 if (!match) { 7068 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7069 == PackageManager.SIGNATURE_MATCH; 7070 } 7071 if (!match) { 7072 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7073 "Package " + pkg.packageName 7074 + " has no signatures that match those in shared user " 7075 + pkgSetting.sharedUser.name + "; ignoring!"); 7076 } 7077 } 7078 } 7079 7080 /** 7081 * Enforces that only the system UID or root's UID can call a method exposed 7082 * via Binder. 7083 * 7084 * @param message used as message if SecurityException is thrown 7085 * @throws SecurityException if the caller is not system or root 7086 */ 7087 private static final void enforceSystemOrRoot(String message) { 7088 final int uid = Binder.getCallingUid(); 7089 if (uid != Process.SYSTEM_UID && uid != 0) { 7090 throw new SecurityException(message); 7091 } 7092 } 7093 7094 @Override 7095 public void performFstrimIfNeeded() { 7096 enforceSystemOrRoot("Only the system can request fstrim"); 7097 7098 // Before everything else, see whether we need to fstrim. 7099 try { 7100 IMountService ms = PackageHelper.getMountService(); 7101 if (ms != null) { 7102 final boolean isUpgrade = isUpgrade(); 7103 boolean doTrim = isUpgrade; 7104 if (doTrim) { 7105 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7106 } else { 7107 final long interval = android.provider.Settings.Global.getLong( 7108 mContext.getContentResolver(), 7109 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7110 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7111 if (interval > 0) { 7112 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7113 if (timeSinceLast > interval) { 7114 doTrim = true; 7115 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7116 + "; running immediately"); 7117 } 7118 } 7119 } 7120 if (doTrim) { 7121 if (!isFirstBoot()) { 7122 try { 7123 ActivityManagerNative.getDefault().showBootMessage( 7124 mContext.getResources().getString( 7125 R.string.android_upgrading_fstrim), true); 7126 } catch (RemoteException e) { 7127 } 7128 } 7129 ms.runMaintenance(); 7130 } 7131 } else { 7132 Slog.e(TAG, "Mount service unavailable!"); 7133 } 7134 } catch (RemoteException e) { 7135 // Can't happen; MountService is local 7136 } 7137 } 7138 7139 @Override 7140 public void updatePackagesIfNeeded() { 7141 enforceSystemOrRoot("Only the system can request package update"); 7142 7143 // We need to re-extract after an OTA. 7144 boolean causeUpgrade = isUpgrade(); 7145 7146 // First boot or factory reset. 7147 // Note: we also handle devices that are upgrading to N right now as if it is their 7148 // first boot, as they do not have profile data. 7149 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7150 7151 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7152 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7153 7154 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7155 return; 7156 } 7157 7158 List<PackageParser.Package> pkgs; 7159 synchronized (mPackages) { 7160 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7161 } 7162 7163 int curr = 0; 7164 int total = pkgs.size(); 7165 for (PackageParser.Package pkg : pkgs) { 7166 curr++; 7167 7168 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7169 if (DEBUG_DEXOPT) { 7170 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7171 } 7172 continue; 7173 } 7174 7175 if (DEBUG_DEXOPT) { 7176 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7177 } 7178 7179 if (!isFirstBoot()) { 7180 try { 7181 ActivityManagerNative.getDefault().showBootMessage( 7182 mContext.getResources().getString(R.string.android_upgrading_apk, 7183 curr, total), true); 7184 } catch (RemoteException e) { 7185 } 7186 } 7187 7188 performDexOpt(pkg.packageName, 7189 null /* instructionSet */, 7190 true /* checkProfiles */, 7191 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7192 false /* force */); 7193 } 7194 } 7195 7196 @Override 7197 public void notifyPackageUse(String packageName, int reason) { 7198 synchronized (mPackages) { 7199 PackageParser.Package p = mPackages.get(packageName); 7200 if (p == null) { 7201 return; 7202 } 7203 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7204 } 7205 } 7206 7207 // TODO: this is not used nor needed. Delete it. 7208 @Override 7209 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7210 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7211 getFullCompilerFilter(), false /* force */); 7212 } 7213 7214 @Override 7215 public boolean performDexOpt(String packageName, String instructionSet, 7216 boolean checkProfiles, int compileReason, boolean force) { 7217 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7218 getCompilerFilterForReason(compileReason), force); 7219 } 7220 7221 @Override 7222 public boolean performDexOptMode(String packageName, String instructionSet, 7223 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7224 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7225 targetCompilerFilter, force); 7226 } 7227 7228 private boolean performDexOptTraced(String packageName, String instructionSet, 7229 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7231 try { 7232 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7233 targetCompilerFilter, force); 7234 } finally { 7235 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7236 } 7237 } 7238 7239 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7240 // if the package can now be considered up to date for the given filter. 7241 private boolean performDexOptInternal(String packageName, String instructionSet, 7242 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7243 PackageParser.Package p; 7244 final String targetInstructionSet; 7245 synchronized (mPackages) { 7246 p = mPackages.get(packageName); 7247 if (p == null) { 7248 return false; 7249 } 7250 mPackageUsage.write(false); 7251 7252 targetInstructionSet = instructionSet != null ? instructionSet : 7253 getPrimaryInstructionSet(p.applicationInfo); 7254 } 7255 long callingId = Binder.clearCallingIdentity(); 7256 try { 7257 synchronized (mInstallLock) { 7258 final String[] instructionSets = new String[] { targetInstructionSet }; 7259 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7260 checkProfiles, targetCompilerFilter, force); 7261 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7262 } 7263 } finally { 7264 Binder.restoreCallingIdentity(callingId); 7265 } 7266 } 7267 7268 public ArraySet<String> getOptimizablePackages() { 7269 ArraySet<String> pkgs = new ArraySet<String>(); 7270 synchronized (mPackages) { 7271 for (PackageParser.Package p : mPackages.values()) { 7272 if (PackageDexOptimizer.canOptimizePackage(p)) { 7273 pkgs.add(p.packageName); 7274 } 7275 } 7276 } 7277 return pkgs; 7278 } 7279 7280 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7281 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7282 boolean force) { 7283 // Select the dex optimizer based on the force parameter. 7284 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7285 // allocate an object here. 7286 PackageDexOptimizer pdo = force 7287 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7288 : mPackageDexOptimizer; 7289 7290 // Optimize all dependencies first. Note: we ignore the return value and march on 7291 // on errors. 7292 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7293 if (!deps.isEmpty()) { 7294 for (PackageParser.Package depPackage : deps) { 7295 // TODO: Analyze and investigate if we (should) profile libraries. 7296 // Currently this will do a full compilation of the library by default. 7297 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7298 false /* checkProfiles */, 7299 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7300 } 7301 } 7302 7303 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7304 targetCompilerFilter); 7305 } 7306 7307 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7308 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7309 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7310 Set<String> collectedNames = new HashSet<>(); 7311 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7312 7313 retValue.remove(p); 7314 7315 return retValue; 7316 } else { 7317 return Collections.emptyList(); 7318 } 7319 } 7320 7321 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7322 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7323 if (!collectedNames.contains(p.packageName)) { 7324 collectedNames.add(p.packageName); 7325 collected.add(p); 7326 7327 if (p.usesLibraries != null) { 7328 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7329 } 7330 if (p.usesOptionalLibraries != null) { 7331 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7332 collectedNames); 7333 } 7334 } 7335 } 7336 7337 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7338 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7339 for (String libName : libs) { 7340 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7341 if (libPkg != null) { 7342 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7343 } 7344 } 7345 } 7346 7347 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7348 synchronized (mPackages) { 7349 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7350 if (lib != null && lib.apk != null) { 7351 return mPackages.get(lib.apk); 7352 } 7353 } 7354 return null; 7355 } 7356 7357 public void shutdown() { 7358 mPackageUsage.write(true); 7359 } 7360 7361 @Override 7362 public void forceDexOpt(String packageName) { 7363 enforceSystemOrRoot("forceDexOpt"); 7364 7365 PackageParser.Package pkg; 7366 synchronized (mPackages) { 7367 pkg = mPackages.get(packageName); 7368 if (pkg == null) { 7369 throw new IllegalArgumentException("Unknown package: " + packageName); 7370 } 7371 } 7372 7373 synchronized (mInstallLock) { 7374 final String[] instructionSets = new String[] { 7375 getPrimaryInstructionSet(pkg.applicationInfo) }; 7376 7377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7378 7379 // Whoever is calling forceDexOpt wants a fully compiled package. 7380 // Don't use profiles since that may cause compilation to be skipped. 7381 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7382 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7383 true /* force */); 7384 7385 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7386 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7387 throw new IllegalStateException("Failed to dexopt: " + res); 7388 } 7389 } 7390 } 7391 7392 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7393 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7394 Slog.w(TAG, "Unable to update from " + oldPkg.name 7395 + " to " + newPkg.packageName 7396 + ": old package not in system partition"); 7397 return false; 7398 } else if (mPackages.get(oldPkg.name) != null) { 7399 Slog.w(TAG, "Unable to update from " + oldPkg.name 7400 + " to " + newPkg.packageName 7401 + ": old package still exists"); 7402 return false; 7403 } 7404 return true; 7405 } 7406 7407 void removeCodePathLI(File codePath) { 7408 if (codePath.isDirectory()) { 7409 try { 7410 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7411 } catch (InstallerException e) { 7412 Slog.w(TAG, "Failed to remove code path", e); 7413 } 7414 } else { 7415 codePath.delete(); 7416 } 7417 } 7418 7419 private int[] resolveUserIds(int userId) { 7420 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7421 } 7422 7423 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7424 if (pkg == null) { 7425 Slog.wtf(TAG, "Package was null!", new Throwable()); 7426 return; 7427 } 7428 clearAppDataLeafLIF(pkg, userId, flags); 7429 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7430 for (int i = 0; i < childCount; i++) { 7431 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7432 } 7433 } 7434 7435 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7436 final PackageSetting ps; 7437 synchronized (mPackages) { 7438 ps = mSettings.mPackages.get(pkg.packageName); 7439 } 7440 for (int realUserId : resolveUserIds(userId)) { 7441 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7442 try { 7443 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7444 ceDataInode); 7445 } catch (InstallerException e) { 7446 Slog.w(TAG, String.valueOf(e)); 7447 } 7448 } 7449 } 7450 7451 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7452 if (pkg == null) { 7453 Slog.wtf(TAG, "Package was null!", new Throwable()); 7454 return; 7455 } 7456 destroyAppDataLeafLIF(pkg, userId, flags); 7457 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7458 for (int i = 0; i < childCount; i++) { 7459 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7460 } 7461 } 7462 7463 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7464 final PackageSetting ps; 7465 synchronized (mPackages) { 7466 ps = mSettings.mPackages.get(pkg.packageName); 7467 } 7468 for (int realUserId : resolveUserIds(userId)) { 7469 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7470 try { 7471 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7472 ceDataInode); 7473 } catch (InstallerException e) { 7474 Slog.w(TAG, String.valueOf(e)); 7475 } 7476 } 7477 } 7478 7479 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7480 if (pkg == null) { 7481 Slog.wtf(TAG, "Package was null!", new Throwable()); 7482 return; 7483 } 7484 destroyAppProfilesLeafLIF(pkg); 7485 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7486 for (int i = 0; i < childCount; i++) { 7487 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7488 } 7489 } 7490 7491 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7492 try { 7493 mInstaller.destroyAppProfiles(pkg.packageName); 7494 } catch (InstallerException e) { 7495 Slog.w(TAG, String.valueOf(e)); 7496 } 7497 } 7498 7499 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7500 if (pkg == null) { 7501 Slog.wtf(TAG, "Package was null!", new Throwable()); 7502 return; 7503 } 7504 clearAppProfilesLeafLIF(pkg); 7505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7506 for (int i = 0; i < childCount; i++) { 7507 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7508 } 7509 } 7510 7511 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7512 try { 7513 mInstaller.clearAppProfiles(pkg.packageName); 7514 } catch (InstallerException e) { 7515 Slog.w(TAG, String.valueOf(e)); 7516 } 7517 } 7518 7519 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7520 long lastUpdateTime) { 7521 // Set parent install/update time 7522 PackageSetting ps = (PackageSetting) pkg.mExtras; 7523 if (ps != null) { 7524 ps.firstInstallTime = firstInstallTime; 7525 ps.lastUpdateTime = lastUpdateTime; 7526 } 7527 // Set children install/update time 7528 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7529 for (int i = 0; i < childCount; i++) { 7530 PackageParser.Package childPkg = pkg.childPackages.get(i); 7531 ps = (PackageSetting) childPkg.mExtras; 7532 if (ps != null) { 7533 ps.firstInstallTime = firstInstallTime; 7534 ps.lastUpdateTime = lastUpdateTime; 7535 } 7536 } 7537 } 7538 7539 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7540 PackageParser.Package changingLib) { 7541 if (file.path != null) { 7542 usesLibraryFiles.add(file.path); 7543 return; 7544 } 7545 PackageParser.Package p = mPackages.get(file.apk); 7546 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7547 // If we are doing this while in the middle of updating a library apk, 7548 // then we need to make sure to use that new apk for determining the 7549 // dependencies here. (We haven't yet finished committing the new apk 7550 // to the package manager state.) 7551 if (p == null || p.packageName.equals(changingLib.packageName)) { 7552 p = changingLib; 7553 } 7554 } 7555 if (p != null) { 7556 usesLibraryFiles.addAll(p.getAllCodePaths()); 7557 } 7558 } 7559 7560 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7561 PackageParser.Package changingLib) throws PackageManagerException { 7562 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7563 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7564 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7565 for (int i=0; i<N; i++) { 7566 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7567 if (file == null) { 7568 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7569 "Package " + pkg.packageName + " requires unavailable shared library " 7570 + pkg.usesLibraries.get(i) + "; failing!"); 7571 } 7572 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7573 } 7574 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7575 for (int i=0; i<N; i++) { 7576 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7577 if (file == null) { 7578 Slog.w(TAG, "Package " + pkg.packageName 7579 + " desires unavailable shared library " 7580 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7581 } else { 7582 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7583 } 7584 } 7585 N = usesLibraryFiles.size(); 7586 if (N > 0) { 7587 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7588 } else { 7589 pkg.usesLibraryFiles = null; 7590 } 7591 } 7592 } 7593 7594 private static boolean hasString(List<String> list, List<String> which) { 7595 if (list == null) { 7596 return false; 7597 } 7598 for (int i=list.size()-1; i>=0; i--) { 7599 for (int j=which.size()-1; j>=0; j--) { 7600 if (which.get(j).equals(list.get(i))) { 7601 return true; 7602 } 7603 } 7604 } 7605 return false; 7606 } 7607 7608 private void updateAllSharedLibrariesLPw() { 7609 for (PackageParser.Package pkg : mPackages.values()) { 7610 try { 7611 updateSharedLibrariesLPw(pkg, null); 7612 } catch (PackageManagerException e) { 7613 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7614 } 7615 } 7616 } 7617 7618 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7619 PackageParser.Package changingPkg) { 7620 ArrayList<PackageParser.Package> res = null; 7621 for (PackageParser.Package pkg : mPackages.values()) { 7622 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7623 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7624 if (res == null) { 7625 res = new ArrayList<PackageParser.Package>(); 7626 } 7627 res.add(pkg); 7628 try { 7629 updateSharedLibrariesLPw(pkg, changingPkg); 7630 } catch (PackageManagerException e) { 7631 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7632 } 7633 } 7634 } 7635 return res; 7636 } 7637 7638 /** 7639 * Derive the value of the {@code cpuAbiOverride} based on the provided 7640 * value and an optional stored value from the package settings. 7641 */ 7642 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7643 String cpuAbiOverride = null; 7644 7645 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7646 cpuAbiOverride = null; 7647 } else if (abiOverride != null) { 7648 cpuAbiOverride = abiOverride; 7649 } else if (settings != null) { 7650 cpuAbiOverride = settings.cpuAbiOverrideString; 7651 } 7652 7653 return cpuAbiOverride; 7654 } 7655 7656 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7657 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7658 throws PackageManagerException { 7659 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7660 // If the package has children and this is the first dive in the function 7661 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7662 // whether all packages (parent and children) would be successfully scanned 7663 // before the actual scan since scanning mutates internal state and we want 7664 // to atomically install the package and its children. 7665 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7666 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7667 scanFlags |= SCAN_CHECK_ONLY; 7668 } 7669 } else { 7670 scanFlags &= ~SCAN_CHECK_ONLY; 7671 } 7672 7673 final PackageParser.Package scannedPkg; 7674 try { 7675 // Scan the parent 7676 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7677 // Scan the children 7678 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7679 for (int i = 0; i < childCount; i++) { 7680 PackageParser.Package childPkg = pkg.childPackages.get(i); 7681 scanPackageLI(childPkg, policyFlags, 7682 scanFlags, currentTime, user); 7683 } 7684 } finally { 7685 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7686 } 7687 7688 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7689 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7690 } 7691 7692 return scannedPkg; 7693 } 7694 7695 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7696 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7697 boolean success = false; 7698 try { 7699 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7700 currentTime, user); 7701 success = true; 7702 return res; 7703 } finally { 7704 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7705 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7706 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7707 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7708 destroyAppProfilesLIF(pkg); 7709 } 7710 } 7711 } 7712 7713 /** 7714 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7715 */ 7716 private static boolean apkHasCode(String fileName) { 7717 StrictJarFile jarFile = null; 7718 try { 7719 jarFile = new StrictJarFile(fileName, 7720 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7721 return jarFile.findEntry("classes.dex") != null; 7722 } catch (IOException ignore) { 7723 } finally { 7724 try { 7725 jarFile.close(); 7726 } catch (IOException ignore) {} 7727 } 7728 return false; 7729 } 7730 7731 /** 7732 * Enforces code policy for the package. This ensures that if an APK has 7733 * declared hasCode="true" in its manifest that the APK actually contains 7734 * code. 7735 * 7736 * @throws PackageManagerException If bytecode could not be found when it should exist 7737 */ 7738 private static void enforceCodePolicy(PackageParser.Package pkg) 7739 throws PackageManagerException { 7740 final boolean shouldHaveCode = 7741 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7742 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7743 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7744 "Package " + pkg.baseCodePath + " code is missing"); 7745 } 7746 7747 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7748 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7749 final boolean splitShouldHaveCode = 7750 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7751 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7752 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7753 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7754 } 7755 } 7756 } 7757 } 7758 7759 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7760 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7761 throws PackageManagerException { 7762 final File scanFile = new File(pkg.codePath); 7763 if (pkg.applicationInfo.getCodePath() == null || 7764 pkg.applicationInfo.getResourcePath() == null) { 7765 // Bail out. The resource and code paths haven't been set. 7766 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7767 "Code and resource paths haven't been set correctly"); 7768 } 7769 7770 // Apply policy 7771 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7772 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7773 if (pkg.applicationInfo.isDirectBootAware()) { 7774 // we're direct boot aware; set for all components 7775 for (PackageParser.Service s : pkg.services) { 7776 s.info.encryptionAware = s.info.directBootAware = true; 7777 } 7778 for (PackageParser.Provider p : pkg.providers) { 7779 p.info.encryptionAware = p.info.directBootAware = true; 7780 } 7781 for (PackageParser.Activity a : pkg.activities) { 7782 a.info.encryptionAware = a.info.directBootAware = true; 7783 } 7784 for (PackageParser.Activity r : pkg.receivers) { 7785 r.info.encryptionAware = r.info.directBootAware = true; 7786 } 7787 } 7788 } else { 7789 // Only allow system apps to be flagged as core apps. 7790 pkg.coreApp = false; 7791 // clear flags not applicable to regular apps 7792 pkg.applicationInfo.privateFlags &= 7793 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7794 pkg.applicationInfo.privateFlags &= 7795 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7796 } 7797 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7798 7799 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7800 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7801 } 7802 7803 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7804 enforceCodePolicy(pkg); 7805 } 7806 7807 if (mCustomResolverComponentName != null && 7808 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7809 setUpCustomResolverActivity(pkg); 7810 } 7811 7812 if (pkg.packageName.equals("android")) { 7813 synchronized (mPackages) { 7814 if (mAndroidApplication != null) { 7815 Slog.w(TAG, "*************************************************"); 7816 Slog.w(TAG, "Core android package being redefined. Skipping."); 7817 Slog.w(TAG, " file=" + scanFile); 7818 Slog.w(TAG, "*************************************************"); 7819 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7820 "Core android package being redefined. Skipping."); 7821 } 7822 7823 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7824 // Set up information for our fall-back user intent resolution activity. 7825 mPlatformPackage = pkg; 7826 pkg.mVersionCode = mSdkVersion; 7827 mAndroidApplication = pkg.applicationInfo; 7828 7829 if (!mResolverReplaced) { 7830 mResolveActivity.applicationInfo = mAndroidApplication; 7831 mResolveActivity.name = ResolverActivity.class.getName(); 7832 mResolveActivity.packageName = mAndroidApplication.packageName; 7833 mResolveActivity.processName = "system:ui"; 7834 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7835 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7836 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7837 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7838 mResolveActivity.exported = true; 7839 mResolveActivity.enabled = true; 7840 mResolveInfo.activityInfo = mResolveActivity; 7841 mResolveInfo.priority = 0; 7842 mResolveInfo.preferredOrder = 0; 7843 mResolveInfo.match = 0; 7844 mResolveComponentName = new ComponentName( 7845 mAndroidApplication.packageName, mResolveActivity.name); 7846 } 7847 } 7848 } 7849 } 7850 7851 if (DEBUG_PACKAGE_SCANNING) { 7852 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7853 Log.d(TAG, "Scanning package " + pkg.packageName); 7854 } 7855 7856 synchronized (mPackages) { 7857 if (mPackages.containsKey(pkg.packageName) 7858 || mSharedLibraries.containsKey(pkg.packageName)) { 7859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7860 "Application package " + pkg.packageName 7861 + " already installed. Skipping duplicate."); 7862 } 7863 7864 // If we're only installing presumed-existing packages, require that the 7865 // scanned APK is both already known and at the path previously established 7866 // for it. Previously unknown packages we pick up normally, but if we have an 7867 // a priori expectation about this package's install presence, enforce it. 7868 // With a singular exception for new system packages. When an OTA contains 7869 // a new system package, we allow the codepath to change from a system location 7870 // to the user-installed location. If we don't allow this change, any newer, 7871 // user-installed version of the application will be ignored. 7872 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7873 if (mExpectingBetter.containsKey(pkg.packageName)) { 7874 logCriticalInfo(Log.WARN, 7875 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7876 } else { 7877 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7878 if (known != null) { 7879 if (DEBUG_PACKAGE_SCANNING) { 7880 Log.d(TAG, "Examining " + pkg.codePath 7881 + " and requiring known paths " + known.codePathString 7882 + " & " + known.resourcePathString); 7883 } 7884 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7885 || !pkg.applicationInfo.getResourcePath().equals( 7886 known.resourcePathString)) { 7887 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7888 "Application package " + pkg.packageName 7889 + " found at " + pkg.applicationInfo.getCodePath() 7890 + " but expected at " + known.codePathString 7891 + "; ignoring."); 7892 } 7893 } 7894 } 7895 } 7896 } 7897 7898 // Initialize package source and resource directories 7899 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7900 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7901 7902 SharedUserSetting suid = null; 7903 PackageSetting pkgSetting = null; 7904 7905 if (!isSystemApp(pkg)) { 7906 // Only system apps can use these features. 7907 pkg.mOriginalPackages = null; 7908 pkg.mRealPackage = null; 7909 pkg.mAdoptPermissions = null; 7910 } 7911 7912 // Getting the package setting may have a side-effect, so if we 7913 // are only checking if scan would succeed, stash a copy of the 7914 // old setting to restore at the end. 7915 PackageSetting nonMutatedPs = null; 7916 7917 // writer 7918 synchronized (mPackages) { 7919 if (pkg.mSharedUserId != null) { 7920 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7921 if (suid == null) { 7922 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7923 "Creating application package " + pkg.packageName 7924 + " for shared user failed"); 7925 } 7926 if (DEBUG_PACKAGE_SCANNING) { 7927 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7928 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7929 + "): packages=" + suid.packages); 7930 } 7931 } 7932 7933 // Check if we are renaming from an original package name. 7934 PackageSetting origPackage = null; 7935 String realName = null; 7936 if (pkg.mOriginalPackages != null) { 7937 // This package may need to be renamed to a previously 7938 // installed name. Let's check on that... 7939 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7940 if (pkg.mOriginalPackages.contains(renamed)) { 7941 // This package had originally been installed as the 7942 // original name, and we have already taken care of 7943 // transitioning to the new one. Just update the new 7944 // one to continue using the old name. 7945 realName = pkg.mRealPackage; 7946 if (!pkg.packageName.equals(renamed)) { 7947 // Callers into this function may have already taken 7948 // care of renaming the package; only do it here if 7949 // it is not already done. 7950 pkg.setPackageName(renamed); 7951 } 7952 7953 } else { 7954 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7955 if ((origPackage = mSettings.peekPackageLPr( 7956 pkg.mOriginalPackages.get(i))) != null) { 7957 // We do have the package already installed under its 7958 // original name... should we use it? 7959 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7960 // New package is not compatible with original. 7961 origPackage = null; 7962 continue; 7963 } else if (origPackage.sharedUser != null) { 7964 // Make sure uid is compatible between packages. 7965 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7966 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7967 + " to " + pkg.packageName + ": old uid " 7968 + origPackage.sharedUser.name 7969 + " differs from " + pkg.mSharedUserId); 7970 origPackage = null; 7971 continue; 7972 } 7973 // TODO: Add case when shared user id is added [b/28144775] 7974 } else { 7975 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7976 + pkg.packageName + " to old name " + origPackage.name); 7977 } 7978 break; 7979 } 7980 } 7981 } 7982 } 7983 7984 if (mTransferedPackages.contains(pkg.packageName)) { 7985 Slog.w(TAG, "Package " + pkg.packageName 7986 + " was transferred to another, but its .apk remains"); 7987 } 7988 7989 // See comments in nonMutatedPs declaration 7990 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7991 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7992 if (foundPs != null) { 7993 nonMutatedPs = new PackageSetting(foundPs); 7994 } 7995 } 7996 7997 // Just create the setting, don't add it yet. For already existing packages 7998 // the PkgSetting exists already and doesn't have to be created. 7999 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8000 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8001 pkg.applicationInfo.primaryCpuAbi, 8002 pkg.applicationInfo.secondaryCpuAbi, 8003 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8004 user, false); 8005 if (pkgSetting == null) { 8006 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8007 "Creating application package " + pkg.packageName + " failed"); 8008 } 8009 8010 if (pkgSetting.origPackage != null) { 8011 // If we are first transitioning from an original package, 8012 // fix up the new package's name now. We need to do this after 8013 // looking up the package under its new name, so getPackageLP 8014 // can take care of fiddling things correctly. 8015 pkg.setPackageName(origPackage.name); 8016 8017 // File a report about this. 8018 String msg = "New package " + pkgSetting.realName 8019 + " renamed to replace old package " + pkgSetting.name; 8020 reportSettingsProblem(Log.WARN, msg); 8021 8022 // Make a note of it. 8023 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8024 mTransferedPackages.add(origPackage.name); 8025 } 8026 8027 // No longer need to retain this. 8028 pkgSetting.origPackage = null; 8029 } 8030 8031 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8032 // Make a note of it. 8033 mTransferedPackages.add(pkg.packageName); 8034 } 8035 8036 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8037 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8038 } 8039 8040 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8041 // Check all shared libraries and map to their actual file path. 8042 // We only do this here for apps not on a system dir, because those 8043 // are the only ones that can fail an install due to this. We 8044 // will take care of the system apps by updating all of their 8045 // library paths after the scan is done. 8046 updateSharedLibrariesLPw(pkg, null); 8047 } 8048 8049 if (mFoundPolicyFile) { 8050 SELinuxMMAC.assignSeinfoValue(pkg); 8051 } 8052 8053 pkg.applicationInfo.uid = pkgSetting.appId; 8054 pkg.mExtras = pkgSetting; 8055 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8056 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8057 // We just determined the app is signed correctly, so bring 8058 // over the latest parsed certs. 8059 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8060 } else { 8061 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8062 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8063 "Package " + pkg.packageName + " upgrade keys do not match the " 8064 + "previously installed version"); 8065 } else { 8066 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8067 String msg = "System package " + pkg.packageName 8068 + " signature changed; retaining data."; 8069 reportSettingsProblem(Log.WARN, msg); 8070 } 8071 } 8072 } else { 8073 try { 8074 verifySignaturesLP(pkgSetting, pkg); 8075 // We just determined the app is signed correctly, so bring 8076 // over the latest parsed certs. 8077 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8078 } catch (PackageManagerException e) { 8079 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8080 throw e; 8081 } 8082 // The signature has changed, but this package is in the system 8083 // image... let's recover! 8084 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8085 // However... if this package is part of a shared user, but it 8086 // doesn't match the signature of the shared user, let's fail. 8087 // What this means is that you can't change the signatures 8088 // associated with an overall shared user, which doesn't seem all 8089 // that unreasonable. 8090 if (pkgSetting.sharedUser != null) { 8091 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8092 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8093 throw new PackageManagerException( 8094 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8095 "Signature mismatch for shared user: " 8096 + pkgSetting.sharedUser); 8097 } 8098 } 8099 // File a report about this. 8100 String msg = "System package " + pkg.packageName 8101 + " signature changed; retaining data."; 8102 reportSettingsProblem(Log.WARN, msg); 8103 } 8104 } 8105 // Verify that this new package doesn't have any content providers 8106 // that conflict with existing packages. Only do this if the 8107 // package isn't already installed, since we don't want to break 8108 // things that are installed. 8109 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8110 final int N = pkg.providers.size(); 8111 int i; 8112 for (i=0; i<N; i++) { 8113 PackageParser.Provider p = pkg.providers.get(i); 8114 if (p.info.authority != null) { 8115 String names[] = p.info.authority.split(";"); 8116 for (int j = 0; j < names.length; j++) { 8117 if (mProvidersByAuthority.containsKey(names[j])) { 8118 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8119 final String otherPackageName = 8120 ((other != null && other.getComponentName() != null) ? 8121 other.getComponentName().getPackageName() : "?"); 8122 throw new PackageManagerException( 8123 INSTALL_FAILED_CONFLICTING_PROVIDER, 8124 "Can't install because provider name " + names[j] 8125 + " (in package " + pkg.applicationInfo.packageName 8126 + ") is already used by " + otherPackageName); 8127 } 8128 } 8129 } 8130 } 8131 } 8132 8133 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8134 // This package wants to adopt ownership of permissions from 8135 // another package. 8136 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8137 final String origName = pkg.mAdoptPermissions.get(i); 8138 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8139 if (orig != null) { 8140 if (verifyPackageUpdateLPr(orig, pkg)) { 8141 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8142 + pkg.packageName); 8143 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8144 } 8145 } 8146 } 8147 } 8148 } 8149 8150 final String pkgName = pkg.packageName; 8151 8152 final long scanFileTime = scanFile.lastModified(); 8153 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8154 pkg.applicationInfo.processName = fixProcessName( 8155 pkg.applicationInfo.packageName, 8156 pkg.applicationInfo.processName, 8157 pkg.applicationInfo.uid); 8158 8159 if (pkg != mPlatformPackage) { 8160 // Get all of our default paths setup 8161 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8162 } 8163 8164 final String path = scanFile.getPath(); 8165 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8166 8167 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8168 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8169 8170 // Some system apps still use directory structure for native libraries 8171 // in which case we might end up not detecting abi solely based on apk 8172 // structure. Try to detect abi based on directory structure. 8173 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8174 pkg.applicationInfo.primaryCpuAbi == null) { 8175 setBundledAppAbisAndRoots(pkg, pkgSetting); 8176 setNativeLibraryPaths(pkg); 8177 } 8178 8179 } else { 8180 if ((scanFlags & SCAN_MOVE) != 0) { 8181 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8182 // but we already have this packages package info in the PackageSetting. We just 8183 // use that and derive the native library path based on the new codepath. 8184 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8185 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8186 } 8187 8188 // Set native library paths again. For moves, the path will be updated based on the 8189 // ABIs we've determined above. For non-moves, the path will be updated based on the 8190 // ABIs we determined during compilation, but the path will depend on the final 8191 // package path (after the rename away from the stage path). 8192 setNativeLibraryPaths(pkg); 8193 } 8194 8195 // This is a special case for the "system" package, where the ABI is 8196 // dictated by the zygote configuration (and init.rc). We should keep track 8197 // of this ABI so that we can deal with "normal" applications that run under 8198 // the same UID correctly. 8199 if (mPlatformPackage == pkg) { 8200 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8201 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8202 } 8203 8204 // If there's a mismatch between the abi-override in the package setting 8205 // and the abiOverride specified for the install. Warn about this because we 8206 // would've already compiled the app without taking the package setting into 8207 // account. 8208 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8209 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8210 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8211 " for package " + pkg.packageName); 8212 } 8213 } 8214 8215 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8216 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8217 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8218 8219 // Copy the derived override back to the parsed package, so that we can 8220 // update the package settings accordingly. 8221 pkg.cpuAbiOverride = cpuAbiOverride; 8222 8223 if (DEBUG_ABI_SELECTION) { 8224 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8225 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8226 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8227 } 8228 8229 // Push the derived path down into PackageSettings so we know what to 8230 // clean up at uninstall time. 8231 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8232 8233 if (DEBUG_ABI_SELECTION) { 8234 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8235 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8236 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8237 } 8238 8239 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8240 // We don't do this here during boot because we can do it all 8241 // at once after scanning all existing packages. 8242 // 8243 // We also do this *before* we perform dexopt on this package, so that 8244 // we can avoid redundant dexopts, and also to make sure we've got the 8245 // code and package path correct. 8246 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8247 pkg, true /* boot complete */); 8248 } 8249 8250 if (mFactoryTest && pkg.requestedPermissions.contains( 8251 android.Manifest.permission.FACTORY_TEST)) { 8252 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8253 } 8254 8255 ArrayList<PackageParser.Package> clientLibPkgs = null; 8256 8257 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8258 if (nonMutatedPs != null) { 8259 synchronized (mPackages) { 8260 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8261 } 8262 } 8263 return pkg; 8264 } 8265 8266 // Only privileged apps and updated privileged apps can add child packages. 8267 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8268 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8269 throw new PackageManagerException("Only privileged apps and updated " 8270 + "privileged apps can add child packages. Ignoring package " 8271 + pkg.packageName); 8272 } 8273 final int childCount = pkg.childPackages.size(); 8274 for (int i = 0; i < childCount; i++) { 8275 PackageParser.Package childPkg = pkg.childPackages.get(i); 8276 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8277 childPkg.packageName)) { 8278 throw new PackageManagerException("Cannot override a child package of " 8279 + "another disabled system app. Ignoring package " + pkg.packageName); 8280 } 8281 } 8282 } 8283 8284 // writer 8285 synchronized (mPackages) { 8286 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8287 // Only system apps can add new shared libraries. 8288 if (pkg.libraryNames != null) { 8289 for (int i=0; i<pkg.libraryNames.size(); i++) { 8290 String name = pkg.libraryNames.get(i); 8291 boolean allowed = false; 8292 if (pkg.isUpdatedSystemApp()) { 8293 // New library entries can only be added through the 8294 // system image. This is important to get rid of a lot 8295 // of nasty edge cases: for example if we allowed a non- 8296 // system update of the app to add a library, then uninstalling 8297 // the update would make the library go away, and assumptions 8298 // we made such as through app install filtering would now 8299 // have allowed apps on the device which aren't compatible 8300 // with it. Better to just have the restriction here, be 8301 // conservative, and create many fewer cases that can negatively 8302 // impact the user experience. 8303 final PackageSetting sysPs = mSettings 8304 .getDisabledSystemPkgLPr(pkg.packageName); 8305 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8306 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8307 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8308 allowed = true; 8309 break; 8310 } 8311 } 8312 } 8313 } else { 8314 allowed = true; 8315 } 8316 if (allowed) { 8317 if (!mSharedLibraries.containsKey(name)) { 8318 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8319 } else if (!name.equals(pkg.packageName)) { 8320 Slog.w(TAG, "Package " + pkg.packageName + " library " 8321 + name + " already exists; skipping"); 8322 } 8323 } else { 8324 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8325 + name + " that is not declared on system image; skipping"); 8326 } 8327 } 8328 if ((scanFlags & SCAN_BOOTING) == 0) { 8329 // If we are not booting, we need to update any applications 8330 // that are clients of our shared library. If we are booting, 8331 // this will all be done once the scan is complete. 8332 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8333 } 8334 } 8335 } 8336 } 8337 8338 if ((scanFlags & SCAN_BOOTING) != 0) { 8339 // No apps can run during boot scan, so they don't need to be frozen 8340 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8341 // Caller asked to not kill app, so it's probably not frozen 8342 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8343 // Caller asked us to ignore frozen check for some reason; they 8344 // probably didn't know the package name 8345 } else { 8346 // We're doing major surgery on this package, so it better be frozen 8347 // right now to keep it from launching 8348 checkPackageFrozen(pkgName); 8349 } 8350 8351 // Also need to kill any apps that are dependent on the library. 8352 if (clientLibPkgs != null) { 8353 for (int i=0; i<clientLibPkgs.size(); i++) { 8354 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8355 killApplication(clientPkg.applicationInfo.packageName, 8356 clientPkg.applicationInfo.uid, "update lib"); 8357 } 8358 } 8359 8360 // Make sure we're not adding any bogus keyset info 8361 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8362 ksms.assertScannedPackageValid(pkg); 8363 8364 // writer 8365 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8366 8367 boolean createIdmapFailed = false; 8368 synchronized (mPackages) { 8369 // We don't expect installation to fail beyond this point 8370 8371 // Add the new setting to mSettings 8372 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8373 // Add the new setting to mPackages 8374 mPackages.put(pkg.applicationInfo.packageName, pkg); 8375 // Make sure we don't accidentally delete its data. 8376 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8377 while (iter.hasNext()) { 8378 PackageCleanItem item = iter.next(); 8379 if (pkgName.equals(item.packageName)) { 8380 iter.remove(); 8381 } 8382 } 8383 8384 // Take care of first install / last update times. 8385 if (currentTime != 0) { 8386 if (pkgSetting.firstInstallTime == 0) { 8387 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8388 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8389 pkgSetting.lastUpdateTime = currentTime; 8390 } 8391 } else if (pkgSetting.firstInstallTime == 0) { 8392 // We need *something*. Take time time stamp of the file. 8393 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8394 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8395 if (scanFileTime != pkgSetting.timeStamp) { 8396 // A package on the system image has changed; consider this 8397 // to be an update. 8398 pkgSetting.lastUpdateTime = scanFileTime; 8399 } 8400 } 8401 8402 // Add the package's KeySets to the global KeySetManagerService 8403 ksms.addScannedPackageLPw(pkg); 8404 8405 int N = pkg.providers.size(); 8406 StringBuilder r = null; 8407 int i; 8408 for (i=0; i<N; i++) { 8409 PackageParser.Provider p = pkg.providers.get(i); 8410 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8411 p.info.processName, pkg.applicationInfo.uid); 8412 mProviders.addProvider(p); 8413 p.syncable = p.info.isSyncable; 8414 if (p.info.authority != null) { 8415 String names[] = p.info.authority.split(";"); 8416 p.info.authority = null; 8417 for (int j = 0; j < names.length; j++) { 8418 if (j == 1 && p.syncable) { 8419 // We only want the first authority for a provider to possibly be 8420 // syncable, so if we already added this provider using a different 8421 // authority clear the syncable flag. We copy the provider before 8422 // changing it because the mProviders object contains a reference 8423 // to a provider that we don't want to change. 8424 // Only do this for the second authority since the resulting provider 8425 // object can be the same for all future authorities for this provider. 8426 p = new PackageParser.Provider(p); 8427 p.syncable = false; 8428 } 8429 if (!mProvidersByAuthority.containsKey(names[j])) { 8430 mProvidersByAuthority.put(names[j], p); 8431 if (p.info.authority == null) { 8432 p.info.authority = names[j]; 8433 } else { 8434 p.info.authority = p.info.authority + ";" + names[j]; 8435 } 8436 if (DEBUG_PACKAGE_SCANNING) { 8437 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8438 Log.d(TAG, "Registered content provider: " + names[j] 8439 + ", className = " + p.info.name + ", isSyncable = " 8440 + p.info.isSyncable); 8441 } 8442 } else { 8443 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8444 Slog.w(TAG, "Skipping provider name " + names[j] + 8445 " (in package " + pkg.applicationInfo.packageName + 8446 "): name already used by " 8447 + ((other != null && other.getComponentName() != null) 8448 ? other.getComponentName().getPackageName() : "?")); 8449 } 8450 } 8451 } 8452 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8453 if (r == null) { 8454 r = new StringBuilder(256); 8455 } else { 8456 r.append(' '); 8457 } 8458 r.append(p.info.name); 8459 } 8460 } 8461 if (r != null) { 8462 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8463 } 8464 8465 N = pkg.services.size(); 8466 r = null; 8467 for (i=0; i<N; i++) { 8468 PackageParser.Service s = pkg.services.get(i); 8469 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8470 s.info.processName, pkg.applicationInfo.uid); 8471 mServices.addService(s); 8472 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8473 if (r == null) { 8474 r = new StringBuilder(256); 8475 } else { 8476 r.append(' '); 8477 } 8478 r.append(s.info.name); 8479 } 8480 } 8481 if (r != null) { 8482 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8483 } 8484 8485 N = pkg.receivers.size(); 8486 r = null; 8487 for (i=0; i<N; i++) { 8488 PackageParser.Activity a = pkg.receivers.get(i); 8489 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8490 a.info.processName, pkg.applicationInfo.uid); 8491 mReceivers.addActivity(a, "receiver"); 8492 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8493 if (r == null) { 8494 r = new StringBuilder(256); 8495 } else { 8496 r.append(' '); 8497 } 8498 r.append(a.info.name); 8499 } 8500 } 8501 if (r != null) { 8502 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8503 } 8504 8505 N = pkg.activities.size(); 8506 r = null; 8507 for (i=0; i<N; i++) { 8508 PackageParser.Activity a = pkg.activities.get(i); 8509 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8510 a.info.processName, pkg.applicationInfo.uid); 8511 mActivities.addActivity(a, "activity"); 8512 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8513 if (r == null) { 8514 r = new StringBuilder(256); 8515 } else { 8516 r.append(' '); 8517 } 8518 r.append(a.info.name); 8519 } 8520 } 8521 if (r != null) { 8522 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8523 } 8524 8525 N = pkg.permissionGroups.size(); 8526 r = null; 8527 for (i=0; i<N; i++) { 8528 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8529 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8530 if (cur == null) { 8531 mPermissionGroups.put(pg.info.name, pg); 8532 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8533 if (r == null) { 8534 r = new StringBuilder(256); 8535 } else { 8536 r.append(' '); 8537 } 8538 r.append(pg.info.name); 8539 } 8540 } else { 8541 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8542 + pg.info.packageName + " ignored: original from " 8543 + cur.info.packageName); 8544 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8545 if (r == null) { 8546 r = new StringBuilder(256); 8547 } else { 8548 r.append(' '); 8549 } 8550 r.append("DUP:"); 8551 r.append(pg.info.name); 8552 } 8553 } 8554 } 8555 if (r != null) { 8556 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8557 } 8558 8559 N = pkg.permissions.size(); 8560 r = null; 8561 for (i=0; i<N; i++) { 8562 PackageParser.Permission p = pkg.permissions.get(i); 8563 8564 // Assume by default that we did not install this permission into the system. 8565 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8566 8567 // Now that permission groups have a special meaning, we ignore permission 8568 // groups for legacy apps to prevent unexpected behavior. In particular, 8569 // permissions for one app being granted to someone just becase they happen 8570 // to be in a group defined by another app (before this had no implications). 8571 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8572 p.group = mPermissionGroups.get(p.info.group); 8573 // Warn for a permission in an unknown group. 8574 if (p.info.group != null && p.group == null) { 8575 Slog.w(TAG, "Permission " + p.info.name + " from package " 8576 + p.info.packageName + " in an unknown group " + p.info.group); 8577 } 8578 } 8579 8580 ArrayMap<String, BasePermission> permissionMap = 8581 p.tree ? mSettings.mPermissionTrees 8582 : mSettings.mPermissions; 8583 BasePermission bp = permissionMap.get(p.info.name); 8584 8585 // Allow system apps to redefine non-system permissions 8586 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8587 final boolean currentOwnerIsSystem = (bp.perm != null 8588 && isSystemApp(bp.perm.owner)); 8589 if (isSystemApp(p.owner)) { 8590 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8591 // It's a built-in permission and no owner, take ownership now 8592 bp.packageSetting = pkgSetting; 8593 bp.perm = p; 8594 bp.uid = pkg.applicationInfo.uid; 8595 bp.sourcePackage = p.info.packageName; 8596 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8597 } else if (!currentOwnerIsSystem) { 8598 String msg = "New decl " + p.owner + " of permission " 8599 + p.info.name + " is system; overriding " + bp.sourcePackage; 8600 reportSettingsProblem(Log.WARN, msg); 8601 bp = null; 8602 } 8603 } 8604 } 8605 8606 if (bp == null) { 8607 bp = new BasePermission(p.info.name, p.info.packageName, 8608 BasePermission.TYPE_NORMAL); 8609 permissionMap.put(p.info.name, bp); 8610 } 8611 8612 if (bp.perm == null) { 8613 if (bp.sourcePackage == null 8614 || bp.sourcePackage.equals(p.info.packageName)) { 8615 BasePermission tree = findPermissionTreeLP(p.info.name); 8616 if (tree == null 8617 || tree.sourcePackage.equals(p.info.packageName)) { 8618 bp.packageSetting = pkgSetting; 8619 bp.perm = p; 8620 bp.uid = pkg.applicationInfo.uid; 8621 bp.sourcePackage = p.info.packageName; 8622 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8623 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8624 if (r == null) { 8625 r = new StringBuilder(256); 8626 } else { 8627 r.append(' '); 8628 } 8629 r.append(p.info.name); 8630 } 8631 } else { 8632 Slog.w(TAG, "Permission " + p.info.name + " from package " 8633 + p.info.packageName + " ignored: base tree " 8634 + tree.name + " is from package " 8635 + tree.sourcePackage); 8636 } 8637 } else { 8638 Slog.w(TAG, "Permission " + p.info.name + " from package " 8639 + p.info.packageName + " ignored: original from " 8640 + bp.sourcePackage); 8641 } 8642 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8643 if (r == null) { 8644 r = new StringBuilder(256); 8645 } else { 8646 r.append(' '); 8647 } 8648 r.append("DUP:"); 8649 r.append(p.info.name); 8650 } 8651 if (bp.perm == p) { 8652 bp.protectionLevel = p.info.protectionLevel; 8653 } 8654 } 8655 8656 if (r != null) { 8657 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8658 } 8659 8660 N = pkg.instrumentation.size(); 8661 r = null; 8662 for (i=0; i<N; i++) { 8663 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8664 a.info.packageName = pkg.applicationInfo.packageName; 8665 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8666 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8667 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8668 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8669 a.info.dataDir = pkg.applicationInfo.dataDir; 8670 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8671 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8672 8673 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8674 // need other information about the application, like the ABI and what not ? 8675 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8676 mInstrumentation.put(a.getComponentName(), a); 8677 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8678 if (r == null) { 8679 r = new StringBuilder(256); 8680 } else { 8681 r.append(' '); 8682 } 8683 r.append(a.info.name); 8684 } 8685 } 8686 if (r != null) { 8687 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8688 } 8689 8690 if (pkg.protectedBroadcasts != null) { 8691 N = pkg.protectedBroadcasts.size(); 8692 for (i=0; i<N; i++) { 8693 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8694 } 8695 } 8696 8697 pkgSetting.setTimeStamp(scanFileTime); 8698 8699 // Create idmap files for pairs of (packages, overlay packages). 8700 // Note: "android", ie framework-res.apk, is handled by native layers. 8701 if (pkg.mOverlayTarget != null) { 8702 // This is an overlay package. 8703 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8704 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8705 mOverlays.put(pkg.mOverlayTarget, 8706 new ArrayMap<String, PackageParser.Package>()); 8707 } 8708 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8709 map.put(pkg.packageName, pkg); 8710 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8711 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8712 createIdmapFailed = true; 8713 } 8714 } 8715 } else if (mOverlays.containsKey(pkg.packageName) && 8716 !pkg.packageName.equals("android")) { 8717 // This is a regular package, with one or more known overlay packages. 8718 createIdmapsForPackageLI(pkg); 8719 } 8720 } 8721 8722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8723 8724 if (createIdmapFailed) { 8725 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8726 "scanPackageLI failed to createIdmap"); 8727 } 8728 return pkg; 8729 } 8730 8731 /** 8732 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8733 * is derived purely on the basis of the contents of {@code scanFile} and 8734 * {@code cpuAbiOverride}. 8735 * 8736 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8737 */ 8738 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8739 String cpuAbiOverride, boolean extractLibs) 8740 throws PackageManagerException { 8741 // TODO: We can probably be smarter about this stuff. For installed apps, 8742 // we can calculate this information at install time once and for all. For 8743 // system apps, we can probably assume that this information doesn't change 8744 // after the first boot scan. As things stand, we do lots of unnecessary work. 8745 8746 // Give ourselves some initial paths; we'll come back for another 8747 // pass once we've determined ABI below. 8748 setNativeLibraryPaths(pkg); 8749 8750 // We would never need to extract libs for forward-locked and external packages, 8751 // since the container service will do it for us. We shouldn't attempt to 8752 // extract libs from system app when it was not updated. 8753 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8754 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8755 extractLibs = false; 8756 } 8757 8758 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8759 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8760 8761 NativeLibraryHelper.Handle handle = null; 8762 try { 8763 handle = NativeLibraryHelper.Handle.create(pkg); 8764 // TODO(multiArch): This can be null for apps that didn't go through the 8765 // usual installation process. We can calculate it again, like we 8766 // do during install time. 8767 // 8768 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8769 // unnecessary. 8770 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8771 8772 // Null out the abis so that they can be recalculated. 8773 pkg.applicationInfo.primaryCpuAbi = null; 8774 pkg.applicationInfo.secondaryCpuAbi = null; 8775 if (isMultiArch(pkg.applicationInfo)) { 8776 // Warn if we've set an abiOverride for multi-lib packages.. 8777 // By definition, we need to copy both 32 and 64 bit libraries for 8778 // such packages. 8779 if (pkg.cpuAbiOverride != null 8780 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8781 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8782 } 8783 8784 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8785 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8786 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8787 if (extractLibs) { 8788 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8789 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8790 useIsaSpecificSubdirs); 8791 } else { 8792 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8793 } 8794 } 8795 8796 maybeThrowExceptionForMultiArchCopy( 8797 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8798 8799 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8800 if (extractLibs) { 8801 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8802 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8803 useIsaSpecificSubdirs); 8804 } else { 8805 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8806 } 8807 } 8808 8809 maybeThrowExceptionForMultiArchCopy( 8810 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8811 8812 if (abi64 >= 0) { 8813 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8814 } 8815 8816 if (abi32 >= 0) { 8817 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8818 if (abi64 >= 0) { 8819 if (pkg.use32bitAbi) { 8820 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8821 pkg.applicationInfo.primaryCpuAbi = abi; 8822 } else { 8823 pkg.applicationInfo.secondaryCpuAbi = abi; 8824 } 8825 } else { 8826 pkg.applicationInfo.primaryCpuAbi = abi; 8827 } 8828 } 8829 8830 } else { 8831 String[] abiList = (cpuAbiOverride != null) ? 8832 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8833 8834 // Enable gross and lame hacks for apps that are built with old 8835 // SDK tools. We must scan their APKs for renderscript bitcode and 8836 // not launch them if it's present. Don't bother checking on devices 8837 // that don't have 64 bit support. 8838 boolean needsRenderScriptOverride = false; 8839 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8840 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8841 abiList = Build.SUPPORTED_32_BIT_ABIS; 8842 needsRenderScriptOverride = true; 8843 } 8844 8845 final int copyRet; 8846 if (extractLibs) { 8847 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8848 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8849 } else { 8850 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8851 } 8852 8853 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8854 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8855 "Error unpackaging native libs for app, errorCode=" + copyRet); 8856 } 8857 8858 if (copyRet >= 0) { 8859 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8860 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8861 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8862 } else if (needsRenderScriptOverride) { 8863 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8864 } 8865 } 8866 } catch (IOException ioe) { 8867 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8868 } finally { 8869 IoUtils.closeQuietly(handle); 8870 } 8871 8872 // Now that we've calculated the ABIs and determined if it's an internal app, 8873 // we will go ahead and populate the nativeLibraryPath. 8874 setNativeLibraryPaths(pkg); 8875 } 8876 8877 /** 8878 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8879 * i.e, so that all packages can be run inside a single process if required. 8880 * 8881 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8882 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8883 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8884 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8885 * updating a package that belongs to a shared user. 8886 * 8887 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8888 * adds unnecessary complexity. 8889 */ 8890 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8891 PackageParser.Package scannedPackage, boolean bootComplete) { 8892 String requiredInstructionSet = null; 8893 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8894 requiredInstructionSet = VMRuntime.getInstructionSet( 8895 scannedPackage.applicationInfo.primaryCpuAbi); 8896 } 8897 8898 PackageSetting requirer = null; 8899 for (PackageSetting ps : packagesForUser) { 8900 // If packagesForUser contains scannedPackage, we skip it. This will happen 8901 // when scannedPackage is an update of an existing package. Without this check, 8902 // we will never be able to change the ABI of any package belonging to a shared 8903 // user, even if it's compatible with other packages. 8904 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8905 if (ps.primaryCpuAbiString == null) { 8906 continue; 8907 } 8908 8909 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8910 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8911 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8912 // this but there's not much we can do. 8913 String errorMessage = "Instruction set mismatch, " 8914 + ((requirer == null) ? "[caller]" : requirer) 8915 + " requires " + requiredInstructionSet + " whereas " + ps 8916 + " requires " + instructionSet; 8917 Slog.w(TAG, errorMessage); 8918 } 8919 8920 if (requiredInstructionSet == null) { 8921 requiredInstructionSet = instructionSet; 8922 requirer = ps; 8923 } 8924 } 8925 } 8926 8927 if (requiredInstructionSet != null) { 8928 String adjustedAbi; 8929 if (requirer != null) { 8930 // requirer != null implies that either scannedPackage was null or that scannedPackage 8931 // did not require an ABI, in which case we have to adjust scannedPackage to match 8932 // the ABI of the set (which is the same as requirer's ABI) 8933 adjustedAbi = requirer.primaryCpuAbiString; 8934 if (scannedPackage != null) { 8935 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8936 } 8937 } else { 8938 // requirer == null implies that we're updating all ABIs in the set to 8939 // match scannedPackage. 8940 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8941 } 8942 8943 for (PackageSetting ps : packagesForUser) { 8944 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8945 if (ps.primaryCpuAbiString != null) { 8946 continue; 8947 } 8948 8949 ps.primaryCpuAbiString = adjustedAbi; 8950 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8951 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8952 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8953 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8954 + " (requirer=" 8955 + (requirer == null ? "null" : requirer.pkg.packageName) 8956 + ", scannedPackage=" 8957 + (scannedPackage != null ? scannedPackage.packageName : "null") 8958 + ")"); 8959 try { 8960 mInstaller.rmdex(ps.codePathString, 8961 getDexCodeInstructionSet(getPreferredInstructionSet())); 8962 } catch (InstallerException ignored) { 8963 } 8964 } 8965 } 8966 } 8967 } 8968 } 8969 8970 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8971 synchronized (mPackages) { 8972 mResolverReplaced = true; 8973 // Set up information for custom user intent resolution activity. 8974 mResolveActivity.applicationInfo = pkg.applicationInfo; 8975 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8976 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8977 mResolveActivity.processName = pkg.applicationInfo.packageName; 8978 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8979 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8980 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8981 mResolveActivity.theme = 0; 8982 mResolveActivity.exported = true; 8983 mResolveActivity.enabled = true; 8984 mResolveInfo.activityInfo = mResolveActivity; 8985 mResolveInfo.priority = 0; 8986 mResolveInfo.preferredOrder = 0; 8987 mResolveInfo.match = 0; 8988 mResolveComponentName = mCustomResolverComponentName; 8989 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8990 mResolveComponentName); 8991 } 8992 } 8993 8994 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8995 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8996 8997 // Set up information for ephemeral installer activity 8998 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8999 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9000 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9001 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9002 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9003 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9004 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9005 mEphemeralInstallerActivity.theme = 0; 9006 mEphemeralInstallerActivity.exported = true; 9007 mEphemeralInstallerActivity.enabled = true; 9008 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9009 mEphemeralInstallerInfo.priority = 0; 9010 mEphemeralInstallerInfo.preferredOrder = 0; 9011 mEphemeralInstallerInfo.match = 0; 9012 9013 if (DEBUG_EPHEMERAL) { 9014 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9015 } 9016 } 9017 9018 private static String calculateBundledApkRoot(final String codePathString) { 9019 final File codePath = new File(codePathString); 9020 final File codeRoot; 9021 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9022 codeRoot = Environment.getRootDirectory(); 9023 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9024 codeRoot = Environment.getOemDirectory(); 9025 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9026 codeRoot = Environment.getVendorDirectory(); 9027 } else { 9028 // Unrecognized code path; take its top real segment as the apk root: 9029 // e.g. /something/app/blah.apk => /something 9030 try { 9031 File f = codePath.getCanonicalFile(); 9032 File parent = f.getParentFile(); // non-null because codePath is a file 9033 File tmp; 9034 while ((tmp = parent.getParentFile()) != null) { 9035 f = parent; 9036 parent = tmp; 9037 } 9038 codeRoot = f; 9039 Slog.w(TAG, "Unrecognized code path " 9040 + codePath + " - using " + codeRoot); 9041 } catch (IOException e) { 9042 // Can't canonicalize the code path -- shenanigans? 9043 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9044 return Environment.getRootDirectory().getPath(); 9045 } 9046 } 9047 return codeRoot.getPath(); 9048 } 9049 9050 /** 9051 * Derive and set the location of native libraries for the given package, 9052 * which varies depending on where and how the package was installed. 9053 */ 9054 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9055 final ApplicationInfo info = pkg.applicationInfo; 9056 final String codePath = pkg.codePath; 9057 final File codeFile = new File(codePath); 9058 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9059 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9060 9061 info.nativeLibraryRootDir = null; 9062 info.nativeLibraryRootRequiresIsa = false; 9063 info.nativeLibraryDir = null; 9064 info.secondaryNativeLibraryDir = null; 9065 9066 if (isApkFile(codeFile)) { 9067 // Monolithic install 9068 if (bundledApp) { 9069 // If "/system/lib64/apkname" exists, assume that is the per-package 9070 // native library directory to use; otherwise use "/system/lib/apkname". 9071 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9072 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9073 getPrimaryInstructionSet(info)); 9074 9075 // This is a bundled system app so choose the path based on the ABI. 9076 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9077 // is just the default path. 9078 final String apkName = deriveCodePathName(codePath); 9079 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9080 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9081 apkName).getAbsolutePath(); 9082 9083 if (info.secondaryCpuAbi != null) { 9084 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9085 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9086 secondaryLibDir, apkName).getAbsolutePath(); 9087 } 9088 } else if (asecApp) { 9089 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9090 .getAbsolutePath(); 9091 } else { 9092 final String apkName = deriveCodePathName(codePath); 9093 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9094 .getAbsolutePath(); 9095 } 9096 9097 info.nativeLibraryRootRequiresIsa = false; 9098 info.nativeLibraryDir = info.nativeLibraryRootDir; 9099 } else { 9100 // Cluster install 9101 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9102 info.nativeLibraryRootRequiresIsa = true; 9103 9104 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9105 getPrimaryInstructionSet(info)).getAbsolutePath(); 9106 9107 if (info.secondaryCpuAbi != null) { 9108 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9109 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9110 } 9111 } 9112 } 9113 9114 /** 9115 * Calculate the abis and roots for a bundled app. These can uniquely 9116 * be determined from the contents of the system partition, i.e whether 9117 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9118 * of this information, and instead assume that the system was built 9119 * sensibly. 9120 */ 9121 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9122 PackageSetting pkgSetting) { 9123 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9124 9125 // If "/system/lib64/apkname" exists, assume that is the per-package 9126 // native library directory to use; otherwise use "/system/lib/apkname". 9127 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9128 setBundledAppAbi(pkg, apkRoot, apkName); 9129 // pkgSetting might be null during rescan following uninstall of updates 9130 // to a bundled app, so accommodate that possibility. The settings in 9131 // that case will be established later from the parsed package. 9132 // 9133 // If the settings aren't null, sync them up with what we've just derived. 9134 // note that apkRoot isn't stored in the package settings. 9135 if (pkgSetting != null) { 9136 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9137 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9138 } 9139 } 9140 9141 /** 9142 * Deduces the ABI of a bundled app and sets the relevant fields on the 9143 * parsed pkg object. 9144 * 9145 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9146 * under which system libraries are installed. 9147 * @param apkName the name of the installed package. 9148 */ 9149 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9150 final File codeFile = new File(pkg.codePath); 9151 9152 final boolean has64BitLibs; 9153 final boolean has32BitLibs; 9154 if (isApkFile(codeFile)) { 9155 // Monolithic install 9156 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9157 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9158 } else { 9159 // Cluster install 9160 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9161 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9162 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9163 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9164 has64BitLibs = (new File(rootDir, isa)).exists(); 9165 } else { 9166 has64BitLibs = false; 9167 } 9168 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9169 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9170 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9171 has32BitLibs = (new File(rootDir, isa)).exists(); 9172 } else { 9173 has32BitLibs = false; 9174 } 9175 } 9176 9177 if (has64BitLibs && !has32BitLibs) { 9178 // The package has 64 bit libs, but not 32 bit libs. Its primary 9179 // ABI should be 64 bit. We can safely assume here that the bundled 9180 // native libraries correspond to the most preferred ABI in the list. 9181 9182 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9183 pkg.applicationInfo.secondaryCpuAbi = null; 9184 } else if (has32BitLibs && !has64BitLibs) { 9185 // The package has 32 bit libs but not 64 bit libs. Its primary 9186 // ABI should be 32 bit. 9187 9188 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9189 pkg.applicationInfo.secondaryCpuAbi = null; 9190 } else if (has32BitLibs && has64BitLibs) { 9191 // The application has both 64 and 32 bit bundled libraries. We check 9192 // here that the app declares multiArch support, and warn if it doesn't. 9193 // 9194 // We will be lenient here and record both ABIs. The primary will be the 9195 // ABI that's higher on the list, i.e, a device that's configured to prefer 9196 // 64 bit apps will see a 64 bit primary ABI, 9197 9198 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9199 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9200 } 9201 9202 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9203 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9204 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9205 } else { 9206 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9207 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9208 } 9209 } else { 9210 pkg.applicationInfo.primaryCpuAbi = null; 9211 pkg.applicationInfo.secondaryCpuAbi = null; 9212 } 9213 } 9214 9215 private void killApplication(String pkgName, int appId, String reason) { 9216 // Request the ActivityManager to kill the process(only for existing packages) 9217 // so that we do not end up in a confused state while the user is still using the older 9218 // version of the application while the new one gets installed. 9219 final long token = Binder.clearCallingIdentity(); 9220 try { 9221 IActivityManager am = ActivityManagerNative.getDefault(); 9222 if (am != null) { 9223 try { 9224 am.killApplicationWithAppId(pkgName, appId, reason); 9225 } catch (RemoteException e) { 9226 } 9227 } 9228 } finally { 9229 Binder.restoreCallingIdentity(token); 9230 } 9231 } 9232 9233 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9234 // Remove the parent package setting 9235 PackageSetting ps = (PackageSetting) pkg.mExtras; 9236 if (ps != null) { 9237 removePackageLI(ps, chatty); 9238 } 9239 // Remove the child package setting 9240 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9241 for (int i = 0; i < childCount; i++) { 9242 PackageParser.Package childPkg = pkg.childPackages.get(i); 9243 ps = (PackageSetting) childPkg.mExtras; 9244 if (ps != null) { 9245 removePackageLI(ps, chatty); 9246 } 9247 } 9248 } 9249 9250 void removePackageLI(PackageSetting ps, boolean chatty) { 9251 if (DEBUG_INSTALL) { 9252 if (chatty) 9253 Log.d(TAG, "Removing package " + ps.name); 9254 } 9255 9256 // writer 9257 synchronized (mPackages) { 9258 mPackages.remove(ps.name); 9259 final PackageParser.Package pkg = ps.pkg; 9260 if (pkg != null) { 9261 cleanPackageDataStructuresLILPw(pkg, chatty); 9262 } 9263 } 9264 } 9265 9266 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9267 if (DEBUG_INSTALL) { 9268 if (chatty) 9269 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9270 } 9271 9272 // writer 9273 synchronized (mPackages) { 9274 // Remove the parent package 9275 mPackages.remove(pkg.applicationInfo.packageName); 9276 cleanPackageDataStructuresLILPw(pkg, chatty); 9277 9278 // Remove the child packages 9279 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9280 for (int i = 0; i < childCount; i++) { 9281 PackageParser.Package childPkg = pkg.childPackages.get(i); 9282 mPackages.remove(childPkg.applicationInfo.packageName); 9283 cleanPackageDataStructuresLILPw(childPkg, chatty); 9284 } 9285 } 9286 } 9287 9288 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9289 int N = pkg.providers.size(); 9290 StringBuilder r = null; 9291 int i; 9292 for (i=0; i<N; i++) { 9293 PackageParser.Provider p = pkg.providers.get(i); 9294 mProviders.removeProvider(p); 9295 if (p.info.authority == null) { 9296 9297 /* There was another ContentProvider with this authority when 9298 * this app was installed so this authority is null, 9299 * Ignore it as we don't have to unregister the provider. 9300 */ 9301 continue; 9302 } 9303 String names[] = p.info.authority.split(";"); 9304 for (int j = 0; j < names.length; j++) { 9305 if (mProvidersByAuthority.get(names[j]) == p) { 9306 mProvidersByAuthority.remove(names[j]); 9307 if (DEBUG_REMOVE) { 9308 if (chatty) 9309 Log.d(TAG, "Unregistered content provider: " + names[j] 9310 + ", className = " + p.info.name + ", isSyncable = " 9311 + p.info.isSyncable); 9312 } 9313 } 9314 } 9315 if (DEBUG_REMOVE && chatty) { 9316 if (r == null) { 9317 r = new StringBuilder(256); 9318 } else { 9319 r.append(' '); 9320 } 9321 r.append(p.info.name); 9322 } 9323 } 9324 if (r != null) { 9325 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9326 } 9327 9328 N = pkg.services.size(); 9329 r = null; 9330 for (i=0; i<N; i++) { 9331 PackageParser.Service s = pkg.services.get(i); 9332 mServices.removeService(s); 9333 if (chatty) { 9334 if (r == null) { 9335 r = new StringBuilder(256); 9336 } else { 9337 r.append(' '); 9338 } 9339 r.append(s.info.name); 9340 } 9341 } 9342 if (r != null) { 9343 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9344 } 9345 9346 N = pkg.receivers.size(); 9347 r = null; 9348 for (i=0; i<N; i++) { 9349 PackageParser.Activity a = pkg.receivers.get(i); 9350 mReceivers.removeActivity(a, "receiver"); 9351 if (DEBUG_REMOVE && chatty) { 9352 if (r == null) { 9353 r = new StringBuilder(256); 9354 } else { 9355 r.append(' '); 9356 } 9357 r.append(a.info.name); 9358 } 9359 } 9360 if (r != null) { 9361 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9362 } 9363 9364 N = pkg.activities.size(); 9365 r = null; 9366 for (i=0; i<N; i++) { 9367 PackageParser.Activity a = pkg.activities.get(i); 9368 mActivities.removeActivity(a, "activity"); 9369 if (DEBUG_REMOVE && chatty) { 9370 if (r == null) { 9371 r = new StringBuilder(256); 9372 } else { 9373 r.append(' '); 9374 } 9375 r.append(a.info.name); 9376 } 9377 } 9378 if (r != null) { 9379 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9380 } 9381 9382 N = pkg.permissions.size(); 9383 r = null; 9384 for (i=0; i<N; i++) { 9385 PackageParser.Permission p = pkg.permissions.get(i); 9386 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9387 if (bp == null) { 9388 bp = mSettings.mPermissionTrees.get(p.info.name); 9389 } 9390 if (bp != null && bp.perm == p) { 9391 bp.perm = null; 9392 if (DEBUG_REMOVE && chatty) { 9393 if (r == null) { 9394 r = new StringBuilder(256); 9395 } else { 9396 r.append(' '); 9397 } 9398 r.append(p.info.name); 9399 } 9400 } 9401 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9402 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9403 if (appOpPkgs != null) { 9404 appOpPkgs.remove(pkg.packageName); 9405 } 9406 } 9407 } 9408 if (r != null) { 9409 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9410 } 9411 9412 N = pkg.requestedPermissions.size(); 9413 r = null; 9414 for (i=0; i<N; i++) { 9415 String perm = pkg.requestedPermissions.get(i); 9416 BasePermission bp = mSettings.mPermissions.get(perm); 9417 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9418 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9419 if (appOpPkgs != null) { 9420 appOpPkgs.remove(pkg.packageName); 9421 if (appOpPkgs.isEmpty()) { 9422 mAppOpPermissionPackages.remove(perm); 9423 } 9424 } 9425 } 9426 } 9427 if (r != null) { 9428 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9429 } 9430 9431 N = pkg.instrumentation.size(); 9432 r = null; 9433 for (i=0; i<N; i++) { 9434 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9435 mInstrumentation.remove(a.getComponentName()); 9436 if (DEBUG_REMOVE && chatty) { 9437 if (r == null) { 9438 r = new StringBuilder(256); 9439 } else { 9440 r.append(' '); 9441 } 9442 r.append(a.info.name); 9443 } 9444 } 9445 if (r != null) { 9446 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9447 } 9448 9449 r = null; 9450 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9451 // Only system apps can hold shared libraries. 9452 if (pkg.libraryNames != null) { 9453 for (i=0; i<pkg.libraryNames.size(); i++) { 9454 String name = pkg.libraryNames.get(i); 9455 SharedLibraryEntry cur = mSharedLibraries.get(name); 9456 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9457 mSharedLibraries.remove(name); 9458 if (DEBUG_REMOVE && chatty) { 9459 if (r == null) { 9460 r = new StringBuilder(256); 9461 } else { 9462 r.append(' '); 9463 } 9464 r.append(name); 9465 } 9466 } 9467 } 9468 } 9469 } 9470 if (r != null) { 9471 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9472 } 9473 } 9474 9475 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9476 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9477 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9478 return true; 9479 } 9480 } 9481 return false; 9482 } 9483 9484 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9485 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9486 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9487 9488 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9489 // Update the parent permissions 9490 updatePermissionsLPw(pkg.packageName, pkg, flags); 9491 // Update the child permissions 9492 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9493 for (int i = 0; i < childCount; i++) { 9494 PackageParser.Package childPkg = pkg.childPackages.get(i); 9495 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9496 } 9497 } 9498 9499 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9500 int flags) { 9501 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9502 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9503 } 9504 9505 private void updatePermissionsLPw(String changingPkg, 9506 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9507 // Make sure there are no dangling permission trees. 9508 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9509 while (it.hasNext()) { 9510 final BasePermission bp = it.next(); 9511 if (bp.packageSetting == null) { 9512 // We may not yet have parsed the package, so just see if 9513 // we still know about its settings. 9514 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9515 } 9516 if (bp.packageSetting == null) { 9517 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9518 + " from package " + bp.sourcePackage); 9519 it.remove(); 9520 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9521 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9522 Slog.i(TAG, "Removing old permission tree: " + bp.name 9523 + " from package " + bp.sourcePackage); 9524 flags |= UPDATE_PERMISSIONS_ALL; 9525 it.remove(); 9526 } 9527 } 9528 } 9529 9530 // Make sure all dynamic permissions have been assigned to a package, 9531 // and make sure there are no dangling permissions. 9532 it = mSettings.mPermissions.values().iterator(); 9533 while (it.hasNext()) { 9534 final BasePermission bp = it.next(); 9535 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9536 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9537 + bp.name + " pkg=" + bp.sourcePackage 9538 + " info=" + bp.pendingInfo); 9539 if (bp.packageSetting == null && bp.pendingInfo != null) { 9540 final BasePermission tree = findPermissionTreeLP(bp.name); 9541 if (tree != null && tree.perm != null) { 9542 bp.packageSetting = tree.packageSetting; 9543 bp.perm = new PackageParser.Permission(tree.perm.owner, 9544 new PermissionInfo(bp.pendingInfo)); 9545 bp.perm.info.packageName = tree.perm.info.packageName; 9546 bp.perm.info.name = bp.name; 9547 bp.uid = tree.uid; 9548 } 9549 } 9550 } 9551 if (bp.packageSetting == null) { 9552 // We may not yet have parsed the package, so just see if 9553 // we still know about its settings. 9554 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9555 } 9556 if (bp.packageSetting == null) { 9557 Slog.w(TAG, "Removing dangling permission: " + bp.name 9558 + " from package " + bp.sourcePackage); 9559 it.remove(); 9560 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9561 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9562 Slog.i(TAG, "Removing old permission: " + bp.name 9563 + " from package " + bp.sourcePackage); 9564 flags |= UPDATE_PERMISSIONS_ALL; 9565 it.remove(); 9566 } 9567 } 9568 } 9569 9570 // Now update the permissions for all packages, in particular 9571 // replace the granted permissions of the system packages. 9572 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9573 for (PackageParser.Package pkg : mPackages.values()) { 9574 if (pkg != pkgInfo) { 9575 // Only replace for packages on requested volume 9576 final String volumeUuid = getVolumeUuidForPackage(pkg); 9577 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9578 && Objects.equals(replaceVolumeUuid, volumeUuid); 9579 grantPermissionsLPw(pkg, replace, changingPkg); 9580 } 9581 } 9582 } 9583 9584 if (pkgInfo != null) { 9585 // Only replace for packages on requested volume 9586 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9587 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9588 && Objects.equals(replaceVolumeUuid, volumeUuid); 9589 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9590 } 9591 } 9592 9593 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9594 String packageOfInterest) { 9595 // IMPORTANT: There are two types of permissions: install and runtime. 9596 // Install time permissions are granted when the app is installed to 9597 // all device users and users added in the future. Runtime permissions 9598 // are granted at runtime explicitly to specific users. Normal and signature 9599 // protected permissions are install time permissions. Dangerous permissions 9600 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9601 // otherwise they are runtime permissions. This function does not manage 9602 // runtime permissions except for the case an app targeting Lollipop MR1 9603 // being upgraded to target a newer SDK, in which case dangerous permissions 9604 // are transformed from install time to runtime ones. 9605 9606 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9607 if (ps == null) { 9608 return; 9609 } 9610 9611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9612 9613 PermissionsState permissionsState = ps.getPermissionsState(); 9614 PermissionsState origPermissions = permissionsState; 9615 9616 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9617 9618 boolean runtimePermissionsRevoked = false; 9619 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9620 9621 boolean changedInstallPermission = false; 9622 9623 if (replace) { 9624 ps.installPermissionsFixed = false; 9625 if (!ps.isSharedUser()) { 9626 origPermissions = new PermissionsState(permissionsState); 9627 permissionsState.reset(); 9628 } else { 9629 // We need to know only about runtime permission changes since the 9630 // calling code always writes the install permissions state but 9631 // the runtime ones are written only if changed. The only cases of 9632 // changed runtime permissions here are promotion of an install to 9633 // runtime and revocation of a runtime from a shared user. 9634 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9635 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9636 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9637 runtimePermissionsRevoked = true; 9638 } 9639 } 9640 } 9641 9642 permissionsState.setGlobalGids(mGlobalGids); 9643 9644 final int N = pkg.requestedPermissions.size(); 9645 for (int i=0; i<N; i++) { 9646 final String name = pkg.requestedPermissions.get(i); 9647 final BasePermission bp = mSettings.mPermissions.get(name); 9648 9649 if (DEBUG_INSTALL) { 9650 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9651 } 9652 9653 if (bp == null || bp.packageSetting == null) { 9654 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9655 Slog.w(TAG, "Unknown permission " + name 9656 + " in package " + pkg.packageName); 9657 } 9658 continue; 9659 } 9660 9661 final String perm = bp.name; 9662 boolean allowedSig = false; 9663 int grant = GRANT_DENIED; 9664 9665 // Keep track of app op permissions. 9666 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9667 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9668 if (pkgs == null) { 9669 pkgs = new ArraySet<>(); 9670 mAppOpPermissionPackages.put(bp.name, pkgs); 9671 } 9672 pkgs.add(pkg.packageName); 9673 } 9674 9675 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9676 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9677 >= Build.VERSION_CODES.M; 9678 switch (level) { 9679 case PermissionInfo.PROTECTION_NORMAL: { 9680 // For all apps normal permissions are install time ones. 9681 grant = GRANT_INSTALL; 9682 } break; 9683 9684 case PermissionInfo.PROTECTION_DANGEROUS: { 9685 // If a permission review is required for legacy apps we represent 9686 // their permissions as always granted runtime ones since we need 9687 // to keep the review required permission flag per user while an 9688 // install permission's state is shared across all users. 9689 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9690 // For legacy apps dangerous permissions are install time ones. 9691 grant = GRANT_INSTALL; 9692 } else if (origPermissions.hasInstallPermission(bp.name)) { 9693 // For legacy apps that became modern, install becomes runtime. 9694 grant = GRANT_UPGRADE; 9695 } else if (mPromoteSystemApps 9696 && isSystemApp(ps) 9697 && mExistingSystemPackages.contains(ps.name)) { 9698 // For legacy system apps, install becomes runtime. 9699 // We cannot check hasInstallPermission() for system apps since those 9700 // permissions were granted implicitly and not persisted pre-M. 9701 grant = GRANT_UPGRADE; 9702 } else { 9703 // For modern apps keep runtime permissions unchanged. 9704 grant = GRANT_RUNTIME; 9705 } 9706 } break; 9707 9708 case PermissionInfo.PROTECTION_SIGNATURE: { 9709 // For all apps signature permissions are install time ones. 9710 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9711 if (allowedSig) { 9712 grant = GRANT_INSTALL; 9713 } 9714 } break; 9715 } 9716 9717 if (DEBUG_INSTALL) { 9718 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9719 } 9720 9721 if (grant != GRANT_DENIED) { 9722 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9723 // If this is an existing, non-system package, then 9724 // we can't add any new permissions to it. 9725 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9726 // Except... if this is a permission that was added 9727 // to the platform (note: need to only do this when 9728 // updating the platform). 9729 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9730 grant = GRANT_DENIED; 9731 } 9732 } 9733 } 9734 9735 switch (grant) { 9736 case GRANT_INSTALL: { 9737 // Revoke this as runtime permission to handle the case of 9738 // a runtime permission being downgraded to an install one. 9739 // Also in permission review mode we keep dangerous permissions 9740 // for legacy apps 9741 for (int userId : UserManagerService.getInstance().getUserIds()) { 9742 if (origPermissions.getRuntimePermissionState( 9743 bp.name, userId) != null) { 9744 // Revoke the runtime permission and clear the flags. 9745 origPermissions.revokeRuntimePermission(bp, userId); 9746 origPermissions.updatePermissionFlags(bp, userId, 9747 PackageManager.MASK_PERMISSION_FLAGS, 0); 9748 // If we revoked a permission permission, we have to write. 9749 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9750 changedRuntimePermissionUserIds, userId); 9751 } 9752 } 9753 // Grant an install permission. 9754 if (permissionsState.grantInstallPermission(bp) != 9755 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9756 changedInstallPermission = true; 9757 } 9758 } break; 9759 9760 case GRANT_RUNTIME: { 9761 // Grant previously granted runtime permissions. 9762 for (int userId : UserManagerService.getInstance().getUserIds()) { 9763 PermissionState permissionState = origPermissions 9764 .getRuntimePermissionState(bp.name, userId); 9765 int flags = permissionState != null 9766 ? permissionState.getFlags() : 0; 9767 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9768 if (permissionsState.grantRuntimePermission(bp, userId) == 9769 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9770 // If we cannot put the permission as it was, we have to write. 9771 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9772 changedRuntimePermissionUserIds, userId); 9773 } 9774 // If the app supports runtime permissions no need for a review. 9775 if (Build.PERMISSIONS_REVIEW_REQUIRED 9776 && appSupportsRuntimePermissions 9777 && (flags & PackageManager 9778 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9779 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9780 // Since we changed the flags, we have to write. 9781 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9782 changedRuntimePermissionUserIds, userId); 9783 } 9784 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9785 && !appSupportsRuntimePermissions) { 9786 // For legacy apps that need a permission review, every new 9787 // runtime permission is granted but it is pending a review. 9788 // We also need to review only platform defined runtime 9789 // permissions as these are the only ones the platform knows 9790 // how to disable the API to simulate revocation as legacy 9791 // apps don't expect to run with revoked permissions. 9792 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9793 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9794 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9795 // We changed the flags, hence have to write. 9796 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9797 changedRuntimePermissionUserIds, userId); 9798 } 9799 } 9800 if (permissionsState.grantRuntimePermission(bp, userId) 9801 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9802 // We changed the permission, hence have to write. 9803 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9804 changedRuntimePermissionUserIds, userId); 9805 } 9806 } 9807 // Propagate the permission flags. 9808 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9809 } 9810 } break; 9811 9812 case GRANT_UPGRADE: { 9813 // Grant runtime permissions for a previously held install permission. 9814 PermissionState permissionState = origPermissions 9815 .getInstallPermissionState(bp.name); 9816 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9817 9818 if (origPermissions.revokeInstallPermission(bp) 9819 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9820 // We will be transferring the permission flags, so clear them. 9821 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9822 PackageManager.MASK_PERMISSION_FLAGS, 0); 9823 changedInstallPermission = true; 9824 } 9825 9826 // If the permission is not to be promoted to runtime we ignore it and 9827 // also its other flags as they are not applicable to install permissions. 9828 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9829 for (int userId : currentUserIds) { 9830 if (permissionsState.grantRuntimePermission(bp, userId) != 9831 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9832 // Transfer the permission flags. 9833 permissionsState.updatePermissionFlags(bp, userId, 9834 flags, flags); 9835 // If we granted the permission, we have to write. 9836 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9837 changedRuntimePermissionUserIds, userId); 9838 } 9839 } 9840 } 9841 } break; 9842 9843 default: { 9844 if (packageOfInterest == null 9845 || packageOfInterest.equals(pkg.packageName)) { 9846 Slog.w(TAG, "Not granting permission " + perm 9847 + " to package " + pkg.packageName 9848 + " because it was previously installed without"); 9849 } 9850 } break; 9851 } 9852 } else { 9853 if (permissionsState.revokeInstallPermission(bp) != 9854 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9855 // Also drop the permission flags. 9856 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9857 PackageManager.MASK_PERMISSION_FLAGS, 0); 9858 changedInstallPermission = true; 9859 Slog.i(TAG, "Un-granting permission " + perm 9860 + " from package " + pkg.packageName 9861 + " (protectionLevel=" + bp.protectionLevel 9862 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9863 + ")"); 9864 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9865 // Don't print warning for app op permissions, since it is fine for them 9866 // not to be granted, there is a UI for the user to decide. 9867 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9868 Slog.w(TAG, "Not granting permission " + perm 9869 + " to package " + pkg.packageName 9870 + " (protectionLevel=" + bp.protectionLevel 9871 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9872 + ")"); 9873 } 9874 } 9875 } 9876 } 9877 9878 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9879 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9880 // This is the first that we have heard about this package, so the 9881 // permissions we have now selected are fixed until explicitly 9882 // changed. 9883 ps.installPermissionsFixed = true; 9884 } 9885 9886 // Persist the runtime permissions state for users with changes. If permissions 9887 // were revoked because no app in the shared user declares them we have to 9888 // write synchronously to avoid losing runtime permissions state. 9889 for (int userId : changedRuntimePermissionUserIds) { 9890 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9891 } 9892 9893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9894 } 9895 9896 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9897 boolean allowed = false; 9898 final int NP = PackageParser.NEW_PERMISSIONS.length; 9899 for (int ip=0; ip<NP; ip++) { 9900 final PackageParser.NewPermissionInfo npi 9901 = PackageParser.NEW_PERMISSIONS[ip]; 9902 if (npi.name.equals(perm) 9903 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9904 allowed = true; 9905 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9906 + pkg.packageName); 9907 break; 9908 } 9909 } 9910 return allowed; 9911 } 9912 9913 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9914 BasePermission bp, PermissionsState origPermissions) { 9915 boolean allowed; 9916 allowed = (compareSignatures( 9917 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9918 == PackageManager.SIGNATURE_MATCH) 9919 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9920 == PackageManager.SIGNATURE_MATCH); 9921 if (!allowed && (bp.protectionLevel 9922 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9923 if (isSystemApp(pkg)) { 9924 // For updated system applications, a system permission 9925 // is granted only if it had been defined by the original application. 9926 if (pkg.isUpdatedSystemApp()) { 9927 final PackageSetting sysPs = mSettings 9928 .getDisabledSystemPkgLPr(pkg.packageName); 9929 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9930 // If the original was granted this permission, we take 9931 // that grant decision as read and propagate it to the 9932 // update. 9933 if (sysPs.isPrivileged()) { 9934 allowed = true; 9935 } 9936 } else { 9937 // The system apk may have been updated with an older 9938 // version of the one on the data partition, but which 9939 // granted a new system permission that it didn't have 9940 // before. In this case we do want to allow the app to 9941 // now get the new permission if the ancestral apk is 9942 // privileged to get it. 9943 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9944 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9945 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9946 allowed = true; 9947 break; 9948 } 9949 } 9950 } 9951 // Also if a privileged parent package on the system image or any of 9952 // its children requested a privileged permission, the updated child 9953 // packages can also get the permission. 9954 if (pkg.parentPackage != null) { 9955 final PackageSetting disabledSysParentPs = mSettings 9956 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9957 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9958 && disabledSysParentPs.isPrivileged()) { 9959 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9960 allowed = true; 9961 } else if (disabledSysParentPs.pkg.childPackages != null) { 9962 final int count = disabledSysParentPs.pkg.childPackages.size(); 9963 for (int i = 0; i < count; i++) { 9964 PackageParser.Package disabledSysChildPkg = 9965 disabledSysParentPs.pkg.childPackages.get(i); 9966 if (isPackageRequestingPermission(disabledSysChildPkg, 9967 perm)) { 9968 allowed = true; 9969 break; 9970 } 9971 } 9972 } 9973 } 9974 } 9975 } 9976 } else { 9977 allowed = isPrivilegedApp(pkg); 9978 } 9979 } 9980 } 9981 if (!allowed) { 9982 if (!allowed && (bp.protectionLevel 9983 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9984 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9985 // If this was a previously normal/dangerous permission that got moved 9986 // to a system permission as part of the runtime permission redesign, then 9987 // we still want to blindly grant it to old apps. 9988 allowed = true; 9989 } 9990 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9991 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9992 // If this permission is to be granted to the system installer and 9993 // this app is an installer, then it gets the permission. 9994 allowed = true; 9995 } 9996 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9997 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9998 // If this permission is to be granted to the system verifier and 9999 // this app is a verifier, then it gets the permission. 10000 allowed = true; 10001 } 10002 if (!allowed && (bp.protectionLevel 10003 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10004 && isSystemApp(pkg)) { 10005 // Any pre-installed system app is allowed to get this permission. 10006 allowed = true; 10007 } 10008 if (!allowed && (bp.protectionLevel 10009 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10010 // For development permissions, a development permission 10011 // is granted only if it was already granted. 10012 allowed = origPermissions.hasInstallPermission(perm); 10013 } 10014 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10015 && pkg.packageName.equals(mSetupWizardPackage)) { 10016 // If this permission is to be granted to the system setup wizard and 10017 // this app is a setup wizard, then it gets the permission. 10018 allowed = true; 10019 } 10020 } 10021 return allowed; 10022 } 10023 10024 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10025 final int permCount = pkg.requestedPermissions.size(); 10026 for (int j = 0; j < permCount; j++) { 10027 String requestedPermission = pkg.requestedPermissions.get(j); 10028 if (permission.equals(requestedPermission)) { 10029 return true; 10030 } 10031 } 10032 return false; 10033 } 10034 10035 final class ActivityIntentResolver 10036 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10037 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10038 boolean defaultOnly, int userId) { 10039 if (!sUserManager.exists(userId)) return null; 10040 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10041 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10042 } 10043 10044 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10045 int userId) { 10046 if (!sUserManager.exists(userId)) return null; 10047 mFlags = flags; 10048 return super.queryIntent(intent, resolvedType, 10049 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10050 } 10051 10052 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10053 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10054 if (!sUserManager.exists(userId)) return null; 10055 if (packageActivities == null) { 10056 return null; 10057 } 10058 mFlags = flags; 10059 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10060 final int N = packageActivities.size(); 10061 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10062 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10063 10064 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10065 for (int i = 0; i < N; ++i) { 10066 intentFilters = packageActivities.get(i).intents; 10067 if (intentFilters != null && intentFilters.size() > 0) { 10068 PackageParser.ActivityIntentInfo[] array = 10069 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10070 intentFilters.toArray(array); 10071 listCut.add(array); 10072 } 10073 } 10074 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10075 } 10076 10077 /** 10078 * Finds a privileged activity that matches the specified activity names. 10079 */ 10080 private PackageParser.Activity findMatchingActivity( 10081 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10082 for (PackageParser.Activity sysActivity : activityList) { 10083 if (sysActivity.info.name.equals(activityInfo.name)) { 10084 return sysActivity; 10085 } 10086 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10087 return sysActivity; 10088 } 10089 if (sysActivity.info.targetActivity != null) { 10090 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10091 return sysActivity; 10092 } 10093 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10094 return sysActivity; 10095 } 10096 } 10097 } 10098 return null; 10099 } 10100 10101 public class IterGenerator<E> { 10102 public Iterator<E> generate(ActivityIntentInfo info) { 10103 return null; 10104 } 10105 } 10106 10107 public class ActionIterGenerator extends IterGenerator<String> { 10108 @Override 10109 public Iterator<String> generate(ActivityIntentInfo info) { 10110 return info.actionsIterator(); 10111 } 10112 } 10113 10114 public class CategoriesIterGenerator extends IterGenerator<String> { 10115 @Override 10116 public Iterator<String> generate(ActivityIntentInfo info) { 10117 return info.categoriesIterator(); 10118 } 10119 } 10120 10121 public class SchemesIterGenerator extends IterGenerator<String> { 10122 @Override 10123 public Iterator<String> generate(ActivityIntentInfo info) { 10124 return info.schemesIterator(); 10125 } 10126 } 10127 10128 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10129 @Override 10130 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10131 return info.authoritiesIterator(); 10132 } 10133 } 10134 10135 /** 10136 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10137 * MODIFIED. Do not pass in a list that should not be changed. 10138 */ 10139 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10140 IterGenerator<T> generator, Iterator<T> searchIterator) { 10141 // loop through the set of actions; every one must be found in the intent filter 10142 while (searchIterator.hasNext()) { 10143 // we must have at least one filter in the list to consider a match 10144 if (intentList.size() == 0) { 10145 break; 10146 } 10147 10148 final T searchAction = searchIterator.next(); 10149 10150 // loop through the set of intent filters 10151 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10152 while (intentIter.hasNext()) { 10153 final ActivityIntentInfo intentInfo = intentIter.next(); 10154 boolean selectionFound = false; 10155 10156 // loop through the intent filter's selection criteria; at least one 10157 // of them must match the searched criteria 10158 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10159 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10160 final T intentSelection = intentSelectionIter.next(); 10161 if (intentSelection != null && intentSelection.equals(searchAction)) { 10162 selectionFound = true; 10163 break; 10164 } 10165 } 10166 10167 // the selection criteria wasn't found in this filter's set; this filter 10168 // is not a potential match 10169 if (!selectionFound) { 10170 intentIter.remove(); 10171 } 10172 } 10173 } 10174 } 10175 10176 private boolean isProtectedAction(ActivityIntentInfo filter) { 10177 final Iterator<String> actionsIter = filter.actionsIterator(); 10178 while (actionsIter != null && actionsIter.hasNext()) { 10179 final String filterAction = actionsIter.next(); 10180 if (PROTECTED_ACTIONS.contains(filterAction)) { 10181 return true; 10182 } 10183 } 10184 return false; 10185 } 10186 10187 /** 10188 * Adjusts the priority of the given intent filter according to policy. 10189 * <p> 10190 * <ul> 10191 * <li>The priority for non privileged applications is capped to '0'</li> 10192 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10193 * <li>The priority for unbundled updates to privileged applications is capped to the 10194 * priority defined on the system partition</li> 10195 * </ul> 10196 * <p> 10197 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10198 * allowed to obtain any priority on any action. 10199 */ 10200 private void adjustPriority( 10201 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10202 // nothing to do; priority is fine as-is 10203 if (intent.getPriority() <= 0) { 10204 return; 10205 } 10206 10207 final ActivityInfo activityInfo = intent.activity.info; 10208 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10209 10210 final boolean privilegedApp = 10211 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10212 if (!privilegedApp) { 10213 // non-privileged applications can never define a priority >0 10214 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10215 + " package: " + applicationInfo.packageName 10216 + " activity: " + intent.activity.className 10217 + " origPrio: " + intent.getPriority()); 10218 intent.setPriority(0); 10219 return; 10220 } 10221 10222 if (systemActivities == null) { 10223 // the system package is not disabled; we're parsing the system partition 10224 if (isProtectedAction(intent)) { 10225 if (mDeferProtectedFilters) { 10226 // We can't deal with these just yet. No component should ever obtain a 10227 // >0 priority for a protected actions, with ONE exception -- the setup 10228 // wizard. The setup wizard, however, cannot be known until we're able to 10229 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10230 // until all intent filters have been processed. Chicken, meet egg. 10231 // Let the filter temporarily have a high priority and rectify the 10232 // priorities after all system packages have been scanned. 10233 mProtectedFilters.add(intent); 10234 if (DEBUG_FILTERS) { 10235 Slog.i(TAG, "Protected action; save for later;" 10236 + " package: " + applicationInfo.packageName 10237 + " activity: " + intent.activity.className 10238 + " origPrio: " + intent.getPriority()); 10239 } 10240 return; 10241 } else { 10242 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10243 Slog.i(TAG, "No setup wizard;" 10244 + " All protected intents capped to priority 0"); 10245 } 10246 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10247 if (DEBUG_FILTERS) { 10248 Slog.i(TAG, "Found setup wizard;" 10249 + " allow priority " + intent.getPriority() + ";" 10250 + " package: " + intent.activity.info.packageName 10251 + " activity: " + intent.activity.className 10252 + " priority: " + intent.getPriority()); 10253 } 10254 // setup wizard gets whatever it wants 10255 return; 10256 } 10257 Slog.w(TAG, "Protected action; cap priority to 0;" 10258 + " package: " + intent.activity.info.packageName 10259 + " activity: " + intent.activity.className 10260 + " origPrio: " + intent.getPriority()); 10261 intent.setPriority(0); 10262 return; 10263 } 10264 } 10265 // privileged apps on the system image get whatever priority they request 10266 return; 10267 } 10268 10269 // privileged app unbundled update ... try to find the same activity 10270 final PackageParser.Activity foundActivity = 10271 findMatchingActivity(systemActivities, activityInfo); 10272 if (foundActivity == null) { 10273 // this is a new activity; it cannot obtain >0 priority 10274 if (DEBUG_FILTERS) { 10275 Slog.i(TAG, "New activity; cap priority to 0;" 10276 + " package: " + applicationInfo.packageName 10277 + " activity: " + intent.activity.className 10278 + " origPrio: " + intent.getPriority()); 10279 } 10280 intent.setPriority(0); 10281 return; 10282 } 10283 10284 // found activity, now check for filter equivalence 10285 10286 // a shallow copy is enough; we modify the list, not its contents 10287 final List<ActivityIntentInfo> intentListCopy = 10288 new ArrayList<>(foundActivity.intents); 10289 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10290 10291 // find matching action subsets 10292 final Iterator<String> actionsIterator = intent.actionsIterator(); 10293 if (actionsIterator != null) { 10294 getIntentListSubset( 10295 intentListCopy, new ActionIterGenerator(), actionsIterator); 10296 if (intentListCopy.size() == 0) { 10297 // no more intents to match; we're not equivalent 10298 if (DEBUG_FILTERS) { 10299 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10300 + " package: " + applicationInfo.packageName 10301 + " activity: " + intent.activity.className 10302 + " origPrio: " + intent.getPriority()); 10303 } 10304 intent.setPriority(0); 10305 return; 10306 } 10307 } 10308 10309 // find matching category subsets 10310 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10311 if (categoriesIterator != null) { 10312 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10313 categoriesIterator); 10314 if (intentListCopy.size() == 0) { 10315 // no more intents to match; we're not equivalent 10316 if (DEBUG_FILTERS) { 10317 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10318 + " package: " + applicationInfo.packageName 10319 + " activity: " + intent.activity.className 10320 + " origPrio: " + intent.getPriority()); 10321 } 10322 intent.setPriority(0); 10323 return; 10324 } 10325 } 10326 10327 // find matching schemes subsets 10328 final Iterator<String> schemesIterator = intent.schemesIterator(); 10329 if (schemesIterator != null) { 10330 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10331 schemesIterator); 10332 if (intentListCopy.size() == 0) { 10333 // no more intents to match; we're not equivalent 10334 if (DEBUG_FILTERS) { 10335 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10336 + " package: " + applicationInfo.packageName 10337 + " activity: " + intent.activity.className 10338 + " origPrio: " + intent.getPriority()); 10339 } 10340 intent.setPriority(0); 10341 return; 10342 } 10343 } 10344 10345 // find matching authorities subsets 10346 final Iterator<IntentFilter.AuthorityEntry> 10347 authoritiesIterator = intent.authoritiesIterator(); 10348 if (authoritiesIterator != null) { 10349 getIntentListSubset(intentListCopy, 10350 new AuthoritiesIterGenerator(), 10351 authoritiesIterator); 10352 if (intentListCopy.size() == 0) { 10353 // no more intents to match; we're not equivalent 10354 if (DEBUG_FILTERS) { 10355 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10356 + " package: " + applicationInfo.packageName 10357 + " activity: " + intent.activity.className 10358 + " origPrio: " + intent.getPriority()); 10359 } 10360 intent.setPriority(0); 10361 return; 10362 } 10363 } 10364 10365 // we found matching filter(s); app gets the max priority of all intents 10366 int cappedPriority = 0; 10367 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10368 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10369 } 10370 if (intent.getPriority() > cappedPriority) { 10371 if (DEBUG_FILTERS) { 10372 Slog.i(TAG, "Found matching filter(s);" 10373 + " cap priority to " + cappedPriority + ";" 10374 + " package: " + applicationInfo.packageName 10375 + " activity: " + intent.activity.className 10376 + " origPrio: " + intent.getPriority()); 10377 } 10378 intent.setPriority(cappedPriority); 10379 return; 10380 } 10381 // all this for nothing; the requested priority was <= what was on the system 10382 } 10383 10384 public final void addActivity(PackageParser.Activity a, String type) { 10385 mActivities.put(a.getComponentName(), a); 10386 if (DEBUG_SHOW_INFO) 10387 Log.v( 10388 TAG, " " + type + " " + 10389 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10390 if (DEBUG_SHOW_INFO) 10391 Log.v(TAG, " Class=" + a.info.name); 10392 final int NI = a.intents.size(); 10393 for (int j=0; j<NI; j++) { 10394 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10395 if ("activity".equals(type)) { 10396 final PackageSetting ps = 10397 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10398 final List<PackageParser.Activity> systemActivities = 10399 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10400 adjustPriority(systemActivities, intent); 10401 } 10402 if (DEBUG_SHOW_INFO) { 10403 Log.v(TAG, " IntentFilter:"); 10404 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10405 } 10406 if (!intent.debugCheck()) { 10407 Log.w(TAG, "==> For Activity " + a.info.name); 10408 } 10409 addFilter(intent); 10410 } 10411 } 10412 10413 public final void removeActivity(PackageParser.Activity a, String type) { 10414 mActivities.remove(a.getComponentName()); 10415 if (DEBUG_SHOW_INFO) { 10416 Log.v(TAG, " " + type + " " 10417 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10418 : a.info.name) + ":"); 10419 Log.v(TAG, " Class=" + a.info.name); 10420 } 10421 final int NI = a.intents.size(); 10422 for (int j=0; j<NI; j++) { 10423 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10424 if (DEBUG_SHOW_INFO) { 10425 Log.v(TAG, " IntentFilter:"); 10426 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10427 } 10428 removeFilter(intent); 10429 } 10430 } 10431 10432 @Override 10433 protected boolean allowFilterResult( 10434 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10435 ActivityInfo filterAi = filter.activity.info; 10436 for (int i=dest.size()-1; i>=0; i--) { 10437 ActivityInfo destAi = dest.get(i).activityInfo; 10438 if (destAi.name == filterAi.name 10439 && destAi.packageName == filterAi.packageName) { 10440 return false; 10441 } 10442 } 10443 return true; 10444 } 10445 10446 @Override 10447 protected ActivityIntentInfo[] newArray(int size) { 10448 return new ActivityIntentInfo[size]; 10449 } 10450 10451 @Override 10452 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10453 if (!sUserManager.exists(userId)) return true; 10454 PackageParser.Package p = filter.activity.owner; 10455 if (p != null) { 10456 PackageSetting ps = (PackageSetting)p.mExtras; 10457 if (ps != null) { 10458 // System apps are never considered stopped for purposes of 10459 // filtering, because there may be no way for the user to 10460 // actually re-launch them. 10461 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10462 && ps.getStopped(userId); 10463 } 10464 } 10465 return false; 10466 } 10467 10468 @Override 10469 protected boolean isPackageForFilter(String packageName, 10470 PackageParser.ActivityIntentInfo info) { 10471 return packageName.equals(info.activity.owner.packageName); 10472 } 10473 10474 @Override 10475 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10476 int match, int userId) { 10477 if (!sUserManager.exists(userId)) return null; 10478 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10479 return null; 10480 } 10481 final PackageParser.Activity activity = info.activity; 10482 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10483 if (ps == null) { 10484 return null; 10485 } 10486 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10487 ps.readUserState(userId), userId); 10488 if (ai == null) { 10489 return null; 10490 } 10491 final ResolveInfo res = new ResolveInfo(); 10492 res.activityInfo = ai; 10493 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10494 res.filter = info; 10495 } 10496 if (info != null) { 10497 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10498 } 10499 res.priority = info.getPriority(); 10500 res.preferredOrder = activity.owner.mPreferredOrder; 10501 //System.out.println("Result: " + res.activityInfo.className + 10502 // " = " + res.priority); 10503 res.match = match; 10504 res.isDefault = info.hasDefault; 10505 res.labelRes = info.labelRes; 10506 res.nonLocalizedLabel = info.nonLocalizedLabel; 10507 if (userNeedsBadging(userId)) { 10508 res.noResourceId = true; 10509 } else { 10510 res.icon = info.icon; 10511 } 10512 res.iconResourceId = info.icon; 10513 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10514 return res; 10515 } 10516 10517 @Override 10518 protected void sortResults(List<ResolveInfo> results) { 10519 Collections.sort(results, mResolvePrioritySorter); 10520 } 10521 10522 @Override 10523 protected void dumpFilter(PrintWriter out, String prefix, 10524 PackageParser.ActivityIntentInfo filter) { 10525 out.print(prefix); out.print( 10526 Integer.toHexString(System.identityHashCode(filter.activity))); 10527 out.print(' '); 10528 filter.activity.printComponentShortName(out); 10529 out.print(" filter "); 10530 out.println(Integer.toHexString(System.identityHashCode(filter))); 10531 } 10532 10533 @Override 10534 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10535 return filter.activity; 10536 } 10537 10538 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10539 PackageParser.Activity activity = (PackageParser.Activity)label; 10540 out.print(prefix); out.print( 10541 Integer.toHexString(System.identityHashCode(activity))); 10542 out.print(' '); 10543 activity.printComponentShortName(out); 10544 if (count > 1) { 10545 out.print(" ("); out.print(count); out.print(" filters)"); 10546 } 10547 out.println(); 10548 } 10549 10550 // Keys are String (activity class name), values are Activity. 10551 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10552 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10553 private int mFlags; 10554 } 10555 10556 private final class ServiceIntentResolver 10557 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10558 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10559 boolean defaultOnly, int userId) { 10560 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10561 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10562 } 10563 10564 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10565 int userId) { 10566 if (!sUserManager.exists(userId)) return null; 10567 mFlags = flags; 10568 return super.queryIntent(intent, resolvedType, 10569 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10570 } 10571 10572 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10573 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10574 if (!sUserManager.exists(userId)) return null; 10575 if (packageServices == null) { 10576 return null; 10577 } 10578 mFlags = flags; 10579 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10580 final int N = packageServices.size(); 10581 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10582 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10583 10584 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10585 for (int i = 0; i < N; ++i) { 10586 intentFilters = packageServices.get(i).intents; 10587 if (intentFilters != null && intentFilters.size() > 0) { 10588 PackageParser.ServiceIntentInfo[] array = 10589 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10590 intentFilters.toArray(array); 10591 listCut.add(array); 10592 } 10593 } 10594 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10595 } 10596 10597 public final void addService(PackageParser.Service s) { 10598 mServices.put(s.getComponentName(), s); 10599 if (DEBUG_SHOW_INFO) { 10600 Log.v(TAG, " " 10601 + (s.info.nonLocalizedLabel != null 10602 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10603 Log.v(TAG, " Class=" + s.info.name); 10604 } 10605 final int NI = s.intents.size(); 10606 int j; 10607 for (j=0; j<NI; j++) { 10608 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10609 if (DEBUG_SHOW_INFO) { 10610 Log.v(TAG, " IntentFilter:"); 10611 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10612 } 10613 if (!intent.debugCheck()) { 10614 Log.w(TAG, "==> For Service " + s.info.name); 10615 } 10616 addFilter(intent); 10617 } 10618 } 10619 10620 public final void removeService(PackageParser.Service s) { 10621 mServices.remove(s.getComponentName()); 10622 if (DEBUG_SHOW_INFO) { 10623 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10624 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10625 Log.v(TAG, " Class=" + s.info.name); 10626 } 10627 final int NI = s.intents.size(); 10628 int j; 10629 for (j=0; j<NI; j++) { 10630 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10631 if (DEBUG_SHOW_INFO) { 10632 Log.v(TAG, " IntentFilter:"); 10633 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10634 } 10635 removeFilter(intent); 10636 } 10637 } 10638 10639 @Override 10640 protected boolean allowFilterResult( 10641 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10642 ServiceInfo filterSi = filter.service.info; 10643 for (int i=dest.size()-1; i>=0; i--) { 10644 ServiceInfo destAi = dest.get(i).serviceInfo; 10645 if (destAi.name == filterSi.name 10646 && destAi.packageName == filterSi.packageName) { 10647 return false; 10648 } 10649 } 10650 return true; 10651 } 10652 10653 @Override 10654 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10655 return new PackageParser.ServiceIntentInfo[size]; 10656 } 10657 10658 @Override 10659 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10660 if (!sUserManager.exists(userId)) return true; 10661 PackageParser.Package p = filter.service.owner; 10662 if (p != null) { 10663 PackageSetting ps = (PackageSetting)p.mExtras; 10664 if (ps != null) { 10665 // System apps are never considered stopped for purposes of 10666 // filtering, because there may be no way for the user to 10667 // actually re-launch them. 10668 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10669 && ps.getStopped(userId); 10670 } 10671 } 10672 return false; 10673 } 10674 10675 @Override 10676 protected boolean isPackageForFilter(String packageName, 10677 PackageParser.ServiceIntentInfo info) { 10678 return packageName.equals(info.service.owner.packageName); 10679 } 10680 10681 @Override 10682 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10683 int match, int userId) { 10684 if (!sUserManager.exists(userId)) return null; 10685 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10686 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10687 return null; 10688 } 10689 final PackageParser.Service service = info.service; 10690 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10691 if (ps == null) { 10692 return null; 10693 } 10694 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10695 ps.readUserState(userId), userId); 10696 if (si == null) { 10697 return null; 10698 } 10699 final ResolveInfo res = new ResolveInfo(); 10700 res.serviceInfo = si; 10701 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10702 res.filter = filter; 10703 } 10704 res.priority = info.getPriority(); 10705 res.preferredOrder = service.owner.mPreferredOrder; 10706 res.match = match; 10707 res.isDefault = info.hasDefault; 10708 res.labelRes = info.labelRes; 10709 res.nonLocalizedLabel = info.nonLocalizedLabel; 10710 res.icon = info.icon; 10711 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10712 return res; 10713 } 10714 10715 @Override 10716 protected void sortResults(List<ResolveInfo> results) { 10717 Collections.sort(results, mResolvePrioritySorter); 10718 } 10719 10720 @Override 10721 protected void dumpFilter(PrintWriter out, String prefix, 10722 PackageParser.ServiceIntentInfo filter) { 10723 out.print(prefix); out.print( 10724 Integer.toHexString(System.identityHashCode(filter.service))); 10725 out.print(' '); 10726 filter.service.printComponentShortName(out); 10727 out.print(" filter "); 10728 out.println(Integer.toHexString(System.identityHashCode(filter))); 10729 } 10730 10731 @Override 10732 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10733 return filter.service; 10734 } 10735 10736 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10737 PackageParser.Service service = (PackageParser.Service)label; 10738 out.print(prefix); out.print( 10739 Integer.toHexString(System.identityHashCode(service))); 10740 out.print(' '); 10741 service.printComponentShortName(out); 10742 if (count > 1) { 10743 out.print(" ("); out.print(count); out.print(" filters)"); 10744 } 10745 out.println(); 10746 } 10747 10748// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10749// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10750// final List<ResolveInfo> retList = Lists.newArrayList(); 10751// while (i.hasNext()) { 10752// final ResolveInfo resolveInfo = (ResolveInfo) i; 10753// if (isEnabledLP(resolveInfo.serviceInfo)) { 10754// retList.add(resolveInfo); 10755// } 10756// } 10757// return retList; 10758// } 10759 10760 // Keys are String (activity class name), values are Activity. 10761 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10762 = new ArrayMap<ComponentName, PackageParser.Service>(); 10763 private int mFlags; 10764 }; 10765 10766 private final class ProviderIntentResolver 10767 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10768 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10769 boolean defaultOnly, int userId) { 10770 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10771 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10772 } 10773 10774 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10775 int userId) { 10776 if (!sUserManager.exists(userId)) 10777 return null; 10778 mFlags = flags; 10779 return super.queryIntent(intent, resolvedType, 10780 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10781 } 10782 10783 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10784 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10785 if (!sUserManager.exists(userId)) 10786 return null; 10787 if (packageProviders == null) { 10788 return null; 10789 } 10790 mFlags = flags; 10791 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10792 final int N = packageProviders.size(); 10793 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10794 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10795 10796 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10797 for (int i = 0; i < N; ++i) { 10798 intentFilters = packageProviders.get(i).intents; 10799 if (intentFilters != null && intentFilters.size() > 0) { 10800 PackageParser.ProviderIntentInfo[] array = 10801 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10802 intentFilters.toArray(array); 10803 listCut.add(array); 10804 } 10805 } 10806 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10807 } 10808 10809 public final void addProvider(PackageParser.Provider p) { 10810 if (mProviders.containsKey(p.getComponentName())) { 10811 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10812 return; 10813 } 10814 10815 mProviders.put(p.getComponentName(), p); 10816 if (DEBUG_SHOW_INFO) { 10817 Log.v(TAG, " " 10818 + (p.info.nonLocalizedLabel != null 10819 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10820 Log.v(TAG, " Class=" + p.info.name); 10821 } 10822 final int NI = p.intents.size(); 10823 int j; 10824 for (j = 0; j < NI; j++) { 10825 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10826 if (DEBUG_SHOW_INFO) { 10827 Log.v(TAG, " IntentFilter:"); 10828 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10829 } 10830 if (!intent.debugCheck()) { 10831 Log.w(TAG, "==> For Provider " + p.info.name); 10832 } 10833 addFilter(intent); 10834 } 10835 } 10836 10837 public final void removeProvider(PackageParser.Provider p) { 10838 mProviders.remove(p.getComponentName()); 10839 if (DEBUG_SHOW_INFO) { 10840 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10841 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10842 Log.v(TAG, " Class=" + p.info.name); 10843 } 10844 final int NI = p.intents.size(); 10845 int j; 10846 for (j = 0; j < NI; j++) { 10847 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10848 if (DEBUG_SHOW_INFO) { 10849 Log.v(TAG, " IntentFilter:"); 10850 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10851 } 10852 removeFilter(intent); 10853 } 10854 } 10855 10856 @Override 10857 protected boolean allowFilterResult( 10858 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10859 ProviderInfo filterPi = filter.provider.info; 10860 for (int i = dest.size() - 1; i >= 0; i--) { 10861 ProviderInfo destPi = dest.get(i).providerInfo; 10862 if (destPi.name == filterPi.name 10863 && destPi.packageName == filterPi.packageName) { 10864 return false; 10865 } 10866 } 10867 return true; 10868 } 10869 10870 @Override 10871 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10872 return new PackageParser.ProviderIntentInfo[size]; 10873 } 10874 10875 @Override 10876 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10877 if (!sUserManager.exists(userId)) 10878 return true; 10879 PackageParser.Package p = filter.provider.owner; 10880 if (p != null) { 10881 PackageSetting ps = (PackageSetting) p.mExtras; 10882 if (ps != null) { 10883 // System apps are never considered stopped for purposes of 10884 // filtering, because there may be no way for the user to 10885 // actually re-launch them. 10886 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10887 && ps.getStopped(userId); 10888 } 10889 } 10890 return false; 10891 } 10892 10893 @Override 10894 protected boolean isPackageForFilter(String packageName, 10895 PackageParser.ProviderIntentInfo info) { 10896 return packageName.equals(info.provider.owner.packageName); 10897 } 10898 10899 @Override 10900 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10901 int match, int userId) { 10902 if (!sUserManager.exists(userId)) 10903 return null; 10904 final PackageParser.ProviderIntentInfo info = filter; 10905 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10906 return null; 10907 } 10908 final PackageParser.Provider provider = info.provider; 10909 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10910 if (ps == null) { 10911 return null; 10912 } 10913 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10914 ps.readUserState(userId), userId); 10915 if (pi == null) { 10916 return null; 10917 } 10918 final ResolveInfo res = new ResolveInfo(); 10919 res.providerInfo = pi; 10920 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10921 res.filter = filter; 10922 } 10923 res.priority = info.getPriority(); 10924 res.preferredOrder = provider.owner.mPreferredOrder; 10925 res.match = match; 10926 res.isDefault = info.hasDefault; 10927 res.labelRes = info.labelRes; 10928 res.nonLocalizedLabel = info.nonLocalizedLabel; 10929 res.icon = info.icon; 10930 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10931 return res; 10932 } 10933 10934 @Override 10935 protected void sortResults(List<ResolveInfo> results) { 10936 Collections.sort(results, mResolvePrioritySorter); 10937 } 10938 10939 @Override 10940 protected void dumpFilter(PrintWriter out, String prefix, 10941 PackageParser.ProviderIntentInfo filter) { 10942 out.print(prefix); 10943 out.print( 10944 Integer.toHexString(System.identityHashCode(filter.provider))); 10945 out.print(' '); 10946 filter.provider.printComponentShortName(out); 10947 out.print(" filter "); 10948 out.println(Integer.toHexString(System.identityHashCode(filter))); 10949 } 10950 10951 @Override 10952 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10953 return filter.provider; 10954 } 10955 10956 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10957 PackageParser.Provider provider = (PackageParser.Provider)label; 10958 out.print(prefix); out.print( 10959 Integer.toHexString(System.identityHashCode(provider))); 10960 out.print(' '); 10961 provider.printComponentShortName(out); 10962 if (count > 1) { 10963 out.print(" ("); out.print(count); out.print(" filters)"); 10964 } 10965 out.println(); 10966 } 10967 10968 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10969 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10970 private int mFlags; 10971 } 10972 10973 private static final class EphemeralIntentResolver 10974 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10975 @Override 10976 protected EphemeralResolveIntentInfo[] newArray(int size) { 10977 return new EphemeralResolveIntentInfo[size]; 10978 } 10979 10980 @Override 10981 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10982 return true; 10983 } 10984 10985 @Override 10986 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10987 int userId) { 10988 if (!sUserManager.exists(userId)) { 10989 return null; 10990 } 10991 return info.getEphemeralResolveInfo(); 10992 } 10993 } 10994 10995 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10996 new Comparator<ResolveInfo>() { 10997 public int compare(ResolveInfo r1, ResolveInfo r2) { 10998 int v1 = r1.priority; 10999 int v2 = r2.priority; 11000 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11001 if (v1 != v2) { 11002 return (v1 > v2) ? -1 : 1; 11003 } 11004 v1 = r1.preferredOrder; 11005 v2 = r2.preferredOrder; 11006 if (v1 != v2) { 11007 return (v1 > v2) ? -1 : 1; 11008 } 11009 if (r1.isDefault != r2.isDefault) { 11010 return r1.isDefault ? -1 : 1; 11011 } 11012 v1 = r1.match; 11013 v2 = r2.match; 11014 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11015 if (v1 != v2) { 11016 return (v1 > v2) ? -1 : 1; 11017 } 11018 if (r1.system != r2.system) { 11019 return r1.system ? -1 : 1; 11020 } 11021 if (r1.activityInfo != null) { 11022 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11023 } 11024 if (r1.serviceInfo != null) { 11025 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11026 } 11027 if (r1.providerInfo != null) { 11028 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11029 } 11030 return 0; 11031 } 11032 }; 11033 11034 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11035 new Comparator<ProviderInfo>() { 11036 public int compare(ProviderInfo p1, ProviderInfo p2) { 11037 final int v1 = p1.initOrder; 11038 final int v2 = p2.initOrder; 11039 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11040 } 11041 }; 11042 11043 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11044 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11045 final int[] userIds) { 11046 mHandler.post(new Runnable() { 11047 @Override 11048 public void run() { 11049 try { 11050 final IActivityManager am = ActivityManagerNative.getDefault(); 11051 if (am == null) return; 11052 final int[] resolvedUserIds; 11053 if (userIds == null) { 11054 resolvedUserIds = am.getRunningUserIds(); 11055 } else { 11056 resolvedUserIds = userIds; 11057 } 11058 for (int id : resolvedUserIds) { 11059 final Intent intent = new Intent(action, 11060 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11061 if (extras != null) { 11062 intent.putExtras(extras); 11063 } 11064 if (targetPkg != null) { 11065 intent.setPackage(targetPkg); 11066 } 11067 // Modify the UID when posting to other users 11068 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11069 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11070 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11071 intent.putExtra(Intent.EXTRA_UID, uid); 11072 } 11073 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11074 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11075 if (DEBUG_BROADCASTS) { 11076 RuntimeException here = new RuntimeException("here"); 11077 here.fillInStackTrace(); 11078 Slog.d(TAG, "Sending to user " + id + ": " 11079 + intent.toShortString(false, true, false, false) 11080 + " " + intent.getExtras(), here); 11081 } 11082 am.broadcastIntent(null, intent, null, finishedReceiver, 11083 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11084 null, finishedReceiver != null, false, id); 11085 } 11086 } catch (RemoteException ex) { 11087 } 11088 } 11089 }); 11090 } 11091 11092 /** 11093 * Check if the external storage media is available. This is true if there 11094 * is a mounted external storage medium or if the external storage is 11095 * emulated. 11096 */ 11097 private boolean isExternalMediaAvailable() { 11098 return mMediaMounted || Environment.isExternalStorageEmulated(); 11099 } 11100 11101 @Override 11102 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11103 // writer 11104 synchronized (mPackages) { 11105 if (!isExternalMediaAvailable()) { 11106 // If the external storage is no longer mounted at this point, 11107 // the caller may not have been able to delete all of this 11108 // packages files and can not delete any more. Bail. 11109 return null; 11110 } 11111 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11112 if (lastPackage != null) { 11113 pkgs.remove(lastPackage); 11114 } 11115 if (pkgs.size() > 0) { 11116 return pkgs.get(0); 11117 } 11118 } 11119 return null; 11120 } 11121 11122 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11123 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11124 userId, andCode ? 1 : 0, packageName); 11125 if (mSystemReady) { 11126 msg.sendToTarget(); 11127 } else { 11128 if (mPostSystemReadyMessages == null) { 11129 mPostSystemReadyMessages = new ArrayList<>(); 11130 } 11131 mPostSystemReadyMessages.add(msg); 11132 } 11133 } 11134 11135 void startCleaningPackages() { 11136 // reader 11137 if (!isExternalMediaAvailable()) { 11138 return; 11139 } 11140 synchronized (mPackages) { 11141 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11142 return; 11143 } 11144 } 11145 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11146 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11147 IActivityManager am = ActivityManagerNative.getDefault(); 11148 if (am != null) { 11149 try { 11150 am.startService(null, intent, null, mContext.getOpPackageName(), 11151 UserHandle.USER_SYSTEM); 11152 } catch (RemoteException e) { 11153 } 11154 } 11155 } 11156 11157 @Override 11158 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11159 int installFlags, String installerPackageName, int userId) { 11160 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11161 11162 final int callingUid = Binder.getCallingUid(); 11163 enforceCrossUserPermission(callingUid, userId, 11164 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11165 11166 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11167 try { 11168 if (observer != null) { 11169 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11170 } 11171 } catch (RemoteException re) { 11172 } 11173 return; 11174 } 11175 11176 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11177 installFlags |= PackageManager.INSTALL_FROM_ADB; 11178 11179 } else { 11180 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11181 // about installerPackageName. 11182 11183 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11184 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11185 } 11186 11187 UserHandle user; 11188 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11189 user = UserHandle.ALL; 11190 } else { 11191 user = new UserHandle(userId); 11192 } 11193 11194 // Only system components can circumvent runtime permissions when installing. 11195 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11196 && mContext.checkCallingOrSelfPermission(Manifest.permission 11197 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11198 throw new SecurityException("You need the " 11199 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11200 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11201 } 11202 11203 final File originFile = new File(originPath); 11204 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11205 11206 final Message msg = mHandler.obtainMessage(INIT_COPY); 11207 final VerificationInfo verificationInfo = new VerificationInfo( 11208 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11209 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11210 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11211 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11212 null /*certificates*/); 11213 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11214 msg.obj = params; 11215 11216 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11217 System.identityHashCode(msg.obj)); 11218 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11219 System.identityHashCode(msg.obj)); 11220 11221 mHandler.sendMessage(msg); 11222 } 11223 11224 void installStage(String packageName, File stagedDir, String stagedCid, 11225 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11226 String installerPackageName, int installerUid, UserHandle user, 11227 Certificate[][] certificates) { 11228 if (DEBUG_EPHEMERAL) { 11229 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11230 Slog.d(TAG, "Ephemeral install of " + packageName); 11231 } 11232 } 11233 final VerificationInfo verificationInfo = new VerificationInfo( 11234 sessionParams.originatingUri, sessionParams.referrerUri, 11235 sessionParams.originatingUid, installerUid); 11236 11237 final OriginInfo origin; 11238 if (stagedDir != null) { 11239 origin = OriginInfo.fromStagedFile(stagedDir); 11240 } else { 11241 origin = OriginInfo.fromStagedContainer(stagedCid); 11242 } 11243 11244 final Message msg = mHandler.obtainMessage(INIT_COPY); 11245 final InstallParams params = new InstallParams(origin, null, observer, 11246 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11247 verificationInfo, user, sessionParams.abiOverride, 11248 sessionParams.grantedRuntimePermissions, certificates); 11249 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11250 msg.obj = params; 11251 11252 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11253 System.identityHashCode(msg.obj)); 11254 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11255 System.identityHashCode(msg.obj)); 11256 11257 mHandler.sendMessage(msg); 11258 } 11259 11260 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11261 int userId) { 11262 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11263 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11264 } 11265 11266 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11267 int appId, int userId) { 11268 Bundle extras = new Bundle(1); 11269 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11270 11271 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11272 packageName, extras, 0, null, null, new int[] {userId}); 11273 try { 11274 IActivityManager am = ActivityManagerNative.getDefault(); 11275 if (isSystem && am.isUserRunning(userId, 0)) { 11276 // The just-installed/enabled app is bundled on the system, so presumed 11277 // to be able to run automatically without needing an explicit launch. 11278 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11279 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11280 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11281 .setPackage(packageName); 11282 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11283 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11284 } 11285 } catch (RemoteException e) { 11286 // shouldn't happen 11287 Slog.w(TAG, "Unable to bootstrap installed package", e); 11288 } 11289 } 11290 11291 @Override 11292 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11293 int userId) { 11294 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11295 PackageSetting pkgSetting; 11296 final int uid = Binder.getCallingUid(); 11297 enforceCrossUserPermission(uid, userId, 11298 true /* requireFullPermission */, true /* checkShell */, 11299 "setApplicationHiddenSetting for user " + userId); 11300 11301 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11302 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11303 return false; 11304 } 11305 11306 long callingId = Binder.clearCallingIdentity(); 11307 try { 11308 boolean sendAdded = false; 11309 boolean sendRemoved = false; 11310 // writer 11311 synchronized (mPackages) { 11312 pkgSetting = mSettings.mPackages.get(packageName); 11313 if (pkgSetting == null) { 11314 return false; 11315 } 11316 if (pkgSetting.getHidden(userId) != hidden) { 11317 pkgSetting.setHidden(hidden, userId); 11318 mSettings.writePackageRestrictionsLPr(userId); 11319 if (hidden) { 11320 sendRemoved = true; 11321 } else { 11322 sendAdded = true; 11323 } 11324 } 11325 } 11326 if (sendAdded) { 11327 sendPackageAddedForUser(packageName, pkgSetting, userId); 11328 return true; 11329 } 11330 if (sendRemoved) { 11331 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11332 "hiding pkg"); 11333 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11334 return true; 11335 } 11336 } finally { 11337 Binder.restoreCallingIdentity(callingId); 11338 } 11339 return false; 11340 } 11341 11342 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11343 int userId) { 11344 final PackageRemovedInfo info = new PackageRemovedInfo(); 11345 info.removedPackage = packageName; 11346 info.removedUsers = new int[] {userId}; 11347 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11348 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11349 } 11350 11351 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11352 if (pkgList.length > 0) { 11353 Bundle extras = new Bundle(1); 11354 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11355 11356 sendPackageBroadcast( 11357 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11358 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11359 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11360 new int[] {userId}); 11361 } 11362 } 11363 11364 /** 11365 * Returns true if application is not found or there was an error. Otherwise it returns 11366 * the hidden state of the package for the given user. 11367 */ 11368 @Override 11369 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11370 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11372 true /* requireFullPermission */, false /* checkShell */, 11373 "getApplicationHidden for user " + userId); 11374 PackageSetting pkgSetting; 11375 long callingId = Binder.clearCallingIdentity(); 11376 try { 11377 // writer 11378 synchronized (mPackages) { 11379 pkgSetting = mSettings.mPackages.get(packageName); 11380 if (pkgSetting == null) { 11381 return true; 11382 } 11383 return pkgSetting.getHidden(userId); 11384 } 11385 } finally { 11386 Binder.restoreCallingIdentity(callingId); 11387 } 11388 } 11389 11390 /** 11391 * @hide 11392 */ 11393 @Override 11394 public int installExistingPackageAsUser(String packageName, int userId) { 11395 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11396 null); 11397 PackageSetting pkgSetting; 11398 final int uid = Binder.getCallingUid(); 11399 enforceCrossUserPermission(uid, userId, 11400 true /* requireFullPermission */, true /* checkShell */, 11401 "installExistingPackage for user " + userId); 11402 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11403 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11404 } 11405 11406 long callingId = Binder.clearCallingIdentity(); 11407 try { 11408 boolean installed = false; 11409 11410 // writer 11411 synchronized (mPackages) { 11412 pkgSetting = mSettings.mPackages.get(packageName); 11413 if (pkgSetting == null) { 11414 return PackageManager.INSTALL_FAILED_INVALID_URI; 11415 } 11416 if (!pkgSetting.getInstalled(userId)) { 11417 pkgSetting.setInstalled(true, userId); 11418 pkgSetting.setHidden(false, userId); 11419 mSettings.writePackageRestrictionsLPr(userId); 11420 installed = true; 11421 } 11422 } 11423 11424 if (installed) { 11425 if (pkgSetting.pkg != null) { 11426 synchronized (mInstallLock) { 11427 // We don't need to freeze for a brand new install 11428 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11429 } 11430 } 11431 sendPackageAddedForUser(packageName, pkgSetting, userId); 11432 } 11433 } finally { 11434 Binder.restoreCallingIdentity(callingId); 11435 } 11436 11437 return PackageManager.INSTALL_SUCCEEDED; 11438 } 11439 11440 boolean isUserRestricted(int userId, String restrictionKey) { 11441 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11442 if (restrictions.getBoolean(restrictionKey, false)) { 11443 Log.w(TAG, "User is restricted: " + restrictionKey); 11444 return true; 11445 } 11446 return false; 11447 } 11448 11449 @Override 11450 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11451 int userId) { 11452 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11453 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11454 true /* requireFullPermission */, true /* checkShell */, 11455 "setPackagesSuspended for user " + userId); 11456 11457 if (ArrayUtils.isEmpty(packageNames)) { 11458 return packageNames; 11459 } 11460 11461 // List of package names for whom the suspended state has changed. 11462 List<String> changedPackages = new ArrayList<>(packageNames.length); 11463 // List of package names for whom the suspended state is not set as requested in this 11464 // method. 11465 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11466 for (int i = 0; i < packageNames.length; i++) { 11467 String packageName = packageNames[i]; 11468 long callingId = Binder.clearCallingIdentity(); 11469 try { 11470 boolean changed = false; 11471 final int appId; 11472 synchronized (mPackages) { 11473 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11474 if (pkgSetting == null) { 11475 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11476 + "\". Skipping suspending/un-suspending."); 11477 unactionedPackages.add(packageName); 11478 continue; 11479 } 11480 appId = pkgSetting.appId; 11481 if (pkgSetting.getSuspended(userId) != suspended) { 11482 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11483 unactionedPackages.add(packageName); 11484 continue; 11485 } 11486 pkgSetting.setSuspended(suspended, userId); 11487 mSettings.writePackageRestrictionsLPr(userId); 11488 changed = true; 11489 changedPackages.add(packageName); 11490 } 11491 } 11492 11493 if (changed && suspended) { 11494 killApplication(packageName, UserHandle.getUid(userId, appId), 11495 "suspending package"); 11496 } 11497 } finally { 11498 Binder.restoreCallingIdentity(callingId); 11499 } 11500 } 11501 11502 if (!changedPackages.isEmpty()) { 11503 sendPackagesSuspendedForUser(changedPackages.toArray( 11504 new String[changedPackages.size()]), userId, suspended); 11505 } 11506 11507 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11508 } 11509 11510 @Override 11511 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11512 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11513 true /* requireFullPermission */, false /* checkShell */, 11514 "isPackageSuspendedForUser for user " + userId); 11515 synchronized (mPackages) { 11516 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11517 if (pkgSetting == null) { 11518 throw new IllegalArgumentException("Unknown target package: " + packageName); 11519 } 11520 return pkgSetting.getSuspended(userId); 11521 } 11522 } 11523 11524 /** 11525 * TODO: cache and disallow blocking the active dialer. 11526 * 11527 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11528 */ 11529 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11530 if (isPackageDeviceAdmin(packageName, userId)) { 11531 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11532 + "\": has an active device admin"); 11533 return false; 11534 } 11535 11536 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11537 if (packageName.equals(activeLauncherPackageName)) { 11538 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11539 + "\": contains the active launcher"); 11540 return false; 11541 } 11542 11543 if (packageName.equals(mRequiredInstallerPackage)) { 11544 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11545 + "\": required for package installation"); 11546 return false; 11547 } 11548 11549 if (packageName.equals(mRequiredVerifierPackage)) { 11550 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11551 + "\": required for package verification"); 11552 return false; 11553 } 11554 11555 final PackageParser.Package pkg = mPackages.get(packageName); 11556 if (pkg != null && isPrivilegedApp(pkg)) { 11557 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11558 + "\": is a privileged app"); 11559 return false; 11560 } 11561 11562 return true; 11563 } 11564 11565 private String getActiveLauncherPackageName(int userId) { 11566 Intent intent = new Intent(Intent.ACTION_MAIN); 11567 intent.addCategory(Intent.CATEGORY_HOME); 11568 ResolveInfo resolveInfo = resolveIntent( 11569 intent, 11570 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11571 PackageManager.MATCH_DEFAULT_ONLY, 11572 userId); 11573 11574 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11575 } 11576 11577 @Override 11578 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11579 mContext.enforceCallingOrSelfPermission( 11580 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11581 "Only package verification agents can verify applications"); 11582 11583 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11584 final PackageVerificationResponse response = new PackageVerificationResponse( 11585 verificationCode, Binder.getCallingUid()); 11586 msg.arg1 = id; 11587 msg.obj = response; 11588 mHandler.sendMessage(msg); 11589 } 11590 11591 @Override 11592 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11593 long millisecondsToDelay) { 11594 mContext.enforceCallingOrSelfPermission( 11595 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11596 "Only package verification agents can extend verification timeouts"); 11597 11598 final PackageVerificationState state = mPendingVerification.get(id); 11599 final PackageVerificationResponse response = new PackageVerificationResponse( 11600 verificationCodeAtTimeout, Binder.getCallingUid()); 11601 11602 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11603 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11604 } 11605 if (millisecondsToDelay < 0) { 11606 millisecondsToDelay = 0; 11607 } 11608 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11609 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11610 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11611 } 11612 11613 if ((state != null) && !state.timeoutExtended()) { 11614 state.extendTimeout(); 11615 11616 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11617 msg.arg1 = id; 11618 msg.obj = response; 11619 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11620 } 11621 } 11622 11623 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11624 int verificationCode, UserHandle user) { 11625 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11626 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11627 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11628 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11629 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11630 11631 mContext.sendBroadcastAsUser(intent, user, 11632 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11633 } 11634 11635 private ComponentName matchComponentForVerifier(String packageName, 11636 List<ResolveInfo> receivers) { 11637 ActivityInfo targetReceiver = null; 11638 11639 final int NR = receivers.size(); 11640 for (int i = 0; i < NR; i++) { 11641 final ResolveInfo info = receivers.get(i); 11642 if (info.activityInfo == null) { 11643 continue; 11644 } 11645 11646 if (packageName.equals(info.activityInfo.packageName)) { 11647 targetReceiver = info.activityInfo; 11648 break; 11649 } 11650 } 11651 11652 if (targetReceiver == null) { 11653 return null; 11654 } 11655 11656 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11657 } 11658 11659 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11660 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11661 if (pkgInfo.verifiers.length == 0) { 11662 return null; 11663 } 11664 11665 final int N = pkgInfo.verifiers.length; 11666 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11667 for (int i = 0; i < N; i++) { 11668 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11669 11670 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11671 receivers); 11672 if (comp == null) { 11673 continue; 11674 } 11675 11676 final int verifierUid = getUidForVerifier(verifierInfo); 11677 if (verifierUid == -1) { 11678 continue; 11679 } 11680 11681 if (DEBUG_VERIFY) { 11682 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11683 + " with the correct signature"); 11684 } 11685 sufficientVerifiers.add(comp); 11686 verificationState.addSufficientVerifier(verifierUid); 11687 } 11688 11689 return sufficientVerifiers; 11690 } 11691 11692 private int getUidForVerifier(VerifierInfo verifierInfo) { 11693 synchronized (mPackages) { 11694 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11695 if (pkg == null) { 11696 return -1; 11697 } else if (pkg.mSignatures.length != 1) { 11698 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11699 + " has more than one signature; ignoring"); 11700 return -1; 11701 } 11702 11703 /* 11704 * If the public key of the package's signature does not match 11705 * our expected public key, then this is a different package and 11706 * we should skip. 11707 */ 11708 11709 final byte[] expectedPublicKey; 11710 try { 11711 final Signature verifierSig = pkg.mSignatures[0]; 11712 final PublicKey publicKey = verifierSig.getPublicKey(); 11713 expectedPublicKey = publicKey.getEncoded(); 11714 } catch (CertificateException e) { 11715 return -1; 11716 } 11717 11718 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11719 11720 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11721 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11722 + " does not have the expected public key; ignoring"); 11723 return -1; 11724 } 11725 11726 return pkg.applicationInfo.uid; 11727 } 11728 } 11729 11730 @Override 11731 public void finishPackageInstall(int token, boolean didLaunch) { 11732 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11733 11734 if (DEBUG_INSTALL) { 11735 Slog.v(TAG, "BM finishing package install for " + token); 11736 } 11737 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11738 11739 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11740 mHandler.sendMessage(msg); 11741 } 11742 11743 /** 11744 * Get the verification agent timeout. 11745 * 11746 * @return verification timeout in milliseconds 11747 */ 11748 private long getVerificationTimeout() { 11749 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11750 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11751 DEFAULT_VERIFICATION_TIMEOUT); 11752 } 11753 11754 /** 11755 * Get the default verification agent response code. 11756 * 11757 * @return default verification response code 11758 */ 11759 private int getDefaultVerificationResponse() { 11760 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11761 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11762 DEFAULT_VERIFICATION_RESPONSE); 11763 } 11764 11765 /** 11766 * Check whether or not package verification has been enabled. 11767 * 11768 * @return true if verification should be performed 11769 */ 11770 private boolean isVerificationEnabled(int userId, int installFlags) { 11771 if (!DEFAULT_VERIFY_ENABLE) { 11772 return false; 11773 } 11774 // Ephemeral apps don't get the full verification treatment 11775 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11776 if (DEBUG_EPHEMERAL) { 11777 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11778 } 11779 return false; 11780 } 11781 11782 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11783 11784 // Check if installing from ADB 11785 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11786 // Do not run verification in a test harness environment 11787 if (ActivityManager.isRunningInTestHarness()) { 11788 return false; 11789 } 11790 if (ensureVerifyAppsEnabled) { 11791 return true; 11792 } 11793 // Check if the developer does not want package verification for ADB installs 11794 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11795 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11796 return false; 11797 } 11798 } 11799 11800 if (ensureVerifyAppsEnabled) { 11801 return true; 11802 } 11803 11804 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11805 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11806 } 11807 11808 @Override 11809 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11810 throws RemoteException { 11811 mContext.enforceCallingOrSelfPermission( 11812 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11813 "Only intentfilter verification agents can verify applications"); 11814 11815 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11816 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11817 Binder.getCallingUid(), verificationCode, failedDomains); 11818 msg.arg1 = id; 11819 msg.obj = response; 11820 mHandler.sendMessage(msg); 11821 } 11822 11823 @Override 11824 public int getIntentVerificationStatus(String packageName, int userId) { 11825 synchronized (mPackages) { 11826 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11827 } 11828 } 11829 11830 @Override 11831 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11832 mContext.enforceCallingOrSelfPermission( 11833 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11834 11835 boolean result = false; 11836 synchronized (mPackages) { 11837 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11838 } 11839 if (result) { 11840 scheduleWritePackageRestrictionsLocked(userId); 11841 } 11842 return result; 11843 } 11844 11845 @Override 11846 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11847 String packageName) { 11848 synchronized (mPackages) { 11849 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11850 } 11851 } 11852 11853 @Override 11854 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11855 if (TextUtils.isEmpty(packageName)) { 11856 return ParceledListSlice.emptyList(); 11857 } 11858 synchronized (mPackages) { 11859 PackageParser.Package pkg = mPackages.get(packageName); 11860 if (pkg == null || pkg.activities == null) { 11861 return ParceledListSlice.emptyList(); 11862 } 11863 final int count = pkg.activities.size(); 11864 ArrayList<IntentFilter> result = new ArrayList<>(); 11865 for (int n=0; n<count; n++) { 11866 PackageParser.Activity activity = pkg.activities.get(n); 11867 if (activity.intents != null && activity.intents.size() > 0) { 11868 result.addAll(activity.intents); 11869 } 11870 } 11871 return new ParceledListSlice<>(result); 11872 } 11873 } 11874 11875 @Override 11876 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11877 mContext.enforceCallingOrSelfPermission( 11878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11879 11880 synchronized (mPackages) { 11881 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11882 if (packageName != null) { 11883 result |= updateIntentVerificationStatus(packageName, 11884 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11885 userId); 11886 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11887 packageName, userId); 11888 } 11889 return result; 11890 } 11891 } 11892 11893 @Override 11894 public String getDefaultBrowserPackageName(int userId) { 11895 synchronized (mPackages) { 11896 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11897 } 11898 } 11899 11900 /** 11901 * Get the "allow unknown sources" setting. 11902 * 11903 * @return the current "allow unknown sources" setting 11904 */ 11905 private int getUnknownSourcesSettings() { 11906 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11907 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11908 -1); 11909 } 11910 11911 @Override 11912 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11913 final int uid = Binder.getCallingUid(); 11914 // writer 11915 synchronized (mPackages) { 11916 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11917 if (targetPackageSetting == null) { 11918 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11919 } 11920 11921 PackageSetting installerPackageSetting; 11922 if (installerPackageName != null) { 11923 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11924 if (installerPackageSetting == null) { 11925 throw new IllegalArgumentException("Unknown installer package: " 11926 + installerPackageName); 11927 } 11928 } else { 11929 installerPackageSetting = null; 11930 } 11931 11932 Signature[] callerSignature; 11933 Object obj = mSettings.getUserIdLPr(uid); 11934 if (obj != null) { 11935 if (obj instanceof SharedUserSetting) { 11936 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11937 } else if (obj instanceof PackageSetting) { 11938 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11939 } else { 11940 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11941 } 11942 } else { 11943 throw new SecurityException("Unknown calling UID: " + uid); 11944 } 11945 11946 // Verify: can't set installerPackageName to a package that is 11947 // not signed with the same cert as the caller. 11948 if (installerPackageSetting != null) { 11949 if (compareSignatures(callerSignature, 11950 installerPackageSetting.signatures.mSignatures) 11951 != PackageManager.SIGNATURE_MATCH) { 11952 throw new SecurityException( 11953 "Caller does not have same cert as new installer package " 11954 + installerPackageName); 11955 } 11956 } 11957 11958 // Verify: if target already has an installer package, it must 11959 // be signed with the same cert as the caller. 11960 if (targetPackageSetting.installerPackageName != null) { 11961 PackageSetting setting = mSettings.mPackages.get( 11962 targetPackageSetting.installerPackageName); 11963 // If the currently set package isn't valid, then it's always 11964 // okay to change it. 11965 if (setting != null) { 11966 if (compareSignatures(callerSignature, 11967 setting.signatures.mSignatures) 11968 != PackageManager.SIGNATURE_MATCH) { 11969 throw new SecurityException( 11970 "Caller does not have same cert as old installer package " 11971 + targetPackageSetting.installerPackageName); 11972 } 11973 } 11974 } 11975 11976 // Okay! 11977 targetPackageSetting.installerPackageName = installerPackageName; 11978 if (installerPackageName != null) { 11979 mSettings.mInstallerPackages.add(installerPackageName); 11980 } 11981 scheduleWriteSettingsLocked(); 11982 } 11983 } 11984 11985 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11986 // Queue up an async operation since the package installation may take a little while. 11987 mHandler.post(new Runnable() { 11988 public void run() { 11989 mHandler.removeCallbacks(this); 11990 // Result object to be returned 11991 PackageInstalledInfo res = new PackageInstalledInfo(); 11992 res.setReturnCode(currentStatus); 11993 res.uid = -1; 11994 res.pkg = null; 11995 res.removedInfo = null; 11996 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11997 args.doPreInstall(res.returnCode); 11998 synchronized (mInstallLock) { 11999 installPackageTracedLI(args, res); 12000 } 12001 args.doPostInstall(res.returnCode, res.uid); 12002 } 12003 12004 // A restore should be performed at this point if (a) the install 12005 // succeeded, (b) the operation is not an update, and (c) the new 12006 // package has not opted out of backup participation. 12007 final boolean update = res.removedInfo != null 12008 && res.removedInfo.removedPackage != null; 12009 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12010 boolean doRestore = !update 12011 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12012 12013 // Set up the post-install work request bookkeeping. This will be used 12014 // and cleaned up by the post-install event handling regardless of whether 12015 // there's a restore pass performed. Token values are >= 1. 12016 int token; 12017 if (mNextInstallToken < 0) mNextInstallToken = 1; 12018 token = mNextInstallToken++; 12019 12020 PostInstallData data = new PostInstallData(args, res); 12021 mRunningInstalls.put(token, data); 12022 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12023 12024 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12025 // Pass responsibility to the Backup Manager. It will perform a 12026 // restore if appropriate, then pass responsibility back to the 12027 // Package Manager to run the post-install observer callbacks 12028 // and broadcasts. 12029 IBackupManager bm = IBackupManager.Stub.asInterface( 12030 ServiceManager.getService(Context.BACKUP_SERVICE)); 12031 if (bm != null) { 12032 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12033 + " to BM for possible restore"); 12034 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12035 try { 12036 // TODO: http://b/22388012 12037 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12038 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12039 } else { 12040 doRestore = false; 12041 } 12042 } catch (RemoteException e) { 12043 // can't happen; the backup manager is local 12044 } catch (Exception e) { 12045 Slog.e(TAG, "Exception trying to enqueue restore", e); 12046 doRestore = false; 12047 } 12048 } else { 12049 Slog.e(TAG, "Backup Manager not found!"); 12050 doRestore = false; 12051 } 12052 } 12053 12054 if (!doRestore) { 12055 // No restore possible, or the Backup Manager was mysteriously not 12056 // available -- just fire the post-install work request directly. 12057 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12058 12059 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12060 12061 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12062 mHandler.sendMessage(msg); 12063 } 12064 } 12065 }); 12066 } 12067 12068 /** 12069 * Callback from PackageSettings whenever an app is first transitioned out of the 12070 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12071 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12072 * here whether the app is the target of an ongoing install, and only send the 12073 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12074 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12075 * handling. 12076 */ 12077 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12078 // Serialize this with the rest of the install-process message chain. In the 12079 // restore-at-install case, this Runnable will necessarily run before the 12080 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12081 // are coherent. In the non-restore case, the app has already completed install 12082 // and been launched through some other means, so it is not in a problematic 12083 // state for observers to see the FIRST_LAUNCH signal. 12084 mHandler.post(new Runnable() { 12085 @Override 12086 public void run() { 12087 for (int i = 0; i < mRunningInstalls.size(); i++) { 12088 final PostInstallData data = mRunningInstalls.valueAt(i); 12089 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12090 // right package; but is it for the right user? 12091 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12092 if (userId == data.res.newUsers[uIndex]) { 12093 if (DEBUG_BACKUP) { 12094 Slog.i(TAG, "Package " + pkgName 12095 + " being restored so deferring FIRST_LAUNCH"); 12096 } 12097 return; 12098 } 12099 } 12100 } 12101 } 12102 // didn't find it, so not being restored 12103 if (DEBUG_BACKUP) { 12104 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12105 } 12106 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12107 } 12108 }); 12109 } 12110 12111 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12112 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12113 installerPkg, null, userIds); 12114 } 12115 12116 private abstract class HandlerParams { 12117 private static final int MAX_RETRIES = 4; 12118 12119 /** 12120 * Number of times startCopy() has been attempted and had a non-fatal 12121 * error. 12122 */ 12123 private int mRetries = 0; 12124 12125 /** User handle for the user requesting the information or installation. */ 12126 private final UserHandle mUser; 12127 String traceMethod; 12128 int traceCookie; 12129 12130 HandlerParams(UserHandle user) { 12131 mUser = user; 12132 } 12133 12134 UserHandle getUser() { 12135 return mUser; 12136 } 12137 12138 HandlerParams setTraceMethod(String traceMethod) { 12139 this.traceMethod = traceMethod; 12140 return this; 12141 } 12142 12143 HandlerParams setTraceCookie(int traceCookie) { 12144 this.traceCookie = traceCookie; 12145 return this; 12146 } 12147 12148 final boolean startCopy() { 12149 boolean res; 12150 try { 12151 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12152 12153 if (++mRetries > MAX_RETRIES) { 12154 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12155 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12156 handleServiceError(); 12157 return false; 12158 } else { 12159 handleStartCopy(); 12160 res = true; 12161 } 12162 } catch (RemoteException e) { 12163 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12164 mHandler.sendEmptyMessage(MCS_RECONNECT); 12165 res = false; 12166 } 12167 handleReturnCode(); 12168 return res; 12169 } 12170 12171 final void serviceError() { 12172 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12173 handleServiceError(); 12174 handleReturnCode(); 12175 } 12176 12177 abstract void handleStartCopy() throws RemoteException; 12178 abstract void handleServiceError(); 12179 abstract void handleReturnCode(); 12180 } 12181 12182 class MeasureParams extends HandlerParams { 12183 private final PackageStats mStats; 12184 private boolean mSuccess; 12185 12186 private final IPackageStatsObserver mObserver; 12187 12188 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12189 super(new UserHandle(stats.userHandle)); 12190 mObserver = observer; 12191 mStats = stats; 12192 } 12193 12194 @Override 12195 public String toString() { 12196 return "MeasureParams{" 12197 + Integer.toHexString(System.identityHashCode(this)) 12198 + " " + mStats.packageName + "}"; 12199 } 12200 12201 @Override 12202 void handleStartCopy() throws RemoteException { 12203 synchronized (mInstallLock) { 12204 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12205 } 12206 12207 if (mSuccess) { 12208 final boolean mounted; 12209 if (Environment.isExternalStorageEmulated()) { 12210 mounted = true; 12211 } else { 12212 final String status = Environment.getExternalStorageState(); 12213 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12214 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12215 } 12216 12217 if (mounted) { 12218 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12219 12220 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12221 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12222 12223 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12224 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12225 12226 // Always subtract cache size, since it's a subdirectory 12227 mStats.externalDataSize -= mStats.externalCacheSize; 12228 12229 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12230 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12231 12232 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12233 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12234 } 12235 } 12236 } 12237 12238 @Override 12239 void handleReturnCode() { 12240 if (mObserver != null) { 12241 try { 12242 mObserver.onGetStatsCompleted(mStats, mSuccess); 12243 } catch (RemoteException e) { 12244 Slog.i(TAG, "Observer no longer exists."); 12245 } 12246 } 12247 } 12248 12249 @Override 12250 void handleServiceError() { 12251 Slog.e(TAG, "Could not measure application " + mStats.packageName 12252 + " external storage"); 12253 } 12254 } 12255 12256 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12257 throws RemoteException { 12258 long result = 0; 12259 for (File path : paths) { 12260 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12261 } 12262 return result; 12263 } 12264 12265 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12266 for (File path : paths) { 12267 try { 12268 mcs.clearDirectory(path.getAbsolutePath()); 12269 } catch (RemoteException e) { 12270 } 12271 } 12272 } 12273 12274 static class OriginInfo { 12275 /** 12276 * Location where install is coming from, before it has been 12277 * copied/renamed into place. This could be a single monolithic APK 12278 * file, or a cluster directory. This location may be untrusted. 12279 */ 12280 final File file; 12281 final String cid; 12282 12283 /** 12284 * Flag indicating that {@link #file} or {@link #cid} has already been 12285 * staged, meaning downstream users don't need to defensively copy the 12286 * contents. 12287 */ 12288 final boolean staged; 12289 12290 /** 12291 * Flag indicating that {@link #file} or {@link #cid} is an already 12292 * installed app that is being moved. 12293 */ 12294 final boolean existing; 12295 12296 final String resolvedPath; 12297 final File resolvedFile; 12298 12299 static OriginInfo fromNothing() { 12300 return new OriginInfo(null, null, false, false); 12301 } 12302 12303 static OriginInfo fromUntrustedFile(File file) { 12304 return new OriginInfo(file, null, false, false); 12305 } 12306 12307 static OriginInfo fromExistingFile(File file) { 12308 return new OriginInfo(file, null, false, true); 12309 } 12310 12311 static OriginInfo fromStagedFile(File file) { 12312 return new OriginInfo(file, null, true, false); 12313 } 12314 12315 static OriginInfo fromStagedContainer(String cid) { 12316 return new OriginInfo(null, cid, true, false); 12317 } 12318 12319 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12320 this.file = file; 12321 this.cid = cid; 12322 this.staged = staged; 12323 this.existing = existing; 12324 12325 if (cid != null) { 12326 resolvedPath = PackageHelper.getSdDir(cid); 12327 resolvedFile = new File(resolvedPath); 12328 } else if (file != null) { 12329 resolvedPath = file.getAbsolutePath(); 12330 resolvedFile = file; 12331 } else { 12332 resolvedPath = null; 12333 resolvedFile = null; 12334 } 12335 } 12336 } 12337 12338 static class MoveInfo { 12339 final int moveId; 12340 final String fromUuid; 12341 final String toUuid; 12342 final String packageName; 12343 final String dataAppName; 12344 final int appId; 12345 final String seinfo; 12346 final int targetSdkVersion; 12347 12348 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12349 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12350 this.moveId = moveId; 12351 this.fromUuid = fromUuid; 12352 this.toUuid = toUuid; 12353 this.packageName = packageName; 12354 this.dataAppName = dataAppName; 12355 this.appId = appId; 12356 this.seinfo = seinfo; 12357 this.targetSdkVersion = targetSdkVersion; 12358 } 12359 } 12360 12361 static class VerificationInfo { 12362 /** A constant used to indicate that a uid value is not present. */ 12363 public static final int NO_UID = -1; 12364 12365 /** URI referencing where the package was downloaded from. */ 12366 final Uri originatingUri; 12367 12368 /** HTTP referrer URI associated with the originatingURI. */ 12369 final Uri referrer; 12370 12371 /** UID of the application that the install request originated from. */ 12372 final int originatingUid; 12373 12374 /** UID of application requesting the install */ 12375 final int installerUid; 12376 12377 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12378 this.originatingUri = originatingUri; 12379 this.referrer = referrer; 12380 this.originatingUid = originatingUid; 12381 this.installerUid = installerUid; 12382 } 12383 } 12384 12385 class InstallParams extends HandlerParams { 12386 final OriginInfo origin; 12387 final MoveInfo move; 12388 final IPackageInstallObserver2 observer; 12389 int installFlags; 12390 final String installerPackageName; 12391 final String volumeUuid; 12392 private InstallArgs mArgs; 12393 private int mRet; 12394 final String packageAbiOverride; 12395 final String[] grantedRuntimePermissions; 12396 final VerificationInfo verificationInfo; 12397 final Certificate[][] certificates; 12398 12399 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12400 int installFlags, String installerPackageName, String volumeUuid, 12401 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12402 String[] grantedPermissions, Certificate[][] certificates) { 12403 super(user); 12404 this.origin = origin; 12405 this.move = move; 12406 this.observer = observer; 12407 this.installFlags = installFlags; 12408 this.installerPackageName = installerPackageName; 12409 this.volumeUuid = volumeUuid; 12410 this.verificationInfo = verificationInfo; 12411 this.packageAbiOverride = packageAbiOverride; 12412 this.grantedRuntimePermissions = grantedPermissions; 12413 this.certificates = certificates; 12414 } 12415 12416 @Override 12417 public String toString() { 12418 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12419 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12420 } 12421 12422 private int installLocationPolicy(PackageInfoLite pkgLite) { 12423 String packageName = pkgLite.packageName; 12424 int installLocation = pkgLite.installLocation; 12425 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12426 // reader 12427 synchronized (mPackages) { 12428 // Currently installed package which the new package is attempting to replace or 12429 // null if no such package is installed. 12430 PackageParser.Package installedPkg = mPackages.get(packageName); 12431 // Package which currently owns the data which the new package will own if installed. 12432 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12433 // will be null whereas dataOwnerPkg will contain information about the package 12434 // which was uninstalled while keeping its data. 12435 PackageParser.Package dataOwnerPkg = installedPkg; 12436 if (dataOwnerPkg == null) { 12437 PackageSetting ps = mSettings.mPackages.get(packageName); 12438 if (ps != null) { 12439 dataOwnerPkg = ps.pkg; 12440 } 12441 } 12442 12443 if (dataOwnerPkg != null) { 12444 // If installed, the package will get access to data left on the device by its 12445 // predecessor. As a security measure, this is permited only if this is not a 12446 // version downgrade or if the predecessor package is marked as debuggable and 12447 // a downgrade is explicitly requested. 12448 // 12449 // On debuggable platform builds, downgrades are permitted even for 12450 // non-debuggable packages to make testing easier. Debuggable platform builds do 12451 // not offer security guarantees and thus it's OK to disable some security 12452 // mechanisms to make debugging/testing easier on those builds. However, even on 12453 // debuggable builds downgrades of packages are permitted only if requested via 12454 // installFlags. This is because we aim to keep the behavior of debuggable 12455 // platform builds as close as possible to the behavior of non-debuggable 12456 // platform builds. 12457 final boolean downgradeRequested = 12458 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12459 final boolean packageDebuggable = 12460 (dataOwnerPkg.applicationInfo.flags 12461 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12462 final boolean downgradePermitted = 12463 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12464 if (!downgradePermitted) { 12465 try { 12466 checkDowngrade(dataOwnerPkg, pkgLite); 12467 } catch (PackageManagerException e) { 12468 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12469 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12470 } 12471 } 12472 } 12473 12474 if (installedPkg != null) { 12475 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12476 // Check for updated system application. 12477 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12478 if (onSd) { 12479 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12480 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12481 } 12482 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12483 } else { 12484 if (onSd) { 12485 // Install flag overrides everything. 12486 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12487 } 12488 // If current upgrade specifies particular preference 12489 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12490 // Application explicitly specified internal. 12491 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12492 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12493 // App explictly prefers external. Let policy decide 12494 } else { 12495 // Prefer previous location 12496 if (isExternal(installedPkg)) { 12497 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12498 } 12499 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12500 } 12501 } 12502 } else { 12503 // Invalid install. Return error code 12504 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12505 } 12506 } 12507 } 12508 // All the special cases have been taken care of. 12509 // Return result based on recommended install location. 12510 if (onSd) { 12511 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12512 } 12513 return pkgLite.recommendedInstallLocation; 12514 } 12515 12516 /* 12517 * Invoke remote method to get package information and install 12518 * location values. Override install location based on default 12519 * policy if needed and then create install arguments based 12520 * on the install location. 12521 */ 12522 public void handleStartCopy() throws RemoteException { 12523 int ret = PackageManager.INSTALL_SUCCEEDED; 12524 12525 // If we're already staged, we've firmly committed to an install location 12526 if (origin.staged) { 12527 if (origin.file != null) { 12528 installFlags |= PackageManager.INSTALL_INTERNAL; 12529 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12530 } else if (origin.cid != null) { 12531 installFlags |= PackageManager.INSTALL_EXTERNAL; 12532 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12533 } else { 12534 throw new IllegalStateException("Invalid stage location"); 12535 } 12536 } 12537 12538 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12539 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12540 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12541 PackageInfoLite pkgLite = null; 12542 12543 if (onInt && onSd) { 12544 // Check if both bits are set. 12545 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12546 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12547 } else if (onSd && ephemeral) { 12548 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12549 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12550 } else { 12551 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12552 packageAbiOverride); 12553 12554 if (DEBUG_EPHEMERAL && ephemeral) { 12555 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12556 } 12557 12558 /* 12559 * If we have too little free space, try to free cache 12560 * before giving up. 12561 */ 12562 if (!origin.staged && pkgLite.recommendedInstallLocation 12563 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12564 // TODO: focus freeing disk space on the target device 12565 final StorageManager storage = StorageManager.from(mContext); 12566 final long lowThreshold = storage.getStorageLowBytes( 12567 Environment.getDataDirectory()); 12568 12569 final long sizeBytes = mContainerService.calculateInstalledSize( 12570 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12571 12572 try { 12573 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12574 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12575 installFlags, packageAbiOverride); 12576 } catch (InstallerException e) { 12577 Slog.w(TAG, "Failed to free cache", e); 12578 } 12579 12580 /* 12581 * The cache free must have deleted the file we 12582 * downloaded to install. 12583 * 12584 * TODO: fix the "freeCache" call to not delete 12585 * the file we care about. 12586 */ 12587 if (pkgLite.recommendedInstallLocation 12588 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12589 pkgLite.recommendedInstallLocation 12590 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12591 } 12592 } 12593 } 12594 12595 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12596 int loc = pkgLite.recommendedInstallLocation; 12597 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12598 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12599 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12600 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12601 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12602 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12603 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12604 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12605 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12606 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12607 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12608 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12609 } else { 12610 // Override with defaults if needed. 12611 loc = installLocationPolicy(pkgLite); 12612 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12613 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12614 } else if (!onSd && !onInt) { 12615 // Override install location with flags 12616 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12617 // Set the flag to install on external media. 12618 installFlags |= PackageManager.INSTALL_EXTERNAL; 12619 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12620 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12621 if (DEBUG_EPHEMERAL) { 12622 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12623 } 12624 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12625 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12626 |PackageManager.INSTALL_INTERNAL); 12627 } else { 12628 // Make sure the flag for installing on external 12629 // media is unset 12630 installFlags |= PackageManager.INSTALL_INTERNAL; 12631 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12632 } 12633 } 12634 } 12635 } 12636 12637 final InstallArgs args = createInstallArgs(this); 12638 mArgs = args; 12639 12640 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12641 // TODO: http://b/22976637 12642 // Apps installed for "all" users use the device owner to verify the app 12643 UserHandle verifierUser = getUser(); 12644 if (verifierUser == UserHandle.ALL) { 12645 verifierUser = UserHandle.SYSTEM; 12646 } 12647 12648 /* 12649 * Determine if we have any installed package verifiers. If we 12650 * do, then we'll defer to them to verify the packages. 12651 */ 12652 final int requiredUid = mRequiredVerifierPackage == null ? -1 12653 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12654 verifierUser.getIdentifier()); 12655 if (!origin.existing && requiredUid != -1 12656 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12657 final Intent verification = new Intent( 12658 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12659 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12660 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12661 PACKAGE_MIME_TYPE); 12662 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12663 12664 // Query all live verifiers based on current user state 12665 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12666 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12667 12668 if (DEBUG_VERIFY) { 12669 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12670 + verification.toString() + " with " + pkgLite.verifiers.length 12671 + " optional verifiers"); 12672 } 12673 12674 final int verificationId = mPendingVerificationToken++; 12675 12676 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12677 12678 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12679 installerPackageName); 12680 12681 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12682 installFlags); 12683 12684 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12685 pkgLite.packageName); 12686 12687 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12688 pkgLite.versionCode); 12689 12690 if (verificationInfo != null) { 12691 if (verificationInfo.originatingUri != null) { 12692 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12693 verificationInfo.originatingUri); 12694 } 12695 if (verificationInfo.referrer != null) { 12696 verification.putExtra(Intent.EXTRA_REFERRER, 12697 verificationInfo.referrer); 12698 } 12699 if (verificationInfo.originatingUid >= 0) { 12700 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12701 verificationInfo.originatingUid); 12702 } 12703 if (verificationInfo.installerUid >= 0) { 12704 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12705 verificationInfo.installerUid); 12706 } 12707 } 12708 12709 final PackageVerificationState verificationState = new PackageVerificationState( 12710 requiredUid, args); 12711 12712 mPendingVerification.append(verificationId, verificationState); 12713 12714 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12715 receivers, verificationState); 12716 12717 /* 12718 * If any sufficient verifiers were listed in the package 12719 * manifest, attempt to ask them. 12720 */ 12721 if (sufficientVerifiers != null) { 12722 final int N = sufficientVerifiers.size(); 12723 if (N == 0) { 12724 Slog.i(TAG, "Additional verifiers required, but none installed."); 12725 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12726 } else { 12727 for (int i = 0; i < N; i++) { 12728 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12729 12730 final Intent sufficientIntent = new Intent(verification); 12731 sufficientIntent.setComponent(verifierComponent); 12732 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12733 } 12734 } 12735 } 12736 12737 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12738 mRequiredVerifierPackage, receivers); 12739 if (ret == PackageManager.INSTALL_SUCCEEDED 12740 && mRequiredVerifierPackage != null) { 12741 Trace.asyncTraceBegin( 12742 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12743 /* 12744 * Send the intent to the required verification agent, 12745 * but only start the verification timeout after the 12746 * target BroadcastReceivers have run. 12747 */ 12748 verification.setComponent(requiredVerifierComponent); 12749 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12750 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12751 new BroadcastReceiver() { 12752 @Override 12753 public void onReceive(Context context, Intent intent) { 12754 final Message msg = mHandler 12755 .obtainMessage(CHECK_PENDING_VERIFICATION); 12756 msg.arg1 = verificationId; 12757 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12758 } 12759 }, null, 0, null, null); 12760 12761 /* 12762 * We don't want the copy to proceed until verification 12763 * succeeds, so null out this field. 12764 */ 12765 mArgs = null; 12766 } 12767 } else { 12768 /* 12769 * No package verification is enabled, so immediately start 12770 * the remote call to initiate copy using temporary file. 12771 */ 12772 ret = args.copyApk(mContainerService, true); 12773 } 12774 } 12775 12776 mRet = ret; 12777 } 12778 12779 @Override 12780 void handleReturnCode() { 12781 // If mArgs is null, then MCS couldn't be reached. When it 12782 // reconnects, it will try again to install. At that point, this 12783 // will succeed. 12784 if (mArgs != null) { 12785 processPendingInstall(mArgs, mRet); 12786 } 12787 } 12788 12789 @Override 12790 void handleServiceError() { 12791 mArgs = createInstallArgs(this); 12792 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12793 } 12794 12795 public boolean isForwardLocked() { 12796 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12797 } 12798 } 12799 12800 /** 12801 * Used during creation of InstallArgs 12802 * 12803 * @param installFlags package installation flags 12804 * @return true if should be installed on external storage 12805 */ 12806 private static boolean installOnExternalAsec(int installFlags) { 12807 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12808 return false; 12809 } 12810 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12811 return true; 12812 } 12813 return false; 12814 } 12815 12816 /** 12817 * Used during creation of InstallArgs 12818 * 12819 * @param installFlags package installation flags 12820 * @return true if should be installed as forward locked 12821 */ 12822 private static boolean installForwardLocked(int installFlags) { 12823 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12824 } 12825 12826 private InstallArgs createInstallArgs(InstallParams params) { 12827 if (params.move != null) { 12828 return new MoveInstallArgs(params); 12829 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12830 return new AsecInstallArgs(params); 12831 } else { 12832 return new FileInstallArgs(params); 12833 } 12834 } 12835 12836 /** 12837 * Create args that describe an existing installed package. Typically used 12838 * when cleaning up old installs, or used as a move source. 12839 */ 12840 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12841 String resourcePath, String[] instructionSets) { 12842 final boolean isInAsec; 12843 if (installOnExternalAsec(installFlags)) { 12844 /* Apps on SD card are always in ASEC containers. */ 12845 isInAsec = true; 12846 } else if (installForwardLocked(installFlags) 12847 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12848 /* 12849 * Forward-locked apps are only in ASEC containers if they're the 12850 * new style 12851 */ 12852 isInAsec = true; 12853 } else { 12854 isInAsec = false; 12855 } 12856 12857 if (isInAsec) { 12858 return new AsecInstallArgs(codePath, instructionSets, 12859 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12860 } else { 12861 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12862 } 12863 } 12864 12865 static abstract class InstallArgs { 12866 /** @see InstallParams#origin */ 12867 final OriginInfo origin; 12868 /** @see InstallParams#move */ 12869 final MoveInfo move; 12870 12871 final IPackageInstallObserver2 observer; 12872 // Always refers to PackageManager flags only 12873 final int installFlags; 12874 final String installerPackageName; 12875 final String volumeUuid; 12876 final UserHandle user; 12877 final String abiOverride; 12878 final String[] installGrantPermissions; 12879 /** If non-null, drop an async trace when the install completes */ 12880 final String traceMethod; 12881 final int traceCookie; 12882 final Certificate[][] certificates; 12883 12884 // The list of instruction sets supported by this app. This is currently 12885 // only used during the rmdex() phase to clean up resources. We can get rid of this 12886 // if we move dex files under the common app path. 12887 /* nullable */ String[] instructionSets; 12888 12889 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12890 int installFlags, String installerPackageName, String volumeUuid, 12891 UserHandle user, String[] instructionSets, 12892 String abiOverride, String[] installGrantPermissions, 12893 String traceMethod, int traceCookie, Certificate[][] certificates) { 12894 this.origin = origin; 12895 this.move = move; 12896 this.installFlags = installFlags; 12897 this.observer = observer; 12898 this.installerPackageName = installerPackageName; 12899 this.volumeUuid = volumeUuid; 12900 this.user = user; 12901 this.instructionSets = instructionSets; 12902 this.abiOverride = abiOverride; 12903 this.installGrantPermissions = installGrantPermissions; 12904 this.traceMethod = traceMethod; 12905 this.traceCookie = traceCookie; 12906 this.certificates = certificates; 12907 } 12908 12909 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12910 abstract int doPreInstall(int status); 12911 12912 /** 12913 * Rename package into final resting place. All paths on the given 12914 * scanned package should be updated to reflect the rename. 12915 */ 12916 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12917 abstract int doPostInstall(int status, int uid); 12918 12919 /** @see PackageSettingBase#codePathString */ 12920 abstract String getCodePath(); 12921 /** @see PackageSettingBase#resourcePathString */ 12922 abstract String getResourcePath(); 12923 12924 // Need installer lock especially for dex file removal. 12925 abstract void cleanUpResourcesLI(); 12926 abstract boolean doPostDeleteLI(boolean delete); 12927 12928 /** 12929 * Called before the source arguments are copied. This is used mostly 12930 * for MoveParams when it needs to read the source file to put it in the 12931 * destination. 12932 */ 12933 int doPreCopy() { 12934 return PackageManager.INSTALL_SUCCEEDED; 12935 } 12936 12937 /** 12938 * Called after the source arguments are copied. This is used mostly for 12939 * MoveParams when it needs to read the source file to put it in the 12940 * destination. 12941 */ 12942 int doPostCopy(int uid) { 12943 return PackageManager.INSTALL_SUCCEEDED; 12944 } 12945 12946 protected boolean isFwdLocked() { 12947 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12948 } 12949 12950 protected boolean isExternalAsec() { 12951 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12952 } 12953 12954 protected boolean isEphemeral() { 12955 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12956 } 12957 12958 UserHandle getUser() { 12959 return user; 12960 } 12961 } 12962 12963 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12964 if (!allCodePaths.isEmpty()) { 12965 if (instructionSets == null) { 12966 throw new IllegalStateException("instructionSet == null"); 12967 } 12968 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12969 for (String codePath : allCodePaths) { 12970 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12971 try { 12972 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12973 } catch (InstallerException ignored) { 12974 } 12975 } 12976 } 12977 } 12978 } 12979 12980 /** 12981 * Logic to handle installation of non-ASEC applications, including copying 12982 * and renaming logic. 12983 */ 12984 class FileInstallArgs extends InstallArgs { 12985 private File codeFile; 12986 private File resourceFile; 12987 12988 // Example topology: 12989 // /data/app/com.example/base.apk 12990 // /data/app/com.example/split_foo.apk 12991 // /data/app/com.example/lib/arm/libfoo.so 12992 // /data/app/com.example/lib/arm64/libfoo.so 12993 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12994 12995 /** New install */ 12996 FileInstallArgs(InstallParams params) { 12997 super(params.origin, params.move, params.observer, params.installFlags, 12998 params.installerPackageName, params.volumeUuid, 12999 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13000 params.grantedRuntimePermissions, 13001 params.traceMethod, params.traceCookie, params.certificates); 13002 if (isFwdLocked()) { 13003 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13004 } 13005 } 13006 13007 /** Existing install */ 13008 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13009 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13010 null, null, null, 0, null /*certificates*/); 13011 this.codeFile = (codePath != null) ? new File(codePath) : null; 13012 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13013 } 13014 13015 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13016 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13017 try { 13018 return doCopyApk(imcs, temp); 13019 } finally { 13020 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13021 } 13022 } 13023 13024 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13025 if (origin.staged) { 13026 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13027 codeFile = origin.file; 13028 resourceFile = origin.file; 13029 return PackageManager.INSTALL_SUCCEEDED; 13030 } 13031 13032 try { 13033 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13034 final File tempDir = 13035 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13036 codeFile = tempDir; 13037 resourceFile = tempDir; 13038 } catch (IOException e) { 13039 Slog.w(TAG, "Failed to create copy file: " + e); 13040 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13041 } 13042 13043 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13044 @Override 13045 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13046 if (!FileUtils.isValidExtFilename(name)) { 13047 throw new IllegalArgumentException("Invalid filename: " + name); 13048 } 13049 try { 13050 final File file = new File(codeFile, name); 13051 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13052 O_RDWR | O_CREAT, 0644); 13053 Os.chmod(file.getAbsolutePath(), 0644); 13054 return new ParcelFileDescriptor(fd); 13055 } catch (ErrnoException e) { 13056 throw new RemoteException("Failed to open: " + e.getMessage()); 13057 } 13058 } 13059 }; 13060 13061 int ret = PackageManager.INSTALL_SUCCEEDED; 13062 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13063 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13064 Slog.e(TAG, "Failed to copy package"); 13065 return ret; 13066 } 13067 13068 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13069 NativeLibraryHelper.Handle handle = null; 13070 try { 13071 handle = NativeLibraryHelper.Handle.create(codeFile); 13072 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13073 abiOverride); 13074 } catch (IOException e) { 13075 Slog.e(TAG, "Copying native libraries failed", e); 13076 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13077 } finally { 13078 IoUtils.closeQuietly(handle); 13079 } 13080 13081 return ret; 13082 } 13083 13084 int doPreInstall(int status) { 13085 if (status != PackageManager.INSTALL_SUCCEEDED) { 13086 cleanUp(); 13087 } 13088 return status; 13089 } 13090 13091 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13092 if (status != PackageManager.INSTALL_SUCCEEDED) { 13093 cleanUp(); 13094 return false; 13095 } 13096 13097 final File targetDir = codeFile.getParentFile(); 13098 final File beforeCodeFile = codeFile; 13099 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13100 13101 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13102 try { 13103 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13104 } catch (ErrnoException e) { 13105 Slog.w(TAG, "Failed to rename", e); 13106 return false; 13107 } 13108 13109 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13110 Slog.w(TAG, "Failed to restorecon"); 13111 return false; 13112 } 13113 13114 // Reflect the rename internally 13115 codeFile = afterCodeFile; 13116 resourceFile = afterCodeFile; 13117 13118 // Reflect the rename in scanned details 13119 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13120 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13121 afterCodeFile, pkg.baseCodePath)); 13122 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13123 afterCodeFile, pkg.splitCodePaths)); 13124 13125 // Reflect the rename in app info 13126 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13127 pkg.setApplicationInfoCodePath(pkg.codePath); 13128 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13129 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13130 pkg.setApplicationInfoResourcePath(pkg.codePath); 13131 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13132 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13133 13134 return true; 13135 } 13136 13137 int doPostInstall(int status, int uid) { 13138 if (status != PackageManager.INSTALL_SUCCEEDED) { 13139 cleanUp(); 13140 } 13141 return status; 13142 } 13143 13144 @Override 13145 String getCodePath() { 13146 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13147 } 13148 13149 @Override 13150 String getResourcePath() { 13151 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13152 } 13153 13154 private boolean cleanUp() { 13155 if (codeFile == null || !codeFile.exists()) { 13156 return false; 13157 } 13158 13159 removeCodePathLI(codeFile); 13160 13161 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13162 resourceFile.delete(); 13163 } 13164 13165 return true; 13166 } 13167 13168 void cleanUpResourcesLI() { 13169 // Try enumerating all code paths before deleting 13170 List<String> allCodePaths = Collections.EMPTY_LIST; 13171 if (codeFile != null && codeFile.exists()) { 13172 try { 13173 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13174 allCodePaths = pkg.getAllCodePaths(); 13175 } catch (PackageParserException e) { 13176 // Ignored; we tried our best 13177 } 13178 } 13179 13180 cleanUp(); 13181 removeDexFiles(allCodePaths, instructionSets); 13182 } 13183 13184 boolean doPostDeleteLI(boolean delete) { 13185 // XXX err, shouldn't we respect the delete flag? 13186 cleanUpResourcesLI(); 13187 return true; 13188 } 13189 } 13190 13191 private boolean isAsecExternal(String cid) { 13192 final String asecPath = PackageHelper.getSdFilesystem(cid); 13193 return !asecPath.startsWith(mAsecInternalPath); 13194 } 13195 13196 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13197 PackageManagerException { 13198 if (copyRet < 0) { 13199 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13200 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13201 throw new PackageManagerException(copyRet, message); 13202 } 13203 } 13204 } 13205 13206 /** 13207 * Extract the MountService "container ID" from the full code path of an 13208 * .apk. 13209 */ 13210 static String cidFromCodePath(String fullCodePath) { 13211 int eidx = fullCodePath.lastIndexOf("/"); 13212 String subStr1 = fullCodePath.substring(0, eidx); 13213 int sidx = subStr1.lastIndexOf("/"); 13214 return subStr1.substring(sidx+1, eidx); 13215 } 13216 13217 /** 13218 * Logic to handle installation of ASEC applications, including copying and 13219 * renaming logic. 13220 */ 13221 class AsecInstallArgs extends InstallArgs { 13222 static final String RES_FILE_NAME = "pkg.apk"; 13223 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13224 13225 String cid; 13226 String packagePath; 13227 String resourcePath; 13228 13229 /** New install */ 13230 AsecInstallArgs(InstallParams params) { 13231 super(params.origin, params.move, params.observer, params.installFlags, 13232 params.installerPackageName, params.volumeUuid, 13233 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13234 params.grantedRuntimePermissions, 13235 params.traceMethod, params.traceCookie, params.certificates); 13236 } 13237 13238 /** Existing install */ 13239 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13240 boolean isExternal, boolean isForwardLocked) { 13241 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13242 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13243 instructionSets, null, null, null, 0, null /*certificates*/); 13244 // Hackily pretend we're still looking at a full code path 13245 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13246 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13247 } 13248 13249 // Extract cid from fullCodePath 13250 int eidx = fullCodePath.lastIndexOf("/"); 13251 String subStr1 = fullCodePath.substring(0, eidx); 13252 int sidx = subStr1.lastIndexOf("/"); 13253 cid = subStr1.substring(sidx+1, eidx); 13254 setMountPath(subStr1); 13255 } 13256 13257 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13258 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13259 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13260 instructionSets, null, null, null, 0, null /*certificates*/); 13261 this.cid = cid; 13262 setMountPath(PackageHelper.getSdDir(cid)); 13263 } 13264 13265 void createCopyFile() { 13266 cid = mInstallerService.allocateExternalStageCidLegacy(); 13267 } 13268 13269 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13270 if (origin.staged && origin.cid != null) { 13271 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13272 cid = origin.cid; 13273 setMountPath(PackageHelper.getSdDir(cid)); 13274 return PackageManager.INSTALL_SUCCEEDED; 13275 } 13276 13277 if (temp) { 13278 createCopyFile(); 13279 } else { 13280 /* 13281 * Pre-emptively destroy the container since it's destroyed if 13282 * copying fails due to it existing anyway. 13283 */ 13284 PackageHelper.destroySdDir(cid); 13285 } 13286 13287 final String newMountPath = imcs.copyPackageToContainer( 13288 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13289 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13290 13291 if (newMountPath != null) { 13292 setMountPath(newMountPath); 13293 return PackageManager.INSTALL_SUCCEEDED; 13294 } else { 13295 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13296 } 13297 } 13298 13299 @Override 13300 String getCodePath() { 13301 return packagePath; 13302 } 13303 13304 @Override 13305 String getResourcePath() { 13306 return resourcePath; 13307 } 13308 13309 int doPreInstall(int status) { 13310 if (status != PackageManager.INSTALL_SUCCEEDED) { 13311 // Destroy container 13312 PackageHelper.destroySdDir(cid); 13313 } else { 13314 boolean mounted = PackageHelper.isContainerMounted(cid); 13315 if (!mounted) { 13316 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13317 Process.SYSTEM_UID); 13318 if (newMountPath != null) { 13319 setMountPath(newMountPath); 13320 } else { 13321 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13322 } 13323 } 13324 } 13325 return status; 13326 } 13327 13328 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13329 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13330 String newMountPath = null; 13331 if (PackageHelper.isContainerMounted(cid)) { 13332 // Unmount the container 13333 if (!PackageHelper.unMountSdDir(cid)) { 13334 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13335 return false; 13336 } 13337 } 13338 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13339 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13340 " which might be stale. Will try to clean up."); 13341 // Clean up the stale container and proceed to recreate. 13342 if (!PackageHelper.destroySdDir(newCacheId)) { 13343 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13344 return false; 13345 } 13346 // Successfully cleaned up stale container. Try to rename again. 13347 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13348 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13349 + " inspite of cleaning it up."); 13350 return false; 13351 } 13352 } 13353 if (!PackageHelper.isContainerMounted(newCacheId)) { 13354 Slog.w(TAG, "Mounting container " + newCacheId); 13355 newMountPath = PackageHelper.mountSdDir(newCacheId, 13356 getEncryptKey(), Process.SYSTEM_UID); 13357 } else { 13358 newMountPath = PackageHelper.getSdDir(newCacheId); 13359 } 13360 if (newMountPath == null) { 13361 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13362 return false; 13363 } 13364 Log.i(TAG, "Succesfully renamed " + cid + 13365 " to " + newCacheId + 13366 " at new path: " + newMountPath); 13367 cid = newCacheId; 13368 13369 final File beforeCodeFile = new File(packagePath); 13370 setMountPath(newMountPath); 13371 final File afterCodeFile = new File(packagePath); 13372 13373 // Reflect the rename in scanned details 13374 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13375 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13376 afterCodeFile, pkg.baseCodePath)); 13377 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13378 afterCodeFile, pkg.splitCodePaths)); 13379 13380 // Reflect the rename in app info 13381 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13382 pkg.setApplicationInfoCodePath(pkg.codePath); 13383 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13384 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13385 pkg.setApplicationInfoResourcePath(pkg.codePath); 13386 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13387 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13388 13389 return true; 13390 } 13391 13392 private void setMountPath(String mountPath) { 13393 final File mountFile = new File(mountPath); 13394 13395 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13396 if (monolithicFile.exists()) { 13397 packagePath = monolithicFile.getAbsolutePath(); 13398 if (isFwdLocked()) { 13399 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13400 } else { 13401 resourcePath = packagePath; 13402 } 13403 } else { 13404 packagePath = mountFile.getAbsolutePath(); 13405 resourcePath = packagePath; 13406 } 13407 } 13408 13409 int doPostInstall(int status, int uid) { 13410 if (status != PackageManager.INSTALL_SUCCEEDED) { 13411 cleanUp(); 13412 } else { 13413 final int groupOwner; 13414 final String protectedFile; 13415 if (isFwdLocked()) { 13416 groupOwner = UserHandle.getSharedAppGid(uid); 13417 protectedFile = RES_FILE_NAME; 13418 } else { 13419 groupOwner = -1; 13420 protectedFile = null; 13421 } 13422 13423 if (uid < Process.FIRST_APPLICATION_UID 13424 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13425 Slog.e(TAG, "Failed to finalize " + cid); 13426 PackageHelper.destroySdDir(cid); 13427 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13428 } 13429 13430 boolean mounted = PackageHelper.isContainerMounted(cid); 13431 if (!mounted) { 13432 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13433 } 13434 } 13435 return status; 13436 } 13437 13438 private void cleanUp() { 13439 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13440 13441 // Destroy secure container 13442 PackageHelper.destroySdDir(cid); 13443 } 13444 13445 private List<String> getAllCodePaths() { 13446 final File codeFile = new File(getCodePath()); 13447 if (codeFile != null && codeFile.exists()) { 13448 try { 13449 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13450 return pkg.getAllCodePaths(); 13451 } catch (PackageParserException e) { 13452 // Ignored; we tried our best 13453 } 13454 } 13455 return Collections.EMPTY_LIST; 13456 } 13457 13458 void cleanUpResourcesLI() { 13459 // Enumerate all code paths before deleting 13460 cleanUpResourcesLI(getAllCodePaths()); 13461 } 13462 13463 private void cleanUpResourcesLI(List<String> allCodePaths) { 13464 cleanUp(); 13465 removeDexFiles(allCodePaths, instructionSets); 13466 } 13467 13468 String getPackageName() { 13469 return getAsecPackageName(cid); 13470 } 13471 13472 boolean doPostDeleteLI(boolean delete) { 13473 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13474 final List<String> allCodePaths = getAllCodePaths(); 13475 boolean mounted = PackageHelper.isContainerMounted(cid); 13476 if (mounted) { 13477 // Unmount first 13478 if (PackageHelper.unMountSdDir(cid)) { 13479 mounted = false; 13480 } 13481 } 13482 if (!mounted && delete) { 13483 cleanUpResourcesLI(allCodePaths); 13484 } 13485 return !mounted; 13486 } 13487 13488 @Override 13489 int doPreCopy() { 13490 if (isFwdLocked()) { 13491 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13492 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13493 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13494 } 13495 } 13496 13497 return PackageManager.INSTALL_SUCCEEDED; 13498 } 13499 13500 @Override 13501 int doPostCopy(int uid) { 13502 if (isFwdLocked()) { 13503 if (uid < Process.FIRST_APPLICATION_UID 13504 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13505 RES_FILE_NAME)) { 13506 Slog.e(TAG, "Failed to finalize " + cid); 13507 PackageHelper.destroySdDir(cid); 13508 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13509 } 13510 } 13511 13512 return PackageManager.INSTALL_SUCCEEDED; 13513 } 13514 } 13515 13516 /** 13517 * Logic to handle movement of existing installed applications. 13518 */ 13519 class MoveInstallArgs extends InstallArgs { 13520 private File codeFile; 13521 private File resourceFile; 13522 13523 /** New install */ 13524 MoveInstallArgs(InstallParams params) { 13525 super(params.origin, params.move, params.observer, params.installFlags, 13526 params.installerPackageName, params.volumeUuid, 13527 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13528 params.grantedRuntimePermissions, 13529 params.traceMethod, params.traceCookie, params.certificates); 13530 } 13531 13532 int copyApk(IMediaContainerService imcs, boolean temp) { 13533 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13534 + move.fromUuid + " to " + move.toUuid); 13535 synchronized (mInstaller) { 13536 try { 13537 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13538 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13539 } catch (InstallerException e) { 13540 Slog.w(TAG, "Failed to move app", e); 13541 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13542 } 13543 } 13544 13545 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13546 resourceFile = codeFile; 13547 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13548 13549 return PackageManager.INSTALL_SUCCEEDED; 13550 } 13551 13552 int doPreInstall(int status) { 13553 if (status != PackageManager.INSTALL_SUCCEEDED) { 13554 cleanUp(move.toUuid); 13555 } 13556 return status; 13557 } 13558 13559 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13560 if (status != PackageManager.INSTALL_SUCCEEDED) { 13561 cleanUp(move.toUuid); 13562 return false; 13563 } 13564 13565 // Reflect the move in app info 13566 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13567 pkg.setApplicationInfoCodePath(pkg.codePath); 13568 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13569 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13570 pkg.setApplicationInfoResourcePath(pkg.codePath); 13571 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13572 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13573 13574 return true; 13575 } 13576 13577 int doPostInstall(int status, int uid) { 13578 if (status == PackageManager.INSTALL_SUCCEEDED) { 13579 cleanUp(move.fromUuid); 13580 } else { 13581 cleanUp(move.toUuid); 13582 } 13583 return status; 13584 } 13585 13586 @Override 13587 String getCodePath() { 13588 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13589 } 13590 13591 @Override 13592 String getResourcePath() { 13593 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13594 } 13595 13596 private boolean cleanUp(String volumeUuid) { 13597 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13598 move.dataAppName); 13599 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13600 final int[] userIds = sUserManager.getUserIds(); 13601 synchronized (mInstallLock) { 13602 // Clean up both app data and code 13603 // All package moves are frozen until finished 13604 for (int userId : userIds) { 13605 try { 13606 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13607 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13608 } catch (InstallerException e) { 13609 Slog.w(TAG, String.valueOf(e)); 13610 } 13611 } 13612 removeCodePathLI(codeFile); 13613 } 13614 return true; 13615 } 13616 13617 void cleanUpResourcesLI() { 13618 throw new UnsupportedOperationException(); 13619 } 13620 13621 boolean doPostDeleteLI(boolean delete) { 13622 throw new UnsupportedOperationException(); 13623 } 13624 } 13625 13626 static String getAsecPackageName(String packageCid) { 13627 int idx = packageCid.lastIndexOf("-"); 13628 if (idx == -1) { 13629 return packageCid; 13630 } 13631 return packageCid.substring(0, idx); 13632 } 13633 13634 // Utility method used to create code paths based on package name and available index. 13635 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13636 String idxStr = ""; 13637 int idx = 1; 13638 // Fall back to default value of idx=1 if prefix is not 13639 // part of oldCodePath 13640 if (oldCodePath != null) { 13641 String subStr = oldCodePath; 13642 // Drop the suffix right away 13643 if (suffix != null && subStr.endsWith(suffix)) { 13644 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13645 } 13646 // If oldCodePath already contains prefix find out the 13647 // ending index to either increment or decrement. 13648 int sidx = subStr.lastIndexOf(prefix); 13649 if (sidx != -1) { 13650 subStr = subStr.substring(sidx + prefix.length()); 13651 if (subStr != null) { 13652 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13653 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13654 } 13655 try { 13656 idx = Integer.parseInt(subStr); 13657 if (idx <= 1) { 13658 idx++; 13659 } else { 13660 idx--; 13661 } 13662 } catch(NumberFormatException e) { 13663 } 13664 } 13665 } 13666 } 13667 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13668 return prefix + idxStr; 13669 } 13670 13671 private File getNextCodePath(File targetDir, String packageName) { 13672 int suffix = 1; 13673 File result; 13674 do { 13675 result = new File(targetDir, packageName + "-" + suffix); 13676 suffix++; 13677 } while (result.exists()); 13678 return result; 13679 } 13680 13681 // Utility method that returns the relative package path with respect 13682 // to the installation directory. Like say for /data/data/com.test-1.apk 13683 // string com.test-1 is returned. 13684 static String deriveCodePathName(String codePath) { 13685 if (codePath == null) { 13686 return null; 13687 } 13688 final File codeFile = new File(codePath); 13689 final String name = codeFile.getName(); 13690 if (codeFile.isDirectory()) { 13691 return name; 13692 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13693 final int lastDot = name.lastIndexOf('.'); 13694 return name.substring(0, lastDot); 13695 } else { 13696 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13697 return null; 13698 } 13699 } 13700 13701 static class PackageInstalledInfo { 13702 String name; 13703 int uid; 13704 // The set of users that originally had this package installed. 13705 int[] origUsers; 13706 // The set of users that now have this package installed. 13707 int[] newUsers; 13708 PackageParser.Package pkg; 13709 int returnCode; 13710 String returnMsg; 13711 PackageRemovedInfo removedInfo; 13712 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13713 13714 public void setError(int code, String msg) { 13715 setReturnCode(code); 13716 setReturnMessage(msg); 13717 Slog.w(TAG, msg); 13718 } 13719 13720 public void setError(String msg, PackageParserException e) { 13721 setReturnCode(e.error); 13722 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13723 Slog.w(TAG, msg, e); 13724 } 13725 13726 public void setError(String msg, PackageManagerException e) { 13727 returnCode = e.error; 13728 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13729 Slog.w(TAG, msg, e); 13730 } 13731 13732 public void setReturnCode(int returnCode) { 13733 this.returnCode = returnCode; 13734 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13735 for (int i = 0; i < childCount; i++) { 13736 addedChildPackages.valueAt(i).returnCode = returnCode; 13737 } 13738 } 13739 13740 private void setReturnMessage(String returnMsg) { 13741 this.returnMsg = returnMsg; 13742 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13743 for (int i = 0; i < childCount; i++) { 13744 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13745 } 13746 } 13747 13748 // In some error cases we want to convey more info back to the observer 13749 String origPackage; 13750 String origPermission; 13751 } 13752 13753 /* 13754 * Install a non-existing package. 13755 */ 13756 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13757 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13758 PackageInstalledInfo res) { 13759 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13760 13761 // Remember this for later, in case we need to rollback this install 13762 String pkgName = pkg.packageName; 13763 13764 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13765 13766 synchronized(mPackages) { 13767 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13768 // A package with the same name is already installed, though 13769 // it has been renamed to an older name. The package we 13770 // are trying to install should be installed as an update to 13771 // the existing one, but that has not been requested, so bail. 13772 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13773 + " without first uninstalling package running as " 13774 + mSettings.mRenamedPackages.get(pkgName)); 13775 return; 13776 } 13777 if (mPackages.containsKey(pkgName)) { 13778 // Don't allow installation over an existing package with the same name. 13779 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13780 + " without first uninstalling."); 13781 return; 13782 } 13783 } 13784 13785 try { 13786 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13787 System.currentTimeMillis(), user); 13788 13789 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13790 13791 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13792 prepareAppDataAfterInstallLIF(newPackage); 13793 13794 } else { 13795 // Remove package from internal structures, but keep around any 13796 // data that might have already existed 13797 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13798 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13799 } 13800 } catch (PackageManagerException e) { 13801 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13802 } 13803 13804 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13805 } 13806 13807 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13808 // Can't rotate keys during boot or if sharedUser. 13809 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13810 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13811 return false; 13812 } 13813 // app is using upgradeKeySets; make sure all are valid 13814 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13815 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13816 for (int i = 0; i < upgradeKeySets.length; i++) { 13817 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13818 Slog.wtf(TAG, "Package " 13819 + (oldPs.name != null ? oldPs.name : "<null>") 13820 + " contains upgrade-key-set reference to unknown key-set: " 13821 + upgradeKeySets[i] 13822 + " reverting to signatures check."); 13823 return false; 13824 } 13825 } 13826 return true; 13827 } 13828 13829 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13830 // Upgrade keysets are being used. Determine if new package has a superset of the 13831 // required keys. 13832 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13833 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13834 for (int i = 0; i < upgradeKeySets.length; i++) { 13835 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13836 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13837 return true; 13838 } 13839 } 13840 return false; 13841 } 13842 13843 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13844 try (DigestInputStream digestStream = 13845 new DigestInputStream(new FileInputStream(file), digest)) { 13846 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13847 } 13848 } 13849 13850 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13851 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13852 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13853 13854 final PackageParser.Package oldPackage; 13855 final String pkgName = pkg.packageName; 13856 final int[] allUsers; 13857 final int[] installedUsers; 13858 13859 synchronized(mPackages) { 13860 oldPackage = mPackages.get(pkgName); 13861 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13862 13863 // don't allow upgrade to target a release SDK from a pre-release SDK 13864 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13865 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13866 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13867 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13868 if (oldTargetsPreRelease 13869 && !newTargetsPreRelease 13870 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13871 Slog.w(TAG, "Can't install package targeting released sdk"); 13872 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13873 return; 13874 } 13875 13876 // don't allow an upgrade from full to ephemeral 13877 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13878 if (isEphemeral && !oldIsEphemeral) { 13879 // can't downgrade from full to ephemeral 13880 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13881 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13882 return; 13883 } 13884 13885 // verify signatures are valid 13886 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13887 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13888 if (!checkUpgradeKeySetLP(ps, pkg)) { 13889 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13890 "New package not signed by keys specified by upgrade-keysets: " 13891 + pkgName); 13892 return; 13893 } 13894 } else { 13895 // default to original signature matching 13896 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13897 != PackageManager.SIGNATURE_MATCH) { 13898 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13899 "New package has a different signature: " + pkgName); 13900 return; 13901 } 13902 } 13903 13904 // don't allow a system upgrade unless the upgrade hash matches 13905 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13906 byte[] digestBytes = null; 13907 try { 13908 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13909 updateDigest(digest, new File(pkg.baseCodePath)); 13910 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13911 for (String path : pkg.splitCodePaths) { 13912 updateDigest(digest, new File(path)); 13913 } 13914 } 13915 digestBytes = digest.digest(); 13916 } catch (NoSuchAlgorithmException | IOException e) { 13917 res.setError(INSTALL_FAILED_INVALID_APK, 13918 "Could not compute hash: " + pkgName); 13919 return; 13920 } 13921 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13922 res.setError(INSTALL_FAILED_INVALID_APK, 13923 "New package fails restrict-update check: " + pkgName); 13924 return; 13925 } 13926 // retain upgrade restriction 13927 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13928 } 13929 13930 // Check for shared user id changes 13931 String invalidPackageName = 13932 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13933 if (invalidPackageName != null) { 13934 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13935 "Package " + invalidPackageName + " tried to change user " 13936 + oldPackage.mSharedUserId); 13937 return; 13938 } 13939 13940 // In case of rollback, remember per-user/profile install state 13941 allUsers = sUserManager.getUserIds(); 13942 installedUsers = ps.queryInstalledUsers(allUsers, true); 13943 } 13944 13945 // Update what is removed 13946 res.removedInfo = new PackageRemovedInfo(); 13947 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13948 res.removedInfo.removedPackage = oldPackage.packageName; 13949 res.removedInfo.isUpdate = true; 13950 res.removedInfo.origUsers = installedUsers; 13951 final int childCount = (oldPackage.childPackages != null) 13952 ? oldPackage.childPackages.size() : 0; 13953 for (int i = 0; i < childCount; i++) { 13954 boolean childPackageUpdated = false; 13955 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13956 if (res.addedChildPackages != null) { 13957 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13958 if (childRes != null) { 13959 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13960 childRes.removedInfo.removedPackage = childPkg.packageName; 13961 childRes.removedInfo.isUpdate = true; 13962 childPackageUpdated = true; 13963 } 13964 } 13965 if (!childPackageUpdated) { 13966 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13967 childRemovedRes.removedPackage = childPkg.packageName; 13968 childRemovedRes.isUpdate = false; 13969 childRemovedRes.dataRemoved = true; 13970 synchronized (mPackages) { 13971 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13972 if (childPs != null) { 13973 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13974 } 13975 } 13976 if (res.removedInfo.removedChildPackages == null) { 13977 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13978 } 13979 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13980 } 13981 } 13982 13983 boolean sysPkg = (isSystemApp(oldPackage)); 13984 if (sysPkg) { 13985 // Set the system/privileged flags as needed 13986 final boolean privileged = 13987 (oldPackage.applicationInfo.privateFlags 13988 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13989 final int systemPolicyFlags = policyFlags 13990 | PackageParser.PARSE_IS_SYSTEM 13991 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13992 13993 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13994 user, allUsers, installerPackageName, res); 13995 } else { 13996 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13997 user, allUsers, installerPackageName, res); 13998 } 13999 } 14000 14001 public List<String> getPreviousCodePaths(String packageName) { 14002 final PackageSetting ps = mSettings.mPackages.get(packageName); 14003 final List<String> result = new ArrayList<String>(); 14004 if (ps != null && ps.oldCodePaths != null) { 14005 result.addAll(ps.oldCodePaths); 14006 } 14007 return result; 14008 } 14009 14010 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14011 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14012 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14013 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14014 + deletedPackage); 14015 14016 String pkgName = deletedPackage.packageName; 14017 boolean deletedPkg = true; 14018 boolean addedPkg = false; 14019 boolean updatedSettings = false; 14020 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14021 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14022 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14023 14024 final long origUpdateTime = (pkg.mExtras != null) 14025 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14026 14027 // First delete the existing package while retaining the data directory 14028 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14029 res.removedInfo, true, pkg)) { 14030 // If the existing package wasn't successfully deleted 14031 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14032 deletedPkg = false; 14033 } else { 14034 // Successfully deleted the old package; proceed with replace. 14035 14036 // If deleted package lived in a container, give users a chance to 14037 // relinquish resources before killing. 14038 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14039 if (DEBUG_INSTALL) { 14040 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14041 } 14042 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14043 final ArrayList<String> pkgList = new ArrayList<String>(1); 14044 pkgList.add(deletedPackage.applicationInfo.packageName); 14045 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14046 } 14047 14048 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14049 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14050 clearAppProfilesLIF(pkg); 14051 14052 try { 14053 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14054 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14055 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14056 14057 // Update the in-memory copy of the previous code paths. 14058 PackageSetting ps = mSettings.mPackages.get(pkgName); 14059 if (!killApp) { 14060 if (ps.oldCodePaths == null) { 14061 ps.oldCodePaths = new ArraySet<>(); 14062 } 14063 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14064 if (deletedPackage.splitCodePaths != null) { 14065 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14066 } 14067 } else { 14068 ps.oldCodePaths = null; 14069 } 14070 if (ps.childPackageNames != null) { 14071 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14072 final String childPkgName = ps.childPackageNames.get(i); 14073 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14074 childPs.oldCodePaths = ps.oldCodePaths; 14075 } 14076 } 14077 prepareAppDataAfterInstallLIF(newPackage); 14078 addedPkg = true; 14079 } catch (PackageManagerException e) { 14080 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14081 } 14082 } 14083 14084 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14085 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14086 14087 // Revert all internal state mutations and added folders for the failed install 14088 if (addedPkg) { 14089 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14090 res.removedInfo, true, null); 14091 } 14092 14093 // Restore the old package 14094 if (deletedPkg) { 14095 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14096 File restoreFile = new File(deletedPackage.codePath); 14097 // Parse old package 14098 boolean oldExternal = isExternal(deletedPackage); 14099 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14100 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14101 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14102 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14103 try { 14104 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14105 null); 14106 } catch (PackageManagerException e) { 14107 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14108 + e.getMessage()); 14109 return; 14110 } 14111 14112 synchronized (mPackages) { 14113 // Ensure the installer package name up to date 14114 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14115 14116 // Update permissions for restored package 14117 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14118 14119 mSettings.writeLPr(); 14120 } 14121 14122 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14123 } 14124 } else { 14125 synchronized (mPackages) { 14126 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14127 if (ps != null) { 14128 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14129 if (res.removedInfo.removedChildPackages != null) { 14130 final int childCount = res.removedInfo.removedChildPackages.size(); 14131 // Iterate in reverse as we may modify the collection 14132 for (int i = childCount - 1; i >= 0; i--) { 14133 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14134 if (res.addedChildPackages.containsKey(childPackageName)) { 14135 res.removedInfo.removedChildPackages.removeAt(i); 14136 } else { 14137 PackageRemovedInfo childInfo = res.removedInfo 14138 .removedChildPackages.valueAt(i); 14139 childInfo.removedForAllUsers = mPackages.get( 14140 childInfo.removedPackage) == null; 14141 } 14142 } 14143 } 14144 } 14145 } 14146 } 14147 } 14148 14149 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14150 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14151 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14152 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14153 + ", old=" + deletedPackage); 14154 14155 final boolean disabledSystem; 14156 14157 // Remove existing system package 14158 removePackageLI(deletedPackage, true); 14159 14160 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14161 if (!disabledSystem) { 14162 // We didn't need to disable the .apk as a current system package, 14163 // which means we are replacing another update that is already 14164 // installed. We need to make sure to delete the older one's .apk. 14165 res.removedInfo.args = createInstallArgsForExisting(0, 14166 deletedPackage.applicationInfo.getCodePath(), 14167 deletedPackage.applicationInfo.getResourcePath(), 14168 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14169 } else { 14170 res.removedInfo.args = null; 14171 } 14172 14173 // Successfully disabled the old package. Now proceed with re-installation 14174 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14175 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14176 clearAppProfilesLIF(pkg); 14177 14178 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14179 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14180 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14181 14182 PackageParser.Package newPackage = null; 14183 try { 14184 // Add the package to the internal data structures 14185 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14186 14187 // Set the update and install times 14188 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14189 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14190 System.currentTimeMillis()); 14191 14192 // Update the package dynamic state if succeeded 14193 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14194 // Now that the install succeeded make sure we remove data 14195 // directories for any child package the update removed. 14196 final int deletedChildCount = (deletedPackage.childPackages != null) 14197 ? deletedPackage.childPackages.size() : 0; 14198 final int newChildCount = (newPackage.childPackages != null) 14199 ? newPackage.childPackages.size() : 0; 14200 for (int i = 0; i < deletedChildCount; i++) { 14201 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14202 boolean childPackageDeleted = true; 14203 for (int j = 0; j < newChildCount; j++) { 14204 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14205 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14206 childPackageDeleted = false; 14207 break; 14208 } 14209 } 14210 if (childPackageDeleted) { 14211 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14212 deletedChildPkg.packageName); 14213 if (ps != null && res.removedInfo.removedChildPackages != null) { 14214 PackageRemovedInfo removedChildRes = res.removedInfo 14215 .removedChildPackages.get(deletedChildPkg.packageName); 14216 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14217 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14218 } 14219 } 14220 } 14221 14222 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14223 prepareAppDataAfterInstallLIF(newPackage); 14224 } 14225 } catch (PackageManagerException e) { 14226 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14227 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14228 } 14229 14230 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14231 // Re installation failed. Restore old information 14232 // Remove new pkg information 14233 if (newPackage != null) { 14234 removeInstalledPackageLI(newPackage, true); 14235 } 14236 // Add back the old system package 14237 try { 14238 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14239 } catch (PackageManagerException e) { 14240 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14241 } 14242 14243 synchronized (mPackages) { 14244 if (disabledSystem) { 14245 enableSystemPackageLPw(deletedPackage); 14246 } 14247 14248 // Ensure the installer package name up to date 14249 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14250 14251 // Update permissions for restored package 14252 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14253 14254 mSettings.writeLPr(); 14255 } 14256 14257 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14258 + " after failed upgrade"); 14259 } 14260 } 14261 14262 /** 14263 * Checks whether the parent or any of the child packages have a change shared 14264 * user. For a package to be a valid update the shred users of the parent and 14265 * the children should match. We may later support changing child shared users. 14266 * @param oldPkg The updated package. 14267 * @param newPkg The update package. 14268 * @return The shared user that change between the versions. 14269 */ 14270 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14271 PackageParser.Package newPkg) { 14272 // Check parent shared user 14273 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14274 return newPkg.packageName; 14275 } 14276 // Check child shared users 14277 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14278 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14279 for (int i = 0; i < newChildCount; i++) { 14280 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14281 // If this child was present, did it have the same shared user? 14282 for (int j = 0; j < oldChildCount; j++) { 14283 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14284 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14285 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14286 return newChildPkg.packageName; 14287 } 14288 } 14289 } 14290 return null; 14291 } 14292 14293 private void removeNativeBinariesLI(PackageSetting ps) { 14294 // Remove the lib path for the parent package 14295 if (ps != null) { 14296 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14297 // Remove the lib path for the child packages 14298 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14299 for (int i = 0; i < childCount; i++) { 14300 PackageSetting childPs = null; 14301 synchronized (mPackages) { 14302 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14303 } 14304 if (childPs != null) { 14305 NativeLibraryHelper.removeNativeBinariesLI(childPs 14306 .legacyNativeLibraryPathString); 14307 } 14308 } 14309 } 14310 } 14311 14312 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14313 // Enable the parent package 14314 mSettings.enableSystemPackageLPw(pkg.packageName); 14315 // Enable the child packages 14316 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14317 for (int i = 0; i < childCount; i++) { 14318 PackageParser.Package childPkg = pkg.childPackages.get(i); 14319 mSettings.enableSystemPackageLPw(childPkg.packageName); 14320 } 14321 } 14322 14323 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14324 PackageParser.Package newPkg) { 14325 // Disable the parent package (parent always replaced) 14326 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14327 // Disable the child packages 14328 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14329 for (int i = 0; i < childCount; i++) { 14330 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14331 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14332 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14333 } 14334 return disabled; 14335 } 14336 14337 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14338 String installerPackageName) { 14339 // Enable the parent package 14340 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14341 // Enable the child packages 14342 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14343 for (int i = 0; i < childCount; i++) { 14344 PackageParser.Package childPkg = pkg.childPackages.get(i); 14345 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14346 } 14347 } 14348 14349 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14350 // Collect all used permissions in the UID 14351 ArraySet<String> usedPermissions = new ArraySet<>(); 14352 final int packageCount = su.packages.size(); 14353 for (int i = 0; i < packageCount; i++) { 14354 PackageSetting ps = su.packages.valueAt(i); 14355 if (ps.pkg == null) { 14356 continue; 14357 } 14358 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14359 for (int j = 0; j < requestedPermCount; j++) { 14360 String permission = ps.pkg.requestedPermissions.get(j); 14361 BasePermission bp = mSettings.mPermissions.get(permission); 14362 if (bp != null) { 14363 usedPermissions.add(permission); 14364 } 14365 } 14366 } 14367 14368 PermissionsState permissionsState = su.getPermissionsState(); 14369 // Prune install permissions 14370 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14371 final int installPermCount = installPermStates.size(); 14372 for (int i = installPermCount - 1; i >= 0; i--) { 14373 PermissionState permissionState = installPermStates.get(i); 14374 if (!usedPermissions.contains(permissionState.getName())) { 14375 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14376 if (bp != null) { 14377 permissionsState.revokeInstallPermission(bp); 14378 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14379 PackageManager.MASK_PERMISSION_FLAGS, 0); 14380 } 14381 } 14382 } 14383 14384 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14385 14386 // Prune runtime permissions 14387 for (int userId : allUserIds) { 14388 List<PermissionState> runtimePermStates = permissionsState 14389 .getRuntimePermissionStates(userId); 14390 final int runtimePermCount = runtimePermStates.size(); 14391 for (int i = runtimePermCount - 1; i >= 0; i--) { 14392 PermissionState permissionState = runtimePermStates.get(i); 14393 if (!usedPermissions.contains(permissionState.getName())) { 14394 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14395 if (bp != null) { 14396 permissionsState.revokeRuntimePermission(bp, userId); 14397 permissionsState.updatePermissionFlags(bp, userId, 14398 PackageManager.MASK_PERMISSION_FLAGS, 0); 14399 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14400 runtimePermissionChangedUserIds, userId); 14401 } 14402 } 14403 } 14404 } 14405 14406 return runtimePermissionChangedUserIds; 14407 } 14408 14409 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14410 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14411 // Update the parent package setting 14412 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14413 res, user); 14414 // Update the child packages setting 14415 final int childCount = (newPackage.childPackages != null) 14416 ? newPackage.childPackages.size() : 0; 14417 for (int i = 0; i < childCount; i++) { 14418 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14419 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14420 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14421 childRes.origUsers, childRes, user); 14422 } 14423 } 14424 14425 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14426 String installerPackageName, int[] allUsers, int[] installedForUsers, 14427 PackageInstalledInfo res, UserHandle user) { 14428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14429 14430 String pkgName = newPackage.packageName; 14431 synchronized (mPackages) { 14432 //write settings. the installStatus will be incomplete at this stage. 14433 //note that the new package setting would have already been 14434 //added to mPackages. It hasn't been persisted yet. 14435 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14436 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14437 mSettings.writeLPr(); 14438 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14439 } 14440 14441 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14442 synchronized (mPackages) { 14443 updatePermissionsLPw(newPackage.packageName, newPackage, 14444 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14445 ? UPDATE_PERMISSIONS_ALL : 0)); 14446 // For system-bundled packages, we assume that installing an upgraded version 14447 // of the package implies that the user actually wants to run that new code, 14448 // so we enable the package. 14449 PackageSetting ps = mSettings.mPackages.get(pkgName); 14450 final int userId = user.getIdentifier(); 14451 if (ps != null) { 14452 if (isSystemApp(newPackage)) { 14453 if (DEBUG_INSTALL) { 14454 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14455 } 14456 // Enable system package for requested users 14457 if (res.origUsers != null) { 14458 for (int origUserId : res.origUsers) { 14459 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14460 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14461 origUserId, installerPackageName); 14462 } 14463 } 14464 } 14465 // Also convey the prior install/uninstall state 14466 if (allUsers != null && installedForUsers != null) { 14467 for (int currentUserId : allUsers) { 14468 final boolean installed = ArrayUtils.contains( 14469 installedForUsers, currentUserId); 14470 if (DEBUG_INSTALL) { 14471 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14472 } 14473 ps.setInstalled(installed, currentUserId); 14474 } 14475 // these install state changes will be persisted in the 14476 // upcoming call to mSettings.writeLPr(). 14477 } 14478 } 14479 // It's implied that when a user requests installation, they want the app to be 14480 // installed and enabled. 14481 if (userId != UserHandle.USER_ALL) { 14482 ps.setInstalled(true, userId); 14483 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14484 } 14485 } 14486 res.name = pkgName; 14487 res.uid = newPackage.applicationInfo.uid; 14488 res.pkg = newPackage; 14489 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14490 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14491 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14492 //to update install status 14493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14494 mSettings.writeLPr(); 14495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14496 } 14497 14498 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14499 } 14500 14501 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14502 try { 14503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14504 installPackageLI(args, res); 14505 } finally { 14506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14507 } 14508 } 14509 14510 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14511 final int installFlags = args.installFlags; 14512 final String installerPackageName = args.installerPackageName; 14513 final String volumeUuid = args.volumeUuid; 14514 final File tmpPackageFile = new File(args.getCodePath()); 14515 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14516 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14517 || (args.volumeUuid != null)); 14518 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14519 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14520 boolean replace = false; 14521 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14522 if (args.move != null) { 14523 // moving a complete application; perform an initial scan on the new install location 14524 scanFlags |= SCAN_INITIAL; 14525 } 14526 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14527 scanFlags |= SCAN_DONT_KILL_APP; 14528 } 14529 14530 // Result object to be returned 14531 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14532 14533 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14534 14535 // Sanity check 14536 if (ephemeral && (forwardLocked || onExternal)) { 14537 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14538 + " external=" + onExternal); 14539 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14540 return; 14541 } 14542 14543 // Retrieve PackageSettings and parse package 14544 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14545 | PackageParser.PARSE_ENFORCE_CODE 14546 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14547 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14548 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14549 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14550 PackageParser pp = new PackageParser(); 14551 pp.setSeparateProcesses(mSeparateProcesses); 14552 pp.setDisplayMetrics(mMetrics); 14553 14554 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14555 final PackageParser.Package pkg; 14556 try { 14557 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14558 } catch (PackageParserException e) { 14559 res.setError("Failed parse during installPackageLI", e); 14560 return; 14561 } finally { 14562 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14563 } 14564 14565 // If we are installing a clustered package add results for the children 14566 if (pkg.childPackages != null) { 14567 synchronized (mPackages) { 14568 final int childCount = pkg.childPackages.size(); 14569 for (int i = 0; i < childCount; i++) { 14570 PackageParser.Package childPkg = pkg.childPackages.get(i); 14571 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14572 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14573 childRes.pkg = childPkg; 14574 childRes.name = childPkg.packageName; 14575 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14576 if (childPs != null) { 14577 childRes.origUsers = childPs.queryInstalledUsers( 14578 sUserManager.getUserIds(), true); 14579 } 14580 if ((mPackages.containsKey(childPkg.packageName))) { 14581 childRes.removedInfo = new PackageRemovedInfo(); 14582 childRes.removedInfo.removedPackage = childPkg.packageName; 14583 } 14584 if (res.addedChildPackages == null) { 14585 res.addedChildPackages = new ArrayMap<>(); 14586 } 14587 res.addedChildPackages.put(childPkg.packageName, childRes); 14588 } 14589 } 14590 } 14591 14592 // If package doesn't declare API override, mark that we have an install 14593 // time CPU ABI override. 14594 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14595 pkg.cpuAbiOverride = args.abiOverride; 14596 } 14597 14598 String pkgName = res.name = pkg.packageName; 14599 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14600 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14601 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14602 return; 14603 } 14604 } 14605 14606 try { 14607 // either use what we've been given or parse directly from the APK 14608 if (args.certificates != null) { 14609 try { 14610 PackageParser.populateCertificates(pkg, args.certificates); 14611 } catch (PackageParserException e) { 14612 // there was something wrong with the certificates we were given; 14613 // try to pull them from the APK 14614 PackageParser.collectCertificates(pkg, parseFlags); 14615 } 14616 } else { 14617 PackageParser.collectCertificates(pkg, parseFlags); 14618 } 14619 } catch (PackageParserException e) { 14620 res.setError("Failed collect during installPackageLI", e); 14621 return; 14622 } 14623 14624 // Get rid of all references to package scan path via parser. 14625 pp = null; 14626 String oldCodePath = null; 14627 boolean systemApp = false; 14628 synchronized (mPackages) { 14629 // Check if installing already existing package 14630 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14631 String oldName = mSettings.mRenamedPackages.get(pkgName); 14632 if (pkg.mOriginalPackages != null 14633 && pkg.mOriginalPackages.contains(oldName) 14634 && mPackages.containsKey(oldName)) { 14635 // This package is derived from an original package, 14636 // and this device has been updating from that original 14637 // name. We must continue using the original name, so 14638 // rename the new package here. 14639 pkg.setPackageName(oldName); 14640 pkgName = pkg.packageName; 14641 replace = true; 14642 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14643 + oldName + " pkgName=" + pkgName); 14644 } else if (mPackages.containsKey(pkgName)) { 14645 // This package, under its official name, already exists 14646 // on the device; we should replace it. 14647 replace = true; 14648 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14649 } 14650 14651 // Child packages are installed through the parent package 14652 if (pkg.parentPackage != null) { 14653 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14654 "Package " + pkg.packageName + " is child of package " 14655 + pkg.parentPackage.parentPackage + ". Child packages " 14656 + "can be updated only through the parent package."); 14657 return; 14658 } 14659 14660 if (replace) { 14661 // Prevent apps opting out from runtime permissions 14662 PackageParser.Package oldPackage = mPackages.get(pkgName); 14663 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14664 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14665 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14666 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14667 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14668 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14669 + " doesn't support runtime permissions but the old" 14670 + " target SDK " + oldTargetSdk + " does."); 14671 return; 14672 } 14673 14674 // Prevent installing of child packages 14675 if (oldPackage.parentPackage != null) { 14676 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14677 "Package " + pkg.packageName + " is child of package " 14678 + oldPackage.parentPackage + ". Child packages " 14679 + "can be updated only through the parent package."); 14680 return; 14681 } 14682 } 14683 } 14684 14685 PackageSetting ps = mSettings.mPackages.get(pkgName); 14686 if (ps != null) { 14687 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14688 14689 // Quick sanity check that we're signed correctly if updating; 14690 // we'll check this again later when scanning, but we want to 14691 // bail early here before tripping over redefined permissions. 14692 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14693 if (!checkUpgradeKeySetLP(ps, pkg)) { 14694 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14695 + pkg.packageName + " upgrade keys do not match the " 14696 + "previously installed version"); 14697 return; 14698 } 14699 } else { 14700 try { 14701 verifySignaturesLP(ps, pkg); 14702 } catch (PackageManagerException e) { 14703 res.setError(e.error, e.getMessage()); 14704 return; 14705 } 14706 } 14707 14708 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14709 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14710 systemApp = (ps.pkg.applicationInfo.flags & 14711 ApplicationInfo.FLAG_SYSTEM) != 0; 14712 } 14713 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14714 } 14715 14716 // Check whether the newly-scanned package wants to define an already-defined perm 14717 int N = pkg.permissions.size(); 14718 for (int i = N-1; i >= 0; i--) { 14719 PackageParser.Permission perm = pkg.permissions.get(i); 14720 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14721 if (bp != null) { 14722 // If the defining package is signed with our cert, it's okay. This 14723 // also includes the "updating the same package" case, of course. 14724 // "updating same package" could also involve key-rotation. 14725 final boolean sigsOk; 14726 if (bp.sourcePackage.equals(pkg.packageName) 14727 && (bp.packageSetting instanceof PackageSetting) 14728 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14729 scanFlags))) { 14730 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14731 } else { 14732 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14733 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14734 } 14735 if (!sigsOk) { 14736 // If the owning package is the system itself, we log but allow 14737 // install to proceed; we fail the install on all other permission 14738 // redefinitions. 14739 if (!bp.sourcePackage.equals("android")) { 14740 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14741 + pkg.packageName + " attempting to redeclare permission " 14742 + perm.info.name + " already owned by " + bp.sourcePackage); 14743 res.origPermission = perm.info.name; 14744 res.origPackage = bp.sourcePackage; 14745 return; 14746 } else { 14747 Slog.w(TAG, "Package " + pkg.packageName 14748 + " attempting to redeclare system permission " 14749 + perm.info.name + "; ignoring new declaration"); 14750 pkg.permissions.remove(i); 14751 } 14752 } 14753 } 14754 } 14755 } 14756 14757 if (systemApp) { 14758 if (onExternal) { 14759 // Abort update; system app can't be replaced with app on sdcard 14760 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14761 "Cannot install updates to system apps on sdcard"); 14762 return; 14763 } else if (ephemeral) { 14764 // Abort update; system app can't be replaced with an ephemeral app 14765 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14766 "Cannot update a system app with an ephemeral app"); 14767 return; 14768 } 14769 } 14770 14771 if (args.move != null) { 14772 // We did an in-place move, so dex is ready to roll 14773 scanFlags |= SCAN_NO_DEX; 14774 scanFlags |= SCAN_MOVE; 14775 14776 synchronized (mPackages) { 14777 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14778 if (ps == null) { 14779 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14780 "Missing settings for moved package " + pkgName); 14781 } 14782 14783 // We moved the entire application as-is, so bring over the 14784 // previously derived ABI information. 14785 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14786 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14787 } 14788 14789 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14790 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14791 scanFlags |= SCAN_NO_DEX; 14792 14793 try { 14794 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14795 args.abiOverride : pkg.cpuAbiOverride); 14796 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14797 true /* extract libs */); 14798 } catch (PackageManagerException pme) { 14799 Slog.e(TAG, "Error deriving application ABI", pme); 14800 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14801 return; 14802 } 14803 14804 // Shared libraries for the package need to be updated. 14805 synchronized (mPackages) { 14806 try { 14807 updateSharedLibrariesLPw(pkg, null); 14808 } catch (PackageManagerException e) { 14809 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14810 } 14811 } 14812 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14813 // Do not run PackageDexOptimizer through the local performDexOpt 14814 // method because `pkg` is not in `mPackages` yet. 14815 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14816 null /* instructionSets */, false /* checkProfiles */, 14817 getCompilerFilterForReason(REASON_INSTALL)); 14818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14819 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14820 String msg = "Extracting package failed for " + pkgName; 14821 res.setError(INSTALL_FAILED_DEXOPT, msg); 14822 return; 14823 } 14824 14825 // Notify BackgroundDexOptService that the package has been changed. 14826 // If this is an update of a package which used to fail to compile, 14827 // BDOS will remove it from its blacklist. 14828 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14829 } 14830 14831 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14832 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14833 return; 14834 } 14835 14836 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14837 14838 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14839 "installPackageLI")) { 14840 if (replace) { 14841 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14842 installerPackageName, res); 14843 } else { 14844 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14845 args.user, installerPackageName, volumeUuid, res); 14846 } 14847 } 14848 synchronized (mPackages) { 14849 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14850 if (ps != null) { 14851 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14852 } 14853 14854 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14855 for (int i = 0; i < childCount; i++) { 14856 PackageParser.Package childPkg = pkg.childPackages.get(i); 14857 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14858 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14859 if (childPs != null) { 14860 childRes.newUsers = childPs.queryInstalledUsers( 14861 sUserManager.getUserIds(), true); 14862 } 14863 } 14864 } 14865 } 14866 14867 private void startIntentFilterVerifications(int userId, boolean replacing, 14868 PackageParser.Package pkg) { 14869 if (mIntentFilterVerifierComponent == null) { 14870 Slog.w(TAG, "No IntentFilter verification will not be done as " 14871 + "there is no IntentFilterVerifier available!"); 14872 return; 14873 } 14874 14875 final int verifierUid = getPackageUid( 14876 mIntentFilterVerifierComponent.getPackageName(), 14877 MATCH_DEBUG_TRIAGED_MISSING, 14878 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14879 14880 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14881 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14882 mHandler.sendMessage(msg); 14883 14884 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14885 for (int i = 0; i < childCount; i++) { 14886 PackageParser.Package childPkg = pkg.childPackages.get(i); 14887 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14888 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14889 mHandler.sendMessage(msg); 14890 } 14891 } 14892 14893 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14894 PackageParser.Package pkg) { 14895 int size = pkg.activities.size(); 14896 if (size == 0) { 14897 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14898 "No activity, so no need to verify any IntentFilter!"); 14899 return; 14900 } 14901 14902 final boolean hasDomainURLs = hasDomainURLs(pkg); 14903 if (!hasDomainURLs) { 14904 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14905 "No domain URLs, so no need to verify any IntentFilter!"); 14906 return; 14907 } 14908 14909 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14910 + " if any IntentFilter from the " + size 14911 + " Activities needs verification ..."); 14912 14913 int count = 0; 14914 final String packageName = pkg.packageName; 14915 14916 synchronized (mPackages) { 14917 // If this is a new install and we see that we've already run verification for this 14918 // package, we have nothing to do: it means the state was restored from backup. 14919 if (!replacing) { 14920 IntentFilterVerificationInfo ivi = 14921 mSettings.getIntentFilterVerificationLPr(packageName); 14922 if (ivi != null) { 14923 if (DEBUG_DOMAIN_VERIFICATION) { 14924 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14925 + ivi.getStatusString()); 14926 } 14927 return; 14928 } 14929 } 14930 14931 // If any filters need to be verified, then all need to be. 14932 boolean needToVerify = false; 14933 for (PackageParser.Activity a : pkg.activities) { 14934 for (ActivityIntentInfo filter : a.intents) { 14935 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14936 if (DEBUG_DOMAIN_VERIFICATION) { 14937 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14938 } 14939 needToVerify = true; 14940 break; 14941 } 14942 } 14943 } 14944 14945 if (needToVerify) { 14946 final int verificationId = mIntentFilterVerificationToken++; 14947 for (PackageParser.Activity a : pkg.activities) { 14948 for (ActivityIntentInfo filter : a.intents) { 14949 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14950 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14951 "Verification needed for IntentFilter:" + filter.toString()); 14952 mIntentFilterVerifier.addOneIntentFilterVerification( 14953 verifierUid, userId, verificationId, filter, packageName); 14954 count++; 14955 } 14956 } 14957 } 14958 } 14959 } 14960 14961 if (count > 0) { 14962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14963 + " IntentFilter verification" + (count > 1 ? "s" : "") 14964 + " for userId:" + userId); 14965 mIntentFilterVerifier.startVerifications(userId); 14966 } else { 14967 if (DEBUG_DOMAIN_VERIFICATION) { 14968 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14969 } 14970 } 14971 } 14972 14973 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14974 final ComponentName cn = filter.activity.getComponentName(); 14975 final String packageName = cn.getPackageName(); 14976 14977 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14978 packageName); 14979 if (ivi == null) { 14980 return true; 14981 } 14982 int status = ivi.getStatus(); 14983 switch (status) { 14984 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14985 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14986 return true; 14987 14988 default: 14989 // Nothing to do 14990 return false; 14991 } 14992 } 14993 14994 private static boolean isMultiArch(ApplicationInfo info) { 14995 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14996 } 14997 14998 private static boolean isExternal(PackageParser.Package pkg) { 14999 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15000 } 15001 15002 private static boolean isExternal(PackageSetting ps) { 15003 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15004 } 15005 15006 private static boolean isEphemeral(PackageParser.Package pkg) { 15007 return pkg.applicationInfo.isEphemeralApp(); 15008 } 15009 15010 private static boolean isEphemeral(PackageSetting ps) { 15011 return ps.pkg != null && isEphemeral(ps.pkg); 15012 } 15013 15014 private static boolean isSystemApp(PackageParser.Package pkg) { 15015 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15016 } 15017 15018 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15019 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15020 } 15021 15022 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15023 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15024 } 15025 15026 private static boolean isSystemApp(PackageSetting ps) { 15027 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15028 } 15029 15030 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15031 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15032 } 15033 15034 private int packageFlagsToInstallFlags(PackageSetting ps) { 15035 int installFlags = 0; 15036 if (isEphemeral(ps)) { 15037 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15038 } 15039 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15040 // This existing package was an external ASEC install when we have 15041 // the external flag without a UUID 15042 installFlags |= PackageManager.INSTALL_EXTERNAL; 15043 } 15044 if (ps.isForwardLocked()) { 15045 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15046 } 15047 return installFlags; 15048 } 15049 15050 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15051 if (isExternal(pkg)) { 15052 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15053 return StorageManager.UUID_PRIMARY_PHYSICAL; 15054 } else { 15055 return pkg.volumeUuid; 15056 } 15057 } else { 15058 return StorageManager.UUID_PRIVATE_INTERNAL; 15059 } 15060 } 15061 15062 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15063 if (isExternal(pkg)) { 15064 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15065 return mSettings.getExternalVersion(); 15066 } else { 15067 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15068 } 15069 } else { 15070 return mSettings.getInternalVersion(); 15071 } 15072 } 15073 15074 private void deleteTempPackageFiles() { 15075 final FilenameFilter filter = new FilenameFilter() { 15076 public boolean accept(File dir, String name) { 15077 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15078 } 15079 }; 15080 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15081 file.delete(); 15082 } 15083 } 15084 15085 @Override 15086 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15087 int flags) { 15088 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15089 flags); 15090 } 15091 15092 @Override 15093 public void deletePackage(final String packageName, 15094 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15095 mContext.enforceCallingOrSelfPermission( 15096 android.Manifest.permission.DELETE_PACKAGES, null); 15097 Preconditions.checkNotNull(packageName); 15098 Preconditions.checkNotNull(observer); 15099 final int uid = Binder.getCallingUid(); 15100 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15101 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15102 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15103 mContext.enforceCallingOrSelfPermission( 15104 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15105 "deletePackage for user " + userId); 15106 } 15107 15108 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15109 try { 15110 observer.onPackageDeleted(packageName, 15111 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15112 } catch (RemoteException re) { 15113 } 15114 return; 15115 } 15116 15117 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15118 try { 15119 observer.onPackageDeleted(packageName, 15120 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15121 } catch (RemoteException re) { 15122 } 15123 return; 15124 } 15125 15126 if (DEBUG_REMOVE) { 15127 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15128 + " deleteAllUsers: " + deleteAllUsers ); 15129 } 15130 // Queue up an async operation since the package deletion may take a little while. 15131 mHandler.post(new Runnable() { 15132 public void run() { 15133 mHandler.removeCallbacks(this); 15134 int returnCode; 15135 if (!deleteAllUsers) { 15136 returnCode = deletePackageX(packageName, userId, deleteFlags); 15137 } else { 15138 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15139 // If nobody is blocking uninstall, proceed with delete for all users 15140 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15141 returnCode = deletePackageX(packageName, userId, deleteFlags); 15142 } else { 15143 // Otherwise uninstall individually for users with blockUninstalls=false 15144 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15145 for (int userId : users) { 15146 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15147 returnCode = deletePackageX(packageName, userId, userFlags); 15148 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15149 Slog.w(TAG, "Package delete failed for user " + userId 15150 + ", returnCode " + returnCode); 15151 } 15152 } 15153 } 15154 // The app has only been marked uninstalled for certain users. 15155 // We still need to report that delete was blocked 15156 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15157 } 15158 } 15159 try { 15160 observer.onPackageDeleted(packageName, returnCode, null); 15161 } catch (RemoteException e) { 15162 Log.i(TAG, "Observer no longer exists."); 15163 } //end catch 15164 } //end run 15165 }); 15166 } 15167 15168 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15169 int[] result = EMPTY_INT_ARRAY; 15170 for (int userId : userIds) { 15171 if (getBlockUninstallForUser(packageName, userId)) { 15172 result = ArrayUtils.appendInt(result, userId); 15173 } 15174 } 15175 return result; 15176 } 15177 15178 @Override 15179 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15180 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15181 } 15182 15183 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15184 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15185 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15186 try { 15187 if (dpm != null) { 15188 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15189 /* callingUserOnly =*/ false); 15190 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15191 : deviceOwnerComponentName.getPackageName(); 15192 // Does the package contains the device owner? 15193 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15194 // this check is probably not needed, since DO should be registered as a device 15195 // admin on some user too. (Original bug for this: b/17657954) 15196 if (packageName.equals(deviceOwnerPackageName)) { 15197 return true; 15198 } 15199 // Does it contain a device admin for any user? 15200 int[] users; 15201 if (userId == UserHandle.USER_ALL) { 15202 users = sUserManager.getUserIds(); 15203 } else { 15204 users = new int[]{userId}; 15205 } 15206 for (int i = 0; i < users.length; ++i) { 15207 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15208 return true; 15209 } 15210 } 15211 } 15212 } catch (RemoteException e) { 15213 } 15214 return false; 15215 } 15216 15217 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15218 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15219 } 15220 15221 /** 15222 * This method is an internal method that could be get invoked either 15223 * to delete an installed package or to clean up a failed installation. 15224 * After deleting an installed package, a broadcast is sent to notify any 15225 * listeners that the package has been removed. For cleaning up a failed 15226 * installation, the broadcast is not necessary since the package's 15227 * installation wouldn't have sent the initial broadcast either 15228 * The key steps in deleting a package are 15229 * deleting the package information in internal structures like mPackages, 15230 * deleting the packages base directories through installd 15231 * updating mSettings to reflect current status 15232 * persisting settings for later use 15233 * sending a broadcast if necessary 15234 */ 15235 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15236 final PackageRemovedInfo info = new PackageRemovedInfo(); 15237 final boolean res; 15238 15239 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15240 ? UserHandle.ALL : new UserHandle(userId); 15241 15242 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15243 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15244 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15245 } 15246 15247 PackageSetting uninstalledPs = null; 15248 15249 // for the uninstall-updates case and restricted profiles, remember the per- 15250 // user handle installed state 15251 int[] allUsers; 15252 synchronized (mPackages) { 15253 uninstalledPs = mSettings.mPackages.get(packageName); 15254 if (uninstalledPs == null) { 15255 Slog.w(TAG, "Not removing non-existent package " + packageName); 15256 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15257 } 15258 allUsers = sUserManager.getUserIds(); 15259 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15260 } 15261 15262 synchronized (mInstallLock) { 15263 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15264 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15265 "deletePackageX")) { 15266 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15267 deleteFlags | REMOVE_CHATTY, info, true, null); 15268 } 15269 synchronized (mPackages) { 15270 if (res) { 15271 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15272 } 15273 } 15274 } 15275 15276 if (res) { 15277 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15278 info.sendPackageRemovedBroadcasts(killApp); 15279 info.sendSystemPackageUpdatedBroadcasts(); 15280 info.sendSystemPackageAppearedBroadcasts(); 15281 } 15282 // Force a gc here. 15283 Runtime.getRuntime().gc(); 15284 // Delete the resources here after sending the broadcast to let 15285 // other processes clean up before deleting resources. 15286 if (info.args != null) { 15287 synchronized (mInstallLock) { 15288 info.args.doPostDeleteLI(true); 15289 } 15290 } 15291 15292 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15293 } 15294 15295 class PackageRemovedInfo { 15296 String removedPackage; 15297 int uid = -1; 15298 int removedAppId = -1; 15299 int[] origUsers; 15300 int[] removedUsers = null; 15301 boolean isRemovedPackageSystemUpdate = false; 15302 boolean isUpdate; 15303 boolean dataRemoved; 15304 boolean removedForAllUsers; 15305 // Clean up resources deleted packages. 15306 InstallArgs args = null; 15307 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15308 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15309 15310 void sendPackageRemovedBroadcasts(boolean killApp) { 15311 sendPackageRemovedBroadcastInternal(killApp); 15312 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15313 for (int i = 0; i < childCount; i++) { 15314 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15315 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15316 } 15317 } 15318 15319 void sendSystemPackageUpdatedBroadcasts() { 15320 if (isRemovedPackageSystemUpdate) { 15321 sendSystemPackageUpdatedBroadcastsInternal(); 15322 final int childCount = (removedChildPackages != null) 15323 ? removedChildPackages.size() : 0; 15324 for (int i = 0; i < childCount; i++) { 15325 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15326 if (childInfo.isRemovedPackageSystemUpdate) { 15327 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15328 } 15329 } 15330 } 15331 } 15332 15333 void sendSystemPackageAppearedBroadcasts() { 15334 final int packageCount = (appearedChildPackages != null) 15335 ? appearedChildPackages.size() : 0; 15336 for (int i = 0; i < packageCount; i++) { 15337 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15338 for (int userId : installedInfo.newUsers) { 15339 sendPackageAddedForUser(installedInfo.name, true, 15340 UserHandle.getAppId(installedInfo.uid), userId); 15341 } 15342 } 15343 } 15344 15345 private void sendSystemPackageUpdatedBroadcastsInternal() { 15346 Bundle extras = new Bundle(2); 15347 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15348 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15349 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15350 extras, 0, null, null, null); 15351 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15352 extras, 0, null, null, null); 15353 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15354 null, 0, removedPackage, null, null); 15355 } 15356 15357 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15358 Bundle extras = new Bundle(2); 15359 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15360 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15361 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15362 if (isUpdate || isRemovedPackageSystemUpdate) { 15363 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15364 } 15365 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15366 if (removedPackage != null) { 15367 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15368 extras, 0, null, null, removedUsers); 15369 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15370 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15371 removedPackage, extras, 0, null, null, removedUsers); 15372 } 15373 } 15374 if (removedAppId >= 0) { 15375 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15376 removedUsers); 15377 } 15378 } 15379 } 15380 15381 /* 15382 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15383 * flag is not set, the data directory is removed as well. 15384 * make sure this flag is set for partially installed apps. If not its meaningless to 15385 * delete a partially installed application. 15386 */ 15387 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15388 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15389 String packageName = ps.name; 15390 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15391 // Retrieve object to delete permissions for shared user later on 15392 final PackageParser.Package deletedPkg; 15393 final PackageSetting deletedPs; 15394 // reader 15395 synchronized (mPackages) { 15396 deletedPkg = mPackages.get(packageName); 15397 deletedPs = mSettings.mPackages.get(packageName); 15398 if (outInfo != null) { 15399 outInfo.removedPackage = packageName; 15400 outInfo.removedUsers = deletedPs != null 15401 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15402 : null; 15403 } 15404 } 15405 15406 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15407 15408 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15409 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15410 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15411 destroyAppProfilesLIF(deletedPkg); 15412 if (outInfo != null) { 15413 outInfo.dataRemoved = true; 15414 } 15415 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15416 } 15417 15418 // writer 15419 synchronized (mPackages) { 15420 if (deletedPs != null) { 15421 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15422 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15423 clearDefaultBrowserIfNeeded(packageName); 15424 if (outInfo != null) { 15425 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15426 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15427 } 15428 updatePermissionsLPw(deletedPs.name, null, 0); 15429 if (deletedPs.sharedUser != null) { 15430 // Remove permissions associated with package. Since runtime 15431 // permissions are per user we have to kill the removed package 15432 // or packages running under the shared user of the removed 15433 // package if revoking the permissions requested only by the removed 15434 // package is successful and this causes a change in gids. 15435 for (int userId : UserManagerService.getInstance().getUserIds()) { 15436 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15437 userId); 15438 if (userIdToKill == UserHandle.USER_ALL 15439 || userIdToKill >= UserHandle.USER_SYSTEM) { 15440 // If gids changed for this user, kill all affected packages. 15441 mHandler.post(new Runnable() { 15442 @Override 15443 public void run() { 15444 // This has to happen with no lock held. 15445 killApplication(deletedPs.name, deletedPs.appId, 15446 KILL_APP_REASON_GIDS_CHANGED); 15447 } 15448 }); 15449 break; 15450 } 15451 } 15452 } 15453 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15454 } 15455 // make sure to preserve per-user disabled state if this removal was just 15456 // a downgrade of a system app to the factory package 15457 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15458 if (DEBUG_REMOVE) { 15459 Slog.d(TAG, "Propagating install state across downgrade"); 15460 } 15461 for (int userId : allUserHandles) { 15462 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15463 if (DEBUG_REMOVE) { 15464 Slog.d(TAG, " user " + userId + " => " + installed); 15465 } 15466 ps.setInstalled(installed, userId); 15467 } 15468 } 15469 } 15470 // can downgrade to reader 15471 if (writeSettings) { 15472 // Save settings now 15473 mSettings.writeLPr(); 15474 } 15475 } 15476 if (outInfo != null) { 15477 // A user ID was deleted here. Go through all users and remove it 15478 // from KeyStore. 15479 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15480 } 15481 } 15482 15483 static boolean locationIsPrivileged(File path) { 15484 try { 15485 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15486 .getCanonicalPath(); 15487 return path.getCanonicalPath().startsWith(privilegedAppDir); 15488 } catch (IOException e) { 15489 Slog.e(TAG, "Unable to access code path " + path); 15490 } 15491 return false; 15492 } 15493 15494 /* 15495 * Tries to delete system package. 15496 */ 15497 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15498 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15499 boolean writeSettings) { 15500 if (deletedPs.parentPackageName != null) { 15501 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15502 return false; 15503 } 15504 15505 final boolean applyUserRestrictions 15506 = (allUserHandles != null) && (outInfo.origUsers != null); 15507 final PackageSetting disabledPs; 15508 // Confirm if the system package has been updated 15509 // An updated system app can be deleted. This will also have to restore 15510 // the system pkg from system partition 15511 // reader 15512 synchronized (mPackages) { 15513 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15514 } 15515 15516 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15517 + " disabledPs=" + disabledPs); 15518 15519 if (disabledPs == null) { 15520 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15521 return false; 15522 } else if (DEBUG_REMOVE) { 15523 Slog.d(TAG, "Deleting system pkg from data partition"); 15524 } 15525 15526 if (DEBUG_REMOVE) { 15527 if (applyUserRestrictions) { 15528 Slog.d(TAG, "Remembering install states:"); 15529 for (int userId : allUserHandles) { 15530 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15531 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15532 } 15533 } 15534 } 15535 15536 // Delete the updated package 15537 outInfo.isRemovedPackageSystemUpdate = true; 15538 if (outInfo.removedChildPackages != null) { 15539 final int childCount = (deletedPs.childPackageNames != null) 15540 ? deletedPs.childPackageNames.size() : 0; 15541 for (int i = 0; i < childCount; i++) { 15542 String childPackageName = deletedPs.childPackageNames.get(i); 15543 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15544 .contains(childPackageName)) { 15545 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15546 childPackageName); 15547 if (childInfo != null) { 15548 childInfo.isRemovedPackageSystemUpdate = true; 15549 } 15550 } 15551 } 15552 } 15553 15554 if (disabledPs.versionCode < deletedPs.versionCode) { 15555 // Delete data for downgrades 15556 flags &= ~PackageManager.DELETE_KEEP_DATA; 15557 } else { 15558 // Preserve data by setting flag 15559 flags |= PackageManager.DELETE_KEEP_DATA; 15560 } 15561 15562 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15563 outInfo, writeSettings, disabledPs.pkg); 15564 if (!ret) { 15565 return false; 15566 } 15567 15568 // writer 15569 synchronized (mPackages) { 15570 // Reinstate the old system package 15571 enableSystemPackageLPw(disabledPs.pkg); 15572 // Remove any native libraries from the upgraded package. 15573 removeNativeBinariesLI(deletedPs); 15574 } 15575 15576 // Install the system package 15577 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15578 int parseFlags = mDefParseFlags 15579 | PackageParser.PARSE_MUST_BE_APK 15580 | PackageParser.PARSE_IS_SYSTEM 15581 | PackageParser.PARSE_IS_SYSTEM_DIR; 15582 if (locationIsPrivileged(disabledPs.codePath)) { 15583 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15584 } 15585 15586 final PackageParser.Package newPkg; 15587 try { 15588 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15589 } catch (PackageManagerException e) { 15590 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15591 + e.getMessage()); 15592 return false; 15593 } 15594 15595 prepareAppDataAfterInstallLIF(newPkg); 15596 15597 // writer 15598 synchronized (mPackages) { 15599 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15600 15601 // Propagate the permissions state as we do not want to drop on the floor 15602 // runtime permissions. The update permissions method below will take 15603 // care of removing obsolete permissions and grant install permissions. 15604 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15605 updatePermissionsLPw(newPkg.packageName, newPkg, 15606 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15607 15608 if (applyUserRestrictions) { 15609 if (DEBUG_REMOVE) { 15610 Slog.d(TAG, "Propagating install state across reinstall"); 15611 } 15612 for (int userId : allUserHandles) { 15613 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15614 if (DEBUG_REMOVE) { 15615 Slog.d(TAG, " user " + userId + " => " + installed); 15616 } 15617 ps.setInstalled(installed, userId); 15618 15619 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15620 } 15621 // Regardless of writeSettings we need to ensure that this restriction 15622 // state propagation is persisted 15623 mSettings.writeAllUsersPackageRestrictionsLPr(); 15624 } 15625 // can downgrade to reader here 15626 if (writeSettings) { 15627 mSettings.writeLPr(); 15628 } 15629 } 15630 return true; 15631 } 15632 15633 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15634 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15635 PackageRemovedInfo outInfo, boolean writeSettings, 15636 PackageParser.Package replacingPackage) { 15637 synchronized (mPackages) { 15638 if (outInfo != null) { 15639 outInfo.uid = ps.appId; 15640 } 15641 15642 if (outInfo != null && outInfo.removedChildPackages != null) { 15643 final int childCount = (ps.childPackageNames != null) 15644 ? ps.childPackageNames.size() : 0; 15645 for (int i = 0; i < childCount; i++) { 15646 String childPackageName = ps.childPackageNames.get(i); 15647 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15648 if (childPs == null) { 15649 return false; 15650 } 15651 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15652 childPackageName); 15653 if (childInfo != null) { 15654 childInfo.uid = childPs.appId; 15655 } 15656 } 15657 } 15658 } 15659 15660 // Delete package data from internal structures and also remove data if flag is set 15661 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15662 15663 // Delete the child packages data 15664 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15665 for (int i = 0; i < childCount; i++) { 15666 PackageSetting childPs; 15667 synchronized (mPackages) { 15668 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15669 } 15670 if (childPs != null) { 15671 PackageRemovedInfo childOutInfo = (outInfo != null 15672 && outInfo.removedChildPackages != null) 15673 ? outInfo.removedChildPackages.get(childPs.name) : null; 15674 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15675 && (replacingPackage != null 15676 && !replacingPackage.hasChildPackage(childPs.name)) 15677 ? flags & ~DELETE_KEEP_DATA : flags; 15678 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15679 deleteFlags, writeSettings); 15680 } 15681 } 15682 15683 // Delete application code and resources only for parent packages 15684 if (ps.parentPackageName == null) { 15685 if (deleteCodeAndResources && (outInfo != null)) { 15686 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15687 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15688 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15689 } 15690 } 15691 15692 return true; 15693 } 15694 15695 @Override 15696 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15697 int userId) { 15698 mContext.enforceCallingOrSelfPermission( 15699 android.Manifest.permission.DELETE_PACKAGES, null); 15700 synchronized (mPackages) { 15701 PackageSetting ps = mSettings.mPackages.get(packageName); 15702 if (ps == null) { 15703 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15704 return false; 15705 } 15706 if (!ps.getInstalled(userId)) { 15707 // Can't block uninstall for an app that is not installed or enabled. 15708 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15709 return false; 15710 } 15711 ps.setBlockUninstall(blockUninstall, userId); 15712 mSettings.writePackageRestrictionsLPr(userId); 15713 } 15714 return true; 15715 } 15716 15717 @Override 15718 public boolean getBlockUninstallForUser(String packageName, int userId) { 15719 synchronized (mPackages) { 15720 PackageSetting ps = mSettings.mPackages.get(packageName); 15721 if (ps == null) { 15722 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15723 return false; 15724 } 15725 return ps.getBlockUninstall(userId); 15726 } 15727 } 15728 15729 @Override 15730 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15731 int callingUid = Binder.getCallingUid(); 15732 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15733 throw new SecurityException( 15734 "setRequiredForSystemUser can only be run by the system or root"); 15735 } 15736 synchronized (mPackages) { 15737 PackageSetting ps = mSettings.mPackages.get(packageName); 15738 if (ps == null) { 15739 Log.w(TAG, "Package doesn't exist: " + packageName); 15740 return false; 15741 } 15742 if (systemUserApp) { 15743 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15744 } else { 15745 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15746 } 15747 mSettings.writeLPr(); 15748 } 15749 return true; 15750 } 15751 15752 /* 15753 * This method handles package deletion in general 15754 */ 15755 private boolean deletePackageLIF(String packageName, UserHandle user, 15756 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15757 PackageRemovedInfo outInfo, boolean writeSettings, 15758 PackageParser.Package replacingPackage) { 15759 if (packageName == null) { 15760 Slog.w(TAG, "Attempt to delete null packageName."); 15761 return false; 15762 } 15763 15764 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15765 15766 PackageSetting ps; 15767 15768 synchronized (mPackages) { 15769 ps = mSettings.mPackages.get(packageName); 15770 if (ps == null) { 15771 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15772 return false; 15773 } 15774 15775 if (ps.parentPackageName != null && (!isSystemApp(ps) 15776 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15777 if (DEBUG_REMOVE) { 15778 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15779 + ((user == null) ? UserHandle.USER_ALL : user)); 15780 } 15781 final int removedUserId = (user != null) ? user.getIdentifier() 15782 : UserHandle.USER_ALL; 15783 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15784 return false; 15785 } 15786 markPackageUninstalledForUserLPw(ps, user); 15787 scheduleWritePackageRestrictionsLocked(user); 15788 return true; 15789 } 15790 } 15791 15792 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15793 && user.getIdentifier() != UserHandle.USER_ALL)) { 15794 // The caller is asking that the package only be deleted for a single 15795 // user. To do this, we just mark its uninstalled state and delete 15796 // its data. If this is a system app, we only allow this to happen if 15797 // they have set the special DELETE_SYSTEM_APP which requests different 15798 // semantics than normal for uninstalling system apps. 15799 markPackageUninstalledForUserLPw(ps, user); 15800 15801 if (!isSystemApp(ps)) { 15802 // Do not uninstall the APK if an app should be cached 15803 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15804 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15805 // Other user still have this package installed, so all 15806 // we need to do is clear this user's data and save that 15807 // it is uninstalled. 15808 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15809 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15810 return false; 15811 } 15812 scheduleWritePackageRestrictionsLocked(user); 15813 return true; 15814 } else { 15815 // We need to set it back to 'installed' so the uninstall 15816 // broadcasts will be sent correctly. 15817 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15818 ps.setInstalled(true, user.getIdentifier()); 15819 } 15820 } else { 15821 // This is a system app, so we assume that the 15822 // other users still have this package installed, so all 15823 // we need to do is clear this user's data and save that 15824 // it is uninstalled. 15825 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15826 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15827 return false; 15828 } 15829 scheduleWritePackageRestrictionsLocked(user); 15830 return true; 15831 } 15832 } 15833 15834 // If we are deleting a composite package for all users, keep track 15835 // of result for each child. 15836 if (ps.childPackageNames != null && outInfo != null) { 15837 synchronized (mPackages) { 15838 final int childCount = ps.childPackageNames.size(); 15839 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15840 for (int i = 0; i < childCount; i++) { 15841 String childPackageName = ps.childPackageNames.get(i); 15842 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15843 childInfo.removedPackage = childPackageName; 15844 outInfo.removedChildPackages.put(childPackageName, childInfo); 15845 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15846 if (childPs != null) { 15847 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15848 } 15849 } 15850 } 15851 } 15852 15853 boolean ret = false; 15854 if (isSystemApp(ps)) { 15855 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15856 // When an updated system application is deleted we delete the existing resources 15857 // as well and fall back to existing code in system partition 15858 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15859 } else { 15860 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15861 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15862 outInfo, writeSettings, replacingPackage); 15863 } 15864 15865 // Take a note whether we deleted the package for all users 15866 if (outInfo != null) { 15867 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15868 if (outInfo.removedChildPackages != null) { 15869 synchronized (mPackages) { 15870 final int childCount = outInfo.removedChildPackages.size(); 15871 for (int i = 0; i < childCount; i++) { 15872 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15873 if (childInfo != null) { 15874 childInfo.removedForAllUsers = mPackages.get( 15875 childInfo.removedPackage) == null; 15876 } 15877 } 15878 } 15879 } 15880 // If we uninstalled an update to a system app there may be some 15881 // child packages that appeared as they are declared in the system 15882 // app but were not declared in the update. 15883 if (isSystemApp(ps)) { 15884 synchronized (mPackages) { 15885 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15886 final int childCount = (updatedPs.childPackageNames != null) 15887 ? updatedPs.childPackageNames.size() : 0; 15888 for (int i = 0; i < childCount; i++) { 15889 String childPackageName = updatedPs.childPackageNames.get(i); 15890 if (outInfo.removedChildPackages == null 15891 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15892 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15893 if (childPs == null) { 15894 continue; 15895 } 15896 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15897 installRes.name = childPackageName; 15898 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15899 installRes.pkg = mPackages.get(childPackageName); 15900 installRes.uid = childPs.pkg.applicationInfo.uid; 15901 if (outInfo.appearedChildPackages == null) { 15902 outInfo.appearedChildPackages = new ArrayMap<>(); 15903 } 15904 outInfo.appearedChildPackages.put(childPackageName, installRes); 15905 } 15906 } 15907 } 15908 } 15909 } 15910 15911 return ret; 15912 } 15913 15914 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15915 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15916 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15917 for (int nextUserId : userIds) { 15918 if (DEBUG_REMOVE) { 15919 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15920 } 15921 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15922 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15923 false /*hidden*/, false /*suspended*/, null, null, null, 15924 false /*blockUninstall*/, 15925 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15926 } 15927 } 15928 15929 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15930 PackageRemovedInfo outInfo) { 15931 final PackageParser.Package pkg; 15932 synchronized (mPackages) { 15933 pkg = mPackages.get(ps.name); 15934 } 15935 15936 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15937 : new int[] {userId}; 15938 for (int nextUserId : userIds) { 15939 if (DEBUG_REMOVE) { 15940 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15941 + nextUserId); 15942 } 15943 15944 destroyAppDataLIF(pkg, userId, 15945 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15946 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15947 schedulePackageCleaning(ps.name, nextUserId, false); 15948 synchronized (mPackages) { 15949 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15950 scheduleWritePackageRestrictionsLocked(nextUserId); 15951 } 15952 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15953 } 15954 } 15955 15956 if (outInfo != null) { 15957 outInfo.removedPackage = ps.name; 15958 outInfo.removedAppId = ps.appId; 15959 outInfo.removedUsers = userIds; 15960 } 15961 15962 return true; 15963 } 15964 15965 private final class ClearStorageConnection implements ServiceConnection { 15966 IMediaContainerService mContainerService; 15967 15968 @Override 15969 public void onServiceConnected(ComponentName name, IBinder service) { 15970 synchronized (this) { 15971 mContainerService = IMediaContainerService.Stub.asInterface(service); 15972 notifyAll(); 15973 } 15974 } 15975 15976 @Override 15977 public void onServiceDisconnected(ComponentName name) { 15978 } 15979 } 15980 15981 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15982 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15983 15984 final boolean mounted; 15985 if (Environment.isExternalStorageEmulated()) { 15986 mounted = true; 15987 } else { 15988 final String status = Environment.getExternalStorageState(); 15989 15990 mounted = status.equals(Environment.MEDIA_MOUNTED) 15991 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15992 } 15993 15994 if (!mounted) { 15995 return; 15996 } 15997 15998 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15999 int[] users; 16000 if (userId == UserHandle.USER_ALL) { 16001 users = sUserManager.getUserIds(); 16002 } else { 16003 users = new int[] { userId }; 16004 } 16005 final ClearStorageConnection conn = new ClearStorageConnection(); 16006 if (mContext.bindServiceAsUser( 16007 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16008 try { 16009 for (int curUser : users) { 16010 long timeout = SystemClock.uptimeMillis() + 5000; 16011 synchronized (conn) { 16012 long now = SystemClock.uptimeMillis(); 16013 while (conn.mContainerService == null && now < timeout) { 16014 try { 16015 conn.wait(timeout - now); 16016 } catch (InterruptedException e) { 16017 } 16018 } 16019 } 16020 if (conn.mContainerService == null) { 16021 return; 16022 } 16023 16024 final UserEnvironment userEnv = new UserEnvironment(curUser); 16025 clearDirectory(conn.mContainerService, 16026 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16027 if (allData) { 16028 clearDirectory(conn.mContainerService, 16029 userEnv.buildExternalStorageAppDataDirs(packageName)); 16030 clearDirectory(conn.mContainerService, 16031 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16032 } 16033 } 16034 } finally { 16035 mContext.unbindService(conn); 16036 } 16037 } 16038 } 16039 16040 @Override 16041 public void clearApplicationProfileData(String packageName) { 16042 enforceSystemOrRoot("Only the system can clear all profile data"); 16043 16044 final PackageParser.Package pkg; 16045 synchronized (mPackages) { 16046 pkg = mPackages.get(packageName); 16047 } 16048 16049 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16050 synchronized (mInstallLock) { 16051 clearAppProfilesLIF(pkg); 16052 } 16053 } 16054 } 16055 16056 @Override 16057 public void clearApplicationUserData(final String packageName, 16058 final IPackageDataObserver observer, final int userId) { 16059 mContext.enforceCallingOrSelfPermission( 16060 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16061 16062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16063 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16064 16065 final DevicePolicyManagerInternal dpmi = LocalServices 16066 .getService(DevicePolicyManagerInternal.class); 16067 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16068 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16069 } 16070 // Queue up an async operation since the package deletion may take a little while. 16071 mHandler.post(new Runnable() { 16072 public void run() { 16073 mHandler.removeCallbacks(this); 16074 final boolean succeeded; 16075 try (PackageFreezer freezer = freezePackage(packageName, 16076 "clearApplicationUserData")) { 16077 synchronized (mInstallLock) { 16078 succeeded = clearApplicationUserDataLIF(packageName, userId); 16079 } 16080 clearExternalStorageDataSync(packageName, userId, true); 16081 } 16082 if (succeeded) { 16083 // invoke DeviceStorageMonitor's update method to clear any notifications 16084 DeviceStorageMonitorInternal dsm = LocalServices 16085 .getService(DeviceStorageMonitorInternal.class); 16086 if (dsm != null) { 16087 dsm.checkMemory(); 16088 } 16089 } 16090 if(observer != null) { 16091 try { 16092 observer.onRemoveCompleted(packageName, succeeded); 16093 } catch (RemoteException e) { 16094 Log.i(TAG, "Observer no longer exists."); 16095 } 16096 } //end if observer 16097 } //end run 16098 }); 16099 } 16100 16101 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16102 if (packageName == null) { 16103 Slog.w(TAG, "Attempt to delete null packageName."); 16104 return false; 16105 } 16106 16107 // Try finding details about the requested package 16108 PackageParser.Package pkg; 16109 synchronized (mPackages) { 16110 pkg = mPackages.get(packageName); 16111 if (pkg == null) { 16112 final PackageSetting ps = mSettings.mPackages.get(packageName); 16113 if (ps != null) { 16114 pkg = ps.pkg; 16115 } 16116 } 16117 16118 if (pkg == null) { 16119 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16120 return false; 16121 } 16122 16123 PackageSetting ps = (PackageSetting) pkg.mExtras; 16124 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16125 } 16126 16127 clearAppDataLIF(pkg, userId, 16128 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16129 16130 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16131 removeKeystoreDataIfNeeded(userId, appId); 16132 16133 final UserManager um = mContext.getSystemService(UserManager.class); 16134 final int flags; 16135 if (um.isUserUnlockingOrUnlocked(userId)) { 16136 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16137 } else if (um.isUserRunning(userId)) { 16138 flags = StorageManager.FLAG_STORAGE_DE; 16139 } else { 16140 flags = 0; 16141 } 16142 prepareAppDataContentsLIF(pkg, userId, flags); 16143 16144 return true; 16145 } 16146 16147 /** 16148 * Reverts user permission state changes (permissions and flags) in 16149 * all packages for a given user. 16150 * 16151 * @param userId The device user for which to do a reset. 16152 */ 16153 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16154 final int packageCount = mPackages.size(); 16155 for (int i = 0; i < packageCount; i++) { 16156 PackageParser.Package pkg = mPackages.valueAt(i); 16157 PackageSetting ps = (PackageSetting) pkg.mExtras; 16158 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16159 } 16160 } 16161 16162 /** 16163 * Reverts user permission state changes (permissions and flags). 16164 * 16165 * @param ps The package for which to reset. 16166 * @param userId The device user for which to do a reset. 16167 */ 16168 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16169 final PackageSetting ps, final int userId) { 16170 if (ps.pkg == null) { 16171 return; 16172 } 16173 16174 // These are flags that can change base on user actions. 16175 final int userSettableMask = FLAG_PERMISSION_USER_SET 16176 | FLAG_PERMISSION_USER_FIXED 16177 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16178 | FLAG_PERMISSION_REVIEW_REQUIRED; 16179 16180 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16181 | FLAG_PERMISSION_POLICY_FIXED; 16182 16183 boolean writeInstallPermissions = false; 16184 boolean writeRuntimePermissions = false; 16185 16186 final int permissionCount = ps.pkg.requestedPermissions.size(); 16187 for (int i = 0; i < permissionCount; i++) { 16188 String permission = ps.pkg.requestedPermissions.get(i); 16189 16190 BasePermission bp = mSettings.mPermissions.get(permission); 16191 if (bp == null) { 16192 continue; 16193 } 16194 16195 // If shared user we just reset the state to which only this app contributed. 16196 if (ps.sharedUser != null) { 16197 boolean used = false; 16198 final int packageCount = ps.sharedUser.packages.size(); 16199 for (int j = 0; j < packageCount; j++) { 16200 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16201 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16202 && pkg.pkg.requestedPermissions.contains(permission)) { 16203 used = true; 16204 break; 16205 } 16206 } 16207 if (used) { 16208 continue; 16209 } 16210 } 16211 16212 PermissionsState permissionsState = ps.getPermissionsState(); 16213 16214 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16215 16216 // Always clear the user settable flags. 16217 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16218 bp.name) != null; 16219 // If permission review is enabled and this is a legacy app, mark the 16220 // permission as requiring a review as this is the initial state. 16221 int flags = 0; 16222 if (Build.PERMISSIONS_REVIEW_REQUIRED 16223 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16224 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16225 } 16226 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16227 if (hasInstallState) { 16228 writeInstallPermissions = true; 16229 } else { 16230 writeRuntimePermissions = true; 16231 } 16232 } 16233 16234 // Below is only runtime permission handling. 16235 if (!bp.isRuntime()) { 16236 continue; 16237 } 16238 16239 // Never clobber system or policy. 16240 if ((oldFlags & policyOrSystemFlags) != 0) { 16241 continue; 16242 } 16243 16244 // If this permission was granted by default, make sure it is. 16245 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16246 if (permissionsState.grantRuntimePermission(bp, userId) 16247 != PERMISSION_OPERATION_FAILURE) { 16248 writeRuntimePermissions = true; 16249 } 16250 // If permission review is enabled the permissions for a legacy apps 16251 // are represented as constantly granted runtime ones, so don't revoke. 16252 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16253 // Otherwise, reset the permission. 16254 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16255 switch (revokeResult) { 16256 case PERMISSION_OPERATION_SUCCESS: 16257 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16258 writeRuntimePermissions = true; 16259 final int appId = ps.appId; 16260 mHandler.post(new Runnable() { 16261 @Override 16262 public void run() { 16263 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16264 } 16265 }); 16266 } break; 16267 } 16268 } 16269 } 16270 16271 // Synchronously write as we are taking permissions away. 16272 if (writeRuntimePermissions) { 16273 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16274 } 16275 16276 // Synchronously write as we are taking permissions away. 16277 if (writeInstallPermissions) { 16278 mSettings.writeLPr(); 16279 } 16280 } 16281 16282 /** 16283 * Remove entries from the keystore daemon. Will only remove it if the 16284 * {@code appId} is valid. 16285 */ 16286 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16287 if (appId < 0) { 16288 return; 16289 } 16290 16291 final KeyStore keyStore = KeyStore.getInstance(); 16292 if (keyStore != null) { 16293 if (userId == UserHandle.USER_ALL) { 16294 for (final int individual : sUserManager.getUserIds()) { 16295 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16296 } 16297 } else { 16298 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16299 } 16300 } else { 16301 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16302 } 16303 } 16304 16305 @Override 16306 public void deleteApplicationCacheFiles(final String packageName, 16307 final IPackageDataObserver observer) { 16308 final int userId = UserHandle.getCallingUserId(); 16309 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16310 } 16311 16312 @Override 16313 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16314 final IPackageDataObserver observer) { 16315 mContext.enforceCallingOrSelfPermission( 16316 android.Manifest.permission.DELETE_CACHE_FILES, null); 16317 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16318 /* requireFullPermission= */ true, /* checkShell= */ false, 16319 "delete application cache files"); 16320 16321 final PackageParser.Package pkg; 16322 synchronized (mPackages) { 16323 pkg = mPackages.get(packageName); 16324 } 16325 16326 // Queue up an async operation since the package deletion may take a little while. 16327 mHandler.post(new Runnable() { 16328 public void run() { 16329 synchronized (mInstallLock) { 16330 final int flags = StorageManager.FLAG_STORAGE_DE 16331 | StorageManager.FLAG_STORAGE_CE; 16332 // We're only clearing cache files, so we don't care if the 16333 // app is unfrozen and still able to run 16334 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16335 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16336 } 16337 clearExternalStorageDataSync(packageName, userId, false); 16338 if (observer != null) { 16339 try { 16340 observer.onRemoveCompleted(packageName, true); 16341 } catch (RemoteException e) { 16342 Log.i(TAG, "Observer no longer exists."); 16343 } 16344 } 16345 } 16346 }); 16347 } 16348 16349 @Override 16350 public void getPackageSizeInfo(final String packageName, int userHandle, 16351 final IPackageStatsObserver observer) { 16352 mContext.enforceCallingOrSelfPermission( 16353 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16354 if (packageName == null) { 16355 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16356 } 16357 16358 PackageStats stats = new PackageStats(packageName, userHandle); 16359 16360 /* 16361 * Queue up an async operation since the package measurement may take a 16362 * little while. 16363 */ 16364 Message msg = mHandler.obtainMessage(INIT_COPY); 16365 msg.obj = new MeasureParams(stats, observer); 16366 mHandler.sendMessage(msg); 16367 } 16368 16369 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16370 final PackageSetting ps; 16371 synchronized (mPackages) { 16372 ps = mSettings.mPackages.get(packageName); 16373 if (ps == null) { 16374 Slog.w(TAG, "Failed to find settings for " + packageName); 16375 return false; 16376 } 16377 } 16378 try { 16379 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16380 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16381 ps.getCeDataInode(userId), ps.codePathString, stats); 16382 } catch (InstallerException e) { 16383 Slog.w(TAG, String.valueOf(e)); 16384 return false; 16385 } 16386 16387 // For now, ignore code size of packages on system partition 16388 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16389 stats.codeSize = 0; 16390 } 16391 16392 return true; 16393 } 16394 16395 private int getUidTargetSdkVersionLockedLPr(int uid) { 16396 Object obj = mSettings.getUserIdLPr(uid); 16397 if (obj instanceof SharedUserSetting) { 16398 final SharedUserSetting sus = (SharedUserSetting) obj; 16399 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16400 final Iterator<PackageSetting> it = sus.packages.iterator(); 16401 while (it.hasNext()) { 16402 final PackageSetting ps = it.next(); 16403 if (ps.pkg != null) { 16404 int v = ps.pkg.applicationInfo.targetSdkVersion; 16405 if (v < vers) vers = v; 16406 } 16407 } 16408 return vers; 16409 } else if (obj instanceof PackageSetting) { 16410 final PackageSetting ps = (PackageSetting) obj; 16411 if (ps.pkg != null) { 16412 return ps.pkg.applicationInfo.targetSdkVersion; 16413 } 16414 } 16415 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16416 } 16417 16418 @Override 16419 public void addPreferredActivity(IntentFilter filter, int match, 16420 ComponentName[] set, ComponentName activity, int userId) { 16421 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16422 "Adding preferred"); 16423 } 16424 16425 private void addPreferredActivityInternal(IntentFilter filter, int match, 16426 ComponentName[] set, ComponentName activity, boolean always, int userId, 16427 String opname) { 16428 // writer 16429 int callingUid = Binder.getCallingUid(); 16430 enforceCrossUserPermission(callingUid, userId, 16431 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16432 if (filter.countActions() == 0) { 16433 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16434 return; 16435 } 16436 synchronized (mPackages) { 16437 if (mContext.checkCallingOrSelfPermission( 16438 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16439 != PackageManager.PERMISSION_GRANTED) { 16440 if (getUidTargetSdkVersionLockedLPr(callingUid) 16441 < Build.VERSION_CODES.FROYO) { 16442 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16443 + callingUid); 16444 return; 16445 } 16446 mContext.enforceCallingOrSelfPermission( 16447 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16448 } 16449 16450 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16451 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16452 + userId + ":"); 16453 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16454 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16455 scheduleWritePackageRestrictionsLocked(userId); 16456 } 16457 } 16458 16459 @Override 16460 public void replacePreferredActivity(IntentFilter filter, int match, 16461 ComponentName[] set, ComponentName activity, int userId) { 16462 if (filter.countActions() != 1) { 16463 throw new IllegalArgumentException( 16464 "replacePreferredActivity expects filter to have only 1 action."); 16465 } 16466 if (filter.countDataAuthorities() != 0 16467 || filter.countDataPaths() != 0 16468 || filter.countDataSchemes() > 1 16469 || filter.countDataTypes() != 0) { 16470 throw new IllegalArgumentException( 16471 "replacePreferredActivity expects filter to have no data authorities, " + 16472 "paths, or types; and at most one scheme."); 16473 } 16474 16475 final int callingUid = Binder.getCallingUid(); 16476 enforceCrossUserPermission(callingUid, userId, 16477 true /* requireFullPermission */, false /* checkShell */, 16478 "replace preferred activity"); 16479 synchronized (mPackages) { 16480 if (mContext.checkCallingOrSelfPermission( 16481 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16482 != PackageManager.PERMISSION_GRANTED) { 16483 if (getUidTargetSdkVersionLockedLPr(callingUid) 16484 < Build.VERSION_CODES.FROYO) { 16485 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16486 + Binder.getCallingUid()); 16487 return; 16488 } 16489 mContext.enforceCallingOrSelfPermission( 16490 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16491 } 16492 16493 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16494 if (pir != null) { 16495 // Get all of the existing entries that exactly match this filter. 16496 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16497 if (existing != null && existing.size() == 1) { 16498 PreferredActivity cur = existing.get(0); 16499 if (DEBUG_PREFERRED) { 16500 Slog.i(TAG, "Checking replace of preferred:"); 16501 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16502 if (!cur.mPref.mAlways) { 16503 Slog.i(TAG, " -- CUR; not mAlways!"); 16504 } else { 16505 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16506 Slog.i(TAG, " -- CUR: mSet=" 16507 + Arrays.toString(cur.mPref.mSetComponents)); 16508 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16509 Slog.i(TAG, " -- NEW: mMatch=" 16510 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16511 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16512 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16513 } 16514 } 16515 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16516 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16517 && cur.mPref.sameSet(set)) { 16518 // Setting the preferred activity to what it happens to be already 16519 if (DEBUG_PREFERRED) { 16520 Slog.i(TAG, "Replacing with same preferred activity " 16521 + cur.mPref.mShortComponent + " for user " 16522 + userId + ":"); 16523 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16524 } 16525 return; 16526 } 16527 } 16528 16529 if (existing != null) { 16530 if (DEBUG_PREFERRED) { 16531 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16532 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16533 } 16534 for (int i = 0; i < existing.size(); i++) { 16535 PreferredActivity pa = existing.get(i); 16536 if (DEBUG_PREFERRED) { 16537 Slog.i(TAG, "Removing existing preferred activity " 16538 + pa.mPref.mComponent + ":"); 16539 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16540 } 16541 pir.removeFilter(pa); 16542 } 16543 } 16544 } 16545 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16546 "Replacing preferred"); 16547 } 16548 } 16549 16550 @Override 16551 public void clearPackagePreferredActivities(String packageName) { 16552 final int uid = Binder.getCallingUid(); 16553 // writer 16554 synchronized (mPackages) { 16555 PackageParser.Package pkg = mPackages.get(packageName); 16556 if (pkg == null || pkg.applicationInfo.uid != uid) { 16557 if (mContext.checkCallingOrSelfPermission( 16558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16559 != PackageManager.PERMISSION_GRANTED) { 16560 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16561 < Build.VERSION_CODES.FROYO) { 16562 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16563 + Binder.getCallingUid()); 16564 return; 16565 } 16566 mContext.enforceCallingOrSelfPermission( 16567 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16568 } 16569 } 16570 16571 int user = UserHandle.getCallingUserId(); 16572 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16573 scheduleWritePackageRestrictionsLocked(user); 16574 } 16575 } 16576 } 16577 16578 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16579 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16580 ArrayList<PreferredActivity> removed = null; 16581 boolean changed = false; 16582 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16583 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16584 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16585 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16586 continue; 16587 } 16588 Iterator<PreferredActivity> it = pir.filterIterator(); 16589 while (it.hasNext()) { 16590 PreferredActivity pa = it.next(); 16591 // Mark entry for removal only if it matches the package name 16592 // and the entry is of type "always". 16593 if (packageName == null || 16594 (pa.mPref.mComponent.getPackageName().equals(packageName) 16595 && pa.mPref.mAlways)) { 16596 if (removed == null) { 16597 removed = new ArrayList<PreferredActivity>(); 16598 } 16599 removed.add(pa); 16600 } 16601 } 16602 if (removed != null) { 16603 for (int j=0; j<removed.size(); j++) { 16604 PreferredActivity pa = removed.get(j); 16605 pir.removeFilter(pa); 16606 } 16607 changed = true; 16608 } 16609 } 16610 return changed; 16611 } 16612 16613 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16614 private void clearIntentFilterVerificationsLPw(int userId) { 16615 final int packageCount = mPackages.size(); 16616 for (int i = 0; i < packageCount; i++) { 16617 PackageParser.Package pkg = mPackages.valueAt(i); 16618 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16619 } 16620 } 16621 16622 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16623 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16624 if (userId == UserHandle.USER_ALL) { 16625 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16626 sUserManager.getUserIds())) { 16627 for (int oneUserId : sUserManager.getUserIds()) { 16628 scheduleWritePackageRestrictionsLocked(oneUserId); 16629 } 16630 } 16631 } else { 16632 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16633 scheduleWritePackageRestrictionsLocked(userId); 16634 } 16635 } 16636 } 16637 16638 void clearDefaultBrowserIfNeeded(String packageName) { 16639 for (int oneUserId : sUserManager.getUserIds()) { 16640 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16641 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16642 if (packageName.equals(defaultBrowserPackageName)) { 16643 setDefaultBrowserPackageName(null, oneUserId); 16644 } 16645 } 16646 } 16647 16648 @Override 16649 public void resetApplicationPreferences(int userId) { 16650 mContext.enforceCallingOrSelfPermission( 16651 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16652 // writer 16653 synchronized (mPackages) { 16654 final long identity = Binder.clearCallingIdentity(); 16655 try { 16656 clearPackagePreferredActivitiesLPw(null, userId); 16657 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16658 // TODO: We have to reset the default SMS and Phone. This requires 16659 // significant refactoring to keep all default apps in the package 16660 // manager (cleaner but more work) or have the services provide 16661 // callbacks to the package manager to request a default app reset. 16662 applyFactoryDefaultBrowserLPw(userId); 16663 clearIntentFilterVerificationsLPw(userId); 16664 primeDomainVerificationsLPw(userId); 16665 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16666 scheduleWritePackageRestrictionsLocked(userId); 16667 } finally { 16668 Binder.restoreCallingIdentity(identity); 16669 } 16670 } 16671 } 16672 16673 @Override 16674 public int getPreferredActivities(List<IntentFilter> outFilters, 16675 List<ComponentName> outActivities, String packageName) { 16676 16677 int num = 0; 16678 final int userId = UserHandle.getCallingUserId(); 16679 // reader 16680 synchronized (mPackages) { 16681 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16682 if (pir != null) { 16683 final Iterator<PreferredActivity> it = pir.filterIterator(); 16684 while (it.hasNext()) { 16685 final PreferredActivity pa = it.next(); 16686 if (packageName == null 16687 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16688 && pa.mPref.mAlways)) { 16689 if (outFilters != null) { 16690 outFilters.add(new IntentFilter(pa)); 16691 } 16692 if (outActivities != null) { 16693 outActivities.add(pa.mPref.mComponent); 16694 } 16695 } 16696 } 16697 } 16698 } 16699 16700 return num; 16701 } 16702 16703 @Override 16704 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16705 int userId) { 16706 int callingUid = Binder.getCallingUid(); 16707 if (callingUid != Process.SYSTEM_UID) { 16708 throw new SecurityException( 16709 "addPersistentPreferredActivity can only be run by the system"); 16710 } 16711 if (filter.countActions() == 0) { 16712 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16713 return; 16714 } 16715 synchronized (mPackages) { 16716 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16717 ":"); 16718 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16719 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16720 new PersistentPreferredActivity(filter, activity)); 16721 scheduleWritePackageRestrictionsLocked(userId); 16722 } 16723 } 16724 16725 @Override 16726 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16727 int callingUid = Binder.getCallingUid(); 16728 if (callingUid != Process.SYSTEM_UID) { 16729 throw new SecurityException( 16730 "clearPackagePersistentPreferredActivities can only be run by the system"); 16731 } 16732 ArrayList<PersistentPreferredActivity> removed = null; 16733 boolean changed = false; 16734 synchronized (mPackages) { 16735 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16736 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16737 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16738 .valueAt(i); 16739 if (userId != thisUserId) { 16740 continue; 16741 } 16742 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16743 while (it.hasNext()) { 16744 PersistentPreferredActivity ppa = it.next(); 16745 // Mark entry for removal only if it matches the package name. 16746 if (ppa.mComponent.getPackageName().equals(packageName)) { 16747 if (removed == null) { 16748 removed = new ArrayList<PersistentPreferredActivity>(); 16749 } 16750 removed.add(ppa); 16751 } 16752 } 16753 if (removed != null) { 16754 for (int j=0; j<removed.size(); j++) { 16755 PersistentPreferredActivity ppa = removed.get(j); 16756 ppir.removeFilter(ppa); 16757 } 16758 changed = true; 16759 } 16760 } 16761 16762 if (changed) { 16763 scheduleWritePackageRestrictionsLocked(userId); 16764 } 16765 } 16766 } 16767 16768 /** 16769 * Common machinery for picking apart a restored XML blob and passing 16770 * it to a caller-supplied functor to be applied to the running system. 16771 */ 16772 private void restoreFromXml(XmlPullParser parser, int userId, 16773 String expectedStartTag, BlobXmlRestorer functor) 16774 throws IOException, XmlPullParserException { 16775 int type; 16776 while ((type = parser.next()) != XmlPullParser.START_TAG 16777 && type != XmlPullParser.END_DOCUMENT) { 16778 } 16779 if (type != XmlPullParser.START_TAG) { 16780 // oops didn't find a start tag?! 16781 if (DEBUG_BACKUP) { 16782 Slog.e(TAG, "Didn't find start tag during restore"); 16783 } 16784 return; 16785 } 16786Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16787 // this is supposed to be TAG_PREFERRED_BACKUP 16788 if (!expectedStartTag.equals(parser.getName())) { 16789 if (DEBUG_BACKUP) { 16790 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16791 } 16792 return; 16793 } 16794 16795 // skip interfering stuff, then we're aligned with the backing implementation 16796 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16797Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16798 functor.apply(parser, userId); 16799 } 16800 16801 private interface BlobXmlRestorer { 16802 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16803 } 16804 16805 /** 16806 * Non-Binder method, support for the backup/restore mechanism: write the 16807 * full set of preferred activities in its canonical XML format. Returns the 16808 * XML output as a byte array, or null if there is none. 16809 */ 16810 @Override 16811 public byte[] getPreferredActivityBackup(int userId) { 16812 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16813 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16814 } 16815 16816 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16817 try { 16818 final XmlSerializer serializer = new FastXmlSerializer(); 16819 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16820 serializer.startDocument(null, true); 16821 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16822 16823 synchronized (mPackages) { 16824 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16825 } 16826 16827 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16828 serializer.endDocument(); 16829 serializer.flush(); 16830 } catch (Exception e) { 16831 if (DEBUG_BACKUP) { 16832 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16833 } 16834 return null; 16835 } 16836 16837 return dataStream.toByteArray(); 16838 } 16839 16840 @Override 16841 public void restorePreferredActivities(byte[] backup, int userId) { 16842 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16843 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16844 } 16845 16846 try { 16847 final XmlPullParser parser = Xml.newPullParser(); 16848 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16849 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16850 new BlobXmlRestorer() { 16851 @Override 16852 public void apply(XmlPullParser parser, int userId) 16853 throws XmlPullParserException, IOException { 16854 synchronized (mPackages) { 16855 mSettings.readPreferredActivitiesLPw(parser, userId); 16856 } 16857 } 16858 } ); 16859 } catch (Exception e) { 16860 if (DEBUG_BACKUP) { 16861 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16862 } 16863 } 16864 } 16865 16866 /** 16867 * Non-Binder method, support for the backup/restore mechanism: write the 16868 * default browser (etc) settings in its canonical XML format. Returns the default 16869 * browser XML representation as a byte array, or null if there is none. 16870 */ 16871 @Override 16872 public byte[] getDefaultAppsBackup(int userId) { 16873 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16874 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16875 } 16876 16877 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16878 try { 16879 final XmlSerializer serializer = new FastXmlSerializer(); 16880 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16881 serializer.startDocument(null, true); 16882 serializer.startTag(null, TAG_DEFAULT_APPS); 16883 16884 synchronized (mPackages) { 16885 mSettings.writeDefaultAppsLPr(serializer, userId); 16886 } 16887 16888 serializer.endTag(null, TAG_DEFAULT_APPS); 16889 serializer.endDocument(); 16890 serializer.flush(); 16891 } catch (Exception e) { 16892 if (DEBUG_BACKUP) { 16893 Slog.e(TAG, "Unable to write default apps for backup", e); 16894 } 16895 return null; 16896 } 16897 16898 return dataStream.toByteArray(); 16899 } 16900 16901 @Override 16902 public void restoreDefaultApps(byte[] backup, int userId) { 16903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16904 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16905 } 16906 16907 try { 16908 final XmlPullParser parser = Xml.newPullParser(); 16909 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16910 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16911 new BlobXmlRestorer() { 16912 @Override 16913 public void apply(XmlPullParser parser, int userId) 16914 throws XmlPullParserException, IOException { 16915 synchronized (mPackages) { 16916 mSettings.readDefaultAppsLPw(parser, userId); 16917 } 16918 } 16919 } ); 16920 } catch (Exception e) { 16921 if (DEBUG_BACKUP) { 16922 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16923 } 16924 } 16925 } 16926 16927 @Override 16928 public byte[] getIntentFilterVerificationBackup(int userId) { 16929 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16930 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16931 } 16932 16933 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16934 try { 16935 final XmlSerializer serializer = new FastXmlSerializer(); 16936 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16937 serializer.startDocument(null, true); 16938 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16939 16940 synchronized (mPackages) { 16941 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16942 } 16943 16944 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16945 serializer.endDocument(); 16946 serializer.flush(); 16947 } catch (Exception e) { 16948 if (DEBUG_BACKUP) { 16949 Slog.e(TAG, "Unable to write default apps for backup", e); 16950 } 16951 return null; 16952 } 16953 16954 return dataStream.toByteArray(); 16955 } 16956 16957 @Override 16958 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16959 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16960 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16961 } 16962 16963 try { 16964 final XmlPullParser parser = Xml.newPullParser(); 16965 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16966 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16967 new BlobXmlRestorer() { 16968 @Override 16969 public void apply(XmlPullParser parser, int userId) 16970 throws XmlPullParserException, IOException { 16971 synchronized (mPackages) { 16972 mSettings.readAllDomainVerificationsLPr(parser, userId); 16973 mSettings.writeLPr(); 16974 } 16975 } 16976 } ); 16977 } catch (Exception e) { 16978 if (DEBUG_BACKUP) { 16979 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16980 } 16981 } 16982 } 16983 16984 @Override 16985 public byte[] getPermissionGrantBackup(int userId) { 16986 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16987 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16988 } 16989 16990 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16991 try { 16992 final XmlSerializer serializer = new FastXmlSerializer(); 16993 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16994 serializer.startDocument(null, true); 16995 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16996 16997 synchronized (mPackages) { 16998 serializeRuntimePermissionGrantsLPr(serializer, userId); 16999 } 17000 17001 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17002 serializer.endDocument(); 17003 serializer.flush(); 17004 } catch (Exception e) { 17005 if (DEBUG_BACKUP) { 17006 Slog.e(TAG, "Unable to write default apps for backup", e); 17007 } 17008 return null; 17009 } 17010 17011 return dataStream.toByteArray(); 17012 } 17013 17014 @Override 17015 public void restorePermissionGrants(byte[] backup, int userId) { 17016 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17017 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17018 } 17019 17020 try { 17021 final XmlPullParser parser = Xml.newPullParser(); 17022 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17023 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17024 new BlobXmlRestorer() { 17025 @Override 17026 public void apply(XmlPullParser parser, int userId) 17027 throws XmlPullParserException, IOException { 17028 synchronized (mPackages) { 17029 processRestoredPermissionGrantsLPr(parser, userId); 17030 } 17031 } 17032 } ); 17033 } catch (Exception e) { 17034 if (DEBUG_BACKUP) { 17035 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17036 } 17037 } 17038 } 17039 17040 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17041 throws IOException { 17042 serializer.startTag(null, TAG_ALL_GRANTS); 17043 17044 final int N = mSettings.mPackages.size(); 17045 for (int i = 0; i < N; i++) { 17046 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17047 boolean pkgGrantsKnown = false; 17048 17049 PermissionsState packagePerms = ps.getPermissionsState(); 17050 17051 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17052 final int grantFlags = state.getFlags(); 17053 // only look at grants that are not system/policy fixed 17054 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17055 final boolean isGranted = state.isGranted(); 17056 // And only back up the user-twiddled state bits 17057 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17058 final String packageName = mSettings.mPackages.keyAt(i); 17059 if (!pkgGrantsKnown) { 17060 serializer.startTag(null, TAG_GRANT); 17061 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17062 pkgGrantsKnown = true; 17063 } 17064 17065 final boolean userSet = 17066 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17067 final boolean userFixed = 17068 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17069 final boolean revoke = 17070 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17071 17072 serializer.startTag(null, TAG_PERMISSION); 17073 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17074 if (isGranted) { 17075 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17076 } 17077 if (userSet) { 17078 serializer.attribute(null, ATTR_USER_SET, "true"); 17079 } 17080 if (userFixed) { 17081 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17082 } 17083 if (revoke) { 17084 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17085 } 17086 serializer.endTag(null, TAG_PERMISSION); 17087 } 17088 } 17089 } 17090 17091 if (pkgGrantsKnown) { 17092 serializer.endTag(null, TAG_GRANT); 17093 } 17094 } 17095 17096 serializer.endTag(null, TAG_ALL_GRANTS); 17097 } 17098 17099 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17100 throws XmlPullParserException, IOException { 17101 String pkgName = null; 17102 int outerDepth = parser.getDepth(); 17103 int type; 17104 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17105 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17106 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17107 continue; 17108 } 17109 17110 final String tagName = parser.getName(); 17111 if (tagName.equals(TAG_GRANT)) { 17112 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17113 if (DEBUG_BACKUP) { 17114 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17115 } 17116 } else if (tagName.equals(TAG_PERMISSION)) { 17117 17118 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17119 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17120 17121 int newFlagSet = 0; 17122 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17123 newFlagSet |= FLAG_PERMISSION_USER_SET; 17124 } 17125 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17126 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17127 } 17128 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17129 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17130 } 17131 if (DEBUG_BACKUP) { 17132 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17133 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17134 } 17135 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17136 if (ps != null) { 17137 // Already installed so we apply the grant immediately 17138 if (DEBUG_BACKUP) { 17139 Slog.v(TAG, " + already installed; applying"); 17140 } 17141 PermissionsState perms = ps.getPermissionsState(); 17142 BasePermission bp = mSettings.mPermissions.get(permName); 17143 if (bp != null) { 17144 if (isGranted) { 17145 perms.grantRuntimePermission(bp, userId); 17146 } 17147 if (newFlagSet != 0) { 17148 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17149 } 17150 } 17151 } else { 17152 // Need to wait for post-restore install to apply the grant 17153 if (DEBUG_BACKUP) { 17154 Slog.v(TAG, " - not yet installed; saving for later"); 17155 } 17156 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17157 isGranted, newFlagSet, userId); 17158 } 17159 } else { 17160 PackageManagerService.reportSettingsProblem(Log.WARN, 17161 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17162 XmlUtils.skipCurrentTag(parser); 17163 } 17164 } 17165 17166 scheduleWriteSettingsLocked(); 17167 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17168 } 17169 17170 @Override 17171 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17172 int sourceUserId, int targetUserId, int flags) { 17173 mContext.enforceCallingOrSelfPermission( 17174 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17175 int callingUid = Binder.getCallingUid(); 17176 enforceOwnerRights(ownerPackage, callingUid); 17177 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17178 if (intentFilter.countActions() == 0) { 17179 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17180 return; 17181 } 17182 synchronized (mPackages) { 17183 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17184 ownerPackage, targetUserId, flags); 17185 CrossProfileIntentResolver resolver = 17186 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17187 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17188 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17189 if (existing != null) { 17190 int size = existing.size(); 17191 for (int i = 0; i < size; i++) { 17192 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17193 return; 17194 } 17195 } 17196 } 17197 resolver.addFilter(newFilter); 17198 scheduleWritePackageRestrictionsLocked(sourceUserId); 17199 } 17200 } 17201 17202 @Override 17203 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17204 mContext.enforceCallingOrSelfPermission( 17205 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17206 int callingUid = Binder.getCallingUid(); 17207 enforceOwnerRights(ownerPackage, callingUid); 17208 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17209 synchronized (mPackages) { 17210 CrossProfileIntentResolver resolver = 17211 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17212 ArraySet<CrossProfileIntentFilter> set = 17213 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17214 for (CrossProfileIntentFilter filter : set) { 17215 if (filter.getOwnerPackage().equals(ownerPackage)) { 17216 resolver.removeFilter(filter); 17217 } 17218 } 17219 scheduleWritePackageRestrictionsLocked(sourceUserId); 17220 } 17221 } 17222 17223 // Enforcing that callingUid is owning pkg on userId 17224 private void enforceOwnerRights(String pkg, int callingUid) { 17225 // The system owns everything. 17226 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17227 return; 17228 } 17229 int callingUserId = UserHandle.getUserId(callingUid); 17230 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17231 if (pi == null) { 17232 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17233 + callingUserId); 17234 } 17235 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17236 throw new SecurityException("Calling uid " + callingUid 17237 + " does not own package " + pkg); 17238 } 17239 } 17240 17241 @Override 17242 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17243 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17244 } 17245 17246 private Intent getHomeIntent() { 17247 Intent intent = new Intent(Intent.ACTION_MAIN); 17248 intent.addCategory(Intent.CATEGORY_HOME); 17249 return intent; 17250 } 17251 17252 private IntentFilter getHomeFilter() { 17253 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17254 filter.addCategory(Intent.CATEGORY_HOME); 17255 filter.addCategory(Intent.CATEGORY_DEFAULT); 17256 return filter; 17257 } 17258 17259 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17260 int userId) { 17261 Intent intent = getHomeIntent(); 17262 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17263 PackageManager.GET_META_DATA, userId); 17264 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17265 true, false, false, userId); 17266 17267 allHomeCandidates.clear(); 17268 if (list != null) { 17269 for (ResolveInfo ri : list) { 17270 allHomeCandidates.add(ri); 17271 } 17272 } 17273 return (preferred == null || preferred.activityInfo == null) 17274 ? null 17275 : new ComponentName(preferred.activityInfo.packageName, 17276 preferred.activityInfo.name); 17277 } 17278 17279 @Override 17280 public void setHomeActivity(ComponentName comp, int userId) { 17281 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17282 getHomeActivitiesAsUser(homeActivities, userId); 17283 17284 boolean found = false; 17285 17286 final int size = homeActivities.size(); 17287 final ComponentName[] set = new ComponentName[size]; 17288 for (int i = 0; i < size; i++) { 17289 final ResolveInfo candidate = homeActivities.get(i); 17290 final ActivityInfo info = candidate.activityInfo; 17291 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17292 set[i] = activityName; 17293 if (!found && activityName.equals(comp)) { 17294 found = true; 17295 } 17296 } 17297 if (!found) { 17298 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17299 + userId); 17300 } 17301 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17302 set, comp, userId); 17303 } 17304 17305 private @Nullable String getSetupWizardPackageName() { 17306 final Intent intent = new Intent(Intent.ACTION_MAIN); 17307 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17308 17309 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17310 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17311 | MATCH_DISABLED_COMPONENTS, 17312 UserHandle.myUserId()); 17313 if (matches.size() == 1) { 17314 return matches.get(0).getComponentInfo().packageName; 17315 } else { 17316 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17317 + ": matches=" + matches); 17318 return null; 17319 } 17320 } 17321 17322 @Override 17323 public void setApplicationEnabledSetting(String appPackageName, 17324 int newState, int flags, int userId, String callingPackage) { 17325 if (!sUserManager.exists(userId)) return; 17326 if (callingPackage == null) { 17327 callingPackage = Integer.toString(Binder.getCallingUid()); 17328 } 17329 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17330 } 17331 17332 @Override 17333 public void setComponentEnabledSetting(ComponentName componentName, 17334 int newState, int flags, int userId) { 17335 if (!sUserManager.exists(userId)) return; 17336 setEnabledSetting(componentName.getPackageName(), 17337 componentName.getClassName(), newState, flags, userId, null); 17338 } 17339 17340 private void setEnabledSetting(final String packageName, String className, int newState, 17341 final int flags, int userId, String callingPackage) { 17342 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17343 || newState == COMPONENT_ENABLED_STATE_ENABLED 17344 || newState == COMPONENT_ENABLED_STATE_DISABLED 17345 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17346 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17347 throw new IllegalArgumentException("Invalid new component state: " 17348 + newState); 17349 } 17350 PackageSetting pkgSetting; 17351 final int uid = Binder.getCallingUid(); 17352 final int permission; 17353 if (uid == Process.SYSTEM_UID) { 17354 permission = PackageManager.PERMISSION_GRANTED; 17355 } else { 17356 permission = mContext.checkCallingOrSelfPermission( 17357 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17358 } 17359 enforceCrossUserPermission(uid, userId, 17360 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17361 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17362 boolean sendNow = false; 17363 boolean isApp = (className == null); 17364 String componentName = isApp ? packageName : className; 17365 int packageUid = -1; 17366 ArrayList<String> components; 17367 17368 // writer 17369 synchronized (mPackages) { 17370 pkgSetting = mSettings.mPackages.get(packageName); 17371 if (pkgSetting == null) { 17372 if (className == null) { 17373 throw new IllegalArgumentException("Unknown package: " + packageName); 17374 } 17375 throw new IllegalArgumentException( 17376 "Unknown component: " + packageName + "/" + className); 17377 } 17378 // Allow root and verify that userId is not being specified by a different user 17379 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17380 throw new SecurityException( 17381 "Permission Denial: attempt to change component state from pid=" 17382 + Binder.getCallingPid() 17383 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17384 } 17385 if (className == null) { 17386 // We're dealing with an application/package level state change 17387 if (pkgSetting.getEnabled(userId) == newState) { 17388 // Nothing to do 17389 return; 17390 } 17391 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17392 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17393 // Don't care about who enables an app. 17394 callingPackage = null; 17395 } 17396 pkgSetting.setEnabled(newState, userId, callingPackage); 17397 // pkgSetting.pkg.mSetEnabled = newState; 17398 } else { 17399 // We're dealing with a component level state change 17400 // First, verify that this is a valid class name. 17401 PackageParser.Package pkg = pkgSetting.pkg; 17402 if (pkg == null || !pkg.hasComponentClassName(className)) { 17403 if (pkg != null && 17404 pkg.applicationInfo.targetSdkVersion >= 17405 Build.VERSION_CODES.JELLY_BEAN) { 17406 throw new IllegalArgumentException("Component class " + className 17407 + " does not exist in " + packageName); 17408 } else { 17409 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17410 + className + " does not exist in " + packageName); 17411 } 17412 } 17413 switch (newState) { 17414 case COMPONENT_ENABLED_STATE_ENABLED: 17415 if (!pkgSetting.enableComponentLPw(className, userId)) { 17416 return; 17417 } 17418 break; 17419 case COMPONENT_ENABLED_STATE_DISABLED: 17420 if (!pkgSetting.disableComponentLPw(className, userId)) { 17421 return; 17422 } 17423 break; 17424 case COMPONENT_ENABLED_STATE_DEFAULT: 17425 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17426 return; 17427 } 17428 break; 17429 default: 17430 Slog.e(TAG, "Invalid new component state: " + newState); 17431 return; 17432 } 17433 } 17434 scheduleWritePackageRestrictionsLocked(userId); 17435 components = mPendingBroadcasts.get(userId, packageName); 17436 final boolean newPackage = components == null; 17437 if (newPackage) { 17438 components = new ArrayList<String>(); 17439 } 17440 if (!components.contains(componentName)) { 17441 components.add(componentName); 17442 } 17443 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17444 sendNow = true; 17445 // Purge entry from pending broadcast list if another one exists already 17446 // since we are sending one right away. 17447 mPendingBroadcasts.remove(userId, packageName); 17448 } else { 17449 if (newPackage) { 17450 mPendingBroadcasts.put(userId, packageName, components); 17451 } 17452 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17453 // Schedule a message 17454 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17455 } 17456 } 17457 } 17458 17459 long callingId = Binder.clearCallingIdentity(); 17460 try { 17461 if (sendNow) { 17462 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17463 sendPackageChangedBroadcast(packageName, 17464 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17465 } 17466 } finally { 17467 Binder.restoreCallingIdentity(callingId); 17468 } 17469 } 17470 17471 @Override 17472 public void flushPackageRestrictionsAsUser(int userId) { 17473 if (!sUserManager.exists(userId)) { 17474 return; 17475 } 17476 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17477 false /* checkShell */, "flushPackageRestrictions"); 17478 synchronized (mPackages) { 17479 mSettings.writePackageRestrictionsLPr(userId); 17480 mDirtyUsers.remove(userId); 17481 if (mDirtyUsers.isEmpty()) { 17482 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17483 } 17484 } 17485 } 17486 17487 private void sendPackageChangedBroadcast(String packageName, 17488 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17489 if (DEBUG_INSTALL) 17490 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17491 + componentNames); 17492 Bundle extras = new Bundle(4); 17493 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17494 String nameList[] = new String[componentNames.size()]; 17495 componentNames.toArray(nameList); 17496 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17497 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17498 extras.putInt(Intent.EXTRA_UID, packageUid); 17499 // If this is not reporting a change of the overall package, then only send it 17500 // to registered receivers. We don't want to launch a swath of apps for every 17501 // little component state change. 17502 final int flags = !componentNames.contains(packageName) 17503 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17504 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17505 new int[] {UserHandle.getUserId(packageUid)}); 17506 } 17507 17508 @Override 17509 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17510 if (!sUserManager.exists(userId)) return; 17511 final int uid = Binder.getCallingUid(); 17512 final int permission = mContext.checkCallingOrSelfPermission( 17513 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17514 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17515 enforceCrossUserPermission(uid, userId, 17516 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17517 // writer 17518 synchronized (mPackages) { 17519 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17520 allowedByPermission, uid, userId)) { 17521 scheduleWritePackageRestrictionsLocked(userId); 17522 } 17523 } 17524 } 17525 17526 @Override 17527 public String getInstallerPackageName(String packageName) { 17528 // reader 17529 synchronized (mPackages) { 17530 return mSettings.getInstallerPackageNameLPr(packageName); 17531 } 17532 } 17533 17534 public boolean isOrphaned(String packageName) { 17535 // reader 17536 synchronized (mPackages) { 17537 return mSettings.isOrphaned(packageName); 17538 } 17539 } 17540 17541 @Override 17542 public int getApplicationEnabledSetting(String packageName, int userId) { 17543 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17544 int uid = Binder.getCallingUid(); 17545 enforceCrossUserPermission(uid, userId, 17546 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17547 // reader 17548 synchronized (mPackages) { 17549 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17550 } 17551 } 17552 17553 @Override 17554 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17555 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17556 int uid = Binder.getCallingUid(); 17557 enforceCrossUserPermission(uid, userId, 17558 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17559 // reader 17560 synchronized (mPackages) { 17561 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17562 } 17563 } 17564 17565 @Override 17566 public void enterSafeMode() { 17567 enforceSystemOrRoot("Only the system can request entering safe mode"); 17568 17569 if (!mSystemReady) { 17570 mSafeMode = true; 17571 } 17572 } 17573 17574 @Override 17575 public void systemReady() { 17576 mSystemReady = true; 17577 17578 // Read the compatibilty setting when the system is ready. 17579 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17580 mContext.getContentResolver(), 17581 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17582 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17583 if (DEBUG_SETTINGS) { 17584 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17585 } 17586 17587 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17588 17589 synchronized (mPackages) { 17590 // Verify that all of the preferred activity components actually 17591 // exist. It is possible for applications to be updated and at 17592 // that point remove a previously declared activity component that 17593 // had been set as a preferred activity. We try to clean this up 17594 // the next time we encounter that preferred activity, but it is 17595 // possible for the user flow to never be able to return to that 17596 // situation so here we do a sanity check to make sure we haven't 17597 // left any junk around. 17598 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17599 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17600 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17601 removed.clear(); 17602 for (PreferredActivity pa : pir.filterSet()) { 17603 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17604 removed.add(pa); 17605 } 17606 } 17607 if (removed.size() > 0) { 17608 for (int r=0; r<removed.size(); r++) { 17609 PreferredActivity pa = removed.get(r); 17610 Slog.w(TAG, "Removing dangling preferred activity: " 17611 + pa.mPref.mComponent); 17612 pir.removeFilter(pa); 17613 } 17614 mSettings.writePackageRestrictionsLPr( 17615 mSettings.mPreferredActivities.keyAt(i)); 17616 } 17617 } 17618 17619 for (int userId : UserManagerService.getInstance().getUserIds()) { 17620 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17621 grantPermissionsUserIds = ArrayUtils.appendInt( 17622 grantPermissionsUserIds, userId); 17623 } 17624 } 17625 } 17626 sUserManager.systemReady(); 17627 17628 // If we upgraded grant all default permissions before kicking off. 17629 for (int userId : grantPermissionsUserIds) { 17630 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17631 } 17632 17633 // Kick off any messages waiting for system ready 17634 if (mPostSystemReadyMessages != null) { 17635 for (Message msg : mPostSystemReadyMessages) { 17636 msg.sendToTarget(); 17637 } 17638 mPostSystemReadyMessages = null; 17639 } 17640 17641 // Watch for external volumes that come and go over time 17642 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17643 storage.registerListener(mStorageListener); 17644 17645 mInstallerService.systemReady(); 17646 mPackageDexOptimizer.systemReady(); 17647 17648 MountServiceInternal mountServiceInternal = LocalServices.getService( 17649 MountServiceInternal.class); 17650 mountServiceInternal.addExternalStoragePolicy( 17651 new MountServiceInternal.ExternalStorageMountPolicy() { 17652 @Override 17653 public int getMountMode(int uid, String packageName) { 17654 if (Process.isIsolated(uid)) { 17655 return Zygote.MOUNT_EXTERNAL_NONE; 17656 } 17657 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17658 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17659 } 17660 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17661 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17662 } 17663 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17664 return Zygote.MOUNT_EXTERNAL_READ; 17665 } 17666 return Zygote.MOUNT_EXTERNAL_WRITE; 17667 } 17668 17669 @Override 17670 public boolean hasExternalStorage(int uid, String packageName) { 17671 return true; 17672 } 17673 }); 17674 17675 // Now that we're mostly running, clean up stale users and apps 17676 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17677 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17678 } 17679 17680 @Override 17681 public boolean isSafeMode() { 17682 return mSafeMode; 17683 } 17684 17685 @Override 17686 public boolean hasSystemUidErrors() { 17687 return mHasSystemUidErrors; 17688 } 17689 17690 static String arrayToString(int[] array) { 17691 StringBuffer buf = new StringBuffer(128); 17692 buf.append('['); 17693 if (array != null) { 17694 for (int i=0; i<array.length; i++) { 17695 if (i > 0) buf.append(", "); 17696 buf.append(array[i]); 17697 } 17698 } 17699 buf.append(']'); 17700 return buf.toString(); 17701 } 17702 17703 static class DumpState { 17704 public static final int DUMP_LIBS = 1 << 0; 17705 public static final int DUMP_FEATURES = 1 << 1; 17706 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17707 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17708 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17709 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17710 public static final int DUMP_PERMISSIONS = 1 << 6; 17711 public static final int DUMP_PACKAGES = 1 << 7; 17712 public static final int DUMP_SHARED_USERS = 1 << 8; 17713 public static final int DUMP_MESSAGES = 1 << 9; 17714 public static final int DUMP_PROVIDERS = 1 << 10; 17715 public static final int DUMP_VERIFIERS = 1 << 11; 17716 public static final int DUMP_PREFERRED = 1 << 12; 17717 public static final int DUMP_PREFERRED_XML = 1 << 13; 17718 public static final int DUMP_KEYSETS = 1 << 14; 17719 public static final int DUMP_VERSION = 1 << 15; 17720 public static final int DUMP_INSTALLS = 1 << 16; 17721 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17722 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17723 public static final int DUMP_FROZEN = 1 << 19; 17724 17725 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17726 17727 private int mTypes; 17728 17729 private int mOptions; 17730 17731 private boolean mTitlePrinted; 17732 17733 private SharedUserSetting mSharedUser; 17734 17735 public boolean isDumping(int type) { 17736 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17737 return true; 17738 } 17739 17740 return (mTypes & type) != 0; 17741 } 17742 17743 public void setDump(int type) { 17744 mTypes |= type; 17745 } 17746 17747 public boolean isOptionEnabled(int option) { 17748 return (mOptions & option) != 0; 17749 } 17750 17751 public void setOptionEnabled(int option) { 17752 mOptions |= option; 17753 } 17754 17755 public boolean onTitlePrinted() { 17756 final boolean printed = mTitlePrinted; 17757 mTitlePrinted = true; 17758 return printed; 17759 } 17760 17761 public boolean getTitlePrinted() { 17762 return mTitlePrinted; 17763 } 17764 17765 public void setTitlePrinted(boolean enabled) { 17766 mTitlePrinted = enabled; 17767 } 17768 17769 public SharedUserSetting getSharedUser() { 17770 return mSharedUser; 17771 } 17772 17773 public void setSharedUser(SharedUserSetting user) { 17774 mSharedUser = user; 17775 } 17776 } 17777 17778 @Override 17779 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17780 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17781 (new PackageManagerShellCommand(this)).exec( 17782 this, in, out, err, args, resultReceiver); 17783 } 17784 17785 @Override 17786 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17787 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17788 != PackageManager.PERMISSION_GRANTED) { 17789 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17790 + Binder.getCallingPid() 17791 + ", uid=" + Binder.getCallingUid() 17792 + " without permission " 17793 + android.Manifest.permission.DUMP); 17794 return; 17795 } 17796 17797 DumpState dumpState = new DumpState(); 17798 boolean fullPreferred = false; 17799 boolean checkin = false; 17800 17801 String packageName = null; 17802 ArraySet<String> permissionNames = null; 17803 17804 int opti = 0; 17805 while (opti < args.length) { 17806 String opt = args[opti]; 17807 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17808 break; 17809 } 17810 opti++; 17811 17812 if ("-a".equals(opt)) { 17813 // Right now we only know how to print all. 17814 } else if ("-h".equals(opt)) { 17815 pw.println("Package manager dump options:"); 17816 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17817 pw.println(" --checkin: dump for a checkin"); 17818 pw.println(" -f: print details of intent filters"); 17819 pw.println(" -h: print this help"); 17820 pw.println(" cmd may be one of:"); 17821 pw.println(" l[ibraries]: list known shared libraries"); 17822 pw.println(" f[eatures]: list device features"); 17823 pw.println(" k[eysets]: print known keysets"); 17824 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17825 pw.println(" perm[issions]: dump permissions"); 17826 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17827 pw.println(" pref[erred]: print preferred package settings"); 17828 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17829 pw.println(" prov[iders]: dump content providers"); 17830 pw.println(" p[ackages]: dump installed packages"); 17831 pw.println(" s[hared-users]: dump shared user IDs"); 17832 pw.println(" m[essages]: print collected runtime messages"); 17833 pw.println(" v[erifiers]: print package verifier info"); 17834 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17835 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17836 pw.println(" version: print database version info"); 17837 pw.println(" write: write current settings now"); 17838 pw.println(" installs: details about install sessions"); 17839 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17840 pw.println(" <package.name>: info about given package"); 17841 return; 17842 } else if ("--checkin".equals(opt)) { 17843 checkin = true; 17844 } else if ("-f".equals(opt)) { 17845 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17846 } else { 17847 pw.println("Unknown argument: " + opt + "; use -h for help"); 17848 } 17849 } 17850 17851 // Is the caller requesting to dump a particular piece of data? 17852 if (opti < args.length) { 17853 String cmd = args[opti]; 17854 opti++; 17855 // Is this a package name? 17856 if ("android".equals(cmd) || cmd.contains(".")) { 17857 packageName = cmd; 17858 // When dumping a single package, we always dump all of its 17859 // filter information since the amount of data will be reasonable. 17860 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17861 } else if ("check-permission".equals(cmd)) { 17862 if (opti >= args.length) { 17863 pw.println("Error: check-permission missing permission argument"); 17864 return; 17865 } 17866 String perm = args[opti]; 17867 opti++; 17868 if (opti >= args.length) { 17869 pw.println("Error: check-permission missing package argument"); 17870 return; 17871 } 17872 String pkg = args[opti]; 17873 opti++; 17874 int user = UserHandle.getUserId(Binder.getCallingUid()); 17875 if (opti < args.length) { 17876 try { 17877 user = Integer.parseInt(args[opti]); 17878 } catch (NumberFormatException e) { 17879 pw.println("Error: check-permission user argument is not a number: " 17880 + args[opti]); 17881 return; 17882 } 17883 } 17884 pw.println(checkPermission(perm, pkg, user)); 17885 return; 17886 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17887 dumpState.setDump(DumpState.DUMP_LIBS); 17888 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17889 dumpState.setDump(DumpState.DUMP_FEATURES); 17890 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17891 if (opti >= args.length) { 17892 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17893 | DumpState.DUMP_SERVICE_RESOLVERS 17894 | DumpState.DUMP_RECEIVER_RESOLVERS 17895 | DumpState.DUMP_CONTENT_RESOLVERS); 17896 } else { 17897 while (opti < args.length) { 17898 String name = args[opti]; 17899 if ("a".equals(name) || "activity".equals(name)) { 17900 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17901 } else if ("s".equals(name) || "service".equals(name)) { 17902 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17903 } else if ("r".equals(name) || "receiver".equals(name)) { 17904 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17905 } else if ("c".equals(name) || "content".equals(name)) { 17906 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17907 } else { 17908 pw.println("Error: unknown resolver table type: " + name); 17909 return; 17910 } 17911 opti++; 17912 } 17913 } 17914 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17915 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17916 } else if ("permission".equals(cmd)) { 17917 if (opti >= args.length) { 17918 pw.println("Error: permission requires permission name"); 17919 return; 17920 } 17921 permissionNames = new ArraySet<>(); 17922 while (opti < args.length) { 17923 permissionNames.add(args[opti]); 17924 opti++; 17925 } 17926 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17927 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17928 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17929 dumpState.setDump(DumpState.DUMP_PREFERRED); 17930 } else if ("preferred-xml".equals(cmd)) { 17931 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17932 if (opti < args.length && "--full".equals(args[opti])) { 17933 fullPreferred = true; 17934 opti++; 17935 } 17936 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17937 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17938 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17939 dumpState.setDump(DumpState.DUMP_PACKAGES); 17940 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17941 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17942 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17943 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17944 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17945 dumpState.setDump(DumpState.DUMP_MESSAGES); 17946 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17947 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17948 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17949 || "intent-filter-verifiers".equals(cmd)) { 17950 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17951 } else if ("version".equals(cmd)) { 17952 dumpState.setDump(DumpState.DUMP_VERSION); 17953 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17954 dumpState.setDump(DumpState.DUMP_KEYSETS); 17955 } else if ("installs".equals(cmd)) { 17956 dumpState.setDump(DumpState.DUMP_INSTALLS); 17957 } else if ("frozen".equals(cmd)) { 17958 dumpState.setDump(DumpState.DUMP_FROZEN); 17959 } else if ("write".equals(cmd)) { 17960 synchronized (mPackages) { 17961 mSettings.writeLPr(); 17962 pw.println("Settings written."); 17963 return; 17964 } 17965 } 17966 } 17967 17968 if (checkin) { 17969 pw.println("vers,1"); 17970 } 17971 17972 // reader 17973 synchronized (mPackages) { 17974 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17975 if (!checkin) { 17976 if (dumpState.onTitlePrinted()) 17977 pw.println(); 17978 pw.println("Database versions:"); 17979 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17980 } 17981 } 17982 17983 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17984 if (!checkin) { 17985 if (dumpState.onTitlePrinted()) 17986 pw.println(); 17987 pw.println("Verifiers:"); 17988 pw.print(" Required: "); 17989 pw.print(mRequiredVerifierPackage); 17990 pw.print(" (uid="); 17991 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17992 UserHandle.USER_SYSTEM)); 17993 pw.println(")"); 17994 } else if (mRequiredVerifierPackage != null) { 17995 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17996 pw.print(","); 17997 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17998 UserHandle.USER_SYSTEM)); 17999 } 18000 } 18001 18002 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18003 packageName == null) { 18004 if (mIntentFilterVerifierComponent != null) { 18005 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18006 if (!checkin) { 18007 if (dumpState.onTitlePrinted()) 18008 pw.println(); 18009 pw.println("Intent Filter Verifier:"); 18010 pw.print(" Using: "); 18011 pw.print(verifierPackageName); 18012 pw.print(" (uid="); 18013 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18014 UserHandle.USER_SYSTEM)); 18015 pw.println(")"); 18016 } else if (verifierPackageName != null) { 18017 pw.print("ifv,"); pw.print(verifierPackageName); 18018 pw.print(","); 18019 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18020 UserHandle.USER_SYSTEM)); 18021 } 18022 } else { 18023 pw.println(); 18024 pw.println("No Intent Filter Verifier available!"); 18025 } 18026 } 18027 18028 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18029 boolean printedHeader = false; 18030 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18031 while (it.hasNext()) { 18032 String name = it.next(); 18033 SharedLibraryEntry ent = mSharedLibraries.get(name); 18034 if (!checkin) { 18035 if (!printedHeader) { 18036 if (dumpState.onTitlePrinted()) 18037 pw.println(); 18038 pw.println("Libraries:"); 18039 printedHeader = true; 18040 } 18041 pw.print(" "); 18042 } else { 18043 pw.print("lib,"); 18044 } 18045 pw.print(name); 18046 if (!checkin) { 18047 pw.print(" -> "); 18048 } 18049 if (ent.path != null) { 18050 if (!checkin) { 18051 pw.print("(jar) "); 18052 pw.print(ent.path); 18053 } else { 18054 pw.print(",jar,"); 18055 pw.print(ent.path); 18056 } 18057 } else { 18058 if (!checkin) { 18059 pw.print("(apk) "); 18060 pw.print(ent.apk); 18061 } else { 18062 pw.print(",apk,"); 18063 pw.print(ent.apk); 18064 } 18065 } 18066 pw.println(); 18067 } 18068 } 18069 18070 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18071 if (dumpState.onTitlePrinted()) 18072 pw.println(); 18073 if (!checkin) { 18074 pw.println("Features:"); 18075 } 18076 18077 for (FeatureInfo feat : mAvailableFeatures.values()) { 18078 if (checkin) { 18079 pw.print("feat,"); 18080 pw.print(feat.name); 18081 pw.print(","); 18082 pw.println(feat.version); 18083 } else { 18084 pw.print(" "); 18085 pw.print(feat.name); 18086 if (feat.version > 0) { 18087 pw.print(" version="); 18088 pw.print(feat.version); 18089 } 18090 pw.println(); 18091 } 18092 } 18093 } 18094 18095 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18096 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18097 : "Activity Resolver Table:", " ", packageName, 18098 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18099 dumpState.setTitlePrinted(true); 18100 } 18101 } 18102 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18103 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18104 : "Receiver Resolver Table:", " ", packageName, 18105 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18106 dumpState.setTitlePrinted(true); 18107 } 18108 } 18109 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18110 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18111 : "Service Resolver Table:", " ", packageName, 18112 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18113 dumpState.setTitlePrinted(true); 18114 } 18115 } 18116 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18117 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18118 : "Provider Resolver Table:", " ", packageName, 18119 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18120 dumpState.setTitlePrinted(true); 18121 } 18122 } 18123 18124 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18125 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18126 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18127 int user = mSettings.mPreferredActivities.keyAt(i); 18128 if (pir.dump(pw, 18129 dumpState.getTitlePrinted() 18130 ? "\nPreferred Activities User " + user + ":" 18131 : "Preferred Activities User " + user + ":", " ", 18132 packageName, true, false)) { 18133 dumpState.setTitlePrinted(true); 18134 } 18135 } 18136 } 18137 18138 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18139 pw.flush(); 18140 FileOutputStream fout = new FileOutputStream(fd); 18141 BufferedOutputStream str = new BufferedOutputStream(fout); 18142 XmlSerializer serializer = new FastXmlSerializer(); 18143 try { 18144 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18145 serializer.startDocument(null, true); 18146 serializer.setFeature( 18147 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18148 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18149 serializer.endDocument(); 18150 serializer.flush(); 18151 } catch (IllegalArgumentException e) { 18152 pw.println("Failed writing: " + e); 18153 } catch (IllegalStateException e) { 18154 pw.println("Failed writing: " + e); 18155 } catch (IOException e) { 18156 pw.println("Failed writing: " + e); 18157 } 18158 } 18159 18160 if (!checkin 18161 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18162 && packageName == null) { 18163 pw.println(); 18164 int count = mSettings.mPackages.size(); 18165 if (count == 0) { 18166 pw.println("No applications!"); 18167 pw.println(); 18168 } else { 18169 final String prefix = " "; 18170 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18171 if (allPackageSettings.size() == 0) { 18172 pw.println("No domain preferred apps!"); 18173 pw.println(); 18174 } else { 18175 pw.println("App verification status:"); 18176 pw.println(); 18177 count = 0; 18178 for (PackageSetting ps : allPackageSettings) { 18179 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18180 if (ivi == null || ivi.getPackageName() == null) continue; 18181 pw.println(prefix + "Package: " + ivi.getPackageName()); 18182 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18183 pw.println(prefix + "Status: " + ivi.getStatusString()); 18184 pw.println(); 18185 count++; 18186 } 18187 if (count == 0) { 18188 pw.println(prefix + "No app verification established."); 18189 pw.println(); 18190 } 18191 for (int userId : sUserManager.getUserIds()) { 18192 pw.println("App linkages for user " + userId + ":"); 18193 pw.println(); 18194 count = 0; 18195 for (PackageSetting ps : allPackageSettings) { 18196 final long status = ps.getDomainVerificationStatusForUser(userId); 18197 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18198 continue; 18199 } 18200 pw.println(prefix + "Package: " + ps.name); 18201 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18202 String statusStr = IntentFilterVerificationInfo. 18203 getStatusStringFromValue(status); 18204 pw.println(prefix + "Status: " + statusStr); 18205 pw.println(); 18206 count++; 18207 } 18208 if (count == 0) { 18209 pw.println(prefix + "No configured app linkages."); 18210 pw.println(); 18211 } 18212 } 18213 } 18214 } 18215 } 18216 18217 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18218 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18219 if (packageName == null && permissionNames == null) { 18220 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18221 if (iperm == 0) { 18222 if (dumpState.onTitlePrinted()) 18223 pw.println(); 18224 pw.println("AppOp Permissions:"); 18225 } 18226 pw.print(" AppOp Permission "); 18227 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18228 pw.println(":"); 18229 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18230 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18231 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18232 } 18233 } 18234 } 18235 } 18236 18237 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18238 boolean printedSomething = false; 18239 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18240 if (packageName != null && !packageName.equals(p.info.packageName)) { 18241 continue; 18242 } 18243 if (!printedSomething) { 18244 if (dumpState.onTitlePrinted()) 18245 pw.println(); 18246 pw.println("Registered ContentProviders:"); 18247 printedSomething = true; 18248 } 18249 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18250 pw.print(" "); pw.println(p.toString()); 18251 } 18252 printedSomething = false; 18253 for (Map.Entry<String, PackageParser.Provider> entry : 18254 mProvidersByAuthority.entrySet()) { 18255 PackageParser.Provider p = entry.getValue(); 18256 if (packageName != null && !packageName.equals(p.info.packageName)) { 18257 continue; 18258 } 18259 if (!printedSomething) { 18260 if (dumpState.onTitlePrinted()) 18261 pw.println(); 18262 pw.println("ContentProvider Authorities:"); 18263 printedSomething = true; 18264 } 18265 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18266 pw.print(" "); pw.println(p.toString()); 18267 if (p.info != null && p.info.applicationInfo != null) { 18268 final String appInfo = p.info.applicationInfo.toString(); 18269 pw.print(" applicationInfo="); pw.println(appInfo); 18270 } 18271 } 18272 } 18273 18274 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18275 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18276 } 18277 18278 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18279 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18280 } 18281 18282 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18283 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18284 } 18285 18286 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18287 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18288 } 18289 18290 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18291 // XXX should handle packageName != null by dumping only install data that 18292 // the given package is involved with. 18293 if (dumpState.onTitlePrinted()) pw.println(); 18294 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18295 } 18296 18297 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18298 // XXX should handle packageName != null by dumping only install data that 18299 // the given package is involved with. 18300 if (dumpState.onTitlePrinted()) pw.println(); 18301 18302 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18303 ipw.println(); 18304 ipw.println("Frozen packages:"); 18305 ipw.increaseIndent(); 18306 if (mFrozenPackages.size() == 0) { 18307 ipw.println("(none)"); 18308 } else { 18309 for (int i = 0; i < mFrozenPackages.size(); i++) { 18310 ipw.println(mFrozenPackages.valueAt(i)); 18311 } 18312 } 18313 ipw.decreaseIndent(); 18314 } 18315 18316 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18317 if (dumpState.onTitlePrinted()) pw.println(); 18318 mSettings.dumpReadMessagesLPr(pw, dumpState); 18319 18320 pw.println(); 18321 pw.println("Package warning messages:"); 18322 BufferedReader in = null; 18323 String line = null; 18324 try { 18325 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18326 while ((line = in.readLine()) != null) { 18327 if (line.contains("ignored: updated version")) continue; 18328 pw.println(line); 18329 } 18330 } catch (IOException ignored) { 18331 } finally { 18332 IoUtils.closeQuietly(in); 18333 } 18334 } 18335 18336 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18337 BufferedReader in = null; 18338 String line = null; 18339 try { 18340 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18341 while ((line = in.readLine()) != null) { 18342 if (line.contains("ignored: updated version")) continue; 18343 pw.print("msg,"); 18344 pw.println(line); 18345 } 18346 } catch (IOException ignored) { 18347 } finally { 18348 IoUtils.closeQuietly(in); 18349 } 18350 } 18351 } 18352 } 18353 18354 private String dumpDomainString(String packageName) { 18355 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18356 .getList(); 18357 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18358 18359 ArraySet<String> result = new ArraySet<>(); 18360 if (iviList.size() > 0) { 18361 for (IntentFilterVerificationInfo ivi : iviList) { 18362 for (String host : ivi.getDomains()) { 18363 result.add(host); 18364 } 18365 } 18366 } 18367 if (filters != null && filters.size() > 0) { 18368 for (IntentFilter filter : filters) { 18369 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18370 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18371 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18372 result.addAll(filter.getHostsList()); 18373 } 18374 } 18375 } 18376 18377 StringBuilder sb = new StringBuilder(result.size() * 16); 18378 for (String domain : result) { 18379 if (sb.length() > 0) sb.append(" "); 18380 sb.append(domain); 18381 } 18382 return sb.toString(); 18383 } 18384 18385 // ------- apps on sdcard specific code ------- 18386 static final boolean DEBUG_SD_INSTALL = false; 18387 18388 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18389 18390 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18391 18392 private boolean mMediaMounted = false; 18393 18394 static String getEncryptKey() { 18395 try { 18396 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18397 SD_ENCRYPTION_KEYSTORE_NAME); 18398 if (sdEncKey == null) { 18399 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18400 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18401 if (sdEncKey == null) { 18402 Slog.e(TAG, "Failed to create encryption keys"); 18403 return null; 18404 } 18405 } 18406 return sdEncKey; 18407 } catch (NoSuchAlgorithmException nsae) { 18408 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18409 return null; 18410 } catch (IOException ioe) { 18411 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18412 return null; 18413 } 18414 } 18415 18416 /* 18417 * Update media status on PackageManager. 18418 */ 18419 @Override 18420 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18421 int callingUid = Binder.getCallingUid(); 18422 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18423 throw new SecurityException("Media status can only be updated by the system"); 18424 } 18425 // reader; this apparently protects mMediaMounted, but should probably 18426 // be a different lock in that case. 18427 synchronized (mPackages) { 18428 Log.i(TAG, "Updating external media status from " 18429 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18430 + (mediaStatus ? "mounted" : "unmounted")); 18431 if (DEBUG_SD_INSTALL) 18432 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18433 + ", mMediaMounted=" + mMediaMounted); 18434 if (mediaStatus == mMediaMounted) { 18435 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18436 : 0, -1); 18437 mHandler.sendMessage(msg); 18438 return; 18439 } 18440 mMediaMounted = mediaStatus; 18441 } 18442 // Queue up an async operation since the package installation may take a 18443 // little while. 18444 mHandler.post(new Runnable() { 18445 public void run() { 18446 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18447 } 18448 }); 18449 } 18450 18451 /** 18452 * Called by MountService when the initial ASECs to scan are available. 18453 * Should block until all the ASEC containers are finished being scanned. 18454 */ 18455 public void scanAvailableAsecs() { 18456 updateExternalMediaStatusInner(true, false, false); 18457 } 18458 18459 /* 18460 * Collect information of applications on external media, map them against 18461 * existing containers and update information based on current mount status. 18462 * Please note that we always have to report status if reportStatus has been 18463 * set to true especially when unloading packages. 18464 */ 18465 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18466 boolean externalStorage) { 18467 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18468 int[] uidArr = EmptyArray.INT; 18469 18470 final String[] list = PackageHelper.getSecureContainerList(); 18471 if (ArrayUtils.isEmpty(list)) { 18472 Log.i(TAG, "No secure containers found"); 18473 } else { 18474 // Process list of secure containers and categorize them 18475 // as active or stale based on their package internal state. 18476 18477 // reader 18478 synchronized (mPackages) { 18479 for (String cid : list) { 18480 // Leave stages untouched for now; installer service owns them 18481 if (PackageInstallerService.isStageName(cid)) continue; 18482 18483 if (DEBUG_SD_INSTALL) 18484 Log.i(TAG, "Processing container " + cid); 18485 String pkgName = getAsecPackageName(cid); 18486 if (pkgName == null) { 18487 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18488 continue; 18489 } 18490 if (DEBUG_SD_INSTALL) 18491 Log.i(TAG, "Looking for pkg : " + pkgName); 18492 18493 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18494 if (ps == null) { 18495 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18496 continue; 18497 } 18498 18499 /* 18500 * Skip packages that are not external if we're unmounting 18501 * external storage. 18502 */ 18503 if (externalStorage && !isMounted && !isExternal(ps)) { 18504 continue; 18505 } 18506 18507 final AsecInstallArgs args = new AsecInstallArgs(cid, 18508 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18509 // The package status is changed only if the code path 18510 // matches between settings and the container id. 18511 if (ps.codePathString != null 18512 && ps.codePathString.startsWith(args.getCodePath())) { 18513 if (DEBUG_SD_INSTALL) { 18514 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18515 + " at code path: " + ps.codePathString); 18516 } 18517 18518 // We do have a valid package installed on sdcard 18519 processCids.put(args, ps.codePathString); 18520 final int uid = ps.appId; 18521 if (uid != -1) { 18522 uidArr = ArrayUtils.appendInt(uidArr, uid); 18523 } 18524 } else { 18525 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18526 + ps.codePathString); 18527 } 18528 } 18529 } 18530 18531 Arrays.sort(uidArr); 18532 } 18533 18534 // Process packages with valid entries. 18535 if (isMounted) { 18536 if (DEBUG_SD_INSTALL) 18537 Log.i(TAG, "Loading packages"); 18538 loadMediaPackages(processCids, uidArr, externalStorage); 18539 startCleaningPackages(); 18540 mInstallerService.onSecureContainersAvailable(); 18541 } else { 18542 if (DEBUG_SD_INSTALL) 18543 Log.i(TAG, "Unloading packages"); 18544 unloadMediaPackages(processCids, uidArr, reportStatus); 18545 } 18546 } 18547 18548 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18549 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18550 final int size = infos.size(); 18551 final String[] packageNames = new String[size]; 18552 final int[] packageUids = new int[size]; 18553 for (int i = 0; i < size; i++) { 18554 final ApplicationInfo info = infos.get(i); 18555 packageNames[i] = info.packageName; 18556 packageUids[i] = info.uid; 18557 } 18558 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18559 finishedReceiver); 18560 } 18561 18562 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18563 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18564 sendResourcesChangedBroadcast(mediaStatus, replacing, 18565 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18566 } 18567 18568 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18569 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18570 int size = pkgList.length; 18571 if (size > 0) { 18572 // Send broadcasts here 18573 Bundle extras = new Bundle(); 18574 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18575 if (uidArr != null) { 18576 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18577 } 18578 if (replacing) { 18579 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18580 } 18581 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18582 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18583 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18584 } 18585 } 18586 18587 /* 18588 * Look at potentially valid container ids from processCids If package 18589 * information doesn't match the one on record or package scanning fails, 18590 * the cid is added to list of removeCids. We currently don't delete stale 18591 * containers. 18592 */ 18593 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18594 boolean externalStorage) { 18595 ArrayList<String> pkgList = new ArrayList<String>(); 18596 Set<AsecInstallArgs> keys = processCids.keySet(); 18597 18598 for (AsecInstallArgs args : keys) { 18599 String codePath = processCids.get(args); 18600 if (DEBUG_SD_INSTALL) 18601 Log.i(TAG, "Loading container : " + args.cid); 18602 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18603 try { 18604 // Make sure there are no container errors first. 18605 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18606 Slog.e(TAG, "Failed to mount cid : " + args.cid 18607 + " when installing from sdcard"); 18608 continue; 18609 } 18610 // Check code path here. 18611 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18612 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18613 + " does not match one in settings " + codePath); 18614 continue; 18615 } 18616 // Parse package 18617 int parseFlags = mDefParseFlags; 18618 if (args.isExternalAsec()) { 18619 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18620 } 18621 if (args.isFwdLocked()) { 18622 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18623 } 18624 18625 synchronized (mInstallLock) { 18626 PackageParser.Package pkg = null; 18627 try { 18628 // Sadly we don't know the package name yet to freeze it 18629 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18630 SCAN_IGNORE_FROZEN, 0, null); 18631 } catch (PackageManagerException e) { 18632 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18633 } 18634 // Scan the package 18635 if (pkg != null) { 18636 /* 18637 * TODO why is the lock being held? doPostInstall is 18638 * called in other places without the lock. This needs 18639 * to be straightened out. 18640 */ 18641 // writer 18642 synchronized (mPackages) { 18643 retCode = PackageManager.INSTALL_SUCCEEDED; 18644 pkgList.add(pkg.packageName); 18645 // Post process args 18646 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18647 pkg.applicationInfo.uid); 18648 } 18649 } else { 18650 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18651 } 18652 } 18653 18654 } finally { 18655 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18656 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18657 } 18658 } 18659 } 18660 // writer 18661 synchronized (mPackages) { 18662 // If the platform SDK has changed since the last time we booted, 18663 // we need to re-grant app permission to catch any new ones that 18664 // appear. This is really a hack, and means that apps can in some 18665 // cases get permissions that the user didn't initially explicitly 18666 // allow... it would be nice to have some better way to handle 18667 // this situation. 18668 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18669 : mSettings.getInternalVersion(); 18670 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18671 : StorageManager.UUID_PRIVATE_INTERNAL; 18672 18673 int updateFlags = UPDATE_PERMISSIONS_ALL; 18674 if (ver.sdkVersion != mSdkVersion) { 18675 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18676 + mSdkVersion + "; regranting permissions for external"); 18677 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18678 } 18679 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18680 18681 // Yay, everything is now upgraded 18682 ver.forceCurrent(); 18683 18684 // can downgrade to reader 18685 // Persist settings 18686 mSettings.writeLPr(); 18687 } 18688 // Send a broadcast to let everyone know we are done processing 18689 if (pkgList.size() > 0) { 18690 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18691 } 18692 } 18693 18694 /* 18695 * Utility method to unload a list of specified containers 18696 */ 18697 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18698 // Just unmount all valid containers. 18699 for (AsecInstallArgs arg : cidArgs) { 18700 synchronized (mInstallLock) { 18701 arg.doPostDeleteLI(false); 18702 } 18703 } 18704 } 18705 18706 /* 18707 * Unload packages mounted on external media. This involves deleting package 18708 * data from internal structures, sending broadcasts about disabled packages, 18709 * gc'ing to free up references, unmounting all secure containers 18710 * corresponding to packages on external media, and posting a 18711 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18712 * that we always have to post this message if status has been requested no 18713 * matter what. 18714 */ 18715 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18716 final boolean reportStatus) { 18717 if (DEBUG_SD_INSTALL) 18718 Log.i(TAG, "unloading media packages"); 18719 ArrayList<String> pkgList = new ArrayList<String>(); 18720 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18721 final Set<AsecInstallArgs> keys = processCids.keySet(); 18722 for (AsecInstallArgs args : keys) { 18723 String pkgName = args.getPackageName(); 18724 if (DEBUG_SD_INSTALL) 18725 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18726 // Delete package internally 18727 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18728 synchronized (mInstallLock) { 18729 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18730 final boolean res; 18731 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18732 "unloadMediaPackages")) { 18733 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18734 null); 18735 } 18736 if (res) { 18737 pkgList.add(pkgName); 18738 } else { 18739 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18740 failedList.add(args); 18741 } 18742 } 18743 } 18744 18745 // reader 18746 synchronized (mPackages) { 18747 // We didn't update the settings after removing each package; 18748 // write them now for all packages. 18749 mSettings.writeLPr(); 18750 } 18751 18752 // We have to absolutely send UPDATED_MEDIA_STATUS only 18753 // after confirming that all the receivers processed the ordered 18754 // broadcast when packages get disabled, force a gc to clean things up. 18755 // and unload all the containers. 18756 if (pkgList.size() > 0) { 18757 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18758 new IIntentReceiver.Stub() { 18759 public void performReceive(Intent intent, int resultCode, String data, 18760 Bundle extras, boolean ordered, boolean sticky, 18761 int sendingUser) throws RemoteException { 18762 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18763 reportStatus ? 1 : 0, 1, keys); 18764 mHandler.sendMessage(msg); 18765 } 18766 }); 18767 } else { 18768 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18769 keys); 18770 mHandler.sendMessage(msg); 18771 } 18772 } 18773 18774 private void loadPrivatePackages(final VolumeInfo vol) { 18775 mHandler.post(new Runnable() { 18776 @Override 18777 public void run() { 18778 loadPrivatePackagesInner(vol); 18779 } 18780 }); 18781 } 18782 18783 private void loadPrivatePackagesInner(VolumeInfo vol) { 18784 final String volumeUuid = vol.fsUuid; 18785 if (TextUtils.isEmpty(volumeUuid)) { 18786 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18787 return; 18788 } 18789 18790 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18791 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18792 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18793 18794 final VersionInfo ver; 18795 final List<PackageSetting> packages; 18796 synchronized (mPackages) { 18797 ver = mSettings.findOrCreateVersion(volumeUuid); 18798 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18799 } 18800 18801 for (PackageSetting ps : packages) { 18802 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18803 synchronized (mInstallLock) { 18804 final PackageParser.Package pkg; 18805 try { 18806 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18807 loaded.add(pkg.applicationInfo); 18808 18809 } catch (PackageManagerException e) { 18810 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18811 } 18812 18813 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18814 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18815 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18816 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18817 } 18818 } 18819 } 18820 18821 // Reconcile app data for all started/unlocked users 18822 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18823 final UserManager um = mContext.getSystemService(UserManager.class); 18824 for (UserInfo user : um.getUsers()) { 18825 final int flags; 18826 if (um.isUserUnlockingOrUnlocked(user.id)) { 18827 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18828 } else if (um.isUserRunning(user.id)) { 18829 flags = StorageManager.FLAG_STORAGE_DE; 18830 } else { 18831 continue; 18832 } 18833 18834 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18835 synchronized (mInstallLock) { 18836 reconcileAppsDataLI(volumeUuid, user.id, flags); 18837 } 18838 } 18839 18840 synchronized (mPackages) { 18841 int updateFlags = UPDATE_PERMISSIONS_ALL; 18842 if (ver.sdkVersion != mSdkVersion) { 18843 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18844 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18845 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18846 } 18847 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18848 18849 // Yay, everything is now upgraded 18850 ver.forceCurrent(); 18851 18852 mSettings.writeLPr(); 18853 } 18854 18855 for (PackageFreezer freezer : freezers) { 18856 freezer.close(); 18857 } 18858 18859 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18860 sendResourcesChangedBroadcast(true, false, loaded, null); 18861 } 18862 18863 private void unloadPrivatePackages(final VolumeInfo vol) { 18864 mHandler.post(new Runnable() { 18865 @Override 18866 public void run() { 18867 unloadPrivatePackagesInner(vol); 18868 } 18869 }); 18870 } 18871 18872 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18873 final String volumeUuid = vol.fsUuid; 18874 if (TextUtils.isEmpty(volumeUuid)) { 18875 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18876 return; 18877 } 18878 18879 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18880 synchronized (mInstallLock) { 18881 synchronized (mPackages) { 18882 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18883 for (PackageSetting ps : packages) { 18884 if (ps.pkg == null) continue; 18885 18886 final ApplicationInfo info = ps.pkg.applicationInfo; 18887 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18888 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18889 18890 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18891 "unloadPrivatePackagesInner")) { 18892 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18893 false, null)) { 18894 unloaded.add(info); 18895 } else { 18896 Slog.w(TAG, "Failed to unload " + ps.codePath); 18897 } 18898 } 18899 } 18900 18901 mSettings.writeLPr(); 18902 } 18903 } 18904 18905 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18906 sendResourcesChangedBroadcast(false, false, unloaded, null); 18907 } 18908 18909 /** 18910 * Prepare storage areas for given user on all mounted devices. 18911 */ 18912 void prepareUserData(int userId, int userSerial, int flags) { 18913 synchronized (mInstallLock) { 18914 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18915 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18916 final String volumeUuid = vol.getFsUuid(); 18917 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18918 } 18919 } 18920 } 18921 18922 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18923 boolean allowRecover) { 18924 // Prepare storage and verify that serial numbers are consistent; if 18925 // there's a mismatch we need to destroy to avoid leaking data 18926 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18927 try { 18928 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18929 18930 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18931 UserManagerService.enforceSerialNumber( 18932 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18933 } 18934 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18935 UserManagerService.enforceSerialNumber( 18936 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18937 } 18938 18939 synchronized (mInstallLock) { 18940 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18941 } 18942 } catch (Exception e) { 18943 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18944 + " because we failed to prepare: " + e); 18945 destroyUserDataLI(volumeUuid, userId, 18946 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18947 18948 if (allowRecover) { 18949 // Try one last time; if we fail again we're really in trouble 18950 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18951 } 18952 } 18953 } 18954 18955 /** 18956 * Destroy storage areas for given user on all mounted devices. 18957 */ 18958 void destroyUserData(int userId, int flags) { 18959 synchronized (mInstallLock) { 18960 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18961 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18962 final String volumeUuid = vol.getFsUuid(); 18963 destroyUserDataLI(volumeUuid, userId, flags); 18964 } 18965 } 18966 } 18967 18968 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18969 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18970 try { 18971 // Clean up app data, profile data, and media data 18972 mInstaller.destroyUserData(volumeUuid, userId, flags); 18973 18974 // Clean up system data 18975 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18976 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18977 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18978 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18979 } 18980 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18981 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18982 } 18983 } 18984 18985 // Data with special labels is now gone, so finish the job 18986 storage.destroyUserStorage(volumeUuid, userId, flags); 18987 18988 } catch (Exception e) { 18989 logCriticalInfo(Log.WARN, 18990 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18991 } 18992 } 18993 18994 /** 18995 * Examine all users present on given mounted volume, and destroy data 18996 * belonging to users that are no longer valid, or whose user ID has been 18997 * recycled. 18998 */ 18999 private void reconcileUsers(String volumeUuid) { 19000 final List<File> files = new ArrayList<>(); 19001 Collections.addAll(files, FileUtils 19002 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19003 Collections.addAll(files, FileUtils 19004 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19005 for (File file : files) { 19006 if (!file.isDirectory()) continue; 19007 19008 final int userId; 19009 final UserInfo info; 19010 try { 19011 userId = Integer.parseInt(file.getName()); 19012 info = sUserManager.getUserInfo(userId); 19013 } catch (NumberFormatException e) { 19014 Slog.w(TAG, "Invalid user directory " + file); 19015 continue; 19016 } 19017 19018 boolean destroyUser = false; 19019 if (info == null) { 19020 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19021 + " because no matching user was found"); 19022 destroyUser = true; 19023 } else if (!mOnlyCore) { 19024 try { 19025 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19026 } catch (IOException e) { 19027 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19028 + " because we failed to enforce serial number: " + e); 19029 destroyUser = true; 19030 } 19031 } 19032 19033 if (destroyUser) { 19034 synchronized (mInstallLock) { 19035 destroyUserDataLI(volumeUuid, userId, 19036 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19037 } 19038 } 19039 } 19040 } 19041 19042 private void assertPackageKnown(String volumeUuid, String packageName) 19043 throws PackageManagerException { 19044 synchronized (mPackages) { 19045 final PackageSetting ps = mSettings.mPackages.get(packageName); 19046 if (ps == null) { 19047 throw new PackageManagerException("Package " + packageName + " is unknown"); 19048 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19049 throw new PackageManagerException( 19050 "Package " + packageName + " found on unknown volume " + volumeUuid 19051 + "; expected volume " + ps.volumeUuid); 19052 } 19053 } 19054 } 19055 19056 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19057 throws PackageManagerException { 19058 synchronized (mPackages) { 19059 final PackageSetting ps = mSettings.mPackages.get(packageName); 19060 if (ps == null) { 19061 throw new PackageManagerException("Package " + packageName + " is unknown"); 19062 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19063 throw new PackageManagerException( 19064 "Package " + packageName + " found on unknown volume " + volumeUuid 19065 + "; expected volume " + ps.volumeUuid); 19066 } else if (!ps.getInstalled(userId)) { 19067 throw new PackageManagerException( 19068 "Package " + packageName + " not installed for user " + userId); 19069 } 19070 } 19071 } 19072 19073 /** 19074 * Examine all apps present on given mounted volume, and destroy apps that 19075 * aren't expected, either due to uninstallation or reinstallation on 19076 * another volume. 19077 */ 19078 private void reconcileApps(String volumeUuid) { 19079 final File[] files = FileUtils 19080 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19081 for (File file : files) { 19082 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19083 && !PackageInstallerService.isStageName(file.getName()); 19084 if (!isPackage) { 19085 // Ignore entries which are not packages 19086 continue; 19087 } 19088 19089 try { 19090 final PackageLite pkg = PackageParser.parsePackageLite(file, 19091 PackageParser.PARSE_MUST_BE_APK); 19092 assertPackageKnown(volumeUuid, pkg.packageName); 19093 19094 } catch (PackageParserException | PackageManagerException e) { 19095 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19096 synchronized (mInstallLock) { 19097 removeCodePathLI(file); 19098 } 19099 } 19100 } 19101 } 19102 19103 /** 19104 * Reconcile all app data for the given user. 19105 * <p> 19106 * Verifies that directories exist and that ownership and labeling is 19107 * correct for all installed apps on all mounted volumes. 19108 */ 19109 void reconcileAppsData(int userId, int flags) { 19110 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19111 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19112 final String volumeUuid = vol.getFsUuid(); 19113 synchronized (mInstallLock) { 19114 reconcileAppsDataLI(volumeUuid, userId, flags); 19115 } 19116 } 19117 } 19118 19119 /** 19120 * Reconcile all app data on given mounted volume. 19121 * <p> 19122 * Destroys app data that isn't expected, either due to uninstallation or 19123 * reinstallation on another volume. 19124 * <p> 19125 * Verifies that directories exist and that ownership and labeling is 19126 * correct for all installed apps. 19127 */ 19128 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19129 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19130 + Integer.toHexString(flags)); 19131 19132 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19133 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19134 19135 boolean restoreconNeeded = false; 19136 19137 // First look for stale data that doesn't belong, and check if things 19138 // have changed since we did our last restorecon 19139 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19140 if (StorageManager.isFileEncryptedNativeOrEmulated() 19141 && !StorageManager.isUserKeyUnlocked(userId)) { 19142 throw new RuntimeException( 19143 "Yikes, someone asked us to reconcile CE storage while " + userId 19144 + " was still locked; this would have caused massive data loss!"); 19145 } 19146 19147 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19148 19149 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19150 for (File file : files) { 19151 final String packageName = file.getName(); 19152 try { 19153 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19154 } catch (PackageManagerException e) { 19155 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19156 try { 19157 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19158 StorageManager.FLAG_STORAGE_CE, 0); 19159 } catch (InstallerException e2) { 19160 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19161 } 19162 } 19163 } 19164 } 19165 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19166 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19167 19168 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19169 for (File file : files) { 19170 final String packageName = file.getName(); 19171 try { 19172 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19173 } catch (PackageManagerException e) { 19174 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19175 try { 19176 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19177 StorageManager.FLAG_STORAGE_DE, 0); 19178 } catch (InstallerException e2) { 19179 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19180 } 19181 } 19182 } 19183 } 19184 19185 // Ensure that data directories are ready to roll for all packages 19186 // installed for this volume and user 19187 final List<PackageSetting> packages; 19188 synchronized (mPackages) { 19189 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19190 } 19191 int preparedCount = 0; 19192 for (PackageSetting ps : packages) { 19193 final String packageName = ps.name; 19194 if (ps.pkg == null) { 19195 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19196 // TODO: might be due to legacy ASEC apps; we should circle back 19197 // and reconcile again once they're scanned 19198 continue; 19199 } 19200 19201 if (ps.getInstalled(userId)) { 19202 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19203 19204 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19205 // We may have just shuffled around app data directories, so 19206 // prepare them one more time 19207 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19208 } 19209 19210 preparedCount++; 19211 } 19212 } 19213 19214 if (restoreconNeeded) { 19215 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19216 SELinuxMMAC.setRestoreconDone(ceDir); 19217 } 19218 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19219 SELinuxMMAC.setRestoreconDone(deDir); 19220 } 19221 } 19222 19223 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19224 + " packages; restoreconNeeded was " + restoreconNeeded); 19225 } 19226 19227 /** 19228 * Prepare app data for the given app just after it was installed or 19229 * upgraded. This method carefully only touches users that it's installed 19230 * for, and it forces a restorecon to handle any seinfo changes. 19231 * <p> 19232 * Verifies that directories exist and that ownership and labeling is 19233 * correct for all installed apps. If there is an ownership mismatch, it 19234 * will try recovering system apps by wiping data; third-party app data is 19235 * left intact. 19236 * <p> 19237 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19238 */ 19239 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19240 final PackageSetting ps; 19241 synchronized (mPackages) { 19242 ps = mSettings.mPackages.get(pkg.packageName); 19243 mSettings.writeKernelMappingLPr(ps); 19244 } 19245 19246 final UserManager um = mContext.getSystemService(UserManager.class); 19247 for (UserInfo user : um.getUsers()) { 19248 final int flags; 19249 if (um.isUserUnlockingOrUnlocked(user.id)) { 19250 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19251 } else if (um.isUserRunning(user.id)) { 19252 flags = StorageManager.FLAG_STORAGE_DE; 19253 } else { 19254 continue; 19255 } 19256 19257 if (ps.getInstalled(user.id)) { 19258 // Whenever an app changes, force a restorecon of its data 19259 // TODO: when user data is locked, mark that we're still dirty 19260 prepareAppDataLIF(pkg, user.id, flags, true); 19261 } 19262 } 19263 } 19264 19265 /** 19266 * Prepare app data for the given app. 19267 * <p> 19268 * Verifies that directories exist and that ownership and labeling is 19269 * correct for all installed apps. If there is an ownership mismatch, this 19270 * will try recovering system apps by wiping data; third-party app data is 19271 * left intact. 19272 */ 19273 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19274 boolean restoreconNeeded) { 19275 if (pkg == null) { 19276 Slog.wtf(TAG, "Package was null!", new Throwable()); 19277 return; 19278 } 19279 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19280 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19281 for (int i = 0; i < childCount; i++) { 19282 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19283 } 19284 } 19285 19286 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19287 boolean restoreconNeeded) { 19288 if (DEBUG_APP_DATA) { 19289 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19290 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19291 } 19292 19293 final String volumeUuid = pkg.volumeUuid; 19294 final String packageName = pkg.packageName; 19295 final ApplicationInfo app = pkg.applicationInfo; 19296 final int appId = UserHandle.getAppId(app.uid); 19297 19298 Preconditions.checkNotNull(app.seinfo); 19299 19300 try { 19301 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19302 appId, app.seinfo, app.targetSdkVersion); 19303 } catch (InstallerException e) { 19304 if (app.isSystemApp()) { 19305 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19306 + ", but trying to recover: " + e); 19307 destroyAppDataLeafLIF(pkg, userId, flags); 19308 try { 19309 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19310 appId, app.seinfo, app.targetSdkVersion); 19311 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19312 } catch (InstallerException e2) { 19313 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19314 } 19315 } else { 19316 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19317 } 19318 } 19319 19320 if (restoreconNeeded) { 19321 try { 19322 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19323 app.seinfo); 19324 } catch (InstallerException e) { 19325 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19326 } 19327 } 19328 19329 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19330 try { 19331 // CE storage is unlocked right now, so read out the inode and 19332 // remember for use later when it's locked 19333 // TODO: mark this structure as dirty so we persist it! 19334 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19335 StorageManager.FLAG_STORAGE_CE); 19336 synchronized (mPackages) { 19337 final PackageSetting ps = mSettings.mPackages.get(packageName); 19338 if (ps != null) { 19339 ps.setCeDataInode(ceDataInode, userId); 19340 } 19341 } 19342 } catch (InstallerException e) { 19343 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19344 } 19345 } 19346 19347 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19348 } 19349 19350 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19351 if (pkg == null) { 19352 Slog.wtf(TAG, "Package was null!", new Throwable()); 19353 return; 19354 } 19355 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19357 for (int i = 0; i < childCount; i++) { 19358 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19359 } 19360 } 19361 19362 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19363 final String volumeUuid = pkg.volumeUuid; 19364 final String packageName = pkg.packageName; 19365 final ApplicationInfo app = pkg.applicationInfo; 19366 19367 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19368 // Create a native library symlink only if we have native libraries 19369 // and if the native libraries are 32 bit libraries. We do not provide 19370 // this symlink for 64 bit libraries. 19371 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19372 final String nativeLibPath = app.nativeLibraryDir; 19373 try { 19374 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19375 nativeLibPath, userId); 19376 } catch (InstallerException e) { 19377 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19378 } 19379 } 19380 } 19381 } 19382 19383 /** 19384 * For system apps on non-FBE devices, this method migrates any existing 19385 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19386 * requested by the app. 19387 */ 19388 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19389 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19390 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19391 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19392 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19393 try { 19394 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19395 storageTarget); 19396 } catch (InstallerException e) { 19397 logCriticalInfo(Log.WARN, 19398 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19399 } 19400 return true; 19401 } else { 19402 return false; 19403 } 19404 } 19405 19406 public PackageFreezer freezePackage(String packageName, String killReason) { 19407 return new PackageFreezer(packageName, killReason); 19408 } 19409 19410 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19411 String killReason) { 19412 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19413 return new PackageFreezer(); 19414 } else { 19415 return freezePackage(packageName, killReason); 19416 } 19417 } 19418 19419 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19420 String killReason) { 19421 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19422 return new PackageFreezer(); 19423 } else { 19424 return freezePackage(packageName, killReason); 19425 } 19426 } 19427 19428 /** 19429 * Class that freezes and kills the given package upon creation, and 19430 * unfreezes it upon closing. This is typically used when doing surgery on 19431 * app code/data to prevent the app from running while you're working. 19432 */ 19433 private class PackageFreezer implements AutoCloseable { 19434 private final String mPackageName; 19435 private final PackageFreezer[] mChildren; 19436 19437 private final boolean mWeFroze; 19438 19439 private final AtomicBoolean mClosed = new AtomicBoolean(); 19440 private final CloseGuard mCloseGuard = CloseGuard.get(); 19441 19442 /** 19443 * Create and return a stub freezer that doesn't actually do anything, 19444 * typically used when someone requested 19445 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19446 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19447 */ 19448 public PackageFreezer() { 19449 mPackageName = null; 19450 mChildren = null; 19451 mWeFroze = false; 19452 mCloseGuard.open("close"); 19453 } 19454 19455 public PackageFreezer(String packageName, String killReason) { 19456 synchronized (mPackages) { 19457 mPackageName = packageName; 19458 mWeFroze = mFrozenPackages.add(mPackageName); 19459 19460 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19461 if (ps != null) { 19462 killApplication(ps.name, ps.appId, killReason); 19463 } 19464 19465 final PackageParser.Package p = mPackages.get(packageName); 19466 if (p != null && p.childPackages != null) { 19467 final int N = p.childPackages.size(); 19468 mChildren = new PackageFreezer[N]; 19469 for (int i = 0; i < N; i++) { 19470 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19471 killReason); 19472 } 19473 } else { 19474 mChildren = null; 19475 } 19476 } 19477 mCloseGuard.open("close"); 19478 } 19479 19480 @Override 19481 protected void finalize() throws Throwable { 19482 try { 19483 mCloseGuard.warnIfOpen(); 19484 close(); 19485 } finally { 19486 super.finalize(); 19487 } 19488 } 19489 19490 @Override 19491 public void close() { 19492 mCloseGuard.close(); 19493 if (mClosed.compareAndSet(false, true)) { 19494 synchronized (mPackages) { 19495 if (mWeFroze) { 19496 mFrozenPackages.remove(mPackageName); 19497 } 19498 19499 if (mChildren != null) { 19500 for (PackageFreezer freezer : mChildren) { 19501 freezer.close(); 19502 } 19503 } 19504 } 19505 } 19506 } 19507 } 19508 19509 /** 19510 * Verify that given package is currently frozen. 19511 */ 19512 private void checkPackageFrozen(String packageName) { 19513 synchronized (mPackages) { 19514 if (!mFrozenPackages.contains(packageName)) { 19515 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19516 } 19517 } 19518 } 19519 19520 @Override 19521 public int movePackage(final String packageName, final String volumeUuid) { 19522 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19523 19524 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19525 final int moveId = mNextMoveId.getAndIncrement(); 19526 mHandler.post(new Runnable() { 19527 @Override 19528 public void run() { 19529 try { 19530 movePackageInternal(packageName, volumeUuid, moveId, user); 19531 } catch (PackageManagerException e) { 19532 Slog.w(TAG, "Failed to move " + packageName, e); 19533 mMoveCallbacks.notifyStatusChanged(moveId, 19534 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19535 } 19536 } 19537 }); 19538 return moveId; 19539 } 19540 19541 private void movePackageInternal(final String packageName, final String volumeUuid, 19542 final int moveId, UserHandle user) throws PackageManagerException { 19543 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19544 final PackageManager pm = mContext.getPackageManager(); 19545 19546 final boolean currentAsec; 19547 final String currentVolumeUuid; 19548 final File codeFile; 19549 final String installerPackageName; 19550 final String packageAbiOverride; 19551 final int appId; 19552 final String seinfo; 19553 final String label; 19554 final int targetSdkVersion; 19555 final PackageFreezer freezer; 19556 19557 // reader 19558 synchronized (mPackages) { 19559 final PackageParser.Package pkg = mPackages.get(packageName); 19560 final PackageSetting ps = mSettings.mPackages.get(packageName); 19561 if (pkg == null || ps == null) { 19562 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19563 } 19564 19565 if (pkg.applicationInfo.isSystemApp()) { 19566 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19567 "Cannot move system application"); 19568 } 19569 19570 if (pkg.applicationInfo.isExternalAsec()) { 19571 currentAsec = true; 19572 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19573 } else if (pkg.applicationInfo.isForwardLocked()) { 19574 currentAsec = true; 19575 currentVolumeUuid = "forward_locked"; 19576 } else { 19577 currentAsec = false; 19578 currentVolumeUuid = ps.volumeUuid; 19579 19580 final File probe = new File(pkg.codePath); 19581 final File probeOat = new File(probe, "oat"); 19582 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19583 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19584 "Move only supported for modern cluster style installs"); 19585 } 19586 } 19587 19588 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19589 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19590 "Package already moved to " + volumeUuid); 19591 } 19592 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19593 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19594 "Device admin cannot be moved"); 19595 } 19596 19597 if (mFrozenPackages.contains(packageName)) { 19598 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19599 "Failed to move already frozen package"); 19600 } 19601 19602 codeFile = new File(pkg.codePath); 19603 installerPackageName = ps.installerPackageName; 19604 packageAbiOverride = ps.cpuAbiOverrideString; 19605 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19606 seinfo = pkg.applicationInfo.seinfo; 19607 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19608 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19609 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19610 } 19611 19612 final Bundle extras = new Bundle(); 19613 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19614 extras.putString(Intent.EXTRA_TITLE, label); 19615 mMoveCallbacks.notifyCreated(moveId, extras); 19616 19617 int installFlags; 19618 final boolean moveCompleteApp; 19619 final File measurePath; 19620 19621 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19622 installFlags = INSTALL_INTERNAL; 19623 moveCompleteApp = !currentAsec; 19624 measurePath = Environment.getDataAppDirectory(volumeUuid); 19625 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19626 installFlags = INSTALL_EXTERNAL; 19627 moveCompleteApp = false; 19628 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19629 } else { 19630 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19631 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19632 || !volume.isMountedWritable()) { 19633 freezer.close(); 19634 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19635 "Move location not mounted private volume"); 19636 } 19637 19638 Preconditions.checkState(!currentAsec); 19639 19640 installFlags = INSTALL_INTERNAL; 19641 moveCompleteApp = true; 19642 measurePath = Environment.getDataAppDirectory(volumeUuid); 19643 } 19644 19645 final PackageStats stats = new PackageStats(null, -1); 19646 synchronized (mInstaller) { 19647 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19648 freezer.close(); 19649 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19650 "Failed to measure package size"); 19651 } 19652 } 19653 19654 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19655 + stats.dataSize); 19656 19657 final long startFreeBytes = measurePath.getFreeSpace(); 19658 final long sizeBytes; 19659 if (moveCompleteApp) { 19660 sizeBytes = stats.codeSize + stats.dataSize; 19661 } else { 19662 sizeBytes = stats.codeSize; 19663 } 19664 19665 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19666 freezer.close(); 19667 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19668 "Not enough free space to move"); 19669 } 19670 19671 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19672 19673 final CountDownLatch installedLatch = new CountDownLatch(1); 19674 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19675 @Override 19676 public void onUserActionRequired(Intent intent) throws RemoteException { 19677 throw new IllegalStateException(); 19678 } 19679 19680 @Override 19681 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19682 Bundle extras) throws RemoteException { 19683 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19684 + PackageManager.installStatusToString(returnCode, msg)); 19685 19686 installedLatch.countDown(); 19687 freezer.close(); 19688 19689 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19690 switch (status) { 19691 case PackageInstaller.STATUS_SUCCESS: 19692 mMoveCallbacks.notifyStatusChanged(moveId, 19693 PackageManager.MOVE_SUCCEEDED); 19694 break; 19695 case PackageInstaller.STATUS_FAILURE_STORAGE: 19696 mMoveCallbacks.notifyStatusChanged(moveId, 19697 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19698 break; 19699 default: 19700 mMoveCallbacks.notifyStatusChanged(moveId, 19701 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19702 break; 19703 } 19704 } 19705 }; 19706 19707 final MoveInfo move; 19708 if (moveCompleteApp) { 19709 // Kick off a thread to report progress estimates 19710 new Thread() { 19711 @Override 19712 public void run() { 19713 while (true) { 19714 try { 19715 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19716 break; 19717 } 19718 } catch (InterruptedException ignored) { 19719 } 19720 19721 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19722 final int progress = 10 + (int) MathUtils.constrain( 19723 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19724 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19725 } 19726 } 19727 }.start(); 19728 19729 final String dataAppName = codeFile.getName(); 19730 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19731 dataAppName, appId, seinfo, targetSdkVersion); 19732 } else { 19733 move = null; 19734 } 19735 19736 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19737 19738 final Message msg = mHandler.obtainMessage(INIT_COPY); 19739 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19740 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19741 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19742 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19743 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19744 msg.obj = params; 19745 19746 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19747 System.identityHashCode(msg.obj)); 19748 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19749 System.identityHashCode(msg.obj)); 19750 19751 mHandler.sendMessage(msg); 19752 } 19753 19754 @Override 19755 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19757 19758 final int realMoveId = mNextMoveId.getAndIncrement(); 19759 final Bundle extras = new Bundle(); 19760 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19761 mMoveCallbacks.notifyCreated(realMoveId, extras); 19762 19763 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19764 @Override 19765 public void onCreated(int moveId, Bundle extras) { 19766 // Ignored 19767 } 19768 19769 @Override 19770 public void onStatusChanged(int moveId, int status, long estMillis) { 19771 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19772 } 19773 }; 19774 19775 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19776 storage.setPrimaryStorageUuid(volumeUuid, callback); 19777 return realMoveId; 19778 } 19779 19780 @Override 19781 public int getMoveStatus(int moveId) { 19782 mContext.enforceCallingOrSelfPermission( 19783 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19784 return mMoveCallbacks.mLastStatus.get(moveId); 19785 } 19786 19787 @Override 19788 public void registerMoveCallback(IPackageMoveObserver callback) { 19789 mContext.enforceCallingOrSelfPermission( 19790 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19791 mMoveCallbacks.register(callback); 19792 } 19793 19794 @Override 19795 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19796 mContext.enforceCallingOrSelfPermission( 19797 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19798 mMoveCallbacks.unregister(callback); 19799 } 19800 19801 @Override 19802 public boolean setInstallLocation(int loc) { 19803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19804 null); 19805 if (getInstallLocation() == loc) { 19806 return true; 19807 } 19808 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19809 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19810 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19811 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19812 return true; 19813 } 19814 return false; 19815 } 19816 19817 @Override 19818 public int getInstallLocation() { 19819 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19820 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19821 PackageHelper.APP_INSTALL_AUTO); 19822 } 19823 19824 /** Called by UserManagerService */ 19825 void cleanUpUser(UserManagerService userManager, int userHandle) { 19826 synchronized (mPackages) { 19827 mDirtyUsers.remove(userHandle); 19828 mUserNeedsBadging.delete(userHandle); 19829 mSettings.removeUserLPw(userHandle); 19830 mPendingBroadcasts.remove(userHandle); 19831 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19832 removeUnusedPackagesLPw(userManager, userHandle); 19833 } 19834 } 19835 19836 /** 19837 * We're removing userHandle and would like to remove any downloaded packages 19838 * that are no longer in use by any other user. 19839 * @param userHandle the user being removed 19840 */ 19841 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19842 final boolean DEBUG_CLEAN_APKS = false; 19843 int [] users = userManager.getUserIds(); 19844 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19845 while (psit.hasNext()) { 19846 PackageSetting ps = psit.next(); 19847 if (ps.pkg == null) { 19848 continue; 19849 } 19850 final String packageName = ps.pkg.packageName; 19851 // Skip over if system app 19852 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19853 continue; 19854 } 19855 if (DEBUG_CLEAN_APKS) { 19856 Slog.i(TAG, "Checking package " + packageName); 19857 } 19858 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19859 if (keep) { 19860 if (DEBUG_CLEAN_APKS) { 19861 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19862 } 19863 } else { 19864 for (int i = 0; i < users.length; i++) { 19865 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19866 keep = true; 19867 if (DEBUG_CLEAN_APKS) { 19868 Slog.i(TAG, " Keeping package " + packageName + " for user " 19869 + users[i]); 19870 } 19871 break; 19872 } 19873 } 19874 } 19875 if (!keep) { 19876 if (DEBUG_CLEAN_APKS) { 19877 Slog.i(TAG, " Removing package " + packageName); 19878 } 19879 mHandler.post(new Runnable() { 19880 public void run() { 19881 deletePackageX(packageName, userHandle, 0); 19882 } //end run 19883 }); 19884 } 19885 } 19886 } 19887 19888 /** Called by UserManagerService */ 19889 void createNewUser(int userHandle) { 19890 synchronized (mInstallLock) { 19891 mSettings.createNewUserLI(this, mInstaller, userHandle); 19892 } 19893 synchronized (mPackages) { 19894 applyFactoryDefaultBrowserLPw(userHandle); 19895 primeDomainVerificationsLPw(userHandle); 19896 } 19897 } 19898 19899 void newUserCreated(final int userHandle) { 19900 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19901 // If permission review for legacy apps is required, we represent 19902 // dagerous permissions for such apps as always granted runtime 19903 // permissions to keep per user flag state whether review is needed. 19904 // Hence, if a new user is added we have to propagate dangerous 19905 // permission grants for these legacy apps. 19906 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19907 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19908 | UPDATE_PERMISSIONS_REPLACE_ALL); 19909 } 19910 } 19911 19912 @Override 19913 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19914 mContext.enforceCallingOrSelfPermission( 19915 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19916 "Only package verification agents can read the verifier device identity"); 19917 19918 synchronized (mPackages) { 19919 return mSettings.getVerifierDeviceIdentityLPw(); 19920 } 19921 } 19922 19923 @Override 19924 public void setPermissionEnforced(String permission, boolean enforced) { 19925 // TODO: Now that we no longer change GID for storage, this should to away. 19926 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19927 "setPermissionEnforced"); 19928 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19929 synchronized (mPackages) { 19930 if (mSettings.mReadExternalStorageEnforced == null 19931 || mSettings.mReadExternalStorageEnforced != enforced) { 19932 mSettings.mReadExternalStorageEnforced = enforced; 19933 mSettings.writeLPr(); 19934 } 19935 } 19936 // kill any non-foreground processes so we restart them and 19937 // grant/revoke the GID. 19938 final IActivityManager am = ActivityManagerNative.getDefault(); 19939 if (am != null) { 19940 final long token = Binder.clearCallingIdentity(); 19941 try { 19942 am.killProcessesBelowForeground("setPermissionEnforcement"); 19943 } catch (RemoteException e) { 19944 } finally { 19945 Binder.restoreCallingIdentity(token); 19946 } 19947 } 19948 } else { 19949 throw new IllegalArgumentException("No selective enforcement for " + permission); 19950 } 19951 } 19952 19953 @Override 19954 @Deprecated 19955 public boolean isPermissionEnforced(String permission) { 19956 return true; 19957 } 19958 19959 @Override 19960 public boolean isStorageLow() { 19961 final long token = Binder.clearCallingIdentity(); 19962 try { 19963 final DeviceStorageMonitorInternal 19964 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19965 if (dsm != null) { 19966 return dsm.isMemoryLow(); 19967 } else { 19968 return false; 19969 } 19970 } finally { 19971 Binder.restoreCallingIdentity(token); 19972 } 19973 } 19974 19975 @Override 19976 public IPackageInstaller getPackageInstaller() { 19977 return mInstallerService; 19978 } 19979 19980 private boolean userNeedsBadging(int userId) { 19981 int index = mUserNeedsBadging.indexOfKey(userId); 19982 if (index < 0) { 19983 final UserInfo userInfo; 19984 final long token = Binder.clearCallingIdentity(); 19985 try { 19986 userInfo = sUserManager.getUserInfo(userId); 19987 } finally { 19988 Binder.restoreCallingIdentity(token); 19989 } 19990 final boolean b; 19991 if (userInfo != null && userInfo.isManagedProfile()) { 19992 b = true; 19993 } else { 19994 b = false; 19995 } 19996 mUserNeedsBadging.put(userId, b); 19997 return b; 19998 } 19999 return mUserNeedsBadging.valueAt(index); 20000 } 20001 20002 @Override 20003 public KeySet getKeySetByAlias(String packageName, String alias) { 20004 if (packageName == null || alias == null) { 20005 return null; 20006 } 20007 synchronized(mPackages) { 20008 final PackageParser.Package pkg = mPackages.get(packageName); 20009 if (pkg == null) { 20010 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20011 throw new IllegalArgumentException("Unknown package: " + packageName); 20012 } 20013 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20014 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20015 } 20016 } 20017 20018 @Override 20019 public KeySet getSigningKeySet(String packageName) { 20020 if (packageName == null) { 20021 return null; 20022 } 20023 synchronized(mPackages) { 20024 final PackageParser.Package pkg = mPackages.get(packageName); 20025 if (pkg == null) { 20026 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20027 throw new IllegalArgumentException("Unknown package: " + packageName); 20028 } 20029 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20030 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20031 throw new SecurityException("May not access signing KeySet of other apps."); 20032 } 20033 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20034 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20035 } 20036 } 20037 20038 @Override 20039 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20040 if (packageName == null || ks == null) { 20041 return false; 20042 } 20043 synchronized(mPackages) { 20044 final PackageParser.Package pkg = mPackages.get(packageName); 20045 if (pkg == null) { 20046 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20047 throw new IllegalArgumentException("Unknown package: " + packageName); 20048 } 20049 IBinder ksh = ks.getToken(); 20050 if (ksh instanceof KeySetHandle) { 20051 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20052 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20053 } 20054 return false; 20055 } 20056 } 20057 20058 @Override 20059 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20060 if (packageName == null || ks == null) { 20061 return false; 20062 } 20063 synchronized(mPackages) { 20064 final PackageParser.Package pkg = mPackages.get(packageName); 20065 if (pkg == null) { 20066 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20067 throw new IllegalArgumentException("Unknown package: " + packageName); 20068 } 20069 IBinder ksh = ks.getToken(); 20070 if (ksh instanceof KeySetHandle) { 20071 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20072 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20073 } 20074 return false; 20075 } 20076 } 20077 20078 private void deletePackageIfUnusedLPr(final String packageName) { 20079 PackageSetting ps = mSettings.mPackages.get(packageName); 20080 if (ps == null) { 20081 return; 20082 } 20083 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20084 // TODO Implement atomic delete if package is unused 20085 // It is currently possible that the package will be deleted even if it is installed 20086 // after this method returns. 20087 mHandler.post(new Runnable() { 20088 public void run() { 20089 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20090 } 20091 }); 20092 } 20093 } 20094 20095 /** 20096 * Check and throw if the given before/after packages would be considered a 20097 * downgrade. 20098 */ 20099 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20100 throws PackageManagerException { 20101 if (after.versionCode < before.mVersionCode) { 20102 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20103 "Update version code " + after.versionCode + " is older than current " 20104 + before.mVersionCode); 20105 } else if (after.versionCode == before.mVersionCode) { 20106 if (after.baseRevisionCode < before.baseRevisionCode) { 20107 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20108 "Update base revision code " + after.baseRevisionCode 20109 + " is older than current " + before.baseRevisionCode); 20110 } 20111 20112 if (!ArrayUtils.isEmpty(after.splitNames)) { 20113 for (int i = 0; i < after.splitNames.length; i++) { 20114 final String splitName = after.splitNames[i]; 20115 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20116 if (j != -1) { 20117 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20118 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20119 "Update split " + splitName + " revision code " 20120 + after.splitRevisionCodes[i] + " is older than current " 20121 + before.splitRevisionCodes[j]); 20122 } 20123 } 20124 } 20125 } 20126 } 20127 } 20128 20129 private static class MoveCallbacks extends Handler { 20130 private static final int MSG_CREATED = 1; 20131 private static final int MSG_STATUS_CHANGED = 2; 20132 20133 private final RemoteCallbackList<IPackageMoveObserver> 20134 mCallbacks = new RemoteCallbackList<>(); 20135 20136 private final SparseIntArray mLastStatus = new SparseIntArray(); 20137 20138 public MoveCallbacks(Looper looper) { 20139 super(looper); 20140 } 20141 20142 public void register(IPackageMoveObserver callback) { 20143 mCallbacks.register(callback); 20144 } 20145 20146 public void unregister(IPackageMoveObserver callback) { 20147 mCallbacks.unregister(callback); 20148 } 20149 20150 @Override 20151 public void handleMessage(Message msg) { 20152 final SomeArgs args = (SomeArgs) msg.obj; 20153 final int n = mCallbacks.beginBroadcast(); 20154 for (int i = 0; i < n; i++) { 20155 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20156 try { 20157 invokeCallback(callback, msg.what, args); 20158 } catch (RemoteException ignored) { 20159 } 20160 } 20161 mCallbacks.finishBroadcast(); 20162 args.recycle(); 20163 } 20164 20165 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20166 throws RemoteException { 20167 switch (what) { 20168 case MSG_CREATED: { 20169 callback.onCreated(args.argi1, (Bundle) args.arg2); 20170 break; 20171 } 20172 case MSG_STATUS_CHANGED: { 20173 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20174 break; 20175 } 20176 } 20177 } 20178 20179 private void notifyCreated(int moveId, Bundle extras) { 20180 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20181 20182 final SomeArgs args = SomeArgs.obtain(); 20183 args.argi1 = moveId; 20184 args.arg2 = extras; 20185 obtainMessage(MSG_CREATED, args).sendToTarget(); 20186 } 20187 20188 private void notifyStatusChanged(int moveId, int status) { 20189 notifyStatusChanged(moveId, status, -1); 20190 } 20191 20192 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20193 Slog.v(TAG, "Move " + moveId + " status " + status); 20194 20195 final SomeArgs args = SomeArgs.obtain(); 20196 args.argi1 = moveId; 20197 args.argi2 = status; 20198 args.arg3 = estMillis; 20199 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20200 20201 synchronized (mLastStatus) { 20202 mLastStatus.put(moveId, status); 20203 } 20204 } 20205 } 20206 20207 private final static class OnPermissionChangeListeners extends Handler { 20208 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20209 20210 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20211 new RemoteCallbackList<>(); 20212 20213 public OnPermissionChangeListeners(Looper looper) { 20214 super(looper); 20215 } 20216 20217 @Override 20218 public void handleMessage(Message msg) { 20219 switch (msg.what) { 20220 case MSG_ON_PERMISSIONS_CHANGED: { 20221 final int uid = msg.arg1; 20222 handleOnPermissionsChanged(uid); 20223 } break; 20224 } 20225 } 20226 20227 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20228 mPermissionListeners.register(listener); 20229 20230 } 20231 20232 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20233 mPermissionListeners.unregister(listener); 20234 } 20235 20236 public void onPermissionsChanged(int uid) { 20237 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20238 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20239 } 20240 } 20241 20242 private void handleOnPermissionsChanged(int uid) { 20243 final int count = mPermissionListeners.beginBroadcast(); 20244 try { 20245 for (int i = 0; i < count; i++) { 20246 IOnPermissionsChangeListener callback = mPermissionListeners 20247 .getBroadcastItem(i); 20248 try { 20249 callback.onPermissionsChanged(uid); 20250 } catch (RemoteException e) { 20251 Log.e(TAG, "Permission listener is dead", e); 20252 } 20253 } 20254 } finally { 20255 mPermissionListeners.finishBroadcast(); 20256 } 20257 } 20258 } 20259 20260 private class PackageManagerInternalImpl extends PackageManagerInternal { 20261 @Override 20262 public void setLocationPackagesProvider(PackagesProvider provider) { 20263 synchronized (mPackages) { 20264 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20265 } 20266 } 20267 20268 @Override 20269 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20270 synchronized (mPackages) { 20271 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20272 } 20273 } 20274 20275 @Override 20276 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20277 synchronized (mPackages) { 20278 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20279 } 20280 } 20281 20282 @Override 20283 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20284 synchronized (mPackages) { 20285 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20286 } 20287 } 20288 20289 @Override 20290 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20291 synchronized (mPackages) { 20292 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20293 } 20294 } 20295 20296 @Override 20297 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20298 synchronized (mPackages) { 20299 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20300 } 20301 } 20302 20303 @Override 20304 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20305 synchronized (mPackages) { 20306 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20307 packageName, userId); 20308 } 20309 } 20310 20311 @Override 20312 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20313 synchronized (mPackages) { 20314 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20315 packageName, userId); 20316 } 20317 } 20318 20319 @Override 20320 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20321 synchronized (mPackages) { 20322 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20323 packageName, userId); 20324 } 20325 } 20326 20327 @Override 20328 public void setKeepUninstalledPackages(final List<String> packageList) { 20329 Preconditions.checkNotNull(packageList); 20330 List<String> removedFromList = null; 20331 synchronized (mPackages) { 20332 if (mKeepUninstalledPackages != null) { 20333 final int packagesCount = mKeepUninstalledPackages.size(); 20334 for (int i = 0; i < packagesCount; i++) { 20335 String oldPackage = mKeepUninstalledPackages.get(i); 20336 if (packageList != null && packageList.contains(oldPackage)) { 20337 continue; 20338 } 20339 if (removedFromList == null) { 20340 removedFromList = new ArrayList<>(); 20341 } 20342 removedFromList.add(oldPackage); 20343 } 20344 } 20345 mKeepUninstalledPackages = new ArrayList<>(packageList); 20346 if (removedFromList != null) { 20347 final int removedCount = removedFromList.size(); 20348 for (int i = 0; i < removedCount; i++) { 20349 deletePackageIfUnusedLPr(removedFromList.get(i)); 20350 } 20351 } 20352 } 20353 } 20354 20355 @Override 20356 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20357 synchronized (mPackages) { 20358 // If we do not support permission review, done. 20359 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20360 return false; 20361 } 20362 20363 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20364 if (packageSetting == null) { 20365 return false; 20366 } 20367 20368 // Permission review applies only to apps not supporting the new permission model. 20369 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20370 return false; 20371 } 20372 20373 // Legacy apps have the permission and get user consent on launch. 20374 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20375 return permissionsState.isPermissionReviewRequired(userId); 20376 } 20377 } 20378 20379 @Override 20380 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20381 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20382 } 20383 20384 @Override 20385 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20386 int userId) { 20387 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20388 } 20389 } 20390 20391 @Override 20392 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20393 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20394 synchronized (mPackages) { 20395 final long identity = Binder.clearCallingIdentity(); 20396 try { 20397 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20398 packageNames, userId); 20399 } finally { 20400 Binder.restoreCallingIdentity(identity); 20401 } 20402 } 20403 } 20404 20405 private static void enforceSystemOrPhoneCaller(String tag) { 20406 int callingUid = Binder.getCallingUid(); 20407 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20408 throw new SecurityException( 20409 "Cannot call " + tag + " from UID " + callingUid); 20410 } 20411 } 20412 20413 boolean isHistoricalPackageUsageAvailable() { 20414 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20415 } 20416 20417 /** 20418 * Return a <b>copy</b> of the collection of packages known to the package manager. 20419 * @return A copy of the values of mPackages. 20420 */ 20421 Collection<PackageParser.Package> getPackages() { 20422 synchronized (mPackages) { 20423 return new ArrayList<>(mPackages.values()); 20424 } 20425 } 20426 20427 /** 20428 * Logs process start information (including base APK hash) to the security log. 20429 * @hide 20430 */ 20431 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20432 String apkFile, int pid) { 20433 if (!SecurityLog.isLoggingEnabled()) { 20434 return; 20435 } 20436 Bundle data = new Bundle(); 20437 data.putLong("startTimestamp", System.currentTimeMillis()); 20438 data.putString("processName", processName); 20439 data.putInt("uid", uid); 20440 data.putString("seinfo", seinfo); 20441 data.putString("apkFile", apkFile); 20442 data.putInt("pid", pid); 20443 Message msg = mProcessLoggingHandler.obtainMessage( 20444 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20445 msg.setData(data); 20446 mProcessLoggingHandler.sendMessage(msg); 20447 } 20448} 20449