PackageManagerService.java revision 7e01af424355b5bbac64126fef4e3d37c9c41dd7
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.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.os.IParcelFileDescriptorFactory; 230import com.android.internal.os.InstallerConnection.InstallerException; 231import com.android.internal.os.SomeArgs; 232import com.android.internal.os.Zygote; 233import com.android.internal.telephony.CarrierAppUtils; 234import com.android.internal.util.ArrayUtils; 235import com.android.internal.util.FastPrintWriter; 236import com.android.internal.util.FastXmlSerializer; 237import com.android.internal.util.IndentingPrintWriter; 238import com.android.internal.util.Preconditions; 239import com.android.internal.util.XmlUtils; 240import com.android.server.EventLogTags; 241import com.android.server.FgThread; 242import com.android.server.IntentResolver; 243import com.android.server.LocalServices; 244import com.android.server.ServiceThread; 245import com.android.server.SystemConfig; 246import com.android.server.Watchdog; 247import com.android.server.net.NetworkPolicyManagerInternal; 248import com.android.server.pm.PermissionsState.PermissionState; 249import com.android.server.pm.Settings.DatabaseVersion; 250import com.android.server.pm.Settings.VersionInfo; 251import com.android.server.storage.DeviceStorageMonitorInternal; 252 253import dalvik.system.CloseGuard; 254import dalvik.system.DexFile; 255import dalvik.system.VMRuntime; 256 257import libcore.io.IoUtils; 258import libcore.util.EmptyArray; 259 260import org.xmlpull.v1.XmlPullParser; 261import org.xmlpull.v1.XmlPullParserException; 262import org.xmlpull.v1.XmlSerializer; 263 264import java.io.BufferedInputStream; 265import java.io.BufferedOutputStream; 266import java.io.BufferedReader; 267import java.io.ByteArrayInputStream; 268import java.io.ByteArrayOutputStream; 269import java.io.File; 270import java.io.FileDescriptor; 271import java.io.FileInputStream; 272import java.io.FileNotFoundException; 273import java.io.FileOutputStream; 274import java.io.FileReader; 275import java.io.FilenameFilter; 276import java.io.IOException; 277import java.io.InputStream; 278import java.io.PrintWriter; 279import java.nio.charset.StandardCharsets; 280import java.security.DigestInputStream; 281import java.security.MessageDigest; 282import java.security.NoSuchAlgorithmException; 283import java.security.PublicKey; 284import java.security.cert.Certificate; 285import java.security.cert.CertificateEncodingException; 286import java.security.cert.CertificateException; 287import java.text.SimpleDateFormat; 288import java.util.ArrayList; 289import java.util.Arrays; 290import java.util.Collection; 291import java.util.Collections; 292import java.util.Comparator; 293import java.util.Date; 294import java.util.HashSet; 295import java.util.Iterator; 296import java.util.List; 297import java.util.Map; 298import java.util.Objects; 299import java.util.Set; 300import java.util.concurrent.CountDownLatch; 301import java.util.concurrent.TimeUnit; 302import java.util.concurrent.atomic.AtomicBoolean; 303import java.util.concurrent.atomic.AtomicInteger; 304import java.util.concurrent.atomic.AtomicLong; 305 306/** 307 * Keep track of all those APKs everywhere. 308 * <p> 309 * Internally there are two important locks: 310 * <ul> 311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 312 * and other related state. It is a fine-grained lock that should only be held 313 * momentarily, as it's one of the most contended locks in the system. 314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 315 * operations typically involve heavy lifting of application data on disk. Since 316 * {@code installd} is single-threaded, and it's operations can often be slow, 317 * this lock should never be acquired while already holding {@link #mPackages}. 318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 319 * holding {@link #mInstallLock}. 320 * </ul> 321 * Many internal methods rely on the caller to hold the appropriate locks, and 322 * this contract is expressed through method name suffixes: 323 * <ul> 324 * <li>fooLI(): the caller must hold {@link #mInstallLock} 325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 326 * being modified must be frozen 327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 329 * </ul> 330 * <p> 331 * Because this class is very central to the platform's security; please run all 332 * CTS and unit tests whenever making modifications: 333 * 334 * <pre> 335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 337 * </pre> 338 */ 339public class PackageManagerService extends IPackageManager.Stub { 340 static final String TAG = "PackageManager"; 341 static final boolean DEBUG_SETTINGS = false; 342 static final boolean DEBUG_PREFERRED = false; 343 static final boolean DEBUG_UPGRADE = false; 344 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 345 private static final boolean DEBUG_BACKUP = false; 346 private static final boolean DEBUG_INSTALL = false; 347 private static final boolean DEBUG_REMOVE = false; 348 private static final boolean DEBUG_BROADCASTS = false; 349 private static final boolean DEBUG_SHOW_INFO = false; 350 private static final boolean DEBUG_PACKAGE_INFO = false; 351 private static final boolean DEBUG_INTENT_MATCHING = false; 352 private static final boolean DEBUG_PACKAGE_SCANNING = false; 353 private static final boolean DEBUG_VERIFY = false; 354 private static final boolean DEBUG_FILTERS = false; 355 356 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 357 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 358 // user, but by default initialize to this. 359 static final boolean DEBUG_DEXOPT = false; 360 361 private static final boolean DEBUG_ABI_SELECTION = false; 362 private static final boolean DEBUG_EPHEMERAL = false; 363 private static final boolean DEBUG_TRIAGED_MISSING = false; 364 private static final boolean DEBUG_APP_DATA = false; 365 366 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 367 368 private static final boolean DISABLE_EPHEMERAL_APPS = true; 369 370 private static final int RADIO_UID = Process.PHONE_UID; 371 private static final int LOG_UID = Process.LOG_UID; 372 private static final int NFC_UID = Process.NFC_UID; 373 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 374 private static final int SHELL_UID = Process.SHELL_UID; 375 376 // Cap the size of permission trees that 3rd party apps can define 377 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 378 379 // Suffix used during package installation when copying/moving 380 // package apks to install directory. 381 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 382 383 static final int SCAN_NO_DEX = 1<<1; 384 static final int SCAN_FORCE_DEX = 1<<2; 385 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 386 static final int SCAN_NEW_INSTALL = 1<<4; 387 static final int SCAN_NO_PATHS = 1<<5; 388 static final int SCAN_UPDATE_TIME = 1<<6; 389 static final int SCAN_DEFER_DEX = 1<<7; 390 static final int SCAN_BOOTING = 1<<8; 391 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 392 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 393 static final int SCAN_REPLACING = 1<<11; 394 static final int SCAN_REQUIRE_KNOWN = 1<<12; 395 static final int SCAN_MOVE = 1<<13; 396 static final int SCAN_INITIAL = 1<<14; 397 static final int SCAN_CHECK_ONLY = 1<<15; 398 static final int SCAN_DONT_KILL_APP = 1<<17; 399 static final int SCAN_IGNORE_FROZEN = 1<<18; 400 401 static final int REMOVE_CHATTY = 1<<16; 402 403 private static final int[] EMPTY_INT_ARRAY = new int[0]; 404 405 /** 406 * Timeout (in milliseconds) after which the watchdog should declare that 407 * our handler thread is wedged. The usual default for such things is one 408 * minute but we sometimes do very lengthy I/O operations on this thread, 409 * such as installing multi-gigabyte applications, so ours needs to be longer. 410 */ 411 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 412 413 /** 414 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 415 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 416 * settings entry if available, otherwise we use the hardcoded default. If it's been 417 * more than this long since the last fstrim, we force one during the boot sequence. 418 * 419 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 420 * one gets run at the next available charging+idle time. This final mandatory 421 * no-fstrim check kicks in only of the other scheduling criteria is never met. 422 */ 423 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 424 425 /** 426 * Whether verification is enabled by default. 427 */ 428 private static final boolean DEFAULT_VERIFY_ENABLE = true; 429 430 /** 431 * The default maximum time to wait for the verification agent to return in 432 * milliseconds. 433 */ 434 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 435 436 /** 437 * The default response for package verification timeout. 438 * 439 * This can be either PackageManager.VERIFICATION_ALLOW or 440 * PackageManager.VERIFICATION_REJECT. 441 */ 442 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 443 444 static final String PLATFORM_PACKAGE_NAME = "android"; 445 446 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 447 448 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 449 DEFAULT_CONTAINER_PACKAGE, 450 "com.android.defcontainer.DefaultContainerService"); 451 452 private static final String KILL_APP_REASON_GIDS_CHANGED = 453 "permission grant or revoke changed gids"; 454 455 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 456 "permissions revoked"; 457 458 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 459 460 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 461 462 /** Permission grant: not grant the permission. */ 463 private static final int GRANT_DENIED = 1; 464 465 /** Permission grant: grant the permission as an install permission. */ 466 private static final int GRANT_INSTALL = 2; 467 468 /** Permission grant: grant the permission as a runtime one. */ 469 private static final int GRANT_RUNTIME = 3; 470 471 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 472 private static final int GRANT_UPGRADE = 4; 473 474 /** Canonical intent used to identify what counts as a "web browser" app */ 475 private static final Intent sBrowserIntent; 476 static { 477 sBrowserIntent = new Intent(); 478 sBrowserIntent.setAction(Intent.ACTION_VIEW); 479 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 480 sBrowserIntent.setData(Uri.parse("http:")); 481 } 482 483 /** 484 * The set of all protected actions [i.e. those actions for which a high priority 485 * intent filter is disallowed]. 486 */ 487 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 488 static { 489 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 490 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 492 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 493 } 494 495 // Compilation reasons. 496 public static final int REASON_FIRST_BOOT = 0; 497 public static final int REASON_BOOT = 1; 498 public static final int REASON_INSTALL = 2; 499 public static final int REASON_BACKGROUND_DEXOPT = 3; 500 public static final int REASON_AB_OTA = 4; 501 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 502 public static final int REASON_SHARED_APK = 6; 503 public static final int REASON_FORCED_DEXOPT = 7; 504 505 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 506 507 /** Special library name that skips shared libraries check during compilation. */ 508 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 509 510 final ServiceThread mHandlerThread; 511 512 final PackageHandler mHandler; 513 514 private final ProcessLoggingHandler mProcessLoggingHandler; 515 516 /** 517 * Messages for {@link #mHandler} that need to wait for system ready before 518 * being dispatched. 519 */ 520 private ArrayList<Message> mPostSystemReadyMessages; 521 522 final int mSdkVersion = Build.VERSION.SDK_INT; 523 524 final Context mContext; 525 final boolean mFactoryTest; 526 final boolean mOnlyCore; 527 final DisplayMetrics mMetrics; 528 final int mDefParseFlags; 529 final String[] mSeparateProcesses; 530 final boolean mIsUpgrade; 531 final boolean mIsPreNUpgrade; 532 533 /** The location for ASEC container files on internal storage. */ 534 final String mAsecInternalPath; 535 536 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 537 // LOCK HELD. Can be called with mInstallLock held. 538 @GuardedBy("mInstallLock") 539 final Installer mInstaller; 540 541 /** Directory where installed third-party apps stored */ 542 final File mAppInstallDir; 543 final File mEphemeralInstallDir; 544 545 /** 546 * Directory to which applications installed internally have their 547 * 32 bit native libraries copied. 548 */ 549 private File mAppLib32InstallDir; 550 551 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 552 // apps. 553 final File mDrmAppPrivateInstallDir; 554 555 // ---------------------------------------------------------------- 556 557 // Lock for state used when installing and doing other long running 558 // operations. Methods that must be called with this lock held have 559 // the suffix "LI". 560 final Object mInstallLock = new Object(); 561 562 // ---------------------------------------------------------------- 563 564 // Keys are String (package name), values are Package. This also serves 565 // as the lock for the global state. Methods that must be called with 566 // this lock held have the prefix "LP". 567 @GuardedBy("mPackages") 568 final ArrayMap<String, PackageParser.Package> mPackages = 569 new ArrayMap<String, PackageParser.Package>(); 570 571 final ArrayMap<String, Set<String>> mKnownCodebase = 572 new ArrayMap<String, Set<String>>(); 573 574 // Tracks available target package names -> overlay package paths. 575 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 576 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 577 578 /** 579 * Tracks new system packages [received in an OTA] that we expect to 580 * find updated user-installed versions. Keys are package name, values 581 * are package location. 582 */ 583 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 584 /** 585 * Tracks high priority intent filters for protected actions. During boot, certain 586 * filter actions are protected and should never be allowed to have a high priority 587 * intent filter for them. However, there is one, and only one exception -- the 588 * setup wizard. It must be able to define a high priority intent filter for these 589 * actions to ensure there are no escapes from the wizard. We need to delay processing 590 * of these during boot as we need to look at all of the system packages in order 591 * to know which component is the setup wizard. 592 */ 593 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 594 /** 595 * Whether or not processing protected filters should be deferred. 596 */ 597 private boolean mDeferProtectedFilters = true; 598 599 /** 600 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 601 */ 602 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 603 /** 604 * Whether or not system app permissions should be promoted from install to runtime. 605 */ 606 boolean mPromoteSystemApps; 607 608 @GuardedBy("mPackages") 609 final Settings mSettings; 610 611 /** 612 * Set of package names that are currently "frozen", which means active 613 * surgery is being done on the code/data for that package. The platform 614 * will refuse to launch frozen packages to avoid race conditions. 615 * 616 * @see PackageFreezer 617 */ 618 @GuardedBy("mPackages") 619 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 620 621 boolean mRestoredSettings; 622 623 // System configuration read by SystemConfig. 624 final int[] mGlobalGids; 625 final SparseArray<ArraySet<String>> mSystemPermissions; 626 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 627 628 // If mac_permissions.xml was found for seinfo labeling. 629 boolean mFoundPolicyFile; 630 631 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 632 633 public static final class SharedLibraryEntry { 634 public final String path; 635 public final String apk; 636 637 SharedLibraryEntry(String _path, String _apk) { 638 path = _path; 639 apk = _apk; 640 } 641 } 642 643 // Currently known shared libraries. 644 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 645 new ArrayMap<String, SharedLibraryEntry>(); 646 647 // All available activities, for your resolving pleasure. 648 final ActivityIntentResolver mActivities = 649 new ActivityIntentResolver(); 650 651 // All available receivers, for your resolving pleasure. 652 final ActivityIntentResolver mReceivers = 653 new ActivityIntentResolver(); 654 655 // All available services, for your resolving pleasure. 656 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 657 658 // All available providers, for your resolving pleasure. 659 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 660 661 // Mapping from provider base names (first directory in content URI codePath) 662 // to the provider information. 663 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 664 new ArrayMap<String, PackageParser.Provider>(); 665 666 // Mapping from instrumentation class names to info about them. 667 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 668 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 669 670 // Mapping from permission names to info about them. 671 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 672 new ArrayMap<String, PackageParser.PermissionGroup>(); 673 674 // Packages whose data we have transfered into another package, thus 675 // should no longer exist. 676 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 677 678 // Broadcast actions that are only available to the system. 679 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 680 681 /** List of packages waiting for verification. */ 682 final SparseArray<PackageVerificationState> mPendingVerification 683 = new SparseArray<PackageVerificationState>(); 684 685 /** Set of packages associated with each app op permission. */ 686 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 687 688 final PackageInstallerService mInstallerService; 689 690 private final PackageDexOptimizer mPackageDexOptimizer; 691 692 private AtomicInteger mNextMoveId = new AtomicInteger(); 693 private final MoveCallbacks mMoveCallbacks; 694 695 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 696 697 // Cache of users who need badging. 698 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 699 700 /** Token for keys in mPendingVerification. */ 701 private int mPendingVerificationToken = 0; 702 703 volatile boolean mSystemReady; 704 volatile boolean mSafeMode; 705 volatile boolean mHasSystemUidErrors; 706 707 ApplicationInfo mAndroidApplication; 708 final ActivityInfo mResolveActivity = new ActivityInfo(); 709 final ResolveInfo mResolveInfo = new ResolveInfo(); 710 ComponentName mResolveComponentName; 711 PackageParser.Package mPlatformPackage; 712 ComponentName mCustomResolverComponentName; 713 714 boolean mResolverReplaced = false; 715 716 private final @Nullable ComponentName mIntentFilterVerifierComponent; 717 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 718 719 private int mIntentFilterVerificationToken = 0; 720 721 /** Component that knows whether or not an ephemeral application exists */ 722 final ComponentName mEphemeralResolverComponent; 723 /** The service connection to the ephemeral resolver */ 724 final EphemeralResolverConnection mEphemeralResolverConnection; 725 726 /** Component used to install ephemeral applications */ 727 final ComponentName mEphemeralInstallerComponent; 728 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 729 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 730 731 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 732 = new SparseArray<IntentFilterVerificationState>(); 733 734 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 735 new DefaultPermissionGrantPolicy(this); 736 737 // List of packages names to keep cached, even if they are uninstalled for all users 738 private List<String> mKeepUninstalledPackages; 739 740 private static class IFVerificationParams { 741 PackageParser.Package pkg; 742 boolean replacing; 743 int userId; 744 int verifierUid; 745 746 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 747 int _userId, int _verifierUid) { 748 pkg = _pkg; 749 replacing = _replacing; 750 userId = _userId; 751 replacing = _replacing; 752 verifierUid = _verifierUid; 753 } 754 } 755 756 private interface IntentFilterVerifier<T extends IntentFilter> { 757 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 758 T filter, String packageName); 759 void startVerifications(int userId); 760 void receiveVerificationResponse(int verificationId); 761 } 762 763 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 764 private Context mContext; 765 private ComponentName mIntentFilterVerifierComponent; 766 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 767 768 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 769 mContext = context; 770 mIntentFilterVerifierComponent = verifierComponent; 771 } 772 773 private String getDefaultScheme() { 774 return IntentFilter.SCHEME_HTTPS; 775 } 776 777 @Override 778 public void startVerifications(int userId) { 779 // Launch verifications requests 780 int count = mCurrentIntentFilterVerifications.size(); 781 for (int n=0; n<count; n++) { 782 int verificationId = mCurrentIntentFilterVerifications.get(n); 783 final IntentFilterVerificationState ivs = 784 mIntentFilterVerificationStates.get(verificationId); 785 786 String packageName = ivs.getPackageName(); 787 788 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 789 final int filterCount = filters.size(); 790 ArraySet<String> domainsSet = new ArraySet<>(); 791 for (int m=0; m<filterCount; m++) { 792 PackageParser.ActivityIntentInfo filter = filters.get(m); 793 domainsSet.addAll(filter.getHostsList()); 794 } 795 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 796 synchronized (mPackages) { 797 if (mSettings.createIntentFilterVerificationIfNeededLPw( 798 packageName, domainsList) != null) { 799 scheduleWriteSettingsLocked(); 800 } 801 } 802 sendVerificationRequest(userId, verificationId, ivs); 803 } 804 mCurrentIntentFilterVerifications.clear(); 805 } 806 807 private void sendVerificationRequest(int userId, int verificationId, 808 IntentFilterVerificationState ivs) { 809 810 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 813 verificationId); 814 verificationIntent.putExtra( 815 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 816 getDefaultScheme()); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 819 ivs.getHostsString()); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 822 ivs.getPackageName()); 823 verificationIntent.setComponent(mIntentFilterVerifierComponent); 824 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 825 826 UserHandle user = new UserHandle(userId); 827 mContext.sendBroadcastAsUser(verificationIntent, user); 828 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 829 "Sending IntentFilter verification broadcast"); 830 } 831 832 public void receiveVerificationResponse(int verificationId) { 833 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 834 835 final boolean verified = ivs.isVerified(); 836 837 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 838 final int count = filters.size(); 839 if (DEBUG_DOMAIN_VERIFICATION) { 840 Slog.i(TAG, "Received verification response " + verificationId 841 + " for " + count + " filters, verified=" + verified); 842 } 843 for (int n=0; n<count; n++) { 844 PackageParser.ActivityIntentInfo filter = filters.get(n); 845 filter.setVerified(verified); 846 847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 848 + " verified with result:" + verified + " and hosts:" 849 + ivs.getHostsString()); 850 } 851 852 mIntentFilterVerificationStates.remove(verificationId); 853 854 final String packageName = ivs.getPackageName(); 855 IntentFilterVerificationInfo ivi = null; 856 857 synchronized (mPackages) { 858 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 859 } 860 if (ivi == null) { 861 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 862 + verificationId + " packageName:" + packageName); 863 return; 864 } 865 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 866 "Updating IntentFilterVerificationInfo for package " + packageName 867 +" verificationId:" + verificationId); 868 869 synchronized (mPackages) { 870 if (verified) { 871 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 872 } else { 873 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 874 } 875 scheduleWriteSettingsLocked(); 876 877 final int userId = ivs.getUserId(); 878 if (userId != UserHandle.USER_ALL) { 879 final int userStatus = 880 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 881 882 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 883 boolean needUpdate = false; 884 885 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 886 // already been set by the User thru the Disambiguation dialog 887 switch (userStatus) { 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 } else { 892 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 893 } 894 needUpdate = true; 895 break; 896 897 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 898 if (verified) { 899 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 900 needUpdate = true; 901 } 902 break; 903 904 default: 905 // Nothing to do 906 } 907 908 if (needUpdate) { 909 mSettings.updateIntentFilterVerificationStatusLPw( 910 packageName, updatedStatus, userId); 911 scheduleWritePackageRestrictionsLocked(userId); 912 } 913 } 914 } 915 } 916 917 @Override 918 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 919 ActivityIntentInfo filter, String packageName) { 920 if (!hasValidDomains(filter)) { 921 return false; 922 } 923 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 924 if (ivs == null) { 925 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 926 packageName); 927 } 928 if (DEBUG_DOMAIN_VERIFICATION) { 929 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 930 } 931 ivs.addFilter(filter); 932 return true; 933 } 934 935 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 936 int userId, int verificationId, String packageName) { 937 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 938 verifierUid, userId, packageName); 939 ivs.setPendingState(); 940 synchronized (mPackages) { 941 mIntentFilterVerificationStates.append(verificationId, ivs); 942 mCurrentIntentFilterVerifications.add(verificationId); 943 } 944 return ivs; 945 } 946 } 947 948 private static boolean hasValidDomains(ActivityIntentInfo filter) { 949 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 950 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 951 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 952 } 953 954 // Set of pending broadcasts for aggregating enable/disable of components. 955 static class PendingPackageBroadcasts { 956 // for each user id, a map of <package name -> components within that package> 957 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 958 959 public PendingPackageBroadcasts() { 960 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 961 } 962 963 public ArrayList<String> get(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 965 return packages.get(packageName); 966 } 967 968 public void put(int userId, String packageName, ArrayList<String> components) { 969 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 970 packages.put(packageName, components); 971 } 972 973 public void remove(int userId, String packageName) { 974 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 975 if (packages != null) { 976 packages.remove(packageName); 977 } 978 } 979 980 public void remove(int userId) { 981 mUidMap.remove(userId); 982 } 983 984 public int userIdCount() { 985 return mUidMap.size(); 986 } 987 988 public int userIdAt(int n) { 989 return mUidMap.keyAt(n); 990 } 991 992 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 993 return mUidMap.get(userId); 994 } 995 996 public int size() { 997 // total number of pending broadcast entries across all userIds 998 int num = 0; 999 for (int i = 0; i< mUidMap.size(); i++) { 1000 num += mUidMap.valueAt(i).size(); 1001 } 1002 return num; 1003 } 1004 1005 public void clear() { 1006 mUidMap.clear(); 1007 } 1008 1009 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1010 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1011 if (map == null) { 1012 map = new ArrayMap<String, ArrayList<String>>(); 1013 mUidMap.put(userId, map); 1014 } 1015 return map; 1016 } 1017 } 1018 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1019 1020 // Service Connection to remote media container service to copy 1021 // package uri's from external media onto secure containers 1022 // or internal storage. 1023 private IMediaContainerService mContainerService = null; 1024 1025 static final int SEND_PENDING_BROADCAST = 1; 1026 static final int MCS_BOUND = 3; 1027 static final int END_COPY = 4; 1028 static final int INIT_COPY = 5; 1029 static final int MCS_UNBIND = 6; 1030 static final int START_CLEANING_PACKAGE = 7; 1031 static final int FIND_INSTALL_LOC = 8; 1032 static final int POST_INSTALL = 9; 1033 static final int MCS_RECONNECT = 10; 1034 static final int MCS_GIVE_UP = 11; 1035 static final int UPDATED_MEDIA_STATUS = 12; 1036 static final int WRITE_SETTINGS = 13; 1037 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1038 static final int PACKAGE_VERIFIED = 15; 1039 static final int CHECK_PENDING_VERIFICATION = 16; 1040 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1041 static final int INTENT_FILTER_VERIFIED = 18; 1042 1043 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1044 1045 // Delay time in millisecs 1046 static final int BROADCAST_DELAY = 10 * 1000; 1047 1048 static UserManagerService sUserManager; 1049 1050 // Stores a list of users whose package restrictions file needs to be updated 1051 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1052 1053 final private DefaultContainerConnection mDefContainerConn = 1054 new DefaultContainerConnection(); 1055 class DefaultContainerConnection implements ServiceConnection { 1056 public void onServiceConnected(ComponentName name, IBinder service) { 1057 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1058 IMediaContainerService imcs = 1059 IMediaContainerService.Stub.asInterface(service); 1060 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1061 } 1062 1063 public void onServiceDisconnected(ComponentName name) { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1065 } 1066 } 1067 1068 // Recordkeeping of restore-after-install operations that are currently in flight 1069 // between the Package Manager and the Backup Manager 1070 static class PostInstallData { 1071 public InstallArgs args; 1072 public PackageInstalledInfo res; 1073 1074 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1075 args = _a; 1076 res = _r; 1077 } 1078 } 1079 1080 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1081 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1082 1083 // XML tags for backup/restore of various bits of state 1084 private static final String TAG_PREFERRED_BACKUP = "pa"; 1085 private static final String TAG_DEFAULT_APPS = "da"; 1086 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1087 1088 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1089 private static final String TAG_ALL_GRANTS = "rt-grants"; 1090 private static final String TAG_GRANT = "grant"; 1091 private static final String ATTR_PACKAGE_NAME = "pkg"; 1092 1093 private static final String TAG_PERMISSION = "perm"; 1094 private static final String ATTR_PERMISSION_NAME = "name"; 1095 private static final String ATTR_IS_GRANTED = "g"; 1096 private static final String ATTR_USER_SET = "set"; 1097 private static final String ATTR_USER_FIXED = "fixed"; 1098 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1099 1100 // System/policy permission grants are not backed up 1101 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1102 FLAG_PERMISSION_POLICY_FIXED 1103 | FLAG_PERMISSION_SYSTEM_FIXED 1104 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1105 1106 // And we back up these user-adjusted states 1107 private static final int USER_RUNTIME_GRANT_MASK = 1108 FLAG_PERMISSION_USER_SET 1109 | FLAG_PERMISSION_USER_FIXED 1110 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1111 1112 final @Nullable String mRequiredVerifierPackage; 1113 final @NonNull String mRequiredInstallerPackage; 1114 final @Nullable String mSetupWizardPackage; 1115 final @NonNull String mServicesSystemSharedLibraryPackageName; 1116 final @NonNull String mSharedSystemSharedLibraryPackageName; 1117 1118 private final PackageUsage mPackageUsage = new PackageUsage(); 1119 1120 private class PackageUsage { 1121 private static final int WRITE_INTERVAL 1122 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1123 1124 private final Object mFileLock = new Object(); 1125 private final AtomicLong mLastWritten = new AtomicLong(0); 1126 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1127 1128 private boolean mIsHistoricalPackageUsageAvailable = true; 1129 1130 boolean isHistoricalPackageUsageAvailable() { 1131 return mIsHistoricalPackageUsageAvailable; 1132 } 1133 1134 void write(boolean force) { 1135 if (force) { 1136 writeInternal(); 1137 return; 1138 } 1139 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1140 && !DEBUG_DEXOPT) { 1141 return; 1142 } 1143 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1144 new Thread("PackageUsage_DiskWriter") { 1145 @Override 1146 public void run() { 1147 try { 1148 writeInternal(); 1149 } finally { 1150 mBackgroundWriteRunning.set(false); 1151 } 1152 } 1153 }.start(); 1154 } 1155 } 1156 1157 private void writeInternal() { 1158 synchronized (mPackages) { 1159 synchronized (mFileLock) { 1160 AtomicFile file = getFile(); 1161 FileOutputStream f = null; 1162 try { 1163 f = file.startWrite(); 1164 BufferedOutputStream out = new BufferedOutputStream(f); 1165 FileUtils.setPermissions(file.getBaseFile().getPath(), 1166 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1167 StringBuilder sb = new StringBuilder(); 1168 1169 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1170 sb.append('\n'); 1171 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1172 1173 for (PackageParser.Package pkg : mPackages.values()) { 1174 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1175 continue; 1176 } 1177 sb.setLength(0); 1178 sb.append(pkg.packageName); 1179 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1180 sb.append(' '); 1181 sb.append(usageTimeInMillis); 1182 } 1183 sb.append('\n'); 1184 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1185 } 1186 out.flush(); 1187 file.finishWrite(f); 1188 } catch (IOException e) { 1189 if (f != null) { 1190 file.failWrite(f); 1191 } 1192 Log.e(TAG, "Failed to write package usage times", e); 1193 } 1194 } 1195 } 1196 mLastWritten.set(SystemClock.elapsedRealtime()); 1197 } 1198 1199 void readLP() { 1200 synchronized (mFileLock) { 1201 AtomicFile file = getFile(); 1202 BufferedInputStream in = null; 1203 try { 1204 in = new BufferedInputStream(file.openRead()); 1205 StringBuffer sb = new StringBuffer(); 1206 1207 String firstLine = readLine(in, sb); 1208 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1209 readVersion1LP(in, sb); 1210 } else { 1211 readVersion0LP(in, sb, firstLine); 1212 } 1213 } catch (FileNotFoundException expected) { 1214 mIsHistoricalPackageUsageAvailable = false; 1215 } catch (IOException e) { 1216 Log.w(TAG, "Failed to read package usage times", e); 1217 } finally { 1218 IoUtils.closeQuietly(in); 1219 } 1220 } 1221 mLastWritten.set(SystemClock.elapsedRealtime()); 1222 } 1223 1224 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1225 throws IOException { 1226 // Initial version of the file had no version number and stored one 1227 // package-timestamp pair per line. 1228 // Note that the first line has already been read from the InputStream. 1229 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1230 String[] tokens = line.split(" "); 1231 if (tokens.length != 2) { 1232 throw new IOException("Failed to parse " + line + 1233 " as package-timestamp pair."); 1234 } 1235 1236 String packageName = tokens[0]; 1237 PackageParser.Package pkg = mPackages.get(packageName); 1238 if (pkg == null) { 1239 continue; 1240 } 1241 1242 long timestamp = parseAsLong(tokens[1]); 1243 for (int reason = 0; 1244 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1245 reason++) { 1246 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1247 } 1248 } 1249 } 1250 1251 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1252 // Version 1 of the file started with the corresponding version 1253 // number and then stored a package name and eight timestamps per line. 1254 String line; 1255 while ((line = readLine(in, sb)) != null) { 1256 String[] tokens = line.split(" "); 1257 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1258 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1259 } 1260 1261 String packageName = tokens[0]; 1262 PackageParser.Package pkg = mPackages.get(packageName); 1263 if (pkg == null) { 1264 continue; 1265 } 1266 1267 for (int reason = 0; 1268 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1269 reason++) { 1270 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1271 } 1272 } 1273 } 1274 1275 private long parseAsLong(String token) throws IOException { 1276 try { 1277 return Long.parseLong(token); 1278 } catch (NumberFormatException e) { 1279 throw new IOException("Failed to parse " + token + " as a long.", e); 1280 } 1281 } 1282 1283 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1284 return readToken(in, sb, '\n'); 1285 } 1286 1287 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1288 throws IOException { 1289 sb.setLength(0); 1290 while (true) { 1291 int ch = in.read(); 1292 if (ch == -1) { 1293 if (sb.length() == 0) { 1294 return null; 1295 } 1296 throw new IOException("Unexpected EOF"); 1297 } 1298 if (ch == endOfToken) { 1299 return sb.toString(); 1300 } 1301 sb.append((char)ch); 1302 } 1303 } 1304 1305 private AtomicFile getFile() { 1306 File dataDir = Environment.getDataDirectory(); 1307 File systemDir = new File(dataDir, "system"); 1308 File fname = new File(systemDir, "package-usage.list"); 1309 return new AtomicFile(fname); 1310 } 1311 1312 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1313 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1314 } 1315 1316 class PackageHandler extends Handler { 1317 private boolean mBound = false; 1318 final ArrayList<HandlerParams> mPendingInstalls = 1319 new ArrayList<HandlerParams>(); 1320 1321 private boolean connectToService() { 1322 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1323 " DefaultContainerService"); 1324 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1325 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1326 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1327 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1329 mBound = true; 1330 return true; 1331 } 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 return false; 1334 } 1335 1336 private void disconnectService() { 1337 mContainerService = null; 1338 mBound = false; 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 mContext.unbindService(mDefContainerConn); 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1342 } 1343 1344 PackageHandler(Looper looper) { 1345 super(looper); 1346 } 1347 1348 public void handleMessage(Message msg) { 1349 try { 1350 doHandleMessage(msg); 1351 } finally { 1352 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1353 } 1354 } 1355 1356 void doHandleMessage(Message msg) { 1357 switch (msg.what) { 1358 case INIT_COPY: { 1359 HandlerParams params = (HandlerParams) msg.obj; 1360 int idx = mPendingInstalls.size(); 1361 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1362 // If a bind was already initiated we dont really 1363 // need to do anything. The pending install 1364 // will be processed later on. 1365 if (!mBound) { 1366 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1367 System.identityHashCode(mHandler)); 1368 // If this is the only one pending we might 1369 // have to bind to the service again. 1370 if (!connectToService()) { 1371 Slog.e(TAG, "Failed to bind to media container service"); 1372 params.serviceError(); 1373 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1374 System.identityHashCode(mHandler)); 1375 if (params.traceMethod != null) { 1376 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1377 params.traceCookie); 1378 } 1379 return; 1380 } else { 1381 // Once we bind to the service, the first 1382 // pending request will be processed. 1383 mPendingInstalls.add(idx, params); 1384 } 1385 } else { 1386 mPendingInstalls.add(idx, params); 1387 // Already bound to the service. Just make 1388 // sure we trigger off processing the first request. 1389 if (idx == 0) { 1390 mHandler.sendEmptyMessage(MCS_BOUND); 1391 } 1392 } 1393 break; 1394 } 1395 case MCS_BOUND: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1397 if (msg.obj != null) { 1398 mContainerService = (IMediaContainerService) msg.obj; 1399 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1400 System.identityHashCode(mHandler)); 1401 } 1402 if (mContainerService == null) { 1403 if (!mBound) { 1404 // Something seriously wrong since we are not bound and we are not 1405 // waiting for connection. Bail out. 1406 Slog.e(TAG, "Cannot bind to media container service"); 1407 for (HandlerParams params : mPendingInstalls) { 1408 // Indicate service bind error 1409 params.serviceError(); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 if (params.traceMethod != null) { 1413 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1414 params.traceMethod, params.traceCookie); 1415 } 1416 return; 1417 } 1418 mPendingInstalls.clear(); 1419 } else { 1420 Slog.w(TAG, "Waiting to connect to media container service"); 1421 } 1422 } else if (mPendingInstalls.size() > 0) { 1423 HandlerParams params = mPendingInstalls.get(0); 1424 if (params != null) { 1425 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1426 System.identityHashCode(params)); 1427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1428 if (params.startCopy()) { 1429 // We are done... look for more work or to 1430 // go idle. 1431 if (DEBUG_SD_INSTALL) Log.i(TAG, 1432 "Checking for more work or unbind..."); 1433 // Delete pending install 1434 if (mPendingInstalls.size() > 0) { 1435 mPendingInstalls.remove(0); 1436 } 1437 if (mPendingInstalls.size() == 0) { 1438 if (mBound) { 1439 if (DEBUG_SD_INSTALL) Log.i(TAG, 1440 "Posting delayed MCS_UNBIND"); 1441 removeMessages(MCS_UNBIND); 1442 Message ubmsg = obtainMessage(MCS_UNBIND); 1443 // Unbind after a little delay, to avoid 1444 // continual thrashing. 1445 sendMessageDelayed(ubmsg, 10000); 1446 } 1447 } else { 1448 // There are more pending requests in queue. 1449 // Just post MCS_BOUND message to trigger processing 1450 // of next pending install. 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, 1452 "Posting MCS_BOUND for next work"); 1453 mHandler.sendEmptyMessage(MCS_BOUND); 1454 } 1455 } 1456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1457 } 1458 } else { 1459 // Should never happen ideally. 1460 Slog.w(TAG, "Empty queue"); 1461 } 1462 break; 1463 } 1464 case MCS_RECONNECT: { 1465 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1466 if (mPendingInstalls.size() > 0) { 1467 if (mBound) { 1468 disconnectService(); 1469 } 1470 if (!connectToService()) { 1471 Slog.e(TAG, "Failed to bind to media container service"); 1472 for (HandlerParams params : mPendingInstalls) { 1473 // Indicate service bind error 1474 params.serviceError(); 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1476 System.identityHashCode(params)); 1477 } 1478 mPendingInstalls.clear(); 1479 } 1480 } 1481 break; 1482 } 1483 case MCS_UNBIND: { 1484 // If there is no actual work left, then time to unbind. 1485 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1486 1487 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1488 if (mBound) { 1489 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1490 1491 disconnectService(); 1492 } 1493 } else if (mPendingInstalls.size() > 0) { 1494 // There are more pending requests in queue. 1495 // Just post MCS_BOUND message to trigger processing 1496 // of next pending install. 1497 mHandler.sendEmptyMessage(MCS_BOUND); 1498 } 1499 1500 break; 1501 } 1502 case MCS_GIVE_UP: { 1503 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1504 HandlerParams params = mPendingInstalls.remove(0); 1505 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1506 System.identityHashCode(params)); 1507 break; 1508 } 1509 case SEND_PENDING_BROADCAST: { 1510 String packages[]; 1511 ArrayList<String> components[]; 1512 int size = 0; 1513 int uids[]; 1514 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1515 synchronized (mPackages) { 1516 if (mPendingBroadcasts == null) { 1517 return; 1518 } 1519 size = mPendingBroadcasts.size(); 1520 if (size <= 0) { 1521 // Nothing to be done. Just return 1522 return; 1523 } 1524 packages = new String[size]; 1525 components = new ArrayList[size]; 1526 uids = new int[size]; 1527 int i = 0; // filling out the above arrays 1528 1529 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1530 int packageUserId = mPendingBroadcasts.userIdAt(n); 1531 Iterator<Map.Entry<String, ArrayList<String>>> it 1532 = mPendingBroadcasts.packagesForUserId(packageUserId) 1533 .entrySet().iterator(); 1534 while (it.hasNext() && i < size) { 1535 Map.Entry<String, ArrayList<String>> ent = it.next(); 1536 packages[i] = ent.getKey(); 1537 components[i] = ent.getValue(); 1538 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1539 uids[i] = (ps != null) 1540 ? UserHandle.getUid(packageUserId, ps.appId) 1541 : -1; 1542 i++; 1543 } 1544 } 1545 size = i; 1546 mPendingBroadcasts.clear(); 1547 } 1548 // Send broadcasts 1549 for (int i = 0; i < size; i++) { 1550 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1551 } 1552 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1553 break; 1554 } 1555 case START_CLEANING_PACKAGE: { 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1557 final String packageName = (String)msg.obj; 1558 final int userId = msg.arg1; 1559 final boolean andCode = msg.arg2 != 0; 1560 synchronized (mPackages) { 1561 if (userId == UserHandle.USER_ALL) { 1562 int[] users = sUserManager.getUserIds(); 1563 for (int user : users) { 1564 mSettings.addPackageToCleanLPw( 1565 new PackageCleanItem(user, packageName, andCode)); 1566 } 1567 } else { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(userId, packageName, andCode)); 1570 } 1571 } 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1573 startCleaningPackages(); 1574 } break; 1575 case POST_INSTALL: { 1576 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1577 1578 PostInstallData data = mRunningInstalls.get(msg.arg1); 1579 final boolean didRestore = (msg.arg2 != 0); 1580 mRunningInstalls.delete(msg.arg1); 1581 1582 if (data != null) { 1583 InstallArgs args = data.args; 1584 PackageInstalledInfo parentRes = data.res; 1585 1586 final boolean grantPermissions = (args.installFlags 1587 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1588 final boolean killApp = (args.installFlags 1589 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1590 final String[] grantedPermissions = args.installGrantPermissions; 1591 1592 // Handle the parent package 1593 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1594 grantedPermissions, didRestore, args.installerPackageName, 1595 args.observer); 1596 1597 // Handle the child packages 1598 final int childCount = (parentRes.addedChildPackages != null) 1599 ? parentRes.addedChildPackages.size() : 0; 1600 for (int i = 0; i < childCount; i++) { 1601 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1602 handlePackagePostInstall(childRes, grantPermissions, killApp, 1603 grantedPermissions, false, args.installerPackageName, 1604 args.observer); 1605 } 1606 1607 // Log tracing if needed 1608 if (args.traceMethod != null) { 1609 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1610 args.traceCookie); 1611 } 1612 } else { 1613 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1614 } 1615 1616 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1617 } break; 1618 case UPDATED_MEDIA_STATUS: { 1619 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1620 boolean reportStatus = msg.arg1 == 1; 1621 boolean doGc = msg.arg2 == 1; 1622 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1623 if (doGc) { 1624 // Force a gc to clear up stale containers. 1625 Runtime.getRuntime().gc(); 1626 } 1627 if (msg.obj != null) { 1628 @SuppressWarnings("unchecked") 1629 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1631 // Unload containers 1632 unloadAllContainers(args); 1633 } 1634 if (reportStatus) { 1635 try { 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1637 PackageHelper.getMountService().finishMediaUpdate(); 1638 } catch (RemoteException e) { 1639 Log.e(TAG, "MountService not running?"); 1640 } 1641 } 1642 } break; 1643 case WRITE_SETTINGS: { 1644 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1645 synchronized (mPackages) { 1646 removeMessages(WRITE_SETTINGS); 1647 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1648 mSettings.writeLPr(); 1649 mDirtyUsers.clear(); 1650 } 1651 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1652 } break; 1653 case WRITE_PACKAGE_RESTRICTIONS: { 1654 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1655 synchronized (mPackages) { 1656 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1657 for (int userId : mDirtyUsers) { 1658 mSettings.writePackageRestrictionsLPr(userId); 1659 } 1660 mDirtyUsers.clear(); 1661 } 1662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1663 } break; 1664 case CHECK_PENDING_VERIFICATION: { 1665 final int verificationId = msg.arg1; 1666 final PackageVerificationState state = mPendingVerification.get(verificationId); 1667 1668 if ((state != null) && !state.timeoutExtended()) { 1669 final InstallArgs args = state.getInstallArgs(); 1670 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1671 1672 Slog.i(TAG, "Verification timed out for " + originUri); 1673 mPendingVerification.remove(verificationId); 1674 1675 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1676 1677 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1678 Slog.i(TAG, "Continuing with installation of " + originUri); 1679 state.setVerifierResponse(Binder.getCallingUid(), 1680 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1681 broadcastPackageVerified(verificationId, originUri, 1682 PackageManager.VERIFICATION_ALLOW, 1683 state.getInstallArgs().getUser()); 1684 try { 1685 ret = args.copyApk(mContainerService, true); 1686 } catch (RemoteException e) { 1687 Slog.e(TAG, "Could not contact the ContainerService"); 1688 } 1689 } else { 1690 broadcastPackageVerified(verificationId, originUri, 1691 PackageManager.VERIFICATION_REJECT, 1692 state.getInstallArgs().getUser()); 1693 } 1694 1695 Trace.asyncTraceEnd( 1696 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1697 1698 processPendingInstall(args, ret); 1699 mHandler.sendEmptyMessage(MCS_UNBIND); 1700 } 1701 break; 1702 } 1703 case PACKAGE_VERIFIED: { 1704 final int verificationId = msg.arg1; 1705 1706 final PackageVerificationState state = mPendingVerification.get(verificationId); 1707 if (state == null) { 1708 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1709 break; 1710 } 1711 1712 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1713 1714 state.setVerifierResponse(response.callerUid, response.code); 1715 1716 if (state.isVerificationComplete()) { 1717 mPendingVerification.remove(verificationId); 1718 1719 final InstallArgs args = state.getInstallArgs(); 1720 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1721 1722 int ret; 1723 if (state.isInstallAllowed()) { 1724 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1725 broadcastPackageVerified(verificationId, originUri, 1726 response.code, state.getInstallArgs().getUser()); 1727 try { 1728 ret = args.copyApk(mContainerService, true); 1729 } catch (RemoteException e) { 1730 Slog.e(TAG, "Could not contact the ContainerService"); 1731 } 1732 } else { 1733 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1734 } 1735 1736 Trace.asyncTraceEnd( 1737 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1738 1739 processPendingInstall(args, ret); 1740 mHandler.sendEmptyMessage(MCS_UNBIND); 1741 } 1742 1743 break; 1744 } 1745 case START_INTENT_FILTER_VERIFICATIONS: { 1746 IFVerificationParams params = (IFVerificationParams) msg.obj; 1747 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1748 params.replacing, params.pkg); 1749 break; 1750 } 1751 case INTENT_FILTER_VERIFIED: { 1752 final int verificationId = msg.arg1; 1753 1754 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1755 verificationId); 1756 if (state == null) { 1757 Slog.w(TAG, "Invalid IntentFilter verification token " 1758 + verificationId + " received"); 1759 break; 1760 } 1761 1762 final int userId = state.getUserId(); 1763 1764 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1765 "Processing IntentFilter verification with token:" 1766 + verificationId + " and userId:" + userId); 1767 1768 final IntentFilterVerificationResponse response = 1769 (IntentFilterVerificationResponse) msg.obj; 1770 1771 state.setVerifierResponse(response.callerUid, response.code); 1772 1773 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1774 "IntentFilter verification with token:" + verificationId 1775 + " and userId:" + userId 1776 + " is settings verifier response with response code:" 1777 + response.code); 1778 1779 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1780 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1781 + response.getFailedDomainsString()); 1782 } 1783 1784 if (state.isVerificationComplete()) { 1785 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1786 } else { 1787 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1788 "IntentFilter verification with token:" + verificationId 1789 + " was not said to be complete"); 1790 } 1791 1792 break; 1793 } 1794 } 1795 } 1796 } 1797 1798 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1799 boolean killApp, String[] grantedPermissions, 1800 boolean launchedForRestore, String installerPackage, 1801 IPackageInstallObserver2 installObserver) { 1802 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1803 // Send the removed broadcasts 1804 if (res.removedInfo != null) { 1805 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1806 } 1807 1808 // Now that we successfully installed the package, grant runtime 1809 // permissions if requested before broadcasting the install. 1810 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1811 >= Build.VERSION_CODES.M) { 1812 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1813 } 1814 1815 final boolean update = res.removedInfo != null 1816 && res.removedInfo.removedPackage != null; 1817 1818 // If this is the first time we have child packages for a disabled privileged 1819 // app that had no children, we grant requested runtime permissions to the new 1820 // children if the parent on the system image had them already granted. 1821 if (res.pkg.parentPackage != null) { 1822 synchronized (mPackages) { 1823 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1824 } 1825 } 1826 1827 synchronized (mPackages) { 1828 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1829 } 1830 1831 final String packageName = res.pkg.applicationInfo.packageName; 1832 Bundle extras = new Bundle(1); 1833 extras.putInt(Intent.EXTRA_UID, res.uid); 1834 1835 // Determine the set of users who are adding this package for 1836 // the first time vs. those who are seeing an update. 1837 int[] firstUsers = EMPTY_INT_ARRAY; 1838 int[] updateUsers = EMPTY_INT_ARRAY; 1839 if (res.origUsers == null || res.origUsers.length == 0) { 1840 firstUsers = res.newUsers; 1841 } else { 1842 for (int newUser : res.newUsers) { 1843 boolean isNew = true; 1844 for (int origUser : res.origUsers) { 1845 if (origUser == newUser) { 1846 isNew = false; 1847 break; 1848 } 1849 } 1850 if (isNew) { 1851 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1852 } else { 1853 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1854 } 1855 } 1856 } 1857 1858 // Send installed broadcasts if the install/update is not ephemeral 1859 if (!isEphemeral(res.pkg)) { 1860 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1861 1862 // Send added for users that see the package for the first time 1863 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1864 extras, 0 /*flags*/, null /*targetPackage*/, 1865 null /*finishedReceiver*/, firstUsers); 1866 1867 // Send added for users that don't see the package for the first time 1868 if (update) { 1869 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1870 } 1871 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1872 extras, 0 /*flags*/, null /*targetPackage*/, 1873 null /*finishedReceiver*/, updateUsers); 1874 1875 // Send replaced for users that don't see the package for the first time 1876 if (update) { 1877 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1878 packageName, extras, 0 /*flags*/, 1879 null /*targetPackage*/, null /*finishedReceiver*/, 1880 updateUsers); 1881 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1882 null /*package*/, null /*extras*/, 0 /*flags*/, 1883 packageName /*targetPackage*/, 1884 null /*finishedReceiver*/, updateUsers); 1885 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1886 // First-install and we did a restore, so we're responsible for the 1887 // first-launch broadcast. 1888 if (DEBUG_BACKUP) { 1889 Slog.i(TAG, "Post-restore of " + packageName 1890 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1891 } 1892 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1893 } 1894 1895 // Send broadcast package appeared if forward locked/external for all users 1896 // treat asec-hosted packages like removable media on upgrade 1897 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1898 if (DEBUG_INSTALL) { 1899 Slog.i(TAG, "upgrading pkg " + res.pkg 1900 + " is ASEC-hosted -> AVAILABLE"); 1901 } 1902 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1903 ArrayList<String> pkgList = new ArrayList<>(1); 1904 pkgList.add(packageName); 1905 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1906 } 1907 } 1908 1909 // Work that needs to happen on first install within each user 1910 if (firstUsers != null && firstUsers.length > 0) { 1911 synchronized (mPackages) { 1912 for (int userId : firstUsers) { 1913 // If this app is a browser and it's newly-installed for some 1914 // users, clear any default-browser state in those users. The 1915 // app's nature doesn't depend on the user, so we can just check 1916 // its browser nature in any user and generalize. 1917 if (packageIsBrowser(packageName, userId)) { 1918 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1919 } 1920 1921 // We may also need to apply pending (restored) runtime 1922 // permission grants within these users. 1923 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1924 } 1925 } 1926 } 1927 1928 // Log current value of "unknown sources" setting 1929 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1930 getUnknownSourcesSettings()); 1931 1932 // Force a gc to clear up things 1933 Runtime.getRuntime().gc(); 1934 1935 // Remove the replaced package's older resources safely now 1936 // We delete after a gc for applications on sdcard. 1937 if (res.removedInfo != null && res.removedInfo.args != null) { 1938 synchronized (mInstallLock) { 1939 res.removedInfo.args.doPostDeleteLI(true); 1940 } 1941 } 1942 } 1943 1944 // If someone is watching installs - notify them 1945 if (installObserver != null) { 1946 try { 1947 Bundle extras = extrasForInstallResult(res); 1948 installObserver.onPackageInstalled(res.name, res.returnCode, 1949 res.returnMsg, extras); 1950 } catch (RemoteException e) { 1951 Slog.i(TAG, "Observer no longer exists."); 1952 } 1953 } 1954 } 1955 1956 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1957 PackageParser.Package pkg) { 1958 if (pkg.parentPackage == null) { 1959 return; 1960 } 1961 if (pkg.requestedPermissions == null) { 1962 return; 1963 } 1964 final PackageSetting disabledSysParentPs = mSettings 1965 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1966 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1967 || !disabledSysParentPs.isPrivileged() 1968 || (disabledSysParentPs.childPackageNames != null 1969 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1970 return; 1971 } 1972 final int[] allUserIds = sUserManager.getUserIds(); 1973 final int permCount = pkg.requestedPermissions.size(); 1974 for (int i = 0; i < permCount; i++) { 1975 String permission = pkg.requestedPermissions.get(i); 1976 BasePermission bp = mSettings.mPermissions.get(permission); 1977 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1978 continue; 1979 } 1980 for (int userId : allUserIds) { 1981 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1982 permission, userId)) { 1983 grantRuntimePermission(pkg.packageName, permission, userId); 1984 } 1985 } 1986 } 1987 } 1988 1989 private StorageEventListener mStorageListener = new StorageEventListener() { 1990 @Override 1991 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1992 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1993 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1994 final String volumeUuid = vol.getFsUuid(); 1995 1996 // Clean up any users or apps that were removed or recreated 1997 // while this volume was missing 1998 reconcileUsers(volumeUuid); 1999 reconcileApps(volumeUuid); 2000 2001 // Clean up any install sessions that expired or were 2002 // cancelled while this volume was missing 2003 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2004 2005 loadPrivatePackages(vol); 2006 2007 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2008 unloadPrivatePackages(vol); 2009 } 2010 } 2011 2012 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2013 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2014 updateExternalMediaStatus(true, false); 2015 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2016 updateExternalMediaStatus(false, false); 2017 } 2018 } 2019 } 2020 2021 @Override 2022 public void onVolumeForgotten(String fsUuid) { 2023 if (TextUtils.isEmpty(fsUuid)) { 2024 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2025 return; 2026 } 2027 2028 // Remove any apps installed on the forgotten volume 2029 synchronized (mPackages) { 2030 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2031 for (PackageSetting ps : packages) { 2032 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2033 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2034 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2035 } 2036 2037 mSettings.onVolumeForgotten(fsUuid); 2038 mSettings.writeLPr(); 2039 } 2040 } 2041 }; 2042 2043 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2044 String[] grantedPermissions) { 2045 for (int userId : userIds) { 2046 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2047 } 2048 2049 // We could have touched GID membership, so flush out packages.list 2050 synchronized (mPackages) { 2051 mSettings.writePackageListLPr(); 2052 } 2053 } 2054 2055 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2056 String[] grantedPermissions) { 2057 SettingBase sb = (SettingBase) pkg.mExtras; 2058 if (sb == null) { 2059 return; 2060 } 2061 2062 PermissionsState permissionsState = sb.getPermissionsState(); 2063 2064 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2065 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2066 2067 for (String permission : pkg.requestedPermissions) { 2068 final BasePermission bp; 2069 synchronized (mPackages) { 2070 bp = mSettings.mPermissions.get(permission); 2071 } 2072 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2073 && (grantedPermissions == null 2074 || ArrayUtils.contains(grantedPermissions, permission))) { 2075 final int flags = permissionsState.getPermissionFlags(permission, userId); 2076 // Installer cannot change immutable permissions. 2077 if ((flags & immutableFlags) == 0) { 2078 grantRuntimePermission(pkg.packageName, permission, userId); 2079 } 2080 } 2081 } 2082 } 2083 2084 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2085 Bundle extras = null; 2086 switch (res.returnCode) { 2087 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2088 extras = new Bundle(); 2089 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2090 res.origPermission); 2091 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2092 res.origPackage); 2093 break; 2094 } 2095 case PackageManager.INSTALL_SUCCEEDED: { 2096 extras = new Bundle(); 2097 extras.putBoolean(Intent.EXTRA_REPLACING, 2098 res.removedInfo != null && res.removedInfo.removedPackage != null); 2099 break; 2100 } 2101 } 2102 return extras; 2103 } 2104 2105 void scheduleWriteSettingsLocked() { 2106 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2107 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2108 } 2109 } 2110 2111 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2112 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2113 scheduleWritePackageRestrictionsLocked(userId); 2114 } 2115 2116 void scheduleWritePackageRestrictionsLocked(int userId) { 2117 final int[] userIds = (userId == UserHandle.USER_ALL) 2118 ? sUserManager.getUserIds() : new int[]{userId}; 2119 for (int nextUserId : userIds) { 2120 if (!sUserManager.exists(nextUserId)) return; 2121 mDirtyUsers.add(nextUserId); 2122 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2123 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2124 } 2125 } 2126 } 2127 2128 public static PackageManagerService main(Context context, Installer installer, 2129 boolean factoryTest, boolean onlyCore) { 2130 // Self-check for initial settings. 2131 PackageManagerServiceCompilerMapping.checkProperties(); 2132 2133 PackageManagerService m = new PackageManagerService(context, installer, 2134 factoryTest, onlyCore); 2135 m.enableSystemUserPackages(); 2136 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2137 // disabled after already being started. 2138 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2139 UserHandle.USER_SYSTEM); 2140 ServiceManager.addService("package", m); 2141 return m; 2142 } 2143 2144 private void enableSystemUserPackages() { 2145 if (!UserManager.isSplitSystemUser()) { 2146 return; 2147 } 2148 // For system user, enable apps based on the following conditions: 2149 // - app is whitelisted or belong to one of these groups: 2150 // -- system app which has no launcher icons 2151 // -- system app which has INTERACT_ACROSS_USERS permission 2152 // -- system IME app 2153 // - app is not in the blacklist 2154 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2155 Set<String> enableApps = new ArraySet<>(); 2156 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2157 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2158 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2159 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2160 enableApps.addAll(wlApps); 2161 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2162 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2163 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2164 enableApps.removeAll(blApps); 2165 Log.i(TAG, "Applications installed for system user: " + enableApps); 2166 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2167 UserHandle.SYSTEM); 2168 final int allAppsSize = allAps.size(); 2169 synchronized (mPackages) { 2170 for (int i = 0; i < allAppsSize; i++) { 2171 String pName = allAps.get(i); 2172 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2173 // Should not happen, but we shouldn't be failing if it does 2174 if (pkgSetting == null) { 2175 continue; 2176 } 2177 boolean install = enableApps.contains(pName); 2178 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2179 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2180 + " for system user"); 2181 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2182 } 2183 } 2184 } 2185 } 2186 2187 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2188 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2189 Context.DISPLAY_SERVICE); 2190 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2191 } 2192 2193 public PackageManagerService(Context context, Installer installer, 2194 boolean factoryTest, boolean onlyCore) { 2195 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2196 SystemClock.uptimeMillis()); 2197 2198 if (mSdkVersion <= 0) { 2199 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2200 } 2201 2202 mContext = context; 2203 mFactoryTest = factoryTest; 2204 mOnlyCore = onlyCore; 2205 mMetrics = new DisplayMetrics(); 2206 mSettings = new Settings(mPackages); 2207 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2208 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2209 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 2220 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2221 if (separateProcesses != null && separateProcesses.length() > 0) { 2222 if ("*".equals(separateProcesses)) { 2223 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2224 mSeparateProcesses = null; 2225 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2226 } else { 2227 mDefParseFlags = 0; 2228 mSeparateProcesses = separateProcesses.split(","); 2229 Slog.w(TAG, "Running with debug.separate_processes: " 2230 + separateProcesses); 2231 } 2232 } else { 2233 mDefParseFlags = 0; 2234 mSeparateProcesses = null; 2235 } 2236 2237 mInstaller = installer; 2238 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2239 "*dexopt*"); 2240 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2241 2242 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2243 FgThread.get().getLooper()); 2244 2245 getDefaultDisplayMetrics(context, mMetrics); 2246 2247 SystemConfig systemConfig = SystemConfig.getInstance(); 2248 mGlobalGids = systemConfig.getGlobalGids(); 2249 mSystemPermissions = systemConfig.getSystemPermissions(); 2250 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2251 2252 synchronized (mInstallLock) { 2253 // writer 2254 synchronized (mPackages) { 2255 mHandlerThread = new ServiceThread(TAG, 2256 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2257 mHandlerThread.start(); 2258 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2259 mProcessLoggingHandler = new ProcessLoggingHandler(); 2260 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2261 2262 File dataDir = Environment.getDataDirectory(); 2263 mAppInstallDir = new File(dataDir, "app"); 2264 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2265 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2266 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2267 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2268 2269 sUserManager = new UserManagerService(context, this, mPackages); 2270 2271 // Propagate permission configuration in to package manager. 2272 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2273 = systemConfig.getPermissions(); 2274 for (int i=0; i<permConfig.size(); i++) { 2275 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2276 BasePermission bp = mSettings.mPermissions.get(perm.name); 2277 if (bp == null) { 2278 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2279 mSettings.mPermissions.put(perm.name, bp); 2280 } 2281 if (perm.gids != null) { 2282 bp.setGids(perm.gids, perm.perUser); 2283 } 2284 } 2285 2286 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2287 for (int i=0; i<libConfig.size(); i++) { 2288 mSharedLibraries.put(libConfig.keyAt(i), 2289 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2290 } 2291 2292 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2293 2294 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2295 2296 String customResolverActivity = Resources.getSystem().getString( 2297 R.string.config_customResolverActivity); 2298 if (TextUtils.isEmpty(customResolverActivity)) { 2299 customResolverActivity = null; 2300 } else { 2301 mCustomResolverComponentName = ComponentName.unflattenFromString( 2302 customResolverActivity); 2303 } 2304 2305 long startTime = SystemClock.uptimeMillis(); 2306 2307 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2308 startTime); 2309 2310 // Set flag to monitor and not change apk file paths when 2311 // scanning install directories. 2312 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2313 2314 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2315 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2316 2317 if (bootClassPath == null) { 2318 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2319 } 2320 2321 if (systemServerClassPath == null) { 2322 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2323 } 2324 2325 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2326 final String[] dexCodeInstructionSets = 2327 getDexCodeInstructionSets( 2328 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2329 2330 /** 2331 * Ensure all external libraries have had dexopt run on them. 2332 */ 2333 if (mSharedLibraries.size() > 0) { 2334 // NOTE: For now, we're compiling these system "shared libraries" 2335 // (and framework jars) into all available architectures. It's possible 2336 // to compile them only when we come across an app that uses them (there's 2337 // already logic for that in scanPackageLI) but that adds some complexity. 2338 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2339 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2340 final String lib = libEntry.path; 2341 if (lib == null) { 2342 continue; 2343 } 2344 2345 try { 2346 // Shared libraries do not have profiles so we perform a full 2347 // AOT compilation (if needed). 2348 int dexoptNeeded = DexFile.getDexOptNeeded( 2349 lib, dexCodeInstructionSet, 2350 getCompilerFilterForReason(REASON_SHARED_APK), 2351 false /* newProfile */); 2352 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2353 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2354 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2355 getCompilerFilterForReason(REASON_SHARED_APK), 2356 StorageManager.UUID_PRIVATE_INTERNAL, 2357 SKIP_SHARED_LIBRARY_CHECK); 2358 } 2359 } catch (FileNotFoundException e) { 2360 Slog.w(TAG, "Library not found: " + lib); 2361 } catch (IOException | InstallerException e) { 2362 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2363 + e.getMessage()); 2364 } 2365 } 2366 } 2367 } 2368 2369 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2370 2371 final VersionInfo ver = mSettings.getInternalVersion(); 2372 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2373 2374 // when upgrading from pre-M, promote system app permissions from install to runtime 2375 mPromoteSystemApps = 2376 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2377 2378 // save off the names of pre-existing system packages prior to scanning; we don't 2379 // want to automatically grant runtime permissions for new system apps 2380 if (mPromoteSystemApps) { 2381 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2382 while (pkgSettingIter.hasNext()) { 2383 PackageSetting ps = pkgSettingIter.next(); 2384 if (isSystemApp(ps)) { 2385 mExistingSystemPackages.add(ps.name); 2386 } 2387 } 2388 } 2389 2390 // When upgrading from pre-N, we need to handle package extraction like first boot, 2391 // as there is no profiling data available. 2392 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2393 mSettings.setNWorkDone(); 2394 2395 // Collect vendor overlay packages. 2396 // (Do this before scanning any apps.) 2397 // For security and version matching reason, only consider 2398 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2399 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2400 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2401 | PackageParser.PARSE_IS_SYSTEM 2402 | PackageParser.PARSE_IS_SYSTEM_DIR 2403 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2404 2405 // Find base frameworks (resource packages without code). 2406 scanDirTracedLI(frameworkDir, mDefParseFlags 2407 | PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR 2409 | PackageParser.PARSE_IS_PRIVILEGED, 2410 scanFlags | SCAN_NO_DEX, 0); 2411 2412 // Collected privileged system packages. 2413 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2414 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2415 | PackageParser.PARSE_IS_SYSTEM 2416 | PackageParser.PARSE_IS_SYSTEM_DIR 2417 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2418 2419 // Collect ordinary system packages. 2420 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2421 scanDirTracedLI(systemAppDir, mDefParseFlags 2422 | PackageParser.PARSE_IS_SYSTEM 2423 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2424 2425 // Collect all vendor packages. 2426 File vendorAppDir = new File("/vendor/app"); 2427 try { 2428 vendorAppDir = vendorAppDir.getCanonicalFile(); 2429 } catch (IOException e) { 2430 // failed to look up canonical path, continue with original one 2431 } 2432 scanDirTracedLI(vendorAppDir, mDefParseFlags 2433 | PackageParser.PARSE_IS_SYSTEM 2434 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2435 2436 // Collect all OEM packages. 2437 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2438 scanDirTracedLI(oemAppDir, mDefParseFlags 2439 | PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2441 2442 // Prune any system packages that no longer exist. 2443 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2444 if (!mOnlyCore) { 2445 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2446 while (psit.hasNext()) { 2447 PackageSetting ps = psit.next(); 2448 2449 /* 2450 * If this is not a system app, it can't be a 2451 * disable system app. 2452 */ 2453 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2454 continue; 2455 } 2456 2457 /* 2458 * If the package is scanned, it's not erased. 2459 */ 2460 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2461 if (scannedPkg != null) { 2462 /* 2463 * If the system app is both scanned and in the 2464 * disabled packages list, then it must have been 2465 * added via OTA. Remove it from the currently 2466 * scanned package so the previously user-installed 2467 * application can be scanned. 2468 */ 2469 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2470 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2471 + ps.name + "; removing system app. Last known codePath=" 2472 + ps.codePathString + ", installStatus=" + ps.installStatus 2473 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2474 + scannedPkg.mVersionCode); 2475 removePackageLI(scannedPkg, true); 2476 mExpectingBetter.put(ps.name, ps.codePath); 2477 } 2478 2479 continue; 2480 } 2481 2482 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2483 psit.remove(); 2484 logCriticalInfo(Log.WARN, "System package " + ps.name 2485 + " no longer exists; it's data will be wiped"); 2486 // Actual deletion of code and data will be handled by later 2487 // reconciliation step 2488 } else { 2489 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2490 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2491 possiblyDeletedUpdatedSystemApps.add(ps.name); 2492 } 2493 } 2494 } 2495 } 2496 2497 //look for any incomplete package installations 2498 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2499 for (int i = 0; i < deletePkgsList.size(); i++) { 2500 // Actual deletion of code and data will be handled by later 2501 // reconciliation step 2502 final String packageName = deletePkgsList.get(i).name; 2503 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2504 synchronized (mPackages) { 2505 mSettings.removePackageLPw(packageName); 2506 } 2507 } 2508 2509 //delete tmp files 2510 deleteTempPackageFiles(); 2511 2512 // Remove any shared userIDs that have no associated packages 2513 mSettings.pruneSharedUsersLPw(); 2514 2515 if (!mOnlyCore) { 2516 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2517 SystemClock.uptimeMillis()); 2518 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2519 2520 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2521 | PackageParser.PARSE_FORWARD_LOCK, 2522 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2525 | PackageParser.PARSE_IS_EPHEMERAL, 2526 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2527 2528 /** 2529 * Remove disable package settings for any updated system 2530 * apps that were removed via an OTA. If they're not a 2531 * previously-updated app, remove them completely. 2532 * Otherwise, just revoke their system-level permissions. 2533 */ 2534 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2535 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2536 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2537 2538 String msg; 2539 if (deletedPkg == null) { 2540 msg = "Updated system package " + deletedAppName 2541 + " no longer exists; it's data will be wiped"; 2542 // Actual deletion of code and data will be handled by later 2543 // reconciliation step 2544 } else { 2545 msg = "Updated system app + " + deletedAppName 2546 + " no longer present; removing system privileges for " 2547 + deletedAppName; 2548 2549 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2550 2551 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2552 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2553 } 2554 logCriticalInfo(Log.WARN, msg); 2555 } 2556 2557 /** 2558 * Make sure all system apps that we expected to appear on 2559 * the userdata partition actually showed up. If they never 2560 * appeared, crawl back and revive the system version. 2561 */ 2562 for (int i = 0; i < mExpectingBetter.size(); i++) { 2563 final String packageName = mExpectingBetter.keyAt(i); 2564 if (!mPackages.containsKey(packageName)) { 2565 final File scanFile = mExpectingBetter.valueAt(i); 2566 2567 logCriticalInfo(Log.WARN, "Expected better " + packageName 2568 + " but never showed up; reverting to system"); 2569 2570 int reparseFlags = mDefParseFlags; 2571 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2572 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2573 | PackageParser.PARSE_IS_SYSTEM_DIR 2574 | PackageParser.PARSE_IS_PRIVILEGED; 2575 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR; 2578 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2579 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2580 | PackageParser.PARSE_IS_SYSTEM_DIR; 2581 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2582 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2583 | PackageParser.PARSE_IS_SYSTEM_DIR; 2584 } else { 2585 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2586 continue; 2587 } 2588 2589 mSettings.enableSystemPackageLPw(packageName); 2590 2591 try { 2592 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2593 } catch (PackageManagerException e) { 2594 Slog.e(TAG, "Failed to parse original system package: " 2595 + e.getMessage()); 2596 } 2597 } 2598 } 2599 } 2600 mExpectingBetter.clear(); 2601 2602 // Resolve protected action filters. Only the setup wizard is allowed to 2603 // have a high priority filter for these actions. 2604 mSetupWizardPackage = getSetupWizardPackageName(); 2605 if (mProtectedFilters.size() > 0) { 2606 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2607 Slog.i(TAG, "No setup wizard;" 2608 + " All protected intents capped to priority 0"); 2609 } 2610 for (ActivityIntentInfo filter : mProtectedFilters) { 2611 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2612 if (DEBUG_FILTERS) { 2613 Slog.i(TAG, "Found setup wizard;" 2614 + " allow priority " + filter.getPriority() + ";" 2615 + " package: " + filter.activity.info.packageName 2616 + " activity: " + filter.activity.className 2617 + " priority: " + filter.getPriority()); 2618 } 2619 // skip setup wizard; allow it to keep the high priority filter 2620 continue; 2621 } 2622 Slog.w(TAG, "Protected action; cap priority to 0;" 2623 + " package: " + filter.activity.info.packageName 2624 + " activity: " + filter.activity.className 2625 + " origPrio: " + filter.getPriority()); 2626 filter.setPriority(0); 2627 } 2628 } 2629 mDeferProtectedFilters = false; 2630 mProtectedFilters.clear(); 2631 2632 // Now that we know all of the shared libraries, update all clients to have 2633 // the correct library paths. 2634 updateAllSharedLibrariesLPw(); 2635 2636 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2637 // NOTE: We ignore potential failures here during a system scan (like 2638 // the rest of the commands above) because there's precious little we 2639 // can do about it. A settings error is reported, though. 2640 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2641 false /* boot complete */); 2642 } 2643 2644 // Now that we know all the packages we are keeping, 2645 // read and update their last usage times. 2646 mPackageUsage.readLP(); 2647 2648 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2649 SystemClock.uptimeMillis()); 2650 Slog.i(TAG, "Time to scan packages: " 2651 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2652 + " seconds"); 2653 2654 // If the platform SDK has changed since the last time we booted, 2655 // we need to re-grant app permission to catch any new ones that 2656 // appear. This is really a hack, and means that apps can in some 2657 // cases get permissions that the user didn't initially explicitly 2658 // allow... it would be nice to have some better way to handle 2659 // this situation. 2660 int updateFlags = UPDATE_PERMISSIONS_ALL; 2661 if (ver.sdkVersion != mSdkVersion) { 2662 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2663 + mSdkVersion + "; regranting permissions for internal storage"); 2664 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2665 } 2666 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2667 ver.sdkVersion = mSdkVersion; 2668 2669 // If this is the first boot or an update from pre-M, and it is a normal 2670 // boot, then we need to initialize the default preferred apps across 2671 // all defined users. 2672 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2673 for (UserInfo user : sUserManager.getUsers(true)) { 2674 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2675 applyFactoryDefaultBrowserLPw(user.id); 2676 primeDomainVerificationsLPw(user.id); 2677 } 2678 } 2679 2680 // Prepare storage for system user really early during boot, 2681 // since core system apps like SettingsProvider and SystemUI 2682 // can't wait for user to start 2683 final int storageFlags; 2684 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2685 storageFlags = StorageManager.FLAG_STORAGE_DE; 2686 } else { 2687 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2688 } 2689 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2690 storageFlags); 2691 2692 // If this is first boot after an OTA, and a normal boot, then 2693 // we need to clear code cache directories. 2694 if (mIsUpgrade && !onlyCore) { 2695 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2696 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2697 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2698 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2699 // No apps are running this early, so no need to freeze 2700 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2701 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2702 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2703 } 2704 clearAppProfilesLIF(ps.pkg); 2705 } 2706 ver.fingerprint = Build.FINGERPRINT; 2707 } 2708 2709 checkDefaultBrowser(); 2710 2711 // clear only after permissions and other defaults have been updated 2712 mExistingSystemPackages.clear(); 2713 mPromoteSystemApps = false; 2714 2715 // All the changes are done during package scanning. 2716 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2717 2718 // can downgrade to reader 2719 mSettings.writeLPr(); 2720 2721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2722 SystemClock.uptimeMillis()); 2723 2724 if (!mOnlyCore) { 2725 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2726 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2727 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2728 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2729 mIntentFilterVerifierComponent); 2730 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2731 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2732 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2733 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2734 } else { 2735 mRequiredVerifierPackage = null; 2736 mRequiredInstallerPackage = null; 2737 mIntentFilterVerifierComponent = null; 2738 mIntentFilterVerifier = null; 2739 mServicesSystemSharedLibraryPackageName = null; 2740 mSharedSystemSharedLibraryPackageName = null; 2741 } 2742 2743 mInstallerService = new PackageInstallerService(context, this); 2744 2745 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2746 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2747 // both the installer and resolver must be present to enable ephemeral 2748 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2749 if (DEBUG_EPHEMERAL) { 2750 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2751 + " installer:" + ephemeralInstallerComponent); 2752 } 2753 mEphemeralResolverComponent = ephemeralResolverComponent; 2754 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2755 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2756 mEphemeralResolverConnection = 2757 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2758 } else { 2759 if (DEBUG_EPHEMERAL) { 2760 final String missingComponent = 2761 (ephemeralResolverComponent == null) 2762 ? (ephemeralInstallerComponent == null) 2763 ? "resolver and installer" 2764 : "resolver" 2765 : "installer"; 2766 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2767 } 2768 mEphemeralResolverComponent = null; 2769 mEphemeralInstallerComponent = null; 2770 mEphemeralResolverConnection = null; 2771 } 2772 2773 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2774 } // synchronized (mPackages) 2775 } // synchronized (mInstallLock) 2776 2777 // Now after opening every single application zip, make sure they 2778 // are all flushed. Not really needed, but keeps things nice and 2779 // tidy. 2780 Runtime.getRuntime().gc(); 2781 2782 // The initial scanning above does many calls into installd while 2783 // holding the mPackages lock, but we're mostly interested in yelling 2784 // once we have a booted system. 2785 mInstaller.setWarnIfHeld(mPackages); 2786 2787 // Expose private service for system components to use. 2788 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2789 } 2790 2791 @Override 2792 public boolean isFirstBoot() { 2793 return !mRestoredSettings; 2794 } 2795 2796 @Override 2797 public boolean isOnlyCoreApps() { 2798 return mOnlyCore; 2799 } 2800 2801 @Override 2802 public boolean isUpgrade() { 2803 return mIsUpgrade; 2804 } 2805 2806 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2807 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2808 2809 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2810 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2811 UserHandle.USER_SYSTEM); 2812 if (matches.size() == 1) { 2813 return matches.get(0).getComponentInfo().packageName; 2814 } else { 2815 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2816 return null; 2817 } 2818 } 2819 2820 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2821 synchronized (mPackages) { 2822 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2823 if (libraryEntry == null) { 2824 throw new IllegalStateException("Missing required shared library:" + libraryName); 2825 } 2826 return libraryEntry.apk; 2827 } 2828 } 2829 2830 private @NonNull String getRequiredInstallerLPr() { 2831 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2832 intent.addCategory(Intent.CATEGORY_DEFAULT); 2833 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2834 2835 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2836 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2837 UserHandle.USER_SYSTEM); 2838 if (matches.size() == 1) { 2839 ResolveInfo resolveInfo = matches.get(0); 2840 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2841 throw new RuntimeException("The installer must be a privileged app"); 2842 } 2843 return matches.get(0).getComponentInfo().packageName; 2844 } else { 2845 throw new RuntimeException("There must be exactly one installer; found " + matches); 2846 } 2847 } 2848 2849 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2850 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2851 2852 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2853 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2854 UserHandle.USER_SYSTEM); 2855 ResolveInfo best = null; 2856 final int N = matches.size(); 2857 for (int i = 0; i < N; i++) { 2858 final ResolveInfo cur = matches.get(i); 2859 final String packageName = cur.getComponentInfo().packageName; 2860 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2861 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2862 continue; 2863 } 2864 2865 if (best == null || cur.priority > best.priority) { 2866 best = cur; 2867 } 2868 } 2869 2870 if (best != null) { 2871 return best.getComponentInfo().getComponentName(); 2872 } else { 2873 throw new RuntimeException("There must be at least one intent filter verifier"); 2874 } 2875 } 2876 2877 private @Nullable ComponentName getEphemeralResolverLPr() { 2878 final String[] packageArray = 2879 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2880 if (packageArray.length == 0) { 2881 if (DEBUG_EPHEMERAL) { 2882 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2883 } 2884 return null; 2885 } 2886 2887 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2888 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2889 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2890 UserHandle.USER_SYSTEM); 2891 2892 final int N = resolvers.size(); 2893 if (N == 0) { 2894 if (DEBUG_EPHEMERAL) { 2895 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2896 } 2897 return null; 2898 } 2899 2900 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2901 for (int i = 0; i < N; i++) { 2902 final ResolveInfo info = resolvers.get(i); 2903 2904 if (info.serviceInfo == null) { 2905 continue; 2906 } 2907 2908 final String packageName = info.serviceInfo.packageName; 2909 if (!possiblePackages.contains(packageName)) { 2910 if (DEBUG_EPHEMERAL) { 2911 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2912 + " pkg: " + packageName + ", info:" + info); 2913 } 2914 continue; 2915 } 2916 2917 if (DEBUG_EPHEMERAL) { 2918 Slog.v(TAG, "Ephemeral resolver found;" 2919 + " pkg: " + packageName + ", info:" + info); 2920 } 2921 return new ComponentName(packageName, info.serviceInfo.name); 2922 } 2923 if (DEBUG_EPHEMERAL) { 2924 Slog.v(TAG, "Ephemeral resolver NOT found"); 2925 } 2926 return null; 2927 } 2928 2929 private @Nullable ComponentName getEphemeralInstallerLPr() { 2930 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2931 intent.addCategory(Intent.CATEGORY_DEFAULT); 2932 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2933 2934 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2935 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2936 UserHandle.USER_SYSTEM); 2937 if (matches.size() == 0) { 2938 return null; 2939 } else if (matches.size() == 1) { 2940 return matches.get(0).getComponentInfo().getComponentName(); 2941 } else { 2942 throw new RuntimeException( 2943 "There must be at most one ephemeral installer; found " + matches); 2944 } 2945 } 2946 2947 private void primeDomainVerificationsLPw(int userId) { 2948 if (DEBUG_DOMAIN_VERIFICATION) { 2949 Slog.d(TAG, "Priming domain verifications in user " + userId); 2950 } 2951 2952 SystemConfig systemConfig = SystemConfig.getInstance(); 2953 ArraySet<String> packages = systemConfig.getLinkedApps(); 2954 ArraySet<String> domains = new ArraySet<String>(); 2955 2956 for (String packageName : packages) { 2957 PackageParser.Package pkg = mPackages.get(packageName); 2958 if (pkg != null) { 2959 if (!pkg.isSystemApp()) { 2960 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2961 continue; 2962 } 2963 2964 domains.clear(); 2965 for (PackageParser.Activity a : pkg.activities) { 2966 for (ActivityIntentInfo filter : a.intents) { 2967 if (hasValidDomains(filter)) { 2968 domains.addAll(filter.getHostsList()); 2969 } 2970 } 2971 } 2972 2973 if (domains.size() > 0) { 2974 if (DEBUG_DOMAIN_VERIFICATION) { 2975 Slog.v(TAG, " + " + packageName); 2976 } 2977 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2978 // state w.r.t. the formal app-linkage "no verification attempted" state; 2979 // and then 'always' in the per-user state actually used for intent resolution. 2980 final IntentFilterVerificationInfo ivi; 2981 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2982 new ArrayList<String>(domains)); 2983 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2984 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2985 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2986 } else { 2987 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2988 + "' does not handle web links"); 2989 } 2990 } else { 2991 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2992 } 2993 } 2994 2995 scheduleWritePackageRestrictionsLocked(userId); 2996 scheduleWriteSettingsLocked(); 2997 } 2998 2999 private void applyFactoryDefaultBrowserLPw(int userId) { 3000 // The default browser app's package name is stored in a string resource, 3001 // with a product-specific overlay used for vendor customization. 3002 String browserPkg = mContext.getResources().getString( 3003 com.android.internal.R.string.default_browser); 3004 if (!TextUtils.isEmpty(browserPkg)) { 3005 // non-empty string => required to be a known package 3006 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3007 if (ps == null) { 3008 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3009 browserPkg = null; 3010 } else { 3011 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3012 } 3013 } 3014 3015 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3016 // default. If there's more than one, just leave everything alone. 3017 if (browserPkg == null) { 3018 calculateDefaultBrowserLPw(userId); 3019 } 3020 } 3021 3022 private void calculateDefaultBrowserLPw(int userId) { 3023 List<String> allBrowsers = resolveAllBrowserApps(userId); 3024 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3025 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3026 } 3027 3028 private List<String> resolveAllBrowserApps(int userId) { 3029 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3030 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3031 PackageManager.MATCH_ALL, userId); 3032 3033 final int count = list.size(); 3034 List<String> result = new ArrayList<String>(count); 3035 for (int i=0; i<count; i++) { 3036 ResolveInfo info = list.get(i); 3037 if (info.activityInfo == null 3038 || !info.handleAllWebDataURI 3039 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3040 || result.contains(info.activityInfo.packageName)) { 3041 continue; 3042 } 3043 result.add(info.activityInfo.packageName); 3044 } 3045 3046 return result; 3047 } 3048 3049 private boolean packageIsBrowser(String packageName, int userId) { 3050 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3051 PackageManager.MATCH_ALL, userId); 3052 final int N = list.size(); 3053 for (int i = 0; i < N; i++) { 3054 ResolveInfo info = list.get(i); 3055 if (packageName.equals(info.activityInfo.packageName)) { 3056 return true; 3057 } 3058 } 3059 return false; 3060 } 3061 3062 private void checkDefaultBrowser() { 3063 final int myUserId = UserHandle.myUserId(); 3064 final String packageName = getDefaultBrowserPackageName(myUserId); 3065 if (packageName != null) { 3066 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3067 if (info == null) { 3068 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3069 synchronized (mPackages) { 3070 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3071 } 3072 } 3073 } 3074 } 3075 3076 @Override 3077 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3078 throws RemoteException { 3079 try { 3080 return super.onTransact(code, data, reply, flags); 3081 } catch (RuntimeException e) { 3082 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3083 Slog.wtf(TAG, "Package Manager Crash", e); 3084 } 3085 throw e; 3086 } 3087 } 3088 3089 static int[] appendInts(int[] cur, int[] add) { 3090 if (add == null) return cur; 3091 if (cur == null) return add; 3092 final int N = add.length; 3093 for (int i=0; i<N; i++) { 3094 cur = appendInt(cur, add[i]); 3095 } 3096 return cur; 3097 } 3098 3099 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3100 if (!sUserManager.exists(userId)) return null; 3101 if (ps == null) { 3102 return null; 3103 } 3104 final PackageParser.Package p = ps.pkg; 3105 if (p == null) { 3106 return null; 3107 } 3108 3109 final PermissionsState permissionsState = ps.getPermissionsState(); 3110 3111 final int[] gids = permissionsState.computeGids(userId); 3112 final Set<String> permissions = permissionsState.getPermissions(userId); 3113 final PackageUserState state = ps.readUserState(userId); 3114 3115 return PackageParser.generatePackageInfo(p, gids, flags, 3116 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3117 } 3118 3119 @Override 3120 public void checkPackageStartable(String packageName, int userId) { 3121 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3122 3123 synchronized (mPackages) { 3124 final PackageSetting ps = mSettings.mPackages.get(packageName); 3125 if (ps == null) { 3126 throw new SecurityException("Package " + packageName + " was not found!"); 3127 } 3128 3129 if (!ps.getInstalled(userId)) { 3130 throw new SecurityException( 3131 "Package " + packageName + " was not installed for user " + userId + "!"); 3132 } 3133 3134 if (mSafeMode && !ps.isSystem()) { 3135 throw new SecurityException("Package " + packageName + " not a system app!"); 3136 } 3137 3138 if (mFrozenPackages.contains(packageName)) { 3139 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3140 } 3141 3142 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3143 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3144 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3145 } 3146 } 3147 } 3148 3149 @Override 3150 public boolean isPackageAvailable(String packageName, int userId) { 3151 if (!sUserManager.exists(userId)) return false; 3152 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3153 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3154 synchronized (mPackages) { 3155 PackageParser.Package p = mPackages.get(packageName); 3156 if (p != null) { 3157 final PackageSetting ps = (PackageSetting) p.mExtras; 3158 if (ps != null) { 3159 final PackageUserState state = ps.readUserState(userId); 3160 if (state != null) { 3161 return PackageParser.isAvailable(state); 3162 } 3163 } 3164 } 3165 } 3166 return false; 3167 } 3168 3169 @Override 3170 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3171 if (!sUserManager.exists(userId)) return null; 3172 flags = updateFlagsForPackage(flags, userId, packageName); 3173 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3174 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3175 // reader 3176 synchronized (mPackages) { 3177 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3178 PackageParser.Package p = null; 3179 if (matchFactoryOnly) { 3180 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3181 if (ps != null) { 3182 return generatePackageInfo(ps, flags, userId); 3183 } 3184 } 3185 if (p == null) { 3186 p = mPackages.get(packageName); 3187 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3188 return null; 3189 } 3190 } 3191 if (DEBUG_PACKAGE_INFO) 3192 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3193 if (p != null) { 3194 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3195 } 3196 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3197 final PackageSetting ps = mSettings.mPackages.get(packageName); 3198 return generatePackageInfo(ps, flags, userId); 3199 } 3200 } 3201 return null; 3202 } 3203 3204 @Override 3205 public String[] currentToCanonicalPackageNames(String[] names) { 3206 String[] out = new String[names.length]; 3207 // reader 3208 synchronized (mPackages) { 3209 for (int i=names.length-1; i>=0; i--) { 3210 PackageSetting ps = mSettings.mPackages.get(names[i]); 3211 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3212 } 3213 } 3214 return out; 3215 } 3216 3217 @Override 3218 public String[] canonicalToCurrentPackageNames(String[] names) { 3219 String[] out = new String[names.length]; 3220 // reader 3221 synchronized (mPackages) { 3222 for (int i=names.length-1; i>=0; i--) { 3223 String cur = mSettings.mRenamedPackages.get(names[i]); 3224 out[i] = cur != null ? cur : names[i]; 3225 } 3226 } 3227 return out; 3228 } 3229 3230 @Override 3231 public int getPackageUid(String packageName, int flags, int userId) { 3232 if (!sUserManager.exists(userId)) return -1; 3233 flags = updateFlagsForPackage(flags, userId, packageName); 3234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3235 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3236 3237 // reader 3238 synchronized (mPackages) { 3239 final PackageParser.Package p = mPackages.get(packageName); 3240 if (p != null && p.isMatch(flags)) { 3241 return UserHandle.getUid(userId, p.applicationInfo.uid); 3242 } 3243 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3244 final PackageSetting ps = mSettings.mPackages.get(packageName); 3245 if (ps != null && ps.isMatch(flags)) { 3246 return UserHandle.getUid(userId, ps.appId); 3247 } 3248 } 3249 } 3250 3251 return -1; 3252 } 3253 3254 @Override 3255 public int[] getPackageGids(String packageName, int flags, int userId) { 3256 if (!sUserManager.exists(userId)) return null; 3257 flags = updateFlagsForPackage(flags, userId, packageName); 3258 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3259 false /* requireFullPermission */, false /* checkShell */, 3260 "getPackageGids"); 3261 3262 // reader 3263 synchronized (mPackages) { 3264 final PackageParser.Package p = mPackages.get(packageName); 3265 if (p != null && p.isMatch(flags)) { 3266 PackageSetting ps = (PackageSetting) p.mExtras; 3267 return ps.getPermissionsState().computeGids(userId); 3268 } 3269 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3270 final PackageSetting ps = mSettings.mPackages.get(packageName); 3271 if (ps != null && ps.isMatch(flags)) { 3272 return ps.getPermissionsState().computeGids(userId); 3273 } 3274 } 3275 } 3276 3277 return null; 3278 } 3279 3280 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3281 if (bp.perm != null) { 3282 return PackageParser.generatePermissionInfo(bp.perm, flags); 3283 } 3284 PermissionInfo pi = new PermissionInfo(); 3285 pi.name = bp.name; 3286 pi.packageName = bp.sourcePackage; 3287 pi.nonLocalizedLabel = bp.name; 3288 pi.protectionLevel = bp.protectionLevel; 3289 return pi; 3290 } 3291 3292 @Override 3293 public PermissionInfo getPermissionInfo(String name, int flags) { 3294 // reader 3295 synchronized (mPackages) { 3296 final BasePermission p = mSettings.mPermissions.get(name); 3297 if (p != null) { 3298 return generatePermissionInfo(p, flags); 3299 } 3300 return null; 3301 } 3302 } 3303 3304 @Override 3305 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3306 int flags) { 3307 // reader 3308 synchronized (mPackages) { 3309 if (group != null && !mPermissionGroups.containsKey(group)) { 3310 // This is thrown as NameNotFoundException 3311 return null; 3312 } 3313 3314 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3315 for (BasePermission p : mSettings.mPermissions.values()) { 3316 if (group == null) { 3317 if (p.perm == null || p.perm.info.group == null) { 3318 out.add(generatePermissionInfo(p, flags)); 3319 } 3320 } else { 3321 if (p.perm != null && group.equals(p.perm.info.group)) { 3322 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3323 } 3324 } 3325 } 3326 return new ParceledListSlice<>(out); 3327 } 3328 } 3329 3330 @Override 3331 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3332 // reader 3333 synchronized (mPackages) { 3334 return PackageParser.generatePermissionGroupInfo( 3335 mPermissionGroups.get(name), flags); 3336 } 3337 } 3338 3339 @Override 3340 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3341 // reader 3342 synchronized (mPackages) { 3343 final int N = mPermissionGroups.size(); 3344 ArrayList<PermissionGroupInfo> out 3345 = new ArrayList<PermissionGroupInfo>(N); 3346 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3347 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3348 } 3349 return new ParceledListSlice<>(out); 3350 } 3351 } 3352 3353 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3354 int userId) { 3355 if (!sUserManager.exists(userId)) return null; 3356 PackageSetting ps = mSettings.mPackages.get(packageName); 3357 if (ps != null) { 3358 if (ps.pkg == null) { 3359 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3360 if (pInfo != null) { 3361 return pInfo.applicationInfo; 3362 } 3363 return null; 3364 } 3365 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3366 ps.readUserState(userId), userId); 3367 } 3368 return null; 3369 } 3370 3371 @Override 3372 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3373 if (!sUserManager.exists(userId)) return null; 3374 flags = updateFlagsForApplication(flags, userId, packageName); 3375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3376 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3377 // writer 3378 synchronized (mPackages) { 3379 PackageParser.Package p = mPackages.get(packageName); 3380 if (DEBUG_PACKAGE_INFO) Log.v( 3381 TAG, "getApplicationInfo " + packageName 3382 + ": " + p); 3383 if (p != null) { 3384 PackageSetting ps = mSettings.mPackages.get(packageName); 3385 if (ps == null) return null; 3386 // Note: isEnabledLP() does not apply here - always return info 3387 return PackageParser.generateApplicationInfo( 3388 p, flags, ps.readUserState(userId), userId); 3389 } 3390 if ("android".equals(packageName)||"system".equals(packageName)) { 3391 return mAndroidApplication; 3392 } 3393 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3394 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3395 } 3396 } 3397 return null; 3398 } 3399 3400 @Override 3401 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3402 final IPackageDataObserver observer) { 3403 mContext.enforceCallingOrSelfPermission( 3404 android.Manifest.permission.CLEAR_APP_CACHE, null); 3405 // Queue up an async operation since clearing cache may take a little while. 3406 mHandler.post(new Runnable() { 3407 public void run() { 3408 mHandler.removeCallbacks(this); 3409 boolean success = true; 3410 synchronized (mInstallLock) { 3411 try { 3412 mInstaller.freeCache(volumeUuid, freeStorageSize); 3413 } catch (InstallerException e) { 3414 Slog.w(TAG, "Couldn't clear application caches: " + e); 3415 success = false; 3416 } 3417 } 3418 if (observer != null) { 3419 try { 3420 observer.onRemoveCompleted(null, success); 3421 } catch (RemoteException e) { 3422 Slog.w(TAG, "RemoveException when invoking call back"); 3423 } 3424 } 3425 } 3426 }); 3427 } 3428 3429 @Override 3430 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3431 final IntentSender pi) { 3432 mContext.enforceCallingOrSelfPermission( 3433 android.Manifest.permission.CLEAR_APP_CACHE, null); 3434 // Queue up an async operation since clearing cache may take a little while. 3435 mHandler.post(new Runnable() { 3436 public void run() { 3437 mHandler.removeCallbacks(this); 3438 boolean success = true; 3439 synchronized (mInstallLock) { 3440 try { 3441 mInstaller.freeCache(volumeUuid, freeStorageSize); 3442 } catch (InstallerException e) { 3443 Slog.w(TAG, "Couldn't clear application caches: " + e); 3444 success = false; 3445 } 3446 } 3447 if(pi != null) { 3448 try { 3449 // Callback via pending intent 3450 int code = success ? 1 : 0; 3451 pi.sendIntent(null, code, null, 3452 null, null); 3453 } catch (SendIntentException e1) { 3454 Slog.i(TAG, "Failed to send pending intent"); 3455 } 3456 } 3457 } 3458 }); 3459 } 3460 3461 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3462 synchronized (mInstallLock) { 3463 try { 3464 mInstaller.freeCache(volumeUuid, freeStorageSize); 3465 } catch (InstallerException e) { 3466 throw new IOException("Failed to free enough space", e); 3467 } 3468 } 3469 } 3470 3471 /** 3472 * Update given flags based on encryption status of current user. 3473 */ 3474 private int updateFlags(int flags, int userId) { 3475 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3476 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3477 // Caller expressed an explicit opinion about what encryption 3478 // aware/unaware components they want to see, so fall through and 3479 // give them what they want 3480 } else { 3481 // Caller expressed no opinion, so match based on user state 3482 if (StorageManager.isUserKeyUnlocked(userId)) { 3483 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3484 } else { 3485 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3486 } 3487 } 3488 return flags; 3489 } 3490 3491 /** 3492 * Update given flags when being used to request {@link PackageInfo}. 3493 */ 3494 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3495 boolean triaged = true; 3496 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3497 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3498 // Caller is asking for component details, so they'd better be 3499 // asking for specific encryption matching behavior, or be triaged 3500 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3501 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3502 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3503 triaged = false; 3504 } 3505 } 3506 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3507 | PackageManager.MATCH_SYSTEM_ONLY 3508 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3509 triaged = false; 3510 } 3511 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3512 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3513 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3514 } 3515 return updateFlags(flags, userId); 3516 } 3517 3518 /** 3519 * Update given flags when being used to request {@link ApplicationInfo}. 3520 */ 3521 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3522 return updateFlagsForPackage(flags, userId, cookie); 3523 } 3524 3525 /** 3526 * Update given flags when being used to request {@link ComponentInfo}. 3527 */ 3528 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3529 if (cookie instanceof Intent) { 3530 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3531 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3532 } 3533 } 3534 3535 boolean triaged = true; 3536 // Caller is asking for component details, so they'd better be 3537 // asking for specific encryption matching behavior, or be triaged 3538 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3539 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3540 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3541 triaged = false; 3542 } 3543 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3544 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3545 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3546 } 3547 3548 return updateFlags(flags, userId); 3549 } 3550 3551 /** 3552 * Update given flags when being used to request {@link ResolveInfo}. 3553 */ 3554 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3555 // Safe mode means we shouldn't match any third-party components 3556 if (mSafeMode) { 3557 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3558 } 3559 3560 return updateFlagsForComponent(flags, userId, cookie); 3561 } 3562 3563 @Override 3564 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3565 if (!sUserManager.exists(userId)) return null; 3566 flags = updateFlagsForComponent(flags, userId, component); 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3568 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3569 synchronized (mPackages) { 3570 PackageParser.Activity a = mActivities.mActivities.get(component); 3571 3572 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3573 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3574 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3575 if (ps == null) return null; 3576 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3577 userId); 3578 } 3579 if (mResolveComponentName.equals(component)) { 3580 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3581 new PackageUserState(), userId); 3582 } 3583 } 3584 return null; 3585 } 3586 3587 @Override 3588 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3589 String resolvedType) { 3590 synchronized (mPackages) { 3591 if (component.equals(mResolveComponentName)) { 3592 // The resolver supports EVERYTHING! 3593 return true; 3594 } 3595 PackageParser.Activity a = mActivities.mActivities.get(component); 3596 if (a == null) { 3597 return false; 3598 } 3599 for (int i=0; i<a.intents.size(); i++) { 3600 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3601 intent.getData(), intent.getCategories(), TAG) >= 0) { 3602 return true; 3603 } 3604 } 3605 return false; 3606 } 3607 } 3608 3609 @Override 3610 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3611 if (!sUserManager.exists(userId)) return null; 3612 flags = updateFlagsForComponent(flags, userId, component); 3613 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3614 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3615 synchronized (mPackages) { 3616 PackageParser.Activity a = mReceivers.mActivities.get(component); 3617 if (DEBUG_PACKAGE_INFO) Log.v( 3618 TAG, "getReceiverInfo " + component + ": " + a); 3619 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3620 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3621 if (ps == null) return null; 3622 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3623 userId); 3624 } 3625 } 3626 return null; 3627 } 3628 3629 @Override 3630 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3631 if (!sUserManager.exists(userId)) return null; 3632 flags = updateFlagsForComponent(flags, userId, component); 3633 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3634 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3635 synchronized (mPackages) { 3636 PackageParser.Service s = mServices.mServices.get(component); 3637 if (DEBUG_PACKAGE_INFO) Log.v( 3638 TAG, "getServiceInfo " + component + ": " + s); 3639 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3640 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3641 if (ps == null) return null; 3642 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3643 userId); 3644 } 3645 } 3646 return null; 3647 } 3648 3649 @Override 3650 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3651 if (!sUserManager.exists(userId)) return null; 3652 flags = updateFlagsForComponent(flags, userId, component); 3653 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3654 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3655 synchronized (mPackages) { 3656 PackageParser.Provider p = mProviders.mProviders.get(component); 3657 if (DEBUG_PACKAGE_INFO) Log.v( 3658 TAG, "getProviderInfo " + component + ": " + p); 3659 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3660 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3661 if (ps == null) return null; 3662 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3663 userId); 3664 } 3665 } 3666 return null; 3667 } 3668 3669 @Override 3670 public String[] getSystemSharedLibraryNames() { 3671 Set<String> libSet; 3672 synchronized (mPackages) { 3673 libSet = mSharedLibraries.keySet(); 3674 int size = libSet.size(); 3675 if (size > 0) { 3676 String[] libs = new String[size]; 3677 libSet.toArray(libs); 3678 return libs; 3679 } 3680 } 3681 return null; 3682 } 3683 3684 @Override 3685 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3686 synchronized (mPackages) { 3687 return mServicesSystemSharedLibraryPackageName; 3688 } 3689 } 3690 3691 @Override 3692 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3693 synchronized (mPackages) { 3694 return mSharedSystemSharedLibraryPackageName; 3695 } 3696 } 3697 3698 @Override 3699 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3700 synchronized (mPackages) { 3701 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3702 3703 final FeatureInfo fi = new FeatureInfo(); 3704 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3705 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3706 res.add(fi); 3707 3708 return new ParceledListSlice<>(res); 3709 } 3710 } 3711 3712 @Override 3713 public boolean hasSystemFeature(String name, int version) { 3714 synchronized (mPackages) { 3715 final FeatureInfo feat = mAvailableFeatures.get(name); 3716 if (feat == null) { 3717 return false; 3718 } else { 3719 return feat.version >= version; 3720 } 3721 } 3722 } 3723 3724 @Override 3725 public int checkPermission(String permName, String pkgName, int userId) { 3726 if (!sUserManager.exists(userId)) { 3727 return PackageManager.PERMISSION_DENIED; 3728 } 3729 3730 synchronized (mPackages) { 3731 final PackageParser.Package p = mPackages.get(pkgName); 3732 if (p != null && p.mExtras != null) { 3733 final PackageSetting ps = (PackageSetting) p.mExtras; 3734 final PermissionsState permissionsState = ps.getPermissionsState(); 3735 if (permissionsState.hasPermission(permName, userId)) { 3736 return PackageManager.PERMISSION_GRANTED; 3737 } 3738 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3739 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3740 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3741 return PackageManager.PERMISSION_GRANTED; 3742 } 3743 } 3744 } 3745 3746 return PackageManager.PERMISSION_DENIED; 3747 } 3748 3749 @Override 3750 public int checkUidPermission(String permName, int uid) { 3751 final int userId = UserHandle.getUserId(uid); 3752 3753 if (!sUserManager.exists(userId)) { 3754 return PackageManager.PERMISSION_DENIED; 3755 } 3756 3757 synchronized (mPackages) { 3758 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3759 if (obj != null) { 3760 final SettingBase ps = (SettingBase) obj; 3761 final PermissionsState permissionsState = ps.getPermissionsState(); 3762 if (permissionsState.hasPermission(permName, userId)) { 3763 return PackageManager.PERMISSION_GRANTED; 3764 } 3765 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3766 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3767 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 } else { 3771 ArraySet<String> perms = mSystemPermissions.get(uid); 3772 if (perms != null) { 3773 if (perms.contains(permName)) { 3774 return PackageManager.PERMISSION_GRANTED; 3775 } 3776 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3777 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3778 return PackageManager.PERMISSION_GRANTED; 3779 } 3780 } 3781 } 3782 } 3783 3784 return PackageManager.PERMISSION_DENIED; 3785 } 3786 3787 @Override 3788 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3789 if (UserHandle.getCallingUserId() != userId) { 3790 mContext.enforceCallingPermission( 3791 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3792 "isPermissionRevokedByPolicy for user " + userId); 3793 } 3794 3795 if (checkPermission(permission, packageName, userId) 3796 == PackageManager.PERMISSION_GRANTED) { 3797 return false; 3798 } 3799 3800 final long identity = Binder.clearCallingIdentity(); 3801 try { 3802 final int flags = getPermissionFlags(permission, packageName, userId); 3803 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3804 } finally { 3805 Binder.restoreCallingIdentity(identity); 3806 } 3807 } 3808 3809 @Override 3810 public String getPermissionControllerPackageName() { 3811 synchronized (mPackages) { 3812 return mRequiredInstallerPackage; 3813 } 3814 } 3815 3816 /** 3817 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3818 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3819 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3820 * @param message the message to log on security exception 3821 */ 3822 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3823 boolean checkShell, String message) { 3824 if (userId < 0) { 3825 throw new IllegalArgumentException("Invalid userId " + userId); 3826 } 3827 if (checkShell) { 3828 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3829 } 3830 if (userId == UserHandle.getUserId(callingUid)) return; 3831 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3832 if (requireFullPermission) { 3833 mContext.enforceCallingOrSelfPermission( 3834 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3835 } else { 3836 try { 3837 mContext.enforceCallingOrSelfPermission( 3838 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3839 } catch (SecurityException se) { 3840 mContext.enforceCallingOrSelfPermission( 3841 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3842 } 3843 } 3844 } 3845 } 3846 3847 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3848 if (callingUid == Process.SHELL_UID) { 3849 if (userHandle >= 0 3850 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3851 throw new SecurityException("Shell does not have permission to access user " 3852 + userHandle); 3853 } else if (userHandle < 0) { 3854 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3855 + Debug.getCallers(3)); 3856 } 3857 } 3858 } 3859 3860 private BasePermission findPermissionTreeLP(String permName) { 3861 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3862 if (permName.startsWith(bp.name) && 3863 permName.length() > bp.name.length() && 3864 permName.charAt(bp.name.length()) == '.') { 3865 return bp; 3866 } 3867 } 3868 return null; 3869 } 3870 3871 private BasePermission checkPermissionTreeLP(String permName) { 3872 if (permName != null) { 3873 BasePermission bp = findPermissionTreeLP(permName); 3874 if (bp != null) { 3875 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3876 return bp; 3877 } 3878 throw new SecurityException("Calling uid " 3879 + Binder.getCallingUid() 3880 + " is not allowed to add to permission tree " 3881 + bp.name + " owned by uid " + bp.uid); 3882 } 3883 } 3884 throw new SecurityException("No permission tree found for " + permName); 3885 } 3886 3887 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3888 if (s1 == null) { 3889 return s2 == null; 3890 } 3891 if (s2 == null) { 3892 return false; 3893 } 3894 if (s1.getClass() != s2.getClass()) { 3895 return false; 3896 } 3897 return s1.equals(s2); 3898 } 3899 3900 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3901 if (pi1.icon != pi2.icon) return false; 3902 if (pi1.logo != pi2.logo) return false; 3903 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3904 if (!compareStrings(pi1.name, pi2.name)) return false; 3905 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3906 // We'll take care of setting this one. 3907 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3908 // These are not currently stored in settings. 3909 //if (!compareStrings(pi1.group, pi2.group)) return false; 3910 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3911 //if (pi1.labelRes != pi2.labelRes) return false; 3912 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3913 return true; 3914 } 3915 3916 int permissionInfoFootprint(PermissionInfo info) { 3917 int size = info.name.length(); 3918 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3919 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3920 return size; 3921 } 3922 3923 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3924 int size = 0; 3925 for (BasePermission perm : mSettings.mPermissions.values()) { 3926 if (perm.uid == tree.uid) { 3927 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3928 } 3929 } 3930 return size; 3931 } 3932 3933 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3934 // We calculate the max size of permissions defined by this uid and throw 3935 // if that plus the size of 'info' would exceed our stated maximum. 3936 if (tree.uid != Process.SYSTEM_UID) { 3937 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3938 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3939 throw new SecurityException("Permission tree size cap exceeded"); 3940 } 3941 } 3942 } 3943 3944 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3945 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3946 throw new SecurityException("Label must be specified in permission"); 3947 } 3948 BasePermission tree = checkPermissionTreeLP(info.name); 3949 BasePermission bp = mSettings.mPermissions.get(info.name); 3950 boolean added = bp == null; 3951 boolean changed = true; 3952 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3953 if (added) { 3954 enforcePermissionCapLocked(info, tree); 3955 bp = new BasePermission(info.name, tree.sourcePackage, 3956 BasePermission.TYPE_DYNAMIC); 3957 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3958 throw new SecurityException( 3959 "Not allowed to modify non-dynamic permission " 3960 + info.name); 3961 } else { 3962 if (bp.protectionLevel == fixedLevel 3963 && bp.perm.owner.equals(tree.perm.owner) 3964 && bp.uid == tree.uid 3965 && comparePermissionInfos(bp.perm.info, info)) { 3966 changed = false; 3967 } 3968 } 3969 bp.protectionLevel = fixedLevel; 3970 info = new PermissionInfo(info); 3971 info.protectionLevel = fixedLevel; 3972 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3973 bp.perm.info.packageName = tree.perm.info.packageName; 3974 bp.uid = tree.uid; 3975 if (added) { 3976 mSettings.mPermissions.put(info.name, bp); 3977 } 3978 if (changed) { 3979 if (!async) { 3980 mSettings.writeLPr(); 3981 } else { 3982 scheduleWriteSettingsLocked(); 3983 } 3984 } 3985 return added; 3986 } 3987 3988 @Override 3989 public boolean addPermission(PermissionInfo info) { 3990 synchronized (mPackages) { 3991 return addPermissionLocked(info, false); 3992 } 3993 } 3994 3995 @Override 3996 public boolean addPermissionAsync(PermissionInfo info) { 3997 synchronized (mPackages) { 3998 return addPermissionLocked(info, true); 3999 } 4000 } 4001 4002 @Override 4003 public void removePermission(String name) { 4004 synchronized (mPackages) { 4005 checkPermissionTreeLP(name); 4006 BasePermission bp = mSettings.mPermissions.get(name); 4007 if (bp != null) { 4008 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4009 throw new SecurityException( 4010 "Not allowed to modify non-dynamic permission " 4011 + name); 4012 } 4013 mSettings.mPermissions.remove(name); 4014 mSettings.writeLPr(); 4015 } 4016 } 4017 } 4018 4019 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4020 BasePermission bp) { 4021 int index = pkg.requestedPermissions.indexOf(bp.name); 4022 if (index == -1) { 4023 throw new SecurityException("Package " + pkg.packageName 4024 + " has not requested permission " + bp.name); 4025 } 4026 if (!bp.isRuntime() && !bp.isDevelopment()) { 4027 throw new SecurityException("Permission " + bp.name 4028 + " is not a changeable permission type"); 4029 } 4030 } 4031 4032 @Override 4033 public void grantRuntimePermission(String packageName, String name, final int userId) { 4034 if (!sUserManager.exists(userId)) { 4035 Log.e(TAG, "No such user:" + userId); 4036 return; 4037 } 4038 4039 mContext.enforceCallingOrSelfPermission( 4040 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4041 "grantRuntimePermission"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4044 true /* requireFullPermission */, true /* checkShell */, 4045 "grantRuntimePermission"); 4046 4047 final int uid; 4048 final SettingBase sb; 4049 4050 synchronized (mPackages) { 4051 final PackageParser.Package pkg = mPackages.get(packageName); 4052 if (pkg == null) { 4053 throw new IllegalArgumentException("Unknown package: " + packageName); 4054 } 4055 4056 final BasePermission bp = mSettings.mPermissions.get(name); 4057 if (bp == null) { 4058 throw new IllegalArgumentException("Unknown permission: " + name); 4059 } 4060 4061 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4062 4063 // If a permission review is required for legacy apps we represent 4064 // their permissions as always granted runtime ones since we need 4065 // to keep the review required permission flag per user while an 4066 // install permission's state is shared across all users. 4067 if (Build.PERMISSIONS_REVIEW_REQUIRED 4068 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4069 && bp.isRuntime()) { 4070 return; 4071 } 4072 4073 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4074 sb = (SettingBase) pkg.mExtras; 4075 if (sb == null) { 4076 throw new IllegalArgumentException("Unknown package: " + packageName); 4077 } 4078 4079 final PermissionsState permissionsState = sb.getPermissionsState(); 4080 4081 final int flags = permissionsState.getPermissionFlags(name, userId); 4082 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4083 throw new SecurityException("Cannot grant system fixed permission " 4084 + name + " for package " + packageName); 4085 } 4086 4087 if (bp.isDevelopment()) { 4088 // Development permissions must be handled specially, since they are not 4089 // normal runtime permissions. For now they apply to all users. 4090 if (permissionsState.grantInstallPermission(bp) != 4091 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4092 scheduleWriteSettingsLocked(); 4093 } 4094 return; 4095 } 4096 4097 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4098 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4099 return; 4100 } 4101 4102 final int result = permissionsState.grantRuntimePermission(bp, userId); 4103 switch (result) { 4104 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4105 return; 4106 } 4107 4108 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4109 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4110 mHandler.post(new Runnable() { 4111 @Override 4112 public void run() { 4113 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4114 } 4115 }); 4116 } 4117 break; 4118 } 4119 4120 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4121 4122 // Not critical if that is lost - app has to request again. 4123 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4124 } 4125 4126 // Only need to do this if user is initialized. Otherwise it's a new user 4127 // and there are no processes running as the user yet and there's no need 4128 // to make an expensive call to remount processes for the changed permissions. 4129 if (READ_EXTERNAL_STORAGE.equals(name) 4130 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4131 final long token = Binder.clearCallingIdentity(); 4132 try { 4133 if (sUserManager.isInitialized(userId)) { 4134 MountServiceInternal mountServiceInternal = LocalServices.getService( 4135 MountServiceInternal.class); 4136 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4137 } 4138 } finally { 4139 Binder.restoreCallingIdentity(token); 4140 } 4141 } 4142 } 4143 4144 @Override 4145 public void revokeRuntimePermission(String packageName, String name, int userId) { 4146 if (!sUserManager.exists(userId)) { 4147 Log.e(TAG, "No such user:" + userId); 4148 return; 4149 } 4150 4151 mContext.enforceCallingOrSelfPermission( 4152 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4153 "revokeRuntimePermission"); 4154 4155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4156 true /* requireFullPermission */, true /* checkShell */, 4157 "revokeRuntimePermission"); 4158 4159 final int appId; 4160 4161 synchronized (mPackages) { 4162 final PackageParser.Package pkg = mPackages.get(packageName); 4163 if (pkg == null) { 4164 throw new IllegalArgumentException("Unknown package: " + packageName); 4165 } 4166 4167 final BasePermission bp = mSettings.mPermissions.get(name); 4168 if (bp == null) { 4169 throw new IllegalArgumentException("Unknown permission: " + name); 4170 } 4171 4172 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4173 4174 // If a permission review is required for legacy apps we represent 4175 // their permissions as always granted runtime ones since we need 4176 // to keep the review required permission flag per user while an 4177 // install permission's state is shared across all users. 4178 if (Build.PERMISSIONS_REVIEW_REQUIRED 4179 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4180 && bp.isRuntime()) { 4181 return; 4182 } 4183 4184 SettingBase sb = (SettingBase) pkg.mExtras; 4185 if (sb == null) { 4186 throw new IllegalArgumentException("Unknown package: " + packageName); 4187 } 4188 4189 final PermissionsState permissionsState = sb.getPermissionsState(); 4190 4191 final int flags = permissionsState.getPermissionFlags(name, userId); 4192 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4193 throw new SecurityException("Cannot revoke system fixed permission " 4194 + name + " for package " + packageName); 4195 } 4196 4197 if (bp.isDevelopment()) { 4198 // Development permissions must be handled specially, since they are not 4199 // normal runtime permissions. For now they apply to all users. 4200 if (permissionsState.revokeInstallPermission(bp) != 4201 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4202 scheduleWriteSettingsLocked(); 4203 } 4204 return; 4205 } 4206 4207 if (permissionsState.revokeRuntimePermission(bp, userId) == 4208 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4209 return; 4210 } 4211 4212 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4213 4214 // Critical, after this call app should never have the permission. 4215 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4216 4217 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4218 } 4219 4220 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4221 } 4222 4223 @Override 4224 public void resetRuntimePermissions() { 4225 mContext.enforceCallingOrSelfPermission( 4226 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4227 "revokeRuntimePermission"); 4228 4229 int callingUid = Binder.getCallingUid(); 4230 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4231 mContext.enforceCallingOrSelfPermission( 4232 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4233 "resetRuntimePermissions"); 4234 } 4235 4236 synchronized (mPackages) { 4237 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4238 for (int userId : UserManagerService.getInstance().getUserIds()) { 4239 final int packageCount = mPackages.size(); 4240 for (int i = 0; i < packageCount; i++) { 4241 PackageParser.Package pkg = mPackages.valueAt(i); 4242 if (!(pkg.mExtras instanceof PackageSetting)) { 4243 continue; 4244 } 4245 PackageSetting ps = (PackageSetting) pkg.mExtras; 4246 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4247 } 4248 } 4249 } 4250 } 4251 4252 @Override 4253 public int getPermissionFlags(String name, String packageName, int userId) { 4254 if (!sUserManager.exists(userId)) { 4255 return 0; 4256 } 4257 4258 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4259 4260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4261 true /* requireFullPermission */, false /* checkShell */, 4262 "getPermissionFlags"); 4263 4264 synchronized (mPackages) { 4265 final PackageParser.Package pkg = mPackages.get(packageName); 4266 if (pkg == null) { 4267 return 0; 4268 } 4269 4270 final BasePermission bp = mSettings.mPermissions.get(name); 4271 if (bp == null) { 4272 return 0; 4273 } 4274 4275 SettingBase sb = (SettingBase) pkg.mExtras; 4276 if (sb == null) { 4277 return 0; 4278 } 4279 4280 PermissionsState permissionsState = sb.getPermissionsState(); 4281 return permissionsState.getPermissionFlags(name, userId); 4282 } 4283 } 4284 4285 @Override 4286 public void updatePermissionFlags(String name, String packageName, int flagMask, 4287 int flagValues, int userId) { 4288 if (!sUserManager.exists(userId)) { 4289 return; 4290 } 4291 4292 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4293 4294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4295 true /* requireFullPermission */, true /* checkShell */, 4296 "updatePermissionFlags"); 4297 4298 // Only the system can change these flags and nothing else. 4299 if (getCallingUid() != Process.SYSTEM_UID) { 4300 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4301 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4304 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4305 } 4306 4307 synchronized (mPackages) { 4308 final PackageParser.Package pkg = mPackages.get(packageName); 4309 if (pkg == null) { 4310 throw new IllegalArgumentException("Unknown package: " + packageName); 4311 } 4312 4313 final BasePermission bp = mSettings.mPermissions.get(name); 4314 if (bp == null) { 4315 throw new IllegalArgumentException("Unknown permission: " + name); 4316 } 4317 4318 SettingBase sb = (SettingBase) pkg.mExtras; 4319 if (sb == null) { 4320 throw new IllegalArgumentException("Unknown package: " + packageName); 4321 } 4322 4323 PermissionsState permissionsState = sb.getPermissionsState(); 4324 4325 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4326 4327 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4328 // Install and runtime permissions are stored in different places, 4329 // so figure out what permission changed and persist the change. 4330 if (permissionsState.getInstallPermissionState(name) != null) { 4331 scheduleWriteSettingsLocked(); 4332 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4333 || hadState) { 4334 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4335 } 4336 } 4337 } 4338 } 4339 4340 /** 4341 * Update the permission flags for all packages and runtime permissions of a user in order 4342 * to allow device or profile owner to remove POLICY_FIXED. 4343 */ 4344 @Override 4345 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4346 if (!sUserManager.exists(userId)) { 4347 return; 4348 } 4349 4350 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4351 4352 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4353 true /* requireFullPermission */, true /* checkShell */, 4354 "updatePermissionFlagsForAllApps"); 4355 4356 // Only the system can change system fixed flags. 4357 if (getCallingUid() != Process.SYSTEM_UID) { 4358 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4359 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4360 } 4361 4362 synchronized (mPackages) { 4363 boolean changed = false; 4364 final int packageCount = mPackages.size(); 4365 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4366 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4367 SettingBase sb = (SettingBase) pkg.mExtras; 4368 if (sb == null) { 4369 continue; 4370 } 4371 PermissionsState permissionsState = sb.getPermissionsState(); 4372 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4373 userId, flagMask, flagValues); 4374 } 4375 if (changed) { 4376 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4377 } 4378 } 4379 } 4380 4381 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4382 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4383 != PackageManager.PERMISSION_GRANTED 4384 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4385 != PackageManager.PERMISSION_GRANTED) { 4386 throw new SecurityException(message + " requires " 4387 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4388 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4389 } 4390 } 4391 4392 @Override 4393 public boolean shouldShowRequestPermissionRationale(String permissionName, 4394 String packageName, int userId) { 4395 if (UserHandle.getCallingUserId() != userId) { 4396 mContext.enforceCallingPermission( 4397 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4398 "canShowRequestPermissionRationale for user " + userId); 4399 } 4400 4401 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4402 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4403 return false; 4404 } 4405 4406 if (checkPermission(permissionName, packageName, userId) 4407 == PackageManager.PERMISSION_GRANTED) { 4408 return false; 4409 } 4410 4411 final int flags; 4412 4413 final long identity = Binder.clearCallingIdentity(); 4414 try { 4415 flags = getPermissionFlags(permissionName, 4416 packageName, userId); 4417 } finally { 4418 Binder.restoreCallingIdentity(identity); 4419 } 4420 4421 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4422 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4423 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4424 4425 if ((flags & fixedFlags) != 0) { 4426 return false; 4427 } 4428 4429 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4430 } 4431 4432 @Override 4433 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4434 mContext.enforceCallingOrSelfPermission( 4435 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4436 "addOnPermissionsChangeListener"); 4437 4438 synchronized (mPackages) { 4439 mOnPermissionChangeListeners.addListenerLocked(listener); 4440 } 4441 } 4442 4443 @Override 4444 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4445 synchronized (mPackages) { 4446 mOnPermissionChangeListeners.removeListenerLocked(listener); 4447 } 4448 } 4449 4450 @Override 4451 public boolean isProtectedBroadcast(String actionName) { 4452 synchronized (mPackages) { 4453 if (mProtectedBroadcasts.contains(actionName)) { 4454 return true; 4455 } else if (actionName != null) { 4456 // TODO: remove these terrible hacks 4457 if (actionName.startsWith("android.net.netmon.lingerExpired") 4458 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4459 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4460 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4461 return true; 4462 } 4463 } 4464 } 4465 return false; 4466 } 4467 4468 @Override 4469 public int checkSignatures(String pkg1, String pkg2) { 4470 synchronized (mPackages) { 4471 final PackageParser.Package p1 = mPackages.get(pkg1); 4472 final PackageParser.Package p2 = mPackages.get(pkg2); 4473 if (p1 == null || p1.mExtras == null 4474 || p2 == null || p2.mExtras == null) { 4475 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4476 } 4477 return compareSignatures(p1.mSignatures, p2.mSignatures); 4478 } 4479 } 4480 4481 @Override 4482 public int checkUidSignatures(int uid1, int uid2) { 4483 // Map to base uids. 4484 uid1 = UserHandle.getAppId(uid1); 4485 uid2 = UserHandle.getAppId(uid2); 4486 // reader 4487 synchronized (mPackages) { 4488 Signature[] s1; 4489 Signature[] s2; 4490 Object obj = mSettings.getUserIdLPr(uid1); 4491 if (obj != null) { 4492 if (obj instanceof SharedUserSetting) { 4493 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4494 } else if (obj instanceof PackageSetting) { 4495 s1 = ((PackageSetting)obj).signatures.mSignatures; 4496 } else { 4497 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4498 } 4499 } else { 4500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4501 } 4502 obj = mSettings.getUserIdLPr(uid2); 4503 if (obj != null) { 4504 if (obj instanceof SharedUserSetting) { 4505 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4506 } else if (obj instanceof PackageSetting) { 4507 s2 = ((PackageSetting)obj).signatures.mSignatures; 4508 } else { 4509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4510 } 4511 } else { 4512 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4513 } 4514 return compareSignatures(s1, s2); 4515 } 4516 } 4517 4518 /** 4519 * This method should typically only be used when granting or revoking 4520 * permissions, since the app may immediately restart after this call. 4521 * <p> 4522 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4523 * guard your work against the app being relaunched. 4524 */ 4525 private void killUid(int appId, int userId, String reason) { 4526 final long identity = Binder.clearCallingIdentity(); 4527 try { 4528 IActivityManager am = ActivityManagerNative.getDefault(); 4529 if (am != null) { 4530 try { 4531 am.killUid(appId, userId, reason); 4532 } catch (RemoteException e) { 4533 /* ignore - same process */ 4534 } 4535 } 4536 } finally { 4537 Binder.restoreCallingIdentity(identity); 4538 } 4539 } 4540 4541 /** 4542 * Compares two sets of signatures. Returns: 4543 * <br /> 4544 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4553 */ 4554 static int compareSignatures(Signature[] s1, Signature[] s2) { 4555 if (s1 == null) { 4556 return s2 == null 4557 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4558 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4559 } 4560 4561 if (s2 == null) { 4562 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4563 } 4564 4565 if (s1.length != s2.length) { 4566 return PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 // Since both signature sets are of size 1, we can compare without HashSets. 4570 if (s1.length == 1) { 4571 return s1[0].equals(s2[0]) ? 4572 PackageManager.SIGNATURE_MATCH : 4573 PackageManager.SIGNATURE_NO_MATCH; 4574 } 4575 4576 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4577 for (Signature sig : s1) { 4578 set1.add(sig); 4579 } 4580 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4581 for (Signature sig : s2) { 4582 set2.add(sig); 4583 } 4584 // Make sure s2 contains all signatures in s1. 4585 if (set1.equals(set2)) { 4586 return PackageManager.SIGNATURE_MATCH; 4587 } 4588 return PackageManager.SIGNATURE_NO_MATCH; 4589 } 4590 4591 /** 4592 * If the database version for this type of package (internal storage or 4593 * external storage) is less than the version where package signatures 4594 * were updated, return true. 4595 */ 4596 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4597 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4598 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4599 } 4600 4601 /** 4602 * Used for backward compatibility to make sure any packages with 4603 * certificate chains get upgraded to the new style. {@code existingSigs} 4604 * will be in the old format (since they were stored on disk from before the 4605 * system upgrade) and {@code scannedSigs} will be in the newer format. 4606 */ 4607 private int compareSignaturesCompat(PackageSignatures existingSigs, 4608 PackageParser.Package scannedPkg) { 4609 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4610 return PackageManager.SIGNATURE_NO_MATCH; 4611 } 4612 4613 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4614 for (Signature sig : existingSigs.mSignatures) { 4615 existingSet.add(sig); 4616 } 4617 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4618 for (Signature sig : scannedPkg.mSignatures) { 4619 try { 4620 Signature[] chainSignatures = sig.getChainSignatures(); 4621 for (Signature chainSig : chainSignatures) { 4622 scannedCompatSet.add(chainSig); 4623 } 4624 } catch (CertificateEncodingException e) { 4625 scannedCompatSet.add(sig); 4626 } 4627 } 4628 /* 4629 * Make sure the expanded scanned set contains all signatures in the 4630 * existing one. 4631 */ 4632 if (scannedCompatSet.equals(existingSet)) { 4633 // Migrate the old signatures to the new scheme. 4634 existingSigs.assignSignatures(scannedPkg.mSignatures); 4635 // The new KeySets will be re-added later in the scanning process. 4636 synchronized (mPackages) { 4637 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4638 } 4639 return PackageManager.SIGNATURE_MATCH; 4640 } 4641 return PackageManager.SIGNATURE_NO_MATCH; 4642 } 4643 4644 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4645 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4646 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4647 } 4648 4649 private int compareSignaturesRecover(PackageSignatures existingSigs, 4650 PackageParser.Package scannedPkg) { 4651 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4652 return PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 String msg = null; 4656 try { 4657 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4658 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4659 + scannedPkg.packageName); 4660 return PackageManager.SIGNATURE_MATCH; 4661 } 4662 } catch (CertificateException e) { 4663 msg = e.getMessage(); 4664 } 4665 4666 logCriticalInfo(Log.INFO, 4667 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4668 return PackageManager.SIGNATURE_NO_MATCH; 4669 } 4670 4671 @Override 4672 public List<String> getAllPackages() { 4673 synchronized (mPackages) { 4674 return new ArrayList<String>(mPackages.keySet()); 4675 } 4676 } 4677 4678 @Override 4679 public String[] getPackagesForUid(int uid) { 4680 uid = UserHandle.getAppId(uid); 4681 // reader 4682 synchronized (mPackages) { 4683 Object obj = mSettings.getUserIdLPr(uid); 4684 if (obj instanceof SharedUserSetting) { 4685 final SharedUserSetting sus = (SharedUserSetting) obj; 4686 final int N = sus.packages.size(); 4687 final String[] res = new String[N]; 4688 final Iterator<PackageSetting> it = sus.packages.iterator(); 4689 int i = 0; 4690 while (it.hasNext()) { 4691 res[i++] = it.next().name; 4692 } 4693 return res; 4694 } else if (obj instanceof PackageSetting) { 4695 final PackageSetting ps = (PackageSetting) obj; 4696 return new String[] { ps.name }; 4697 } 4698 } 4699 return null; 4700 } 4701 4702 @Override 4703 public String getNameForUid(int uid) { 4704 // reader 4705 synchronized (mPackages) { 4706 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4707 if (obj instanceof SharedUserSetting) { 4708 final SharedUserSetting sus = (SharedUserSetting) obj; 4709 return sus.name + ":" + sus.userId; 4710 } else if (obj instanceof PackageSetting) { 4711 final PackageSetting ps = (PackageSetting) obj; 4712 return ps.name; 4713 } 4714 } 4715 return null; 4716 } 4717 4718 @Override 4719 public int getUidForSharedUser(String sharedUserName) { 4720 if(sharedUserName == null) { 4721 return -1; 4722 } 4723 // reader 4724 synchronized (mPackages) { 4725 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4726 if (suid == null) { 4727 return -1; 4728 } 4729 return suid.userId; 4730 } 4731 } 4732 4733 @Override 4734 public int getFlagsForUid(int uid) { 4735 synchronized (mPackages) { 4736 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4737 if (obj instanceof SharedUserSetting) { 4738 final SharedUserSetting sus = (SharedUserSetting) obj; 4739 return sus.pkgFlags; 4740 } else if (obj instanceof PackageSetting) { 4741 final PackageSetting ps = (PackageSetting) obj; 4742 return ps.pkgFlags; 4743 } 4744 } 4745 return 0; 4746 } 4747 4748 @Override 4749 public int getPrivateFlagsForUid(int uid) { 4750 synchronized (mPackages) { 4751 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4752 if (obj instanceof SharedUserSetting) { 4753 final SharedUserSetting sus = (SharedUserSetting) obj; 4754 return sus.pkgPrivateFlags; 4755 } else if (obj instanceof PackageSetting) { 4756 final PackageSetting ps = (PackageSetting) obj; 4757 return ps.pkgPrivateFlags; 4758 } 4759 } 4760 return 0; 4761 } 4762 4763 @Override 4764 public boolean isUidPrivileged(int uid) { 4765 uid = UserHandle.getAppId(uid); 4766 // reader 4767 synchronized (mPackages) { 4768 Object obj = mSettings.getUserIdLPr(uid); 4769 if (obj instanceof SharedUserSetting) { 4770 final SharedUserSetting sus = (SharedUserSetting) obj; 4771 final Iterator<PackageSetting> it = sus.packages.iterator(); 4772 while (it.hasNext()) { 4773 if (it.next().isPrivileged()) { 4774 return true; 4775 } 4776 } 4777 } else if (obj instanceof PackageSetting) { 4778 final PackageSetting ps = (PackageSetting) obj; 4779 return ps.isPrivileged(); 4780 } 4781 } 4782 return false; 4783 } 4784 4785 @Override 4786 public String[] getAppOpPermissionPackages(String permissionName) { 4787 synchronized (mPackages) { 4788 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4789 if (pkgs == null) { 4790 return null; 4791 } 4792 return pkgs.toArray(new String[pkgs.size()]); 4793 } 4794 } 4795 4796 @Override 4797 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4798 int flags, int userId) { 4799 try { 4800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4801 4802 if (!sUserManager.exists(userId)) return null; 4803 flags = updateFlagsForResolve(flags, userId, intent); 4804 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4805 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4806 4807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4808 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4809 flags, userId); 4810 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4811 4812 final ResolveInfo bestChoice = 4813 chooseBestActivity(intent, resolvedType, flags, query, userId); 4814 4815 if (isEphemeralAllowed(intent, query, userId)) { 4816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4817 final EphemeralResolveInfo ai = 4818 getEphemeralResolveInfo(intent, resolvedType, userId); 4819 if (ai != null) { 4820 if (DEBUG_EPHEMERAL) { 4821 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4822 } 4823 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4824 bestChoice.ephemeralResolveInfo = ai; 4825 } 4826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4827 } 4828 return bestChoice; 4829 } finally { 4830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4831 } 4832 } 4833 4834 @Override 4835 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4836 IntentFilter filter, int match, ComponentName activity) { 4837 final int userId = UserHandle.getCallingUserId(); 4838 if (DEBUG_PREFERRED) { 4839 Log.v(TAG, "setLastChosenActivity intent=" + intent 4840 + " resolvedType=" + resolvedType 4841 + " flags=" + flags 4842 + " filter=" + filter 4843 + " match=" + match 4844 + " activity=" + activity); 4845 filter.dump(new PrintStreamPrinter(System.out), " "); 4846 } 4847 intent.setComponent(null); 4848 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4849 userId); 4850 // Find any earlier preferred or last chosen entries and nuke them 4851 findPreferredActivity(intent, resolvedType, 4852 flags, query, 0, false, true, false, userId); 4853 // Add the new activity as the last chosen for this filter 4854 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4855 "Setting last chosen"); 4856 } 4857 4858 @Override 4859 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4860 final int userId = UserHandle.getCallingUserId(); 4861 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4862 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4863 userId); 4864 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4865 false, false, false, userId); 4866 } 4867 4868 4869 private boolean isEphemeralAllowed( 4870 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4871 // Short circuit and return early if possible. 4872 if (DISABLE_EPHEMERAL_APPS) { 4873 return false; 4874 } 4875 final int callingUser = UserHandle.getCallingUserId(); 4876 if (callingUser != UserHandle.USER_SYSTEM) { 4877 return false; 4878 } 4879 if (mEphemeralResolverConnection == null) { 4880 return false; 4881 } 4882 if (intent.getComponent() != null) { 4883 return false; 4884 } 4885 if (intent.getPackage() != null) { 4886 return false; 4887 } 4888 final boolean isWebUri = hasWebURI(intent); 4889 if (!isWebUri) { 4890 return false; 4891 } 4892 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4893 synchronized (mPackages) { 4894 final int count = resolvedActivites.size(); 4895 for (int n = 0; n < count; n++) { 4896 ResolveInfo info = resolvedActivites.get(n); 4897 String packageName = info.activityInfo.packageName; 4898 PackageSetting ps = mSettings.mPackages.get(packageName); 4899 if (ps != null) { 4900 // Try to get the status from User settings first 4901 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4902 int status = (int) (packedStatus >> 32); 4903 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4904 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4905 if (DEBUG_EPHEMERAL) { 4906 Slog.v(TAG, "DENY ephemeral apps;" 4907 + " pkg: " + packageName + ", status: " + status); 4908 } 4909 return false; 4910 } 4911 } 4912 } 4913 } 4914 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4915 return true; 4916 } 4917 4918 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4919 int userId) { 4920 MessageDigest digest = null; 4921 try { 4922 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4923 } catch (NoSuchAlgorithmException e) { 4924 // If we can't create a digest, ignore ephemeral apps. 4925 return null; 4926 } 4927 4928 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4929 final byte[] digestBytes = digest.digest(hostBytes); 4930 int shaPrefix = 4931 digestBytes[0] << 24 4932 | digestBytes[1] << 16 4933 | digestBytes[2] << 8 4934 | digestBytes[3] << 0; 4935 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4936 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4937 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4938 // No hash prefix match; there are no ephemeral apps for this domain. 4939 return null; 4940 } 4941 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4942 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4943 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4944 continue; 4945 } 4946 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4947 // No filters; this should never happen. 4948 if (filters.isEmpty()) { 4949 continue; 4950 } 4951 // We have a domain match; resolve the filters to see if anything matches. 4952 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4953 for (int j = filters.size() - 1; j >= 0; --j) { 4954 final EphemeralResolveIntentInfo intentInfo = 4955 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4956 ephemeralResolver.addFilter(intentInfo); 4957 } 4958 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4959 intent, resolvedType, false /*defaultOnly*/, userId); 4960 if (!matchedResolveInfoList.isEmpty()) { 4961 return matchedResolveInfoList.get(0); 4962 } 4963 } 4964 // Hash or filter mis-match; no ephemeral apps for this domain. 4965 return null; 4966 } 4967 4968 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4969 int flags, List<ResolveInfo> query, int userId) { 4970 if (query != null) { 4971 final int N = query.size(); 4972 if (N == 1) { 4973 return query.get(0); 4974 } else if (N > 1) { 4975 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4976 // If there is more than one activity with the same priority, 4977 // then let the user decide between them. 4978 ResolveInfo r0 = query.get(0); 4979 ResolveInfo r1 = query.get(1); 4980 if (DEBUG_INTENT_MATCHING || debug) { 4981 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4982 + r1.activityInfo.name + "=" + r1.priority); 4983 } 4984 // If the first activity has a higher priority, or a different 4985 // default, then it is always desirable to pick it. 4986 if (r0.priority != r1.priority 4987 || r0.preferredOrder != r1.preferredOrder 4988 || r0.isDefault != r1.isDefault) { 4989 return query.get(0); 4990 } 4991 // If we have saved a preference for a preferred activity for 4992 // this Intent, use that. 4993 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4994 flags, query, r0.priority, true, false, debug, userId); 4995 if (ri != null) { 4996 return ri; 4997 } 4998 ri = new ResolveInfo(mResolveInfo); 4999 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5000 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5001 ri.activityInfo.applicationInfo = new ApplicationInfo( 5002 ri.activityInfo.applicationInfo); 5003 if (userId != 0) { 5004 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5005 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5006 } 5007 // Make sure that the resolver is displayable in car mode 5008 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5009 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5010 return ri; 5011 } 5012 } 5013 return null; 5014 } 5015 5016 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5017 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5018 final int N = query.size(); 5019 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5020 .get(userId); 5021 // Get the list of persistent preferred activities that handle the intent 5022 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5023 List<PersistentPreferredActivity> pprefs = ppir != null 5024 ? ppir.queryIntent(intent, resolvedType, 5025 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5026 : null; 5027 if (pprefs != null && pprefs.size() > 0) { 5028 final int M = pprefs.size(); 5029 for (int i=0; i<M; i++) { 5030 final PersistentPreferredActivity ppa = pprefs.get(i); 5031 if (DEBUG_PREFERRED || debug) { 5032 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5033 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5034 + "\n component=" + ppa.mComponent); 5035 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5036 } 5037 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5038 flags | MATCH_DISABLED_COMPONENTS, userId); 5039 if (DEBUG_PREFERRED || debug) { 5040 Slog.v(TAG, "Found persistent preferred activity:"); 5041 if (ai != null) { 5042 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5043 } else { 5044 Slog.v(TAG, " null"); 5045 } 5046 } 5047 if (ai == null) { 5048 // This previously registered persistent preferred activity 5049 // component is no longer known. Ignore it and do NOT remove it. 5050 continue; 5051 } 5052 for (int j=0; j<N; j++) { 5053 final ResolveInfo ri = query.get(j); 5054 if (!ri.activityInfo.applicationInfo.packageName 5055 .equals(ai.applicationInfo.packageName)) { 5056 continue; 5057 } 5058 if (!ri.activityInfo.name.equals(ai.name)) { 5059 continue; 5060 } 5061 // Found a persistent preference that can handle the intent. 5062 if (DEBUG_PREFERRED || debug) { 5063 Slog.v(TAG, "Returning persistent preferred activity: " + 5064 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5065 } 5066 return ri; 5067 } 5068 } 5069 } 5070 return null; 5071 } 5072 5073 // TODO: handle preferred activities missing while user has amnesia 5074 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5075 List<ResolveInfo> query, int priority, boolean always, 5076 boolean removeMatches, boolean debug, int userId) { 5077 if (!sUserManager.exists(userId)) return null; 5078 flags = updateFlagsForResolve(flags, userId, intent); 5079 // writer 5080 synchronized (mPackages) { 5081 if (intent.getSelector() != null) { 5082 intent = intent.getSelector(); 5083 } 5084 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5085 5086 // Try to find a matching persistent preferred activity. 5087 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5088 debug, userId); 5089 5090 // If a persistent preferred activity matched, use it. 5091 if (pri != null) { 5092 return pri; 5093 } 5094 5095 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5096 // Get the list of preferred activities that handle the intent 5097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5098 List<PreferredActivity> prefs = pir != null 5099 ? pir.queryIntent(intent, resolvedType, 5100 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5101 : null; 5102 if (prefs != null && prefs.size() > 0) { 5103 boolean changed = false; 5104 try { 5105 // First figure out how good the original match set is. 5106 // We will only allow preferred activities that came 5107 // from the same match quality. 5108 int match = 0; 5109 5110 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5111 5112 final int N = query.size(); 5113 for (int j=0; j<N; j++) { 5114 final ResolveInfo ri = query.get(j); 5115 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5116 + ": 0x" + Integer.toHexString(match)); 5117 if (ri.match > match) { 5118 match = ri.match; 5119 } 5120 } 5121 5122 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5123 + Integer.toHexString(match)); 5124 5125 match &= IntentFilter.MATCH_CATEGORY_MASK; 5126 final int M = prefs.size(); 5127 for (int i=0; i<M; i++) { 5128 final PreferredActivity pa = prefs.get(i); 5129 if (DEBUG_PREFERRED || debug) { 5130 Slog.v(TAG, "Checking PreferredActivity ds=" 5131 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5132 + "\n component=" + pa.mPref.mComponent); 5133 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5134 } 5135 if (pa.mPref.mMatch != match) { 5136 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5137 + Integer.toHexString(pa.mPref.mMatch)); 5138 continue; 5139 } 5140 // If it's not an "always" type preferred activity and that's what we're 5141 // looking for, skip it. 5142 if (always && !pa.mPref.mAlways) { 5143 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5144 continue; 5145 } 5146 final ActivityInfo ai = getActivityInfo( 5147 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5148 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5149 userId); 5150 if (DEBUG_PREFERRED || debug) { 5151 Slog.v(TAG, "Found preferred activity:"); 5152 if (ai != null) { 5153 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5154 } else { 5155 Slog.v(TAG, " null"); 5156 } 5157 } 5158 if (ai == null) { 5159 // This previously registered preferred activity 5160 // component is no longer known. Most likely an update 5161 // to the app was installed and in the new version this 5162 // component no longer exists. Clean it up by removing 5163 // it from the preferred activities list, and skip it. 5164 Slog.w(TAG, "Removing dangling preferred activity: " 5165 + pa.mPref.mComponent); 5166 pir.removeFilter(pa); 5167 changed = true; 5168 continue; 5169 } 5170 for (int j=0; j<N; j++) { 5171 final ResolveInfo ri = query.get(j); 5172 if (!ri.activityInfo.applicationInfo.packageName 5173 .equals(ai.applicationInfo.packageName)) { 5174 continue; 5175 } 5176 if (!ri.activityInfo.name.equals(ai.name)) { 5177 continue; 5178 } 5179 5180 if (removeMatches) { 5181 pir.removeFilter(pa); 5182 changed = true; 5183 if (DEBUG_PREFERRED) { 5184 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5185 } 5186 break; 5187 } 5188 5189 // Okay we found a previously set preferred or last chosen app. 5190 // If the result set is different from when this 5191 // was created, we need to clear it and re-ask the 5192 // user their preference, if we're looking for an "always" type entry. 5193 if (always && !pa.mPref.sameSet(query)) { 5194 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5195 + intent + " type " + resolvedType); 5196 if (DEBUG_PREFERRED) { 5197 Slog.v(TAG, "Removing preferred activity since set changed " 5198 + pa.mPref.mComponent); 5199 } 5200 pir.removeFilter(pa); 5201 // Re-add the filter as a "last chosen" entry (!always) 5202 PreferredActivity lastChosen = new PreferredActivity( 5203 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5204 pir.addFilter(lastChosen); 5205 changed = true; 5206 return null; 5207 } 5208 5209 // Yay! Either the set matched or we're looking for the last chosen 5210 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5211 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5212 return ri; 5213 } 5214 } 5215 } finally { 5216 if (changed) { 5217 if (DEBUG_PREFERRED) { 5218 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5219 } 5220 scheduleWritePackageRestrictionsLocked(userId); 5221 } 5222 } 5223 } 5224 } 5225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5226 return null; 5227 } 5228 5229 /* 5230 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5231 */ 5232 @Override 5233 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5234 int targetUserId) { 5235 mContext.enforceCallingOrSelfPermission( 5236 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5237 List<CrossProfileIntentFilter> matches = 5238 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5239 if (matches != null) { 5240 int size = matches.size(); 5241 for (int i = 0; i < size; i++) { 5242 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5243 } 5244 } 5245 if (hasWebURI(intent)) { 5246 // cross-profile app linking works only towards the parent. 5247 final UserInfo parent = getProfileParent(sourceUserId); 5248 synchronized(mPackages) { 5249 int flags = updateFlagsForResolve(0, parent.id, intent); 5250 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5251 intent, resolvedType, flags, sourceUserId, parent.id); 5252 return xpDomainInfo != null; 5253 } 5254 } 5255 return false; 5256 } 5257 5258 private UserInfo getProfileParent(int userId) { 5259 final long identity = Binder.clearCallingIdentity(); 5260 try { 5261 return sUserManager.getProfileParent(userId); 5262 } finally { 5263 Binder.restoreCallingIdentity(identity); 5264 } 5265 } 5266 5267 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5268 String resolvedType, int userId) { 5269 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5270 if (resolver != null) { 5271 return resolver.queryIntent(intent, resolvedType, false, userId); 5272 } 5273 return null; 5274 } 5275 5276 @Override 5277 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5278 String resolvedType, int flags, int userId) { 5279 try { 5280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5281 5282 return new ParceledListSlice<>( 5283 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5284 } finally { 5285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5286 } 5287 } 5288 5289 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5290 String resolvedType, int flags, int userId) { 5291 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5292 flags = updateFlagsForResolve(flags, userId, intent); 5293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5294 false /* requireFullPermission */, false /* checkShell */, 5295 "query intent activities"); 5296 ComponentName comp = intent.getComponent(); 5297 if (comp == null) { 5298 if (intent.getSelector() != null) { 5299 intent = intent.getSelector(); 5300 comp = intent.getComponent(); 5301 } 5302 } 5303 5304 if (comp != null) { 5305 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5306 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5307 if (ai != null) { 5308 final ResolveInfo ri = new ResolveInfo(); 5309 ri.activityInfo = ai; 5310 list.add(ri); 5311 } 5312 return list; 5313 } 5314 5315 // reader 5316 synchronized (mPackages) { 5317 final String pkgName = intent.getPackage(); 5318 if (pkgName == null) { 5319 List<CrossProfileIntentFilter> matchingFilters = 5320 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5321 // Check for results that need to skip the current profile. 5322 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5323 resolvedType, flags, userId); 5324 if (xpResolveInfo != null) { 5325 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5326 result.add(xpResolveInfo); 5327 return filterIfNotSystemUser(result, userId); 5328 } 5329 5330 // Check for results in the current profile. 5331 List<ResolveInfo> result = mActivities.queryIntent( 5332 intent, resolvedType, flags, userId); 5333 result = filterIfNotSystemUser(result, userId); 5334 5335 // Check for cross profile results. 5336 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5337 xpResolveInfo = queryCrossProfileIntents( 5338 matchingFilters, intent, resolvedType, flags, userId, 5339 hasNonNegativePriorityResult); 5340 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5341 boolean isVisibleToUser = filterIfNotSystemUser( 5342 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5343 if (isVisibleToUser) { 5344 result.add(xpResolveInfo); 5345 Collections.sort(result, mResolvePrioritySorter); 5346 } 5347 } 5348 if (hasWebURI(intent)) { 5349 CrossProfileDomainInfo xpDomainInfo = null; 5350 final UserInfo parent = getProfileParent(userId); 5351 if (parent != null) { 5352 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5353 flags, userId, parent.id); 5354 } 5355 if (xpDomainInfo != null) { 5356 if (xpResolveInfo != null) { 5357 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5358 // in the result. 5359 result.remove(xpResolveInfo); 5360 } 5361 if (result.size() == 0) { 5362 result.add(xpDomainInfo.resolveInfo); 5363 return result; 5364 } 5365 } else if (result.size() <= 1) { 5366 return result; 5367 } 5368 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5369 xpDomainInfo, userId); 5370 Collections.sort(result, mResolvePrioritySorter); 5371 } 5372 return result; 5373 } 5374 final PackageParser.Package pkg = mPackages.get(pkgName); 5375 if (pkg != null) { 5376 return filterIfNotSystemUser( 5377 mActivities.queryIntentForPackage( 5378 intent, resolvedType, flags, pkg.activities, userId), 5379 userId); 5380 } 5381 return new ArrayList<ResolveInfo>(); 5382 } 5383 } 5384 5385 private static class CrossProfileDomainInfo { 5386 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5387 ResolveInfo resolveInfo; 5388 /* Best domain verification status of the activities found in the other profile */ 5389 int bestDomainVerificationStatus; 5390 } 5391 5392 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5393 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5394 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5395 sourceUserId)) { 5396 return null; 5397 } 5398 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5399 resolvedType, flags, parentUserId); 5400 5401 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5402 return null; 5403 } 5404 CrossProfileDomainInfo result = null; 5405 int size = resultTargetUser.size(); 5406 for (int i = 0; i < size; i++) { 5407 ResolveInfo riTargetUser = resultTargetUser.get(i); 5408 // Intent filter verification is only for filters that specify a host. So don't return 5409 // those that handle all web uris. 5410 if (riTargetUser.handleAllWebDataURI) { 5411 continue; 5412 } 5413 String packageName = riTargetUser.activityInfo.packageName; 5414 PackageSetting ps = mSettings.mPackages.get(packageName); 5415 if (ps == null) { 5416 continue; 5417 } 5418 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5419 int status = (int)(verificationState >> 32); 5420 if (result == null) { 5421 result = new CrossProfileDomainInfo(); 5422 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5423 sourceUserId, parentUserId); 5424 result.bestDomainVerificationStatus = status; 5425 } else { 5426 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5427 result.bestDomainVerificationStatus); 5428 } 5429 } 5430 // Don't consider matches with status NEVER across profiles. 5431 if (result != null && result.bestDomainVerificationStatus 5432 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5433 return null; 5434 } 5435 return result; 5436 } 5437 5438 /** 5439 * Verification statuses are ordered from the worse to the best, except for 5440 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5441 */ 5442 private int bestDomainVerificationStatus(int status1, int status2) { 5443 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5444 return status2; 5445 } 5446 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5447 return status1; 5448 } 5449 return (int) MathUtils.max(status1, status2); 5450 } 5451 5452 private boolean isUserEnabled(int userId) { 5453 long callingId = Binder.clearCallingIdentity(); 5454 try { 5455 UserInfo userInfo = sUserManager.getUserInfo(userId); 5456 return userInfo != null && userInfo.isEnabled(); 5457 } finally { 5458 Binder.restoreCallingIdentity(callingId); 5459 } 5460 } 5461 5462 /** 5463 * Filter out activities with systemUserOnly flag set, when current user is not System. 5464 * 5465 * @return filtered list 5466 */ 5467 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5468 if (userId == UserHandle.USER_SYSTEM) { 5469 return resolveInfos; 5470 } 5471 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5472 ResolveInfo info = resolveInfos.get(i); 5473 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5474 resolveInfos.remove(i); 5475 } 5476 } 5477 return resolveInfos; 5478 } 5479 5480 /** 5481 * @param resolveInfos list of resolve infos in descending priority order 5482 * @return if the list contains a resolve info with non-negative priority 5483 */ 5484 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5485 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5486 } 5487 5488 private static boolean hasWebURI(Intent intent) { 5489 if (intent.getData() == null) { 5490 return false; 5491 } 5492 final String scheme = intent.getScheme(); 5493 if (TextUtils.isEmpty(scheme)) { 5494 return false; 5495 } 5496 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5497 } 5498 5499 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5500 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5501 int userId) { 5502 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5503 5504 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5505 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5506 candidates.size()); 5507 } 5508 5509 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5510 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5511 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5513 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5514 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5515 5516 synchronized (mPackages) { 5517 final int count = candidates.size(); 5518 // First, try to use linked apps. Partition the candidates into four lists: 5519 // one for the final results, one for the "do not use ever", one for "undefined status" 5520 // and finally one for "browser app type". 5521 for (int n=0; n<count; n++) { 5522 ResolveInfo info = candidates.get(n); 5523 String packageName = info.activityInfo.packageName; 5524 PackageSetting ps = mSettings.mPackages.get(packageName); 5525 if (ps != null) { 5526 // Add to the special match all list (Browser use case) 5527 if (info.handleAllWebDataURI) { 5528 matchAllList.add(info); 5529 continue; 5530 } 5531 // Try to get the status from User settings first 5532 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5533 int status = (int)(packedStatus >> 32); 5534 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5535 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5536 if (DEBUG_DOMAIN_VERIFICATION) { 5537 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5538 + " : linkgen=" + linkGeneration); 5539 } 5540 // Use link-enabled generation as preferredOrder, i.e. 5541 // prefer newly-enabled over earlier-enabled. 5542 info.preferredOrder = linkGeneration; 5543 alwaysList.add(info); 5544 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5545 if (DEBUG_DOMAIN_VERIFICATION) { 5546 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5547 } 5548 neverList.add(info); 5549 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5550 if (DEBUG_DOMAIN_VERIFICATION) { 5551 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5552 } 5553 alwaysAskList.add(info); 5554 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5555 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5556 if (DEBUG_DOMAIN_VERIFICATION) { 5557 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5558 } 5559 undefinedList.add(info); 5560 } 5561 } 5562 } 5563 5564 // We'll want to include browser possibilities in a few cases 5565 boolean includeBrowser = false; 5566 5567 // First try to add the "always" resolution(s) for the current user, if any 5568 if (alwaysList.size() > 0) { 5569 result.addAll(alwaysList); 5570 } else { 5571 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5572 result.addAll(undefinedList); 5573 // Maybe add one for the other profile. 5574 if (xpDomainInfo != null && ( 5575 xpDomainInfo.bestDomainVerificationStatus 5576 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5577 result.add(xpDomainInfo.resolveInfo); 5578 } 5579 includeBrowser = true; 5580 } 5581 5582 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5583 // If there were 'always' entries their preferred order has been set, so we also 5584 // back that off to make the alternatives equivalent 5585 if (alwaysAskList.size() > 0) { 5586 for (ResolveInfo i : result) { 5587 i.preferredOrder = 0; 5588 } 5589 result.addAll(alwaysAskList); 5590 includeBrowser = true; 5591 } 5592 5593 if (includeBrowser) { 5594 // Also add browsers (all of them or only the default one) 5595 if (DEBUG_DOMAIN_VERIFICATION) { 5596 Slog.v(TAG, " ...including browsers in candidate set"); 5597 } 5598 if ((matchFlags & MATCH_ALL) != 0) { 5599 result.addAll(matchAllList); 5600 } else { 5601 // Browser/generic handling case. If there's a default browser, go straight 5602 // to that (but only if there is no other higher-priority match). 5603 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5604 int maxMatchPrio = 0; 5605 ResolveInfo defaultBrowserMatch = null; 5606 final int numCandidates = matchAllList.size(); 5607 for (int n = 0; n < numCandidates; n++) { 5608 ResolveInfo info = matchAllList.get(n); 5609 // track the highest overall match priority... 5610 if (info.priority > maxMatchPrio) { 5611 maxMatchPrio = info.priority; 5612 } 5613 // ...and the highest-priority default browser match 5614 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5615 if (defaultBrowserMatch == null 5616 || (defaultBrowserMatch.priority < info.priority)) { 5617 if (debug) { 5618 Slog.v(TAG, "Considering default browser match " + info); 5619 } 5620 defaultBrowserMatch = info; 5621 } 5622 } 5623 } 5624 if (defaultBrowserMatch != null 5625 && defaultBrowserMatch.priority >= maxMatchPrio 5626 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5627 { 5628 if (debug) { 5629 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5630 } 5631 result.add(defaultBrowserMatch); 5632 } else { 5633 result.addAll(matchAllList); 5634 } 5635 } 5636 5637 // If there is nothing selected, add all candidates and remove the ones that the user 5638 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5639 if (result.size() == 0) { 5640 result.addAll(candidates); 5641 result.removeAll(neverList); 5642 } 5643 } 5644 } 5645 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5646 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5647 result.size()); 5648 for (ResolveInfo info : result) { 5649 Slog.v(TAG, " + " + info.activityInfo); 5650 } 5651 } 5652 return result; 5653 } 5654 5655 // Returns a packed value as a long: 5656 // 5657 // high 'int'-sized word: link status: undefined/ask/never/always. 5658 // low 'int'-sized word: relative priority among 'always' results. 5659 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5660 long result = ps.getDomainVerificationStatusForUser(userId); 5661 // if none available, get the master status 5662 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5663 if (ps.getIntentFilterVerificationInfo() != null) { 5664 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5665 } 5666 } 5667 return result; 5668 } 5669 5670 private ResolveInfo querySkipCurrentProfileIntents( 5671 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5672 int flags, int sourceUserId) { 5673 if (matchingFilters != null) { 5674 int size = matchingFilters.size(); 5675 for (int i = 0; i < size; i ++) { 5676 CrossProfileIntentFilter filter = matchingFilters.get(i); 5677 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5678 // Checking if there are activities in the target user that can handle the 5679 // intent. 5680 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5681 resolvedType, flags, sourceUserId); 5682 if (resolveInfo != null) { 5683 return resolveInfo; 5684 } 5685 } 5686 } 5687 } 5688 return null; 5689 } 5690 5691 // Return matching ResolveInfo in target user if any. 5692 private ResolveInfo queryCrossProfileIntents( 5693 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5694 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5695 if (matchingFilters != null) { 5696 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5697 // match the same intent. For performance reasons, it is better not to 5698 // run queryIntent twice for the same userId 5699 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5700 int size = matchingFilters.size(); 5701 for (int i = 0; i < size; i++) { 5702 CrossProfileIntentFilter filter = matchingFilters.get(i); 5703 int targetUserId = filter.getTargetUserId(); 5704 boolean skipCurrentProfile = 5705 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5706 boolean skipCurrentProfileIfNoMatchFound = 5707 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5708 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5709 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5710 // Checking if there are activities in the target user that can handle the 5711 // intent. 5712 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5713 resolvedType, flags, sourceUserId); 5714 if (resolveInfo != null) return resolveInfo; 5715 alreadyTriedUserIds.put(targetUserId, true); 5716 } 5717 } 5718 } 5719 return null; 5720 } 5721 5722 /** 5723 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5724 * will forward the intent to the filter's target user. 5725 * Otherwise, returns null. 5726 */ 5727 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5728 String resolvedType, int flags, int sourceUserId) { 5729 int targetUserId = filter.getTargetUserId(); 5730 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5731 resolvedType, flags, targetUserId); 5732 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5733 // If all the matches in the target profile are suspended, return null. 5734 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5735 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5736 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5737 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5738 targetUserId); 5739 } 5740 } 5741 } 5742 return null; 5743 } 5744 5745 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5746 int sourceUserId, int targetUserId) { 5747 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5748 long ident = Binder.clearCallingIdentity(); 5749 boolean targetIsProfile; 5750 try { 5751 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5752 } finally { 5753 Binder.restoreCallingIdentity(ident); 5754 } 5755 String className; 5756 if (targetIsProfile) { 5757 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5758 } else { 5759 className = FORWARD_INTENT_TO_PARENT; 5760 } 5761 ComponentName forwardingActivityComponentName = new ComponentName( 5762 mAndroidApplication.packageName, className); 5763 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5764 sourceUserId); 5765 if (!targetIsProfile) { 5766 forwardingActivityInfo.showUserIcon = targetUserId; 5767 forwardingResolveInfo.noResourceId = true; 5768 } 5769 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5770 forwardingResolveInfo.priority = 0; 5771 forwardingResolveInfo.preferredOrder = 0; 5772 forwardingResolveInfo.match = 0; 5773 forwardingResolveInfo.isDefault = true; 5774 forwardingResolveInfo.filter = filter; 5775 forwardingResolveInfo.targetUserId = targetUserId; 5776 return forwardingResolveInfo; 5777 } 5778 5779 @Override 5780 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5781 Intent[] specifics, String[] specificTypes, Intent intent, 5782 String resolvedType, int flags, int userId) { 5783 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5784 specificTypes, intent, resolvedType, flags, userId)); 5785 } 5786 5787 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5788 Intent[] specifics, String[] specificTypes, Intent intent, 5789 String resolvedType, int flags, int userId) { 5790 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5791 flags = updateFlagsForResolve(flags, userId, intent); 5792 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5793 false /* requireFullPermission */, false /* checkShell */, 5794 "query intent activity options"); 5795 final String resultsAction = intent.getAction(); 5796 5797 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5798 | PackageManager.GET_RESOLVED_FILTER, userId); 5799 5800 if (DEBUG_INTENT_MATCHING) { 5801 Log.v(TAG, "Query " + intent + ": " + results); 5802 } 5803 5804 int specificsPos = 0; 5805 int N; 5806 5807 // todo: note that the algorithm used here is O(N^2). This 5808 // isn't a problem in our current environment, but if we start running 5809 // into situations where we have more than 5 or 10 matches then this 5810 // should probably be changed to something smarter... 5811 5812 // First we go through and resolve each of the specific items 5813 // that were supplied, taking care of removing any corresponding 5814 // duplicate items in the generic resolve list. 5815 if (specifics != null) { 5816 for (int i=0; i<specifics.length; i++) { 5817 final Intent sintent = specifics[i]; 5818 if (sintent == null) { 5819 continue; 5820 } 5821 5822 if (DEBUG_INTENT_MATCHING) { 5823 Log.v(TAG, "Specific #" + i + ": " + sintent); 5824 } 5825 5826 String action = sintent.getAction(); 5827 if (resultsAction != null && resultsAction.equals(action)) { 5828 // If this action was explicitly requested, then don't 5829 // remove things that have it. 5830 action = null; 5831 } 5832 5833 ResolveInfo ri = null; 5834 ActivityInfo ai = null; 5835 5836 ComponentName comp = sintent.getComponent(); 5837 if (comp == null) { 5838 ri = resolveIntent( 5839 sintent, 5840 specificTypes != null ? specificTypes[i] : null, 5841 flags, userId); 5842 if (ri == null) { 5843 continue; 5844 } 5845 if (ri == mResolveInfo) { 5846 // ACK! Must do something better with this. 5847 } 5848 ai = ri.activityInfo; 5849 comp = new ComponentName(ai.applicationInfo.packageName, 5850 ai.name); 5851 } else { 5852 ai = getActivityInfo(comp, flags, userId); 5853 if (ai == null) { 5854 continue; 5855 } 5856 } 5857 5858 // Look for any generic query activities that are duplicates 5859 // of this specific one, and remove them from the results. 5860 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5861 N = results.size(); 5862 int j; 5863 for (j=specificsPos; j<N; j++) { 5864 ResolveInfo sri = results.get(j); 5865 if ((sri.activityInfo.name.equals(comp.getClassName()) 5866 && sri.activityInfo.applicationInfo.packageName.equals( 5867 comp.getPackageName())) 5868 || (action != null && sri.filter.matchAction(action))) { 5869 results.remove(j); 5870 if (DEBUG_INTENT_MATCHING) Log.v( 5871 TAG, "Removing duplicate item from " + j 5872 + " due to specific " + specificsPos); 5873 if (ri == null) { 5874 ri = sri; 5875 } 5876 j--; 5877 N--; 5878 } 5879 } 5880 5881 // Add this specific item to its proper place. 5882 if (ri == null) { 5883 ri = new ResolveInfo(); 5884 ri.activityInfo = ai; 5885 } 5886 results.add(specificsPos, ri); 5887 ri.specificIndex = i; 5888 specificsPos++; 5889 } 5890 } 5891 5892 // Now we go through the remaining generic results and remove any 5893 // duplicate actions that are found here. 5894 N = results.size(); 5895 for (int i=specificsPos; i<N-1; i++) { 5896 final ResolveInfo rii = results.get(i); 5897 if (rii.filter == null) { 5898 continue; 5899 } 5900 5901 // Iterate over all of the actions of this result's intent 5902 // filter... typically this should be just one. 5903 final Iterator<String> it = rii.filter.actionsIterator(); 5904 if (it == null) { 5905 continue; 5906 } 5907 while (it.hasNext()) { 5908 final String action = it.next(); 5909 if (resultsAction != null && resultsAction.equals(action)) { 5910 // If this action was explicitly requested, then don't 5911 // remove things that have it. 5912 continue; 5913 } 5914 for (int j=i+1; j<N; j++) { 5915 final ResolveInfo rij = results.get(j); 5916 if (rij.filter != null && rij.filter.hasAction(action)) { 5917 results.remove(j); 5918 if (DEBUG_INTENT_MATCHING) Log.v( 5919 TAG, "Removing duplicate item from " + j 5920 + " due to action " + action + " at " + i); 5921 j--; 5922 N--; 5923 } 5924 } 5925 } 5926 5927 // If the caller didn't request filter information, drop it now 5928 // so we don't have to marshall/unmarshall it. 5929 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5930 rii.filter = null; 5931 } 5932 } 5933 5934 // Filter out the caller activity if so requested. 5935 if (caller != null) { 5936 N = results.size(); 5937 for (int i=0; i<N; i++) { 5938 ActivityInfo ainfo = results.get(i).activityInfo; 5939 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5940 && caller.getClassName().equals(ainfo.name)) { 5941 results.remove(i); 5942 break; 5943 } 5944 } 5945 } 5946 5947 // If the caller didn't request filter information, 5948 // drop them now so we don't have to 5949 // marshall/unmarshall it. 5950 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5951 N = results.size(); 5952 for (int i=0; i<N; i++) { 5953 results.get(i).filter = null; 5954 } 5955 } 5956 5957 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5958 return results; 5959 } 5960 5961 @Override 5962 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5963 String resolvedType, int flags, int userId) { 5964 return new ParceledListSlice<>( 5965 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5966 } 5967 5968 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5969 String resolvedType, int flags, int userId) { 5970 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5971 flags = updateFlagsForResolve(flags, userId, intent); 5972 ComponentName comp = intent.getComponent(); 5973 if (comp == null) { 5974 if (intent.getSelector() != null) { 5975 intent = intent.getSelector(); 5976 comp = intent.getComponent(); 5977 } 5978 } 5979 if (comp != null) { 5980 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5981 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5982 if (ai != null) { 5983 ResolveInfo ri = new ResolveInfo(); 5984 ri.activityInfo = ai; 5985 list.add(ri); 5986 } 5987 return list; 5988 } 5989 5990 // reader 5991 synchronized (mPackages) { 5992 String pkgName = intent.getPackage(); 5993 if (pkgName == null) { 5994 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5995 } 5996 final PackageParser.Package pkg = mPackages.get(pkgName); 5997 if (pkg != null) { 5998 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5999 userId); 6000 } 6001 return Collections.emptyList(); 6002 } 6003 } 6004 6005 @Override 6006 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6007 if (!sUserManager.exists(userId)) return null; 6008 flags = updateFlagsForResolve(flags, userId, intent); 6009 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6010 if (query != null) { 6011 if (query.size() >= 1) { 6012 // If there is more than one service with the same priority, 6013 // just arbitrarily pick the first one. 6014 return query.get(0); 6015 } 6016 } 6017 return null; 6018 } 6019 6020 @Override 6021 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6022 String resolvedType, int flags, int userId) { 6023 return new ParceledListSlice<>( 6024 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6025 } 6026 6027 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6028 String resolvedType, int flags, int userId) { 6029 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6030 flags = updateFlagsForResolve(flags, userId, intent); 6031 ComponentName comp = intent.getComponent(); 6032 if (comp == null) { 6033 if (intent.getSelector() != null) { 6034 intent = intent.getSelector(); 6035 comp = intent.getComponent(); 6036 } 6037 } 6038 if (comp != null) { 6039 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6040 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6041 if (si != null) { 6042 final ResolveInfo ri = new ResolveInfo(); 6043 ri.serviceInfo = si; 6044 list.add(ri); 6045 } 6046 return list; 6047 } 6048 6049 // reader 6050 synchronized (mPackages) { 6051 String pkgName = intent.getPackage(); 6052 if (pkgName == null) { 6053 return mServices.queryIntent(intent, resolvedType, flags, userId); 6054 } 6055 final PackageParser.Package pkg = mPackages.get(pkgName); 6056 if (pkg != null) { 6057 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6058 userId); 6059 } 6060 return Collections.emptyList(); 6061 } 6062 } 6063 6064 @Override 6065 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6066 String resolvedType, int flags, int userId) { 6067 return new ParceledListSlice<>( 6068 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6069 } 6070 6071 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6072 Intent intent, String resolvedType, int flags, int userId) { 6073 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6074 flags = updateFlagsForResolve(flags, userId, intent); 6075 ComponentName comp = intent.getComponent(); 6076 if (comp == null) { 6077 if (intent.getSelector() != null) { 6078 intent = intent.getSelector(); 6079 comp = intent.getComponent(); 6080 } 6081 } 6082 if (comp != null) { 6083 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6084 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6085 if (pi != null) { 6086 final ResolveInfo ri = new ResolveInfo(); 6087 ri.providerInfo = pi; 6088 list.add(ri); 6089 } 6090 return list; 6091 } 6092 6093 // reader 6094 synchronized (mPackages) { 6095 String pkgName = intent.getPackage(); 6096 if (pkgName == null) { 6097 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6098 } 6099 final PackageParser.Package pkg = mPackages.get(pkgName); 6100 if (pkg != null) { 6101 return mProviders.queryIntentForPackage( 6102 intent, resolvedType, flags, pkg.providers, userId); 6103 } 6104 return Collections.emptyList(); 6105 } 6106 } 6107 6108 @Override 6109 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6110 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6111 flags = updateFlagsForPackage(flags, userId, null); 6112 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6113 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6114 true /* requireFullPermission */, false /* checkShell */, 6115 "get installed packages"); 6116 6117 // writer 6118 synchronized (mPackages) { 6119 ArrayList<PackageInfo> list; 6120 if (listUninstalled) { 6121 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6122 for (PackageSetting ps : mSettings.mPackages.values()) { 6123 final PackageInfo pi; 6124 if (ps.pkg != null) { 6125 pi = generatePackageInfo(ps, flags, userId); 6126 } else { 6127 pi = generatePackageInfo(ps, flags, userId); 6128 } 6129 if (pi != null) { 6130 list.add(pi); 6131 } 6132 } 6133 } else { 6134 list = new ArrayList<PackageInfo>(mPackages.size()); 6135 for (PackageParser.Package p : mPackages.values()) { 6136 final PackageInfo pi = 6137 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6138 if (pi != null) { 6139 list.add(pi); 6140 } 6141 } 6142 } 6143 6144 return new ParceledListSlice<PackageInfo>(list); 6145 } 6146 } 6147 6148 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6149 String[] permissions, boolean[] tmp, int flags, int userId) { 6150 int numMatch = 0; 6151 final PermissionsState permissionsState = ps.getPermissionsState(); 6152 for (int i=0; i<permissions.length; i++) { 6153 final String permission = permissions[i]; 6154 if (permissionsState.hasPermission(permission, userId)) { 6155 tmp[i] = true; 6156 numMatch++; 6157 } else { 6158 tmp[i] = false; 6159 } 6160 } 6161 if (numMatch == 0) { 6162 return; 6163 } 6164 final PackageInfo pi; 6165 if (ps.pkg != null) { 6166 pi = generatePackageInfo(ps, flags, userId); 6167 } else { 6168 pi = generatePackageInfo(ps, flags, userId); 6169 } 6170 // The above might return null in cases of uninstalled apps or install-state 6171 // skew across users/profiles. 6172 if (pi != null) { 6173 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6174 if (numMatch == permissions.length) { 6175 pi.requestedPermissions = permissions; 6176 } else { 6177 pi.requestedPermissions = new String[numMatch]; 6178 numMatch = 0; 6179 for (int i=0; i<permissions.length; i++) { 6180 if (tmp[i]) { 6181 pi.requestedPermissions[numMatch] = permissions[i]; 6182 numMatch++; 6183 } 6184 } 6185 } 6186 } 6187 list.add(pi); 6188 } 6189 } 6190 6191 @Override 6192 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6193 String[] permissions, int flags, int userId) { 6194 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6195 flags = updateFlagsForPackage(flags, userId, permissions); 6196 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6197 6198 // writer 6199 synchronized (mPackages) { 6200 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6201 boolean[] tmpBools = new boolean[permissions.length]; 6202 if (listUninstalled) { 6203 for (PackageSetting ps : mSettings.mPackages.values()) { 6204 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6205 } 6206 } else { 6207 for (PackageParser.Package pkg : mPackages.values()) { 6208 PackageSetting ps = (PackageSetting)pkg.mExtras; 6209 if (ps != null) { 6210 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6211 userId); 6212 } 6213 } 6214 } 6215 6216 return new ParceledListSlice<PackageInfo>(list); 6217 } 6218 } 6219 6220 @Override 6221 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6222 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6223 flags = updateFlagsForApplication(flags, userId, null); 6224 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6225 6226 // writer 6227 synchronized (mPackages) { 6228 ArrayList<ApplicationInfo> list; 6229 if (listUninstalled) { 6230 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6231 for (PackageSetting ps : mSettings.mPackages.values()) { 6232 ApplicationInfo ai; 6233 if (ps.pkg != null) { 6234 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6235 ps.readUserState(userId), userId); 6236 } else { 6237 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6238 } 6239 if (ai != null) { 6240 list.add(ai); 6241 } 6242 } 6243 } else { 6244 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6245 for (PackageParser.Package p : mPackages.values()) { 6246 if (p.mExtras != null) { 6247 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6248 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6249 if (ai != null) { 6250 list.add(ai); 6251 } 6252 } 6253 } 6254 } 6255 6256 return new ParceledListSlice<ApplicationInfo>(list); 6257 } 6258 } 6259 6260 @Override 6261 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6262 if (DISABLE_EPHEMERAL_APPS) { 6263 return null; 6264 } 6265 6266 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6267 "getEphemeralApplications"); 6268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6269 true /* requireFullPermission */, false /* checkShell */, 6270 "getEphemeralApplications"); 6271 synchronized (mPackages) { 6272 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6273 .getEphemeralApplicationsLPw(userId); 6274 if (ephemeralApps != null) { 6275 return new ParceledListSlice<>(ephemeralApps); 6276 } 6277 } 6278 return null; 6279 } 6280 6281 @Override 6282 public boolean isEphemeralApplication(String packageName, int userId) { 6283 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6284 true /* requireFullPermission */, false /* checkShell */, 6285 "isEphemeral"); 6286 if (DISABLE_EPHEMERAL_APPS) { 6287 return false; 6288 } 6289 6290 if (!isCallerSameApp(packageName)) { 6291 return false; 6292 } 6293 synchronized (mPackages) { 6294 PackageParser.Package pkg = mPackages.get(packageName); 6295 if (pkg != null) { 6296 return pkg.applicationInfo.isEphemeralApp(); 6297 } 6298 } 6299 return false; 6300 } 6301 6302 @Override 6303 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6304 if (DISABLE_EPHEMERAL_APPS) { 6305 return null; 6306 } 6307 6308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6309 true /* requireFullPermission */, false /* checkShell */, 6310 "getCookie"); 6311 if (!isCallerSameApp(packageName)) { 6312 return null; 6313 } 6314 synchronized (mPackages) { 6315 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6316 packageName, userId); 6317 } 6318 } 6319 6320 @Override 6321 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6322 if (DISABLE_EPHEMERAL_APPS) { 6323 return true; 6324 } 6325 6326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6327 true /* requireFullPermission */, true /* checkShell */, 6328 "setCookie"); 6329 if (!isCallerSameApp(packageName)) { 6330 return false; 6331 } 6332 synchronized (mPackages) { 6333 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6334 packageName, cookie, userId); 6335 } 6336 } 6337 6338 @Override 6339 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6340 if (DISABLE_EPHEMERAL_APPS) { 6341 return null; 6342 } 6343 6344 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6345 "getEphemeralApplicationIcon"); 6346 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6347 true /* requireFullPermission */, false /* checkShell */, 6348 "getEphemeralApplicationIcon"); 6349 synchronized (mPackages) { 6350 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6351 packageName, userId); 6352 } 6353 } 6354 6355 private boolean isCallerSameApp(String packageName) { 6356 PackageParser.Package pkg = mPackages.get(packageName); 6357 return pkg != null 6358 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6359 } 6360 6361 @Override 6362 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6363 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6364 } 6365 6366 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6367 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6368 6369 // reader 6370 synchronized (mPackages) { 6371 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6372 final int userId = UserHandle.getCallingUserId(); 6373 while (i.hasNext()) { 6374 final PackageParser.Package p = i.next(); 6375 if (p.applicationInfo == null) continue; 6376 6377 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6378 && !p.applicationInfo.isDirectBootAware(); 6379 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6380 && p.applicationInfo.isDirectBootAware(); 6381 6382 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6383 && (!mSafeMode || isSystemApp(p)) 6384 && (matchesUnaware || matchesAware)) { 6385 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6386 if (ps != null) { 6387 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6388 ps.readUserState(userId), userId); 6389 if (ai != null) { 6390 finalList.add(ai); 6391 } 6392 } 6393 } 6394 } 6395 } 6396 6397 return finalList; 6398 } 6399 6400 @Override 6401 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6402 if (!sUserManager.exists(userId)) return null; 6403 flags = updateFlagsForComponent(flags, userId, name); 6404 // reader 6405 synchronized (mPackages) { 6406 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6407 PackageSetting ps = provider != null 6408 ? mSettings.mPackages.get(provider.owner.packageName) 6409 : null; 6410 return ps != null 6411 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6412 ? PackageParser.generateProviderInfo(provider, flags, 6413 ps.readUserState(userId), userId) 6414 : null; 6415 } 6416 } 6417 6418 /** 6419 * @deprecated 6420 */ 6421 @Deprecated 6422 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6423 // reader 6424 synchronized (mPackages) { 6425 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6426 .entrySet().iterator(); 6427 final int userId = UserHandle.getCallingUserId(); 6428 while (i.hasNext()) { 6429 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6430 PackageParser.Provider p = entry.getValue(); 6431 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6432 6433 if (ps != null && p.syncable 6434 && (!mSafeMode || (p.info.applicationInfo.flags 6435 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6436 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6437 ps.readUserState(userId), userId); 6438 if (info != null) { 6439 outNames.add(entry.getKey()); 6440 outInfo.add(info); 6441 } 6442 } 6443 } 6444 } 6445 } 6446 6447 @Override 6448 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6449 int uid, int flags) { 6450 final int userId = processName != null ? UserHandle.getUserId(uid) 6451 : UserHandle.getCallingUserId(); 6452 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6453 flags = updateFlagsForComponent(flags, userId, processName); 6454 6455 ArrayList<ProviderInfo> finalList = null; 6456 // reader 6457 synchronized (mPackages) { 6458 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6459 while (i.hasNext()) { 6460 final PackageParser.Provider p = i.next(); 6461 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6462 if (ps != null && p.info.authority != null 6463 && (processName == null 6464 || (p.info.processName.equals(processName) 6465 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6466 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6467 if (finalList == null) { 6468 finalList = new ArrayList<ProviderInfo>(3); 6469 } 6470 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6471 ps.readUserState(userId), userId); 6472 if (info != null) { 6473 finalList.add(info); 6474 } 6475 } 6476 } 6477 } 6478 6479 if (finalList != null) { 6480 Collections.sort(finalList, mProviderInitOrderSorter); 6481 return new ParceledListSlice<ProviderInfo>(finalList); 6482 } 6483 6484 return ParceledListSlice.emptyList(); 6485 } 6486 6487 @Override 6488 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6489 // reader 6490 synchronized (mPackages) { 6491 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6492 return PackageParser.generateInstrumentationInfo(i, flags); 6493 } 6494 } 6495 6496 @Override 6497 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6498 String targetPackage, int flags) { 6499 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6500 } 6501 6502 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6503 int flags) { 6504 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6505 6506 // reader 6507 synchronized (mPackages) { 6508 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6509 while (i.hasNext()) { 6510 final PackageParser.Instrumentation p = i.next(); 6511 if (targetPackage == null 6512 || targetPackage.equals(p.info.targetPackage)) { 6513 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6514 flags); 6515 if (ii != null) { 6516 finalList.add(ii); 6517 } 6518 } 6519 } 6520 } 6521 6522 return finalList; 6523 } 6524 6525 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6526 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6527 if (overlays == null) { 6528 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6529 return; 6530 } 6531 for (PackageParser.Package opkg : overlays.values()) { 6532 // Not much to do if idmap fails: we already logged the error 6533 // and we certainly don't want to abort installation of pkg simply 6534 // because an overlay didn't fit properly. For these reasons, 6535 // ignore the return value of createIdmapForPackagePairLI. 6536 createIdmapForPackagePairLI(pkg, opkg); 6537 } 6538 } 6539 6540 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6541 PackageParser.Package opkg) { 6542 if (!opkg.mTrustedOverlay) { 6543 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6544 opkg.baseCodePath + ": overlay not trusted"); 6545 return false; 6546 } 6547 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6548 if (overlaySet == null) { 6549 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6550 opkg.baseCodePath + " but target package has no known overlays"); 6551 return false; 6552 } 6553 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6554 // TODO: generate idmap for split APKs 6555 try { 6556 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6557 } catch (InstallerException e) { 6558 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6559 + opkg.baseCodePath); 6560 return false; 6561 } 6562 PackageParser.Package[] overlayArray = 6563 overlaySet.values().toArray(new PackageParser.Package[0]); 6564 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6565 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6566 return p1.mOverlayPriority - p2.mOverlayPriority; 6567 } 6568 }; 6569 Arrays.sort(overlayArray, cmp); 6570 6571 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6572 int i = 0; 6573 for (PackageParser.Package p : overlayArray) { 6574 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6575 } 6576 return true; 6577 } 6578 6579 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6581 try { 6582 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6583 } finally { 6584 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6585 } 6586 } 6587 6588 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6589 final File[] files = dir.listFiles(); 6590 if (ArrayUtils.isEmpty(files)) { 6591 Log.d(TAG, "No files in app dir " + dir); 6592 return; 6593 } 6594 6595 if (DEBUG_PACKAGE_SCANNING) { 6596 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6597 + " flags=0x" + Integer.toHexString(parseFlags)); 6598 } 6599 6600 for (File file : files) { 6601 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6602 && !PackageInstallerService.isStageName(file.getName()); 6603 if (!isPackage) { 6604 // Ignore entries which are not packages 6605 continue; 6606 } 6607 try { 6608 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6609 scanFlags, currentTime, null); 6610 } catch (PackageManagerException e) { 6611 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6612 6613 // Delete invalid userdata apps 6614 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6615 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6616 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6617 removeCodePathLI(file); 6618 } 6619 } 6620 } 6621 } 6622 6623 private static File getSettingsProblemFile() { 6624 File dataDir = Environment.getDataDirectory(); 6625 File systemDir = new File(dataDir, "system"); 6626 File fname = new File(systemDir, "uiderrors.txt"); 6627 return fname; 6628 } 6629 6630 static void reportSettingsProblem(int priority, String msg) { 6631 logCriticalInfo(priority, msg); 6632 } 6633 6634 static void logCriticalInfo(int priority, String msg) { 6635 Slog.println(priority, TAG, msg); 6636 EventLogTags.writePmCriticalInfo(msg); 6637 try { 6638 File fname = getSettingsProblemFile(); 6639 FileOutputStream out = new FileOutputStream(fname, true); 6640 PrintWriter pw = new FastPrintWriter(out); 6641 SimpleDateFormat formatter = new SimpleDateFormat(); 6642 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6643 pw.println(dateString + ": " + msg); 6644 pw.close(); 6645 FileUtils.setPermissions( 6646 fname.toString(), 6647 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6648 -1, -1); 6649 } catch (java.io.IOException e) { 6650 } 6651 } 6652 6653 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6654 final int policyFlags) throws PackageManagerException { 6655 if (ps != null 6656 && ps.codePath.equals(srcFile) 6657 && ps.timeStamp == srcFile.lastModified() 6658 && !isCompatSignatureUpdateNeeded(pkg) 6659 && !isRecoverSignatureUpdateNeeded(pkg)) { 6660 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6661 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6662 ArraySet<PublicKey> signingKs; 6663 synchronized (mPackages) { 6664 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6665 } 6666 if (ps.signatures.mSignatures != null 6667 && ps.signatures.mSignatures.length != 0 6668 && signingKs != null) { 6669 // Optimization: reuse the existing cached certificates 6670 // if the package appears to be unchanged. 6671 pkg.mSignatures = ps.signatures.mSignatures; 6672 pkg.mSigningKeys = signingKs; 6673 return; 6674 } 6675 6676 Slog.w(TAG, "PackageSetting for " + ps.name 6677 + " is missing signatures. Collecting certs again to recover them."); 6678 } else { 6679 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6680 } 6681 6682 try { 6683 PackageParser.collectCertificates(pkg, policyFlags); 6684 } catch (PackageParserException e) { 6685 throw PackageManagerException.from(e); 6686 } 6687 } 6688 6689 /** 6690 * Traces a package scan. 6691 * @see #scanPackageLI(File, int, int, long, UserHandle) 6692 */ 6693 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6694 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6695 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6696 try { 6697 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6698 } finally { 6699 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6700 } 6701 } 6702 6703 /** 6704 * Scans a package and returns the newly parsed package. 6705 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6706 */ 6707 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6708 long currentTime, UserHandle user) throws PackageManagerException { 6709 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6710 PackageParser pp = new PackageParser(); 6711 pp.setSeparateProcesses(mSeparateProcesses); 6712 pp.setOnlyCoreApps(mOnlyCore); 6713 pp.setDisplayMetrics(mMetrics); 6714 6715 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6716 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6717 } 6718 6719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6720 final PackageParser.Package pkg; 6721 try { 6722 pkg = pp.parsePackage(scanFile, parseFlags); 6723 } catch (PackageParserException e) { 6724 throw PackageManagerException.from(e); 6725 } finally { 6726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6727 } 6728 6729 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6730 } 6731 6732 /** 6733 * Scans a package and returns the newly parsed package. 6734 * @throws PackageManagerException on a parse error. 6735 */ 6736 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6737 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6738 throws PackageManagerException { 6739 // If the package has children and this is the first dive in the function 6740 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6741 // packages (parent and children) would be successfully scanned before the 6742 // actual scan since scanning mutates internal state and we want to atomically 6743 // install the package and its children. 6744 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6745 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6746 scanFlags |= SCAN_CHECK_ONLY; 6747 } 6748 } else { 6749 scanFlags &= ~SCAN_CHECK_ONLY; 6750 } 6751 6752 // Scan the parent 6753 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6754 scanFlags, currentTime, user); 6755 6756 // Scan the children 6757 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6758 for (int i = 0; i < childCount; i++) { 6759 PackageParser.Package childPackage = pkg.childPackages.get(i); 6760 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6761 currentTime, user); 6762 } 6763 6764 6765 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6766 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6767 } 6768 6769 return scannedPkg; 6770 } 6771 6772 /** 6773 * Scans a package and returns the newly parsed package. 6774 * @throws PackageManagerException on a parse error. 6775 */ 6776 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6777 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6778 throws PackageManagerException { 6779 PackageSetting ps = null; 6780 PackageSetting updatedPkg; 6781 // reader 6782 synchronized (mPackages) { 6783 // Look to see if we already know about this package. 6784 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6785 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6786 // This package has been renamed to its original name. Let's 6787 // use that. 6788 ps = mSettings.peekPackageLPr(oldName); 6789 } 6790 // If there was no original package, see one for the real package name. 6791 if (ps == null) { 6792 ps = mSettings.peekPackageLPr(pkg.packageName); 6793 } 6794 // Check to see if this package could be hiding/updating a system 6795 // package. Must look for it either under the original or real 6796 // package name depending on our state. 6797 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6798 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6799 6800 // If this is a package we don't know about on the system partition, we 6801 // may need to remove disabled child packages on the system partition 6802 // or may need to not add child packages if the parent apk is updated 6803 // on the data partition and no longer defines this child package. 6804 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6805 // If this is a parent package for an updated system app and this system 6806 // app got an OTA update which no longer defines some of the child packages 6807 // we have to prune them from the disabled system packages. 6808 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6809 if (disabledPs != null) { 6810 final int scannedChildCount = (pkg.childPackages != null) 6811 ? pkg.childPackages.size() : 0; 6812 final int disabledChildCount = disabledPs.childPackageNames != null 6813 ? disabledPs.childPackageNames.size() : 0; 6814 for (int i = 0; i < disabledChildCount; i++) { 6815 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6816 boolean disabledPackageAvailable = false; 6817 for (int j = 0; j < scannedChildCount; j++) { 6818 PackageParser.Package childPkg = pkg.childPackages.get(j); 6819 if (childPkg.packageName.equals(disabledChildPackageName)) { 6820 disabledPackageAvailable = true; 6821 break; 6822 } 6823 } 6824 if (!disabledPackageAvailable) { 6825 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6826 } 6827 } 6828 } 6829 } 6830 } 6831 6832 boolean updatedPkgBetter = false; 6833 // First check if this is a system package that may involve an update 6834 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6835 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6836 // it needs to drop FLAG_PRIVILEGED. 6837 if (locationIsPrivileged(scanFile)) { 6838 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6839 } else { 6840 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6841 } 6842 6843 if (ps != null && !ps.codePath.equals(scanFile)) { 6844 // The path has changed from what was last scanned... check the 6845 // version of the new path against what we have stored to determine 6846 // what to do. 6847 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6848 if (pkg.mVersionCode <= ps.versionCode) { 6849 // The system package has been updated and the code path does not match 6850 // Ignore entry. Skip it. 6851 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6852 + " ignored: updated version " + ps.versionCode 6853 + " better than this " + pkg.mVersionCode); 6854 if (!updatedPkg.codePath.equals(scanFile)) { 6855 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6856 + ps.name + " changing from " + updatedPkg.codePathString 6857 + " to " + scanFile); 6858 updatedPkg.codePath = scanFile; 6859 updatedPkg.codePathString = scanFile.toString(); 6860 updatedPkg.resourcePath = scanFile; 6861 updatedPkg.resourcePathString = scanFile.toString(); 6862 } 6863 updatedPkg.pkg = pkg; 6864 updatedPkg.versionCode = pkg.mVersionCode; 6865 6866 // Update the disabled system child packages to point to the package too. 6867 final int childCount = updatedPkg.childPackageNames != null 6868 ? updatedPkg.childPackageNames.size() : 0; 6869 for (int i = 0; i < childCount; i++) { 6870 String childPackageName = updatedPkg.childPackageNames.get(i); 6871 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6872 childPackageName); 6873 if (updatedChildPkg != null) { 6874 updatedChildPkg.pkg = pkg; 6875 updatedChildPkg.versionCode = pkg.mVersionCode; 6876 } 6877 } 6878 6879 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6880 + scanFile + " ignored: updated version " + ps.versionCode 6881 + " better than this " + pkg.mVersionCode); 6882 } else { 6883 // The current app on the system partition is better than 6884 // what we have updated to on the data partition; switch 6885 // back to the system partition version. 6886 // At this point, its safely assumed that package installation for 6887 // apps in system partition will go through. If not there won't be a working 6888 // version of the app 6889 // writer 6890 synchronized (mPackages) { 6891 // Just remove the loaded entries from package lists. 6892 mPackages.remove(ps.name); 6893 } 6894 6895 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6896 + " reverting from " + ps.codePathString 6897 + ": new version " + pkg.mVersionCode 6898 + " better than installed " + ps.versionCode); 6899 6900 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6901 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6902 synchronized (mInstallLock) { 6903 args.cleanUpResourcesLI(); 6904 } 6905 synchronized (mPackages) { 6906 mSettings.enableSystemPackageLPw(ps.name); 6907 } 6908 updatedPkgBetter = true; 6909 } 6910 } 6911 } 6912 6913 if (updatedPkg != null) { 6914 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6915 // initially 6916 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6917 6918 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6919 // flag set initially 6920 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6921 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6922 } 6923 } 6924 6925 // Verify certificates against what was last scanned 6926 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6927 6928 /* 6929 * A new system app appeared, but we already had a non-system one of the 6930 * same name installed earlier. 6931 */ 6932 boolean shouldHideSystemApp = false; 6933 if (updatedPkg == null && ps != null 6934 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6935 /* 6936 * Check to make sure the signatures match first. If they don't, 6937 * wipe the installed application and its data. 6938 */ 6939 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6940 != PackageManager.SIGNATURE_MATCH) { 6941 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6942 + " signatures don't match existing userdata copy; removing"); 6943 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6944 "scanPackageInternalLI")) { 6945 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6946 } 6947 ps = null; 6948 } else { 6949 /* 6950 * If the newly-added system app is an older version than the 6951 * already installed version, hide it. It will be scanned later 6952 * and re-added like an update. 6953 */ 6954 if (pkg.mVersionCode <= ps.versionCode) { 6955 shouldHideSystemApp = true; 6956 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6957 + " but new version " + pkg.mVersionCode + " better than installed " 6958 + ps.versionCode + "; hiding system"); 6959 } else { 6960 /* 6961 * The newly found system app is a newer version that the 6962 * one previously installed. Simply remove the 6963 * already-installed application and replace it with our own 6964 * while keeping the application data. 6965 */ 6966 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6967 + " reverting from " + ps.codePathString + ": new version " 6968 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6969 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6970 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6971 synchronized (mInstallLock) { 6972 args.cleanUpResourcesLI(); 6973 } 6974 } 6975 } 6976 } 6977 6978 // The apk is forward locked (not public) if its code and resources 6979 // are kept in different files. (except for app in either system or 6980 // vendor path). 6981 // TODO grab this value from PackageSettings 6982 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6983 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6984 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6985 } 6986 } 6987 6988 // TODO: extend to support forward-locked splits 6989 String resourcePath = null; 6990 String baseResourcePath = null; 6991 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6992 if (ps != null && ps.resourcePathString != null) { 6993 resourcePath = ps.resourcePathString; 6994 baseResourcePath = ps.resourcePathString; 6995 } else { 6996 // Should not happen at all. Just log an error. 6997 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6998 } 6999 } else { 7000 resourcePath = pkg.codePath; 7001 baseResourcePath = pkg.baseCodePath; 7002 } 7003 7004 // Set application objects path explicitly. 7005 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7006 pkg.setApplicationInfoCodePath(pkg.codePath); 7007 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7008 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7009 pkg.setApplicationInfoResourcePath(resourcePath); 7010 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7011 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7012 7013 // Note that we invoke the following method only if we are about to unpack an application 7014 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7015 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7016 7017 /* 7018 * If the system app should be overridden by a previously installed 7019 * data, hide the system app now and let the /data/app scan pick it up 7020 * again. 7021 */ 7022 if (shouldHideSystemApp) { 7023 synchronized (mPackages) { 7024 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7025 } 7026 } 7027 7028 return scannedPkg; 7029 } 7030 7031 private static String fixProcessName(String defProcessName, 7032 String processName, int uid) { 7033 if (processName == null) { 7034 return defProcessName; 7035 } 7036 return processName; 7037 } 7038 7039 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7040 throws PackageManagerException { 7041 if (pkgSetting.signatures.mSignatures != null) { 7042 // Already existing package. Make sure signatures match 7043 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7044 == PackageManager.SIGNATURE_MATCH; 7045 if (!match) { 7046 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7047 == PackageManager.SIGNATURE_MATCH; 7048 } 7049 if (!match) { 7050 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7051 == PackageManager.SIGNATURE_MATCH; 7052 } 7053 if (!match) { 7054 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7055 + pkg.packageName + " signatures do not match the " 7056 + "previously installed version; ignoring!"); 7057 } 7058 } 7059 7060 // Check for shared user signatures 7061 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7062 // Already existing package. Make sure signatures match 7063 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7064 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7065 if (!match) { 7066 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7067 == PackageManager.SIGNATURE_MATCH; 7068 } 7069 if (!match) { 7070 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7071 == PackageManager.SIGNATURE_MATCH; 7072 } 7073 if (!match) { 7074 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7075 "Package " + pkg.packageName 7076 + " has no signatures that match those in shared user " 7077 + pkgSetting.sharedUser.name + "; ignoring!"); 7078 } 7079 } 7080 } 7081 7082 /** 7083 * Enforces that only the system UID or root's UID can call a method exposed 7084 * via Binder. 7085 * 7086 * @param message used as message if SecurityException is thrown 7087 * @throws SecurityException if the caller is not system or root 7088 */ 7089 private static final void enforceSystemOrRoot(String message) { 7090 final int uid = Binder.getCallingUid(); 7091 if (uid != Process.SYSTEM_UID && uid != 0) { 7092 throw new SecurityException(message); 7093 } 7094 } 7095 7096 @Override 7097 public void performFstrimIfNeeded() { 7098 enforceSystemOrRoot("Only the system can request fstrim"); 7099 7100 // Before everything else, see whether we need to fstrim. 7101 try { 7102 IMountService ms = PackageHelper.getMountService(); 7103 if (ms != null) { 7104 final boolean isUpgrade = isUpgrade(); 7105 boolean doTrim = isUpgrade; 7106 if (doTrim) { 7107 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7108 } else { 7109 final long interval = android.provider.Settings.Global.getLong( 7110 mContext.getContentResolver(), 7111 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7112 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7113 if (interval > 0) { 7114 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7115 if (timeSinceLast > interval) { 7116 doTrim = true; 7117 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7118 + "; running immediately"); 7119 } 7120 } 7121 } 7122 if (doTrim) { 7123 if (!isFirstBoot()) { 7124 try { 7125 ActivityManagerNative.getDefault().showBootMessage( 7126 mContext.getResources().getString( 7127 R.string.android_upgrading_fstrim), true); 7128 } catch (RemoteException e) { 7129 } 7130 } 7131 ms.runMaintenance(); 7132 } 7133 } else { 7134 Slog.e(TAG, "Mount service unavailable!"); 7135 } 7136 } catch (RemoteException e) { 7137 // Can't happen; MountService is local 7138 } 7139 } 7140 7141 @Override 7142 public void updatePackagesIfNeeded() { 7143 enforceSystemOrRoot("Only the system can request package update"); 7144 7145 // We need to re-extract after an OTA. 7146 boolean causeUpgrade = isUpgrade(); 7147 7148 // First boot or factory reset. 7149 // Note: we also handle devices that are upgrading to N right now as if it is their 7150 // first boot, as they do not have profile data. 7151 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7152 7153 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7154 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7155 7156 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7157 return; 7158 } 7159 7160 List<PackageParser.Package> pkgs; 7161 synchronized (mPackages) { 7162 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7163 } 7164 7165 int numberOfPackagesVisited = 0; 7166 int numberOfPackagesOptimized = 0; 7167 int numberOfPackagesSkipped = 0; 7168 int numberOfPackagesFailed = 0; 7169 final int numberOfPackagesToDexopt = pkgs.size(); 7170 final long startTime = System.nanoTime(); 7171 7172 for (PackageParser.Package pkg : pkgs) { 7173 numberOfPackagesVisited++; 7174 7175 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7176 if (DEBUG_DEXOPT) { 7177 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7178 } 7179 numberOfPackagesSkipped++; 7180 continue; 7181 } 7182 7183 if (DEBUG_DEXOPT) { 7184 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7185 numberOfPackagesToDexopt + ": " + pkg.packageName); 7186 } 7187 7188 if (mIsPreNUpgrade) { 7189 try { 7190 ActivityManagerNative.getDefault().showBootMessage( 7191 mContext.getResources().getString(R.string.android_upgrading_apk, 7192 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7193 } catch (RemoteException e) { 7194 } 7195 } 7196 7197 // checkProfiles is false to avoid merging profiles during boot which 7198 // might interfere with background compilation (b/28612421). 7199 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7200 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7201 // trade-off worth doing to save boot time work. 7202 int dexOptStatus = performDexOptTraced(pkg.packageName, 7203 null /* instructionSet */, 7204 false /* checkProfiles */, 7205 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7206 false /* force */); 7207 switch (dexOptStatus) { 7208 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7209 numberOfPackagesOptimized++; 7210 break; 7211 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7212 numberOfPackagesSkipped++; 7213 break; 7214 case PackageDexOptimizer.DEX_OPT_FAILED: 7215 numberOfPackagesFailed++; 7216 break; 7217 default: 7218 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7219 break; 7220 } 7221 } 7222 7223 final int elapsedTime = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); 7224 // TODO: Log events using MetricsLogger.histogram / MetricsLogger.count 7225 } 7226 7227 @Override 7228 public void notifyPackageUse(String packageName, int reason) { 7229 synchronized (mPackages) { 7230 PackageParser.Package p = mPackages.get(packageName); 7231 if (p == null) { 7232 return; 7233 } 7234 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7235 } 7236 } 7237 7238 // TODO: this is not used nor needed. Delete it. 7239 @Override 7240 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7241 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7242 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7243 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7244 } 7245 7246 @Override 7247 public boolean performDexOpt(String packageName, String instructionSet, 7248 boolean checkProfiles, int compileReason, boolean force) { 7249 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7250 getCompilerFilterForReason(compileReason), force); 7251 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7252 } 7253 7254 @Override 7255 public boolean performDexOptMode(String packageName, String instructionSet, 7256 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7257 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7258 targetCompilerFilter, force); 7259 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7260 } 7261 7262 private int performDexOptTraced(String packageName, String instructionSet, 7263 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7265 try { 7266 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7267 targetCompilerFilter, force); 7268 } finally { 7269 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7270 } 7271 } 7272 7273 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7274 // if the package can now be considered up to date for the given filter. 7275 private int performDexOptInternal(String packageName, String instructionSet, 7276 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7277 PackageParser.Package p; 7278 final String targetInstructionSet; 7279 synchronized (mPackages) { 7280 p = mPackages.get(packageName); 7281 if (p == null) { 7282 // Package could not be found. Report failure. 7283 return PackageDexOptimizer.DEX_OPT_FAILED; 7284 } 7285 mPackageUsage.write(false); 7286 7287 targetInstructionSet = instructionSet != null ? instructionSet : 7288 getPrimaryInstructionSet(p.applicationInfo); 7289 } 7290 long callingId = Binder.clearCallingIdentity(); 7291 try { 7292 synchronized (mInstallLock) { 7293 final String[] instructionSets = new String[] { targetInstructionSet }; 7294 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7295 targetCompilerFilter, force); 7296 } 7297 } finally { 7298 Binder.restoreCallingIdentity(callingId); 7299 } 7300 } 7301 7302 public ArraySet<String> getOptimizablePackages() { 7303 ArraySet<String> pkgs = new ArraySet<String>(); 7304 synchronized (mPackages) { 7305 for (PackageParser.Package p : mPackages.values()) { 7306 if (PackageDexOptimizer.canOptimizePackage(p)) { 7307 pkgs.add(p.packageName); 7308 } 7309 } 7310 } 7311 return pkgs; 7312 } 7313 7314 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7315 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7316 boolean force) { 7317 // Select the dex optimizer based on the force parameter. 7318 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7319 // allocate an object here. 7320 PackageDexOptimizer pdo = force 7321 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7322 : mPackageDexOptimizer; 7323 7324 // Optimize all dependencies first. Note: we ignore the return value and march on 7325 // on errors. 7326 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7327 if (!deps.isEmpty()) { 7328 for (PackageParser.Package depPackage : deps) { 7329 // TODO: Analyze and investigate if we (should) profile libraries. 7330 // Currently this will do a full compilation of the library by default. 7331 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7332 false /* checkProfiles */, 7333 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7334 } 7335 } 7336 7337 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7338 targetCompilerFilter); 7339 } 7340 7341 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7342 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7343 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7344 Set<String> collectedNames = new HashSet<>(); 7345 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7346 7347 retValue.remove(p); 7348 7349 return retValue; 7350 } else { 7351 return Collections.emptyList(); 7352 } 7353 } 7354 7355 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7356 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7357 if (!collectedNames.contains(p.packageName)) { 7358 collectedNames.add(p.packageName); 7359 collected.add(p); 7360 7361 if (p.usesLibraries != null) { 7362 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7363 } 7364 if (p.usesOptionalLibraries != null) { 7365 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7366 collectedNames); 7367 } 7368 } 7369 } 7370 7371 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7372 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7373 for (String libName : libs) { 7374 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7375 if (libPkg != null) { 7376 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7377 } 7378 } 7379 } 7380 7381 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7382 synchronized (mPackages) { 7383 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7384 if (lib != null && lib.apk != null) { 7385 return mPackages.get(lib.apk); 7386 } 7387 } 7388 return null; 7389 } 7390 7391 public void shutdown() { 7392 mPackageUsage.write(true); 7393 } 7394 7395 @Override 7396 public void forceDexOpt(String packageName) { 7397 enforceSystemOrRoot("forceDexOpt"); 7398 7399 PackageParser.Package pkg; 7400 synchronized (mPackages) { 7401 pkg = mPackages.get(packageName); 7402 if (pkg == null) { 7403 throw new IllegalArgumentException("Unknown package: " + packageName); 7404 } 7405 } 7406 7407 synchronized (mInstallLock) { 7408 final String[] instructionSets = new String[] { 7409 getPrimaryInstructionSet(pkg.applicationInfo) }; 7410 7411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7412 7413 // Whoever is calling forceDexOpt wants a fully compiled package. 7414 // Don't use profiles since that may cause compilation to be skipped. 7415 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7416 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7417 true /* force */); 7418 7419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7420 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7421 throw new IllegalStateException("Failed to dexopt: " + res); 7422 } 7423 } 7424 } 7425 7426 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7427 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7428 Slog.w(TAG, "Unable to update from " + oldPkg.name 7429 + " to " + newPkg.packageName 7430 + ": old package not in system partition"); 7431 return false; 7432 } else if (mPackages.get(oldPkg.name) != null) { 7433 Slog.w(TAG, "Unable to update from " + oldPkg.name 7434 + " to " + newPkg.packageName 7435 + ": old package still exists"); 7436 return false; 7437 } 7438 return true; 7439 } 7440 7441 void removeCodePathLI(File codePath) { 7442 if (codePath.isDirectory()) { 7443 try { 7444 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7445 } catch (InstallerException e) { 7446 Slog.w(TAG, "Failed to remove code path", e); 7447 } 7448 } else { 7449 codePath.delete(); 7450 } 7451 } 7452 7453 private int[] resolveUserIds(int userId) { 7454 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7455 } 7456 7457 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7458 if (pkg == null) { 7459 Slog.wtf(TAG, "Package was null!", new Throwable()); 7460 return; 7461 } 7462 clearAppDataLeafLIF(pkg, userId, flags); 7463 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7464 for (int i = 0; i < childCount; i++) { 7465 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7466 } 7467 } 7468 7469 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7470 final PackageSetting ps; 7471 synchronized (mPackages) { 7472 ps = mSettings.mPackages.get(pkg.packageName); 7473 } 7474 for (int realUserId : resolveUserIds(userId)) { 7475 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7476 try { 7477 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7478 ceDataInode); 7479 } catch (InstallerException e) { 7480 Slog.w(TAG, String.valueOf(e)); 7481 } 7482 } 7483 } 7484 7485 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7486 if (pkg == null) { 7487 Slog.wtf(TAG, "Package was null!", new Throwable()); 7488 return; 7489 } 7490 destroyAppDataLeafLIF(pkg, userId, flags); 7491 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7492 for (int i = 0; i < childCount; i++) { 7493 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7494 } 7495 } 7496 7497 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7498 final PackageSetting ps; 7499 synchronized (mPackages) { 7500 ps = mSettings.mPackages.get(pkg.packageName); 7501 } 7502 for (int realUserId : resolveUserIds(userId)) { 7503 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7504 try { 7505 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7506 ceDataInode); 7507 } catch (InstallerException e) { 7508 Slog.w(TAG, String.valueOf(e)); 7509 } 7510 } 7511 } 7512 7513 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7514 if (pkg == null) { 7515 Slog.wtf(TAG, "Package was null!", new Throwable()); 7516 return; 7517 } 7518 destroyAppProfilesLeafLIF(pkg); 7519 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7520 for (int i = 0; i < childCount; i++) { 7521 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7522 } 7523 } 7524 7525 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7526 try { 7527 mInstaller.destroyAppProfiles(pkg.packageName); 7528 } catch (InstallerException e) { 7529 Slog.w(TAG, String.valueOf(e)); 7530 } 7531 } 7532 7533 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7534 if (pkg == null) { 7535 Slog.wtf(TAG, "Package was null!", new Throwable()); 7536 return; 7537 } 7538 clearAppProfilesLeafLIF(pkg); 7539 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7540 for (int i = 0; i < childCount; i++) { 7541 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7542 } 7543 } 7544 7545 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7546 try { 7547 mInstaller.clearAppProfiles(pkg.packageName); 7548 } catch (InstallerException e) { 7549 Slog.w(TAG, String.valueOf(e)); 7550 } 7551 } 7552 7553 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7554 long lastUpdateTime) { 7555 // Set parent install/update time 7556 PackageSetting ps = (PackageSetting) pkg.mExtras; 7557 if (ps != null) { 7558 ps.firstInstallTime = firstInstallTime; 7559 ps.lastUpdateTime = lastUpdateTime; 7560 } 7561 // Set children install/update time 7562 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7563 for (int i = 0; i < childCount; i++) { 7564 PackageParser.Package childPkg = pkg.childPackages.get(i); 7565 ps = (PackageSetting) childPkg.mExtras; 7566 if (ps != null) { 7567 ps.firstInstallTime = firstInstallTime; 7568 ps.lastUpdateTime = lastUpdateTime; 7569 } 7570 } 7571 } 7572 7573 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7574 PackageParser.Package changingLib) { 7575 if (file.path != null) { 7576 usesLibraryFiles.add(file.path); 7577 return; 7578 } 7579 PackageParser.Package p = mPackages.get(file.apk); 7580 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7581 // If we are doing this while in the middle of updating a library apk, 7582 // then we need to make sure to use that new apk for determining the 7583 // dependencies here. (We haven't yet finished committing the new apk 7584 // to the package manager state.) 7585 if (p == null || p.packageName.equals(changingLib.packageName)) { 7586 p = changingLib; 7587 } 7588 } 7589 if (p != null) { 7590 usesLibraryFiles.addAll(p.getAllCodePaths()); 7591 } 7592 } 7593 7594 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7595 PackageParser.Package changingLib) throws PackageManagerException { 7596 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7597 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7598 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7599 for (int i=0; i<N; i++) { 7600 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7601 if (file == null) { 7602 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7603 "Package " + pkg.packageName + " requires unavailable shared library " 7604 + pkg.usesLibraries.get(i) + "; failing!"); 7605 } 7606 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7607 } 7608 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7609 for (int i=0; i<N; i++) { 7610 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7611 if (file == null) { 7612 Slog.w(TAG, "Package " + pkg.packageName 7613 + " desires unavailable shared library " 7614 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7615 } else { 7616 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7617 } 7618 } 7619 N = usesLibraryFiles.size(); 7620 if (N > 0) { 7621 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7622 } else { 7623 pkg.usesLibraryFiles = null; 7624 } 7625 } 7626 } 7627 7628 private static boolean hasString(List<String> list, List<String> which) { 7629 if (list == null) { 7630 return false; 7631 } 7632 for (int i=list.size()-1; i>=0; i--) { 7633 for (int j=which.size()-1; j>=0; j--) { 7634 if (which.get(j).equals(list.get(i))) { 7635 return true; 7636 } 7637 } 7638 } 7639 return false; 7640 } 7641 7642 private void updateAllSharedLibrariesLPw() { 7643 for (PackageParser.Package pkg : mPackages.values()) { 7644 try { 7645 updateSharedLibrariesLPw(pkg, null); 7646 } catch (PackageManagerException e) { 7647 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7648 } 7649 } 7650 } 7651 7652 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7653 PackageParser.Package changingPkg) { 7654 ArrayList<PackageParser.Package> res = null; 7655 for (PackageParser.Package pkg : mPackages.values()) { 7656 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7657 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7658 if (res == null) { 7659 res = new ArrayList<PackageParser.Package>(); 7660 } 7661 res.add(pkg); 7662 try { 7663 updateSharedLibrariesLPw(pkg, changingPkg); 7664 } catch (PackageManagerException e) { 7665 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7666 } 7667 } 7668 } 7669 return res; 7670 } 7671 7672 /** 7673 * Derive the value of the {@code cpuAbiOverride} based on the provided 7674 * value and an optional stored value from the package settings. 7675 */ 7676 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7677 String cpuAbiOverride = null; 7678 7679 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7680 cpuAbiOverride = null; 7681 } else if (abiOverride != null) { 7682 cpuAbiOverride = abiOverride; 7683 } else if (settings != null) { 7684 cpuAbiOverride = settings.cpuAbiOverrideString; 7685 } 7686 7687 return cpuAbiOverride; 7688 } 7689 7690 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7691 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7692 throws PackageManagerException { 7693 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7694 // If the package has children and this is the first dive in the function 7695 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7696 // whether all packages (parent and children) would be successfully scanned 7697 // before the actual scan since scanning mutates internal state and we want 7698 // to atomically install the package and its children. 7699 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7700 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7701 scanFlags |= SCAN_CHECK_ONLY; 7702 } 7703 } else { 7704 scanFlags &= ~SCAN_CHECK_ONLY; 7705 } 7706 7707 final PackageParser.Package scannedPkg; 7708 try { 7709 // Scan the parent 7710 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7711 // Scan the children 7712 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7713 for (int i = 0; i < childCount; i++) { 7714 PackageParser.Package childPkg = pkg.childPackages.get(i); 7715 scanPackageLI(childPkg, policyFlags, 7716 scanFlags, currentTime, user); 7717 } 7718 } finally { 7719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7720 } 7721 7722 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7723 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7724 } 7725 7726 return scannedPkg; 7727 } 7728 7729 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7730 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7731 boolean success = false; 7732 try { 7733 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7734 currentTime, user); 7735 success = true; 7736 return res; 7737 } finally { 7738 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7739 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7740 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7741 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7742 destroyAppProfilesLIF(pkg); 7743 } 7744 } 7745 } 7746 7747 /** 7748 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7749 */ 7750 private static boolean apkHasCode(String fileName) { 7751 StrictJarFile jarFile = null; 7752 try { 7753 jarFile = new StrictJarFile(fileName, 7754 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7755 return jarFile.findEntry("classes.dex") != null; 7756 } catch (IOException ignore) { 7757 } finally { 7758 try { 7759 jarFile.close(); 7760 } catch (IOException ignore) {} 7761 } 7762 return false; 7763 } 7764 7765 /** 7766 * Enforces code policy for the package. This ensures that if an APK has 7767 * declared hasCode="true" in its manifest that the APK actually contains 7768 * code. 7769 * 7770 * @throws PackageManagerException If bytecode could not be found when it should exist 7771 */ 7772 private static void enforceCodePolicy(PackageParser.Package pkg) 7773 throws PackageManagerException { 7774 final boolean shouldHaveCode = 7775 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7776 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7777 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7778 "Package " + pkg.baseCodePath + " code is missing"); 7779 } 7780 7781 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7782 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7783 final boolean splitShouldHaveCode = 7784 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7785 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7786 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7787 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7788 } 7789 } 7790 } 7791 } 7792 7793 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7794 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7795 throws PackageManagerException { 7796 final File scanFile = new File(pkg.codePath); 7797 if (pkg.applicationInfo.getCodePath() == null || 7798 pkg.applicationInfo.getResourcePath() == null) { 7799 // Bail out. The resource and code paths haven't been set. 7800 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7801 "Code and resource paths haven't been set correctly"); 7802 } 7803 7804 // Apply policy 7805 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7806 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7807 if (pkg.applicationInfo.isDirectBootAware()) { 7808 // we're direct boot aware; set for all components 7809 for (PackageParser.Service s : pkg.services) { 7810 s.info.encryptionAware = s.info.directBootAware = true; 7811 } 7812 for (PackageParser.Provider p : pkg.providers) { 7813 p.info.encryptionAware = p.info.directBootAware = true; 7814 } 7815 for (PackageParser.Activity a : pkg.activities) { 7816 a.info.encryptionAware = a.info.directBootAware = true; 7817 } 7818 for (PackageParser.Activity r : pkg.receivers) { 7819 r.info.encryptionAware = r.info.directBootAware = true; 7820 } 7821 } 7822 } else { 7823 // Only allow system apps to be flagged as core apps. 7824 pkg.coreApp = false; 7825 // clear flags not applicable to regular apps 7826 pkg.applicationInfo.privateFlags &= 7827 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7828 pkg.applicationInfo.privateFlags &= 7829 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7830 } 7831 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7832 7833 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7834 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7835 } 7836 7837 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7838 enforceCodePolicy(pkg); 7839 } 7840 7841 if (mCustomResolverComponentName != null && 7842 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7843 setUpCustomResolverActivity(pkg); 7844 } 7845 7846 if (pkg.packageName.equals("android")) { 7847 synchronized (mPackages) { 7848 if (mAndroidApplication != null) { 7849 Slog.w(TAG, "*************************************************"); 7850 Slog.w(TAG, "Core android package being redefined. Skipping."); 7851 Slog.w(TAG, " file=" + scanFile); 7852 Slog.w(TAG, "*************************************************"); 7853 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7854 "Core android package being redefined. Skipping."); 7855 } 7856 7857 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7858 // Set up information for our fall-back user intent resolution activity. 7859 mPlatformPackage = pkg; 7860 pkg.mVersionCode = mSdkVersion; 7861 mAndroidApplication = pkg.applicationInfo; 7862 7863 if (!mResolverReplaced) { 7864 mResolveActivity.applicationInfo = mAndroidApplication; 7865 mResolveActivity.name = ResolverActivity.class.getName(); 7866 mResolveActivity.packageName = mAndroidApplication.packageName; 7867 mResolveActivity.processName = "system:ui"; 7868 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7869 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7870 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7871 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7872 mResolveActivity.exported = true; 7873 mResolveActivity.enabled = true; 7874 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7875 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7876 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7877 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7878 | ActivityInfo.CONFIG_ORIENTATION 7879 | ActivityInfo.CONFIG_KEYBOARD 7880 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7881 mResolveInfo.activityInfo = mResolveActivity; 7882 mResolveInfo.priority = 0; 7883 mResolveInfo.preferredOrder = 0; 7884 mResolveInfo.match = 0; 7885 mResolveComponentName = new ComponentName( 7886 mAndroidApplication.packageName, mResolveActivity.name); 7887 } 7888 } 7889 } 7890 } 7891 7892 if (DEBUG_PACKAGE_SCANNING) { 7893 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7894 Log.d(TAG, "Scanning package " + pkg.packageName); 7895 } 7896 7897 synchronized (mPackages) { 7898 if (mPackages.containsKey(pkg.packageName) 7899 || mSharedLibraries.containsKey(pkg.packageName)) { 7900 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7901 "Application package " + pkg.packageName 7902 + " already installed. Skipping duplicate."); 7903 } 7904 7905 // If we're only installing presumed-existing packages, require that the 7906 // scanned APK is both already known and at the path previously established 7907 // for it. Previously unknown packages we pick up normally, but if we have an 7908 // a priori expectation about this package's install presence, enforce it. 7909 // With a singular exception for new system packages. When an OTA contains 7910 // a new system package, we allow the codepath to change from a system location 7911 // to the user-installed location. If we don't allow this change, any newer, 7912 // user-installed version of the application will be ignored. 7913 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7914 if (mExpectingBetter.containsKey(pkg.packageName)) { 7915 logCriticalInfo(Log.WARN, 7916 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7917 } else { 7918 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7919 if (known != null) { 7920 if (DEBUG_PACKAGE_SCANNING) { 7921 Log.d(TAG, "Examining " + pkg.codePath 7922 + " and requiring known paths " + known.codePathString 7923 + " & " + known.resourcePathString); 7924 } 7925 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7926 || !pkg.applicationInfo.getResourcePath().equals( 7927 known.resourcePathString)) { 7928 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7929 "Application package " + pkg.packageName 7930 + " found at " + pkg.applicationInfo.getCodePath() 7931 + " but expected at " + known.codePathString 7932 + "; ignoring."); 7933 } 7934 } 7935 } 7936 } 7937 } 7938 7939 // Initialize package source and resource directories 7940 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7941 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7942 7943 SharedUserSetting suid = null; 7944 PackageSetting pkgSetting = null; 7945 7946 if (!isSystemApp(pkg)) { 7947 // Only system apps can use these features. 7948 pkg.mOriginalPackages = null; 7949 pkg.mRealPackage = null; 7950 pkg.mAdoptPermissions = null; 7951 } 7952 7953 // Getting the package setting may have a side-effect, so if we 7954 // are only checking if scan would succeed, stash a copy of the 7955 // old setting to restore at the end. 7956 PackageSetting nonMutatedPs = null; 7957 7958 // writer 7959 synchronized (mPackages) { 7960 if (pkg.mSharedUserId != null) { 7961 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7962 if (suid == null) { 7963 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7964 "Creating application package " + pkg.packageName 7965 + " for shared user failed"); 7966 } 7967 if (DEBUG_PACKAGE_SCANNING) { 7968 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7969 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7970 + "): packages=" + suid.packages); 7971 } 7972 } 7973 7974 // Check if we are renaming from an original package name. 7975 PackageSetting origPackage = null; 7976 String realName = null; 7977 if (pkg.mOriginalPackages != null) { 7978 // This package may need to be renamed to a previously 7979 // installed name. Let's check on that... 7980 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7981 if (pkg.mOriginalPackages.contains(renamed)) { 7982 // This package had originally been installed as the 7983 // original name, and we have already taken care of 7984 // transitioning to the new one. Just update the new 7985 // one to continue using the old name. 7986 realName = pkg.mRealPackage; 7987 if (!pkg.packageName.equals(renamed)) { 7988 // Callers into this function may have already taken 7989 // care of renaming the package; only do it here if 7990 // it is not already done. 7991 pkg.setPackageName(renamed); 7992 } 7993 7994 } else { 7995 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7996 if ((origPackage = mSettings.peekPackageLPr( 7997 pkg.mOriginalPackages.get(i))) != null) { 7998 // We do have the package already installed under its 7999 // original name... should we use it? 8000 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8001 // New package is not compatible with original. 8002 origPackage = null; 8003 continue; 8004 } else if (origPackage.sharedUser != null) { 8005 // Make sure uid is compatible between packages. 8006 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8007 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8008 + " to " + pkg.packageName + ": old uid " 8009 + origPackage.sharedUser.name 8010 + " differs from " + pkg.mSharedUserId); 8011 origPackage = null; 8012 continue; 8013 } 8014 // TODO: Add case when shared user id is added [b/28144775] 8015 } else { 8016 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8017 + pkg.packageName + " to old name " + origPackage.name); 8018 } 8019 break; 8020 } 8021 } 8022 } 8023 } 8024 8025 if (mTransferedPackages.contains(pkg.packageName)) { 8026 Slog.w(TAG, "Package " + pkg.packageName 8027 + " was transferred to another, but its .apk remains"); 8028 } 8029 8030 // See comments in nonMutatedPs declaration 8031 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8032 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8033 if (foundPs != null) { 8034 nonMutatedPs = new PackageSetting(foundPs); 8035 } 8036 } 8037 8038 // Just create the setting, don't add it yet. For already existing packages 8039 // the PkgSetting exists already and doesn't have to be created. 8040 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8041 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8042 pkg.applicationInfo.primaryCpuAbi, 8043 pkg.applicationInfo.secondaryCpuAbi, 8044 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8045 user, false); 8046 if (pkgSetting == null) { 8047 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8048 "Creating application package " + pkg.packageName + " failed"); 8049 } 8050 8051 if (pkgSetting.origPackage != null) { 8052 // If we are first transitioning from an original package, 8053 // fix up the new package's name now. We need to do this after 8054 // looking up the package under its new name, so getPackageLP 8055 // can take care of fiddling things correctly. 8056 pkg.setPackageName(origPackage.name); 8057 8058 // File a report about this. 8059 String msg = "New package " + pkgSetting.realName 8060 + " renamed to replace old package " + pkgSetting.name; 8061 reportSettingsProblem(Log.WARN, msg); 8062 8063 // Make a note of it. 8064 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8065 mTransferedPackages.add(origPackage.name); 8066 } 8067 8068 // No longer need to retain this. 8069 pkgSetting.origPackage = null; 8070 } 8071 8072 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8073 // Make a note of it. 8074 mTransferedPackages.add(pkg.packageName); 8075 } 8076 8077 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8078 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8079 } 8080 8081 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8082 // Check all shared libraries and map to their actual file path. 8083 // We only do this here for apps not on a system dir, because those 8084 // are the only ones that can fail an install due to this. We 8085 // will take care of the system apps by updating all of their 8086 // library paths after the scan is done. 8087 updateSharedLibrariesLPw(pkg, null); 8088 } 8089 8090 if (mFoundPolicyFile) { 8091 SELinuxMMAC.assignSeinfoValue(pkg); 8092 } 8093 8094 pkg.applicationInfo.uid = pkgSetting.appId; 8095 pkg.mExtras = pkgSetting; 8096 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8097 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8098 // We just determined the app is signed correctly, so bring 8099 // over the latest parsed certs. 8100 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8101 } else { 8102 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8103 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8104 "Package " + pkg.packageName + " upgrade keys do not match the " 8105 + "previously installed version"); 8106 } else { 8107 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8108 String msg = "System package " + pkg.packageName 8109 + " signature changed; retaining data."; 8110 reportSettingsProblem(Log.WARN, msg); 8111 } 8112 } 8113 } else { 8114 try { 8115 verifySignaturesLP(pkgSetting, pkg); 8116 // We just determined the app is signed correctly, so bring 8117 // over the latest parsed certs. 8118 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8119 } catch (PackageManagerException e) { 8120 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8121 throw e; 8122 } 8123 // The signature has changed, but this package is in the system 8124 // image... let's recover! 8125 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8126 // However... if this package is part of a shared user, but it 8127 // doesn't match the signature of the shared user, let's fail. 8128 // What this means is that you can't change the signatures 8129 // associated with an overall shared user, which doesn't seem all 8130 // that unreasonable. 8131 if (pkgSetting.sharedUser != null) { 8132 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8133 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8134 throw new PackageManagerException( 8135 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8136 "Signature mismatch for shared user: " 8137 + pkgSetting.sharedUser); 8138 } 8139 } 8140 // File a report about this. 8141 String msg = "System package " + pkg.packageName 8142 + " signature changed; retaining data."; 8143 reportSettingsProblem(Log.WARN, msg); 8144 } 8145 } 8146 // Verify that this new package doesn't have any content providers 8147 // that conflict with existing packages. Only do this if the 8148 // package isn't already installed, since we don't want to break 8149 // things that are installed. 8150 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8151 final int N = pkg.providers.size(); 8152 int i; 8153 for (i=0; i<N; i++) { 8154 PackageParser.Provider p = pkg.providers.get(i); 8155 if (p.info.authority != null) { 8156 String names[] = p.info.authority.split(";"); 8157 for (int j = 0; j < names.length; j++) { 8158 if (mProvidersByAuthority.containsKey(names[j])) { 8159 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8160 final String otherPackageName = 8161 ((other != null && other.getComponentName() != null) ? 8162 other.getComponentName().getPackageName() : "?"); 8163 throw new PackageManagerException( 8164 INSTALL_FAILED_CONFLICTING_PROVIDER, 8165 "Can't install because provider name " + names[j] 8166 + " (in package " + pkg.applicationInfo.packageName 8167 + ") is already used by " + otherPackageName); 8168 } 8169 } 8170 } 8171 } 8172 } 8173 8174 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8175 // This package wants to adopt ownership of permissions from 8176 // another package. 8177 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8178 final String origName = pkg.mAdoptPermissions.get(i); 8179 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8180 if (orig != null) { 8181 if (verifyPackageUpdateLPr(orig, pkg)) { 8182 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8183 + pkg.packageName); 8184 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8185 } 8186 } 8187 } 8188 } 8189 } 8190 8191 final String pkgName = pkg.packageName; 8192 8193 final long scanFileTime = scanFile.lastModified(); 8194 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8195 pkg.applicationInfo.processName = fixProcessName( 8196 pkg.applicationInfo.packageName, 8197 pkg.applicationInfo.processName, 8198 pkg.applicationInfo.uid); 8199 8200 if (pkg != mPlatformPackage) { 8201 // Get all of our default paths setup 8202 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8203 } 8204 8205 final String path = scanFile.getPath(); 8206 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8207 8208 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8209 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8210 8211 // Some system apps still use directory structure for native libraries 8212 // in which case we might end up not detecting abi solely based on apk 8213 // structure. Try to detect abi based on directory structure. 8214 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8215 pkg.applicationInfo.primaryCpuAbi == null) { 8216 setBundledAppAbisAndRoots(pkg, pkgSetting); 8217 setNativeLibraryPaths(pkg); 8218 } 8219 8220 } else { 8221 if ((scanFlags & SCAN_MOVE) != 0) { 8222 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8223 // but we already have this packages package info in the PackageSetting. We just 8224 // use that and derive the native library path based on the new codepath. 8225 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8226 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8227 } 8228 8229 // Set native library paths again. For moves, the path will be updated based on the 8230 // ABIs we've determined above. For non-moves, the path will be updated based on the 8231 // ABIs we determined during compilation, but the path will depend on the final 8232 // package path (after the rename away from the stage path). 8233 setNativeLibraryPaths(pkg); 8234 } 8235 8236 // This is a special case for the "system" package, where the ABI is 8237 // dictated by the zygote configuration (and init.rc). We should keep track 8238 // of this ABI so that we can deal with "normal" applications that run under 8239 // the same UID correctly. 8240 if (mPlatformPackage == pkg) { 8241 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8242 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8243 } 8244 8245 // If there's a mismatch between the abi-override in the package setting 8246 // and the abiOverride specified for the install. Warn about this because we 8247 // would've already compiled the app without taking the package setting into 8248 // account. 8249 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8250 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8251 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8252 " for package " + pkg.packageName); 8253 } 8254 } 8255 8256 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8257 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8258 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8259 8260 // Copy the derived override back to the parsed package, so that we can 8261 // update the package settings accordingly. 8262 pkg.cpuAbiOverride = cpuAbiOverride; 8263 8264 if (DEBUG_ABI_SELECTION) { 8265 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8266 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8267 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8268 } 8269 8270 // Push the derived path down into PackageSettings so we know what to 8271 // clean up at uninstall time. 8272 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8273 8274 if (DEBUG_ABI_SELECTION) { 8275 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8276 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8277 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8278 } 8279 8280 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8281 // We don't do this here during boot because we can do it all 8282 // at once after scanning all existing packages. 8283 // 8284 // We also do this *before* we perform dexopt on this package, so that 8285 // we can avoid redundant dexopts, and also to make sure we've got the 8286 // code and package path correct. 8287 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8288 pkg, true /* boot complete */); 8289 } 8290 8291 if (mFactoryTest && pkg.requestedPermissions.contains( 8292 android.Manifest.permission.FACTORY_TEST)) { 8293 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8294 } 8295 8296 ArrayList<PackageParser.Package> clientLibPkgs = null; 8297 8298 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8299 if (nonMutatedPs != null) { 8300 synchronized (mPackages) { 8301 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8302 } 8303 } 8304 return pkg; 8305 } 8306 8307 // Only privileged apps and updated privileged apps can add child packages. 8308 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8309 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8310 throw new PackageManagerException("Only privileged apps and updated " 8311 + "privileged apps can add child packages. Ignoring package " 8312 + pkg.packageName); 8313 } 8314 final int childCount = pkg.childPackages.size(); 8315 for (int i = 0; i < childCount; i++) { 8316 PackageParser.Package childPkg = pkg.childPackages.get(i); 8317 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8318 childPkg.packageName)) { 8319 throw new PackageManagerException("Cannot override a child package of " 8320 + "another disabled system app. Ignoring package " + pkg.packageName); 8321 } 8322 } 8323 } 8324 8325 // writer 8326 synchronized (mPackages) { 8327 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8328 // Only system apps can add new shared libraries. 8329 if (pkg.libraryNames != null) { 8330 for (int i=0; i<pkg.libraryNames.size(); i++) { 8331 String name = pkg.libraryNames.get(i); 8332 boolean allowed = false; 8333 if (pkg.isUpdatedSystemApp()) { 8334 // New library entries can only be added through the 8335 // system image. This is important to get rid of a lot 8336 // of nasty edge cases: for example if we allowed a non- 8337 // system update of the app to add a library, then uninstalling 8338 // the update would make the library go away, and assumptions 8339 // we made such as through app install filtering would now 8340 // have allowed apps on the device which aren't compatible 8341 // with it. Better to just have the restriction here, be 8342 // conservative, and create many fewer cases that can negatively 8343 // impact the user experience. 8344 final PackageSetting sysPs = mSettings 8345 .getDisabledSystemPkgLPr(pkg.packageName); 8346 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8347 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8348 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8349 allowed = true; 8350 break; 8351 } 8352 } 8353 } 8354 } else { 8355 allowed = true; 8356 } 8357 if (allowed) { 8358 if (!mSharedLibraries.containsKey(name)) { 8359 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8360 } else if (!name.equals(pkg.packageName)) { 8361 Slog.w(TAG, "Package " + pkg.packageName + " library " 8362 + name + " already exists; skipping"); 8363 } 8364 } else { 8365 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8366 + name + " that is not declared on system image; skipping"); 8367 } 8368 } 8369 if ((scanFlags & SCAN_BOOTING) == 0) { 8370 // If we are not booting, we need to update any applications 8371 // that are clients of our shared library. If we are booting, 8372 // this will all be done once the scan is complete. 8373 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8374 } 8375 } 8376 } 8377 } 8378 8379 if ((scanFlags & SCAN_BOOTING) != 0) { 8380 // No apps can run during boot scan, so they don't need to be frozen 8381 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8382 // Caller asked to not kill app, so it's probably not frozen 8383 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8384 // Caller asked us to ignore frozen check for some reason; they 8385 // probably didn't know the package name 8386 } else { 8387 // We're doing major surgery on this package, so it better be frozen 8388 // right now to keep it from launching 8389 checkPackageFrozen(pkgName); 8390 } 8391 8392 // Also need to kill any apps that are dependent on the library. 8393 if (clientLibPkgs != null) { 8394 for (int i=0; i<clientLibPkgs.size(); i++) { 8395 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8396 killApplication(clientPkg.applicationInfo.packageName, 8397 clientPkg.applicationInfo.uid, "update lib"); 8398 } 8399 } 8400 8401 // Make sure we're not adding any bogus keyset info 8402 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8403 ksms.assertScannedPackageValid(pkg); 8404 8405 // writer 8406 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8407 8408 boolean createIdmapFailed = false; 8409 synchronized (mPackages) { 8410 // We don't expect installation to fail beyond this point 8411 8412 // Add the new setting to mSettings 8413 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8414 // Add the new setting to mPackages 8415 mPackages.put(pkg.applicationInfo.packageName, pkg); 8416 // Make sure we don't accidentally delete its data. 8417 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8418 while (iter.hasNext()) { 8419 PackageCleanItem item = iter.next(); 8420 if (pkgName.equals(item.packageName)) { 8421 iter.remove(); 8422 } 8423 } 8424 8425 // Take care of first install / last update times. 8426 if (currentTime != 0) { 8427 if (pkgSetting.firstInstallTime == 0) { 8428 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8429 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8430 pkgSetting.lastUpdateTime = currentTime; 8431 } 8432 } else if (pkgSetting.firstInstallTime == 0) { 8433 // We need *something*. Take time time stamp of the file. 8434 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8435 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8436 if (scanFileTime != pkgSetting.timeStamp) { 8437 // A package on the system image has changed; consider this 8438 // to be an update. 8439 pkgSetting.lastUpdateTime = scanFileTime; 8440 } 8441 } 8442 8443 // Add the package's KeySets to the global KeySetManagerService 8444 ksms.addScannedPackageLPw(pkg); 8445 8446 int N = pkg.providers.size(); 8447 StringBuilder r = null; 8448 int i; 8449 for (i=0; i<N; i++) { 8450 PackageParser.Provider p = pkg.providers.get(i); 8451 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8452 p.info.processName, pkg.applicationInfo.uid); 8453 mProviders.addProvider(p); 8454 p.syncable = p.info.isSyncable; 8455 if (p.info.authority != null) { 8456 String names[] = p.info.authority.split(";"); 8457 p.info.authority = null; 8458 for (int j = 0; j < names.length; j++) { 8459 if (j == 1 && p.syncable) { 8460 // We only want the first authority for a provider to possibly be 8461 // syncable, so if we already added this provider using a different 8462 // authority clear the syncable flag. We copy the provider before 8463 // changing it because the mProviders object contains a reference 8464 // to a provider that we don't want to change. 8465 // Only do this for the second authority since the resulting provider 8466 // object can be the same for all future authorities for this provider. 8467 p = new PackageParser.Provider(p); 8468 p.syncable = false; 8469 } 8470 if (!mProvidersByAuthority.containsKey(names[j])) { 8471 mProvidersByAuthority.put(names[j], p); 8472 if (p.info.authority == null) { 8473 p.info.authority = names[j]; 8474 } else { 8475 p.info.authority = p.info.authority + ";" + names[j]; 8476 } 8477 if (DEBUG_PACKAGE_SCANNING) { 8478 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8479 Log.d(TAG, "Registered content provider: " + names[j] 8480 + ", className = " + p.info.name + ", isSyncable = " 8481 + p.info.isSyncable); 8482 } 8483 } else { 8484 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8485 Slog.w(TAG, "Skipping provider name " + names[j] + 8486 " (in package " + pkg.applicationInfo.packageName + 8487 "): name already used by " 8488 + ((other != null && other.getComponentName() != null) 8489 ? other.getComponentName().getPackageName() : "?")); 8490 } 8491 } 8492 } 8493 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8494 if (r == null) { 8495 r = new StringBuilder(256); 8496 } else { 8497 r.append(' '); 8498 } 8499 r.append(p.info.name); 8500 } 8501 } 8502 if (r != null) { 8503 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8504 } 8505 8506 N = pkg.services.size(); 8507 r = null; 8508 for (i=0; i<N; i++) { 8509 PackageParser.Service s = pkg.services.get(i); 8510 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8511 s.info.processName, pkg.applicationInfo.uid); 8512 mServices.addService(s); 8513 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8514 if (r == null) { 8515 r = new StringBuilder(256); 8516 } else { 8517 r.append(' '); 8518 } 8519 r.append(s.info.name); 8520 } 8521 } 8522 if (r != null) { 8523 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8524 } 8525 8526 N = pkg.receivers.size(); 8527 r = null; 8528 for (i=0; i<N; i++) { 8529 PackageParser.Activity a = pkg.receivers.get(i); 8530 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8531 a.info.processName, pkg.applicationInfo.uid); 8532 mReceivers.addActivity(a, "receiver"); 8533 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8534 if (r == null) { 8535 r = new StringBuilder(256); 8536 } else { 8537 r.append(' '); 8538 } 8539 r.append(a.info.name); 8540 } 8541 } 8542 if (r != null) { 8543 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8544 } 8545 8546 N = pkg.activities.size(); 8547 r = null; 8548 for (i=0; i<N; i++) { 8549 PackageParser.Activity a = pkg.activities.get(i); 8550 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8551 a.info.processName, pkg.applicationInfo.uid); 8552 mActivities.addActivity(a, "activity"); 8553 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8554 if (r == null) { 8555 r = new StringBuilder(256); 8556 } else { 8557 r.append(' '); 8558 } 8559 r.append(a.info.name); 8560 } 8561 } 8562 if (r != null) { 8563 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8564 } 8565 8566 N = pkg.permissionGroups.size(); 8567 r = null; 8568 for (i=0; i<N; i++) { 8569 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8570 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8571 if (cur == null) { 8572 mPermissionGroups.put(pg.info.name, pg); 8573 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8574 if (r == null) { 8575 r = new StringBuilder(256); 8576 } else { 8577 r.append(' '); 8578 } 8579 r.append(pg.info.name); 8580 } 8581 } else { 8582 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8583 + pg.info.packageName + " ignored: original from " 8584 + cur.info.packageName); 8585 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8586 if (r == null) { 8587 r = new StringBuilder(256); 8588 } else { 8589 r.append(' '); 8590 } 8591 r.append("DUP:"); 8592 r.append(pg.info.name); 8593 } 8594 } 8595 } 8596 if (r != null) { 8597 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8598 } 8599 8600 N = pkg.permissions.size(); 8601 r = null; 8602 for (i=0; i<N; i++) { 8603 PackageParser.Permission p = pkg.permissions.get(i); 8604 8605 // Assume by default that we did not install this permission into the system. 8606 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8607 8608 // Now that permission groups have a special meaning, we ignore permission 8609 // groups for legacy apps to prevent unexpected behavior. In particular, 8610 // permissions for one app being granted to someone just becase they happen 8611 // to be in a group defined by another app (before this had no implications). 8612 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8613 p.group = mPermissionGroups.get(p.info.group); 8614 // Warn for a permission in an unknown group. 8615 if (p.info.group != null && p.group == null) { 8616 Slog.w(TAG, "Permission " + p.info.name + " from package " 8617 + p.info.packageName + " in an unknown group " + p.info.group); 8618 } 8619 } 8620 8621 ArrayMap<String, BasePermission> permissionMap = 8622 p.tree ? mSettings.mPermissionTrees 8623 : mSettings.mPermissions; 8624 BasePermission bp = permissionMap.get(p.info.name); 8625 8626 // Allow system apps to redefine non-system permissions 8627 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8628 final boolean currentOwnerIsSystem = (bp.perm != null 8629 && isSystemApp(bp.perm.owner)); 8630 if (isSystemApp(p.owner)) { 8631 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8632 // It's a built-in permission and no owner, take ownership now 8633 bp.packageSetting = pkgSetting; 8634 bp.perm = p; 8635 bp.uid = pkg.applicationInfo.uid; 8636 bp.sourcePackage = p.info.packageName; 8637 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8638 } else if (!currentOwnerIsSystem) { 8639 String msg = "New decl " + p.owner + " of permission " 8640 + p.info.name + " is system; overriding " + bp.sourcePackage; 8641 reportSettingsProblem(Log.WARN, msg); 8642 bp = null; 8643 } 8644 } 8645 } 8646 8647 if (bp == null) { 8648 bp = new BasePermission(p.info.name, p.info.packageName, 8649 BasePermission.TYPE_NORMAL); 8650 permissionMap.put(p.info.name, bp); 8651 } 8652 8653 if (bp.perm == null) { 8654 if (bp.sourcePackage == null 8655 || bp.sourcePackage.equals(p.info.packageName)) { 8656 BasePermission tree = findPermissionTreeLP(p.info.name); 8657 if (tree == null 8658 || tree.sourcePackage.equals(p.info.packageName)) { 8659 bp.packageSetting = pkgSetting; 8660 bp.perm = p; 8661 bp.uid = pkg.applicationInfo.uid; 8662 bp.sourcePackage = p.info.packageName; 8663 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8664 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8665 if (r == null) { 8666 r = new StringBuilder(256); 8667 } else { 8668 r.append(' '); 8669 } 8670 r.append(p.info.name); 8671 } 8672 } else { 8673 Slog.w(TAG, "Permission " + p.info.name + " from package " 8674 + p.info.packageName + " ignored: base tree " 8675 + tree.name + " is from package " 8676 + tree.sourcePackage); 8677 } 8678 } else { 8679 Slog.w(TAG, "Permission " + p.info.name + " from package " 8680 + p.info.packageName + " ignored: original from " 8681 + bp.sourcePackage); 8682 } 8683 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8684 if (r == null) { 8685 r = new StringBuilder(256); 8686 } else { 8687 r.append(' '); 8688 } 8689 r.append("DUP:"); 8690 r.append(p.info.name); 8691 } 8692 if (bp.perm == p) { 8693 bp.protectionLevel = p.info.protectionLevel; 8694 } 8695 } 8696 8697 if (r != null) { 8698 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8699 } 8700 8701 N = pkg.instrumentation.size(); 8702 r = null; 8703 for (i=0; i<N; i++) { 8704 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8705 a.info.packageName = pkg.applicationInfo.packageName; 8706 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8707 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8708 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8709 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8710 a.info.dataDir = pkg.applicationInfo.dataDir; 8711 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8712 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8713 8714 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8715 // need other information about the application, like the ABI and what not ? 8716 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8717 mInstrumentation.put(a.getComponentName(), a); 8718 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8719 if (r == null) { 8720 r = new StringBuilder(256); 8721 } else { 8722 r.append(' '); 8723 } 8724 r.append(a.info.name); 8725 } 8726 } 8727 if (r != null) { 8728 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8729 } 8730 8731 if (pkg.protectedBroadcasts != null) { 8732 N = pkg.protectedBroadcasts.size(); 8733 for (i=0; i<N; i++) { 8734 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8735 } 8736 } 8737 8738 pkgSetting.setTimeStamp(scanFileTime); 8739 8740 // Create idmap files for pairs of (packages, overlay packages). 8741 // Note: "android", ie framework-res.apk, is handled by native layers. 8742 if (pkg.mOverlayTarget != null) { 8743 // This is an overlay package. 8744 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8745 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8746 mOverlays.put(pkg.mOverlayTarget, 8747 new ArrayMap<String, PackageParser.Package>()); 8748 } 8749 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8750 map.put(pkg.packageName, pkg); 8751 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8752 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8753 createIdmapFailed = true; 8754 } 8755 } 8756 } else if (mOverlays.containsKey(pkg.packageName) && 8757 !pkg.packageName.equals("android")) { 8758 // This is a regular package, with one or more known overlay packages. 8759 createIdmapsForPackageLI(pkg); 8760 } 8761 } 8762 8763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8764 8765 if (createIdmapFailed) { 8766 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8767 "scanPackageLI failed to createIdmap"); 8768 } 8769 return pkg; 8770 } 8771 8772 /** 8773 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8774 * is derived purely on the basis of the contents of {@code scanFile} and 8775 * {@code cpuAbiOverride}. 8776 * 8777 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8778 */ 8779 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8780 String cpuAbiOverride, boolean extractLibs) 8781 throws PackageManagerException { 8782 // TODO: We can probably be smarter about this stuff. For installed apps, 8783 // we can calculate this information at install time once and for all. For 8784 // system apps, we can probably assume that this information doesn't change 8785 // after the first boot scan. As things stand, we do lots of unnecessary work. 8786 8787 // Give ourselves some initial paths; we'll come back for another 8788 // pass once we've determined ABI below. 8789 setNativeLibraryPaths(pkg); 8790 8791 // We would never need to extract libs for forward-locked and external packages, 8792 // since the container service will do it for us. We shouldn't attempt to 8793 // extract libs from system app when it was not updated. 8794 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8795 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8796 extractLibs = false; 8797 } 8798 8799 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8800 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8801 8802 NativeLibraryHelper.Handle handle = null; 8803 try { 8804 handle = NativeLibraryHelper.Handle.create(pkg); 8805 // TODO(multiArch): This can be null for apps that didn't go through the 8806 // usual installation process. We can calculate it again, like we 8807 // do during install time. 8808 // 8809 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8810 // unnecessary. 8811 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8812 8813 // Null out the abis so that they can be recalculated. 8814 pkg.applicationInfo.primaryCpuAbi = null; 8815 pkg.applicationInfo.secondaryCpuAbi = null; 8816 if (isMultiArch(pkg.applicationInfo)) { 8817 // Warn if we've set an abiOverride for multi-lib packages.. 8818 // By definition, we need to copy both 32 and 64 bit libraries for 8819 // such packages. 8820 if (pkg.cpuAbiOverride != null 8821 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8822 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8823 } 8824 8825 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8826 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8827 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8828 if (extractLibs) { 8829 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8830 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8831 useIsaSpecificSubdirs); 8832 } else { 8833 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8834 } 8835 } 8836 8837 maybeThrowExceptionForMultiArchCopy( 8838 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8839 8840 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8841 if (extractLibs) { 8842 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8843 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8844 useIsaSpecificSubdirs); 8845 } else { 8846 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8847 } 8848 } 8849 8850 maybeThrowExceptionForMultiArchCopy( 8851 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8852 8853 if (abi64 >= 0) { 8854 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8855 } 8856 8857 if (abi32 >= 0) { 8858 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8859 if (abi64 >= 0) { 8860 if (pkg.use32bitAbi) { 8861 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8862 pkg.applicationInfo.primaryCpuAbi = abi; 8863 } else { 8864 pkg.applicationInfo.secondaryCpuAbi = abi; 8865 } 8866 } else { 8867 pkg.applicationInfo.primaryCpuAbi = abi; 8868 } 8869 } 8870 8871 } else { 8872 String[] abiList = (cpuAbiOverride != null) ? 8873 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8874 8875 // Enable gross and lame hacks for apps that are built with old 8876 // SDK tools. We must scan their APKs for renderscript bitcode and 8877 // not launch them if it's present. Don't bother checking on devices 8878 // that don't have 64 bit support. 8879 boolean needsRenderScriptOverride = false; 8880 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8881 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8882 abiList = Build.SUPPORTED_32_BIT_ABIS; 8883 needsRenderScriptOverride = true; 8884 } 8885 8886 final int copyRet; 8887 if (extractLibs) { 8888 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8889 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8890 } else { 8891 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8892 } 8893 8894 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8895 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8896 "Error unpackaging native libs for app, errorCode=" + copyRet); 8897 } 8898 8899 if (copyRet >= 0) { 8900 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8901 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8902 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8903 } else if (needsRenderScriptOverride) { 8904 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8905 } 8906 } 8907 } catch (IOException ioe) { 8908 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8909 } finally { 8910 IoUtils.closeQuietly(handle); 8911 } 8912 8913 // Now that we've calculated the ABIs and determined if it's an internal app, 8914 // we will go ahead and populate the nativeLibraryPath. 8915 setNativeLibraryPaths(pkg); 8916 } 8917 8918 /** 8919 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8920 * i.e, so that all packages can be run inside a single process if required. 8921 * 8922 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8923 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8924 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8925 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8926 * updating a package that belongs to a shared user. 8927 * 8928 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8929 * adds unnecessary complexity. 8930 */ 8931 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8932 PackageParser.Package scannedPackage, boolean bootComplete) { 8933 String requiredInstructionSet = null; 8934 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8935 requiredInstructionSet = VMRuntime.getInstructionSet( 8936 scannedPackage.applicationInfo.primaryCpuAbi); 8937 } 8938 8939 PackageSetting requirer = null; 8940 for (PackageSetting ps : packagesForUser) { 8941 // If packagesForUser contains scannedPackage, we skip it. This will happen 8942 // when scannedPackage is an update of an existing package. Without this check, 8943 // we will never be able to change the ABI of any package belonging to a shared 8944 // user, even if it's compatible with other packages. 8945 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8946 if (ps.primaryCpuAbiString == null) { 8947 continue; 8948 } 8949 8950 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8951 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8952 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8953 // this but there's not much we can do. 8954 String errorMessage = "Instruction set mismatch, " 8955 + ((requirer == null) ? "[caller]" : requirer) 8956 + " requires " + requiredInstructionSet + " whereas " + ps 8957 + " requires " + instructionSet; 8958 Slog.w(TAG, errorMessage); 8959 } 8960 8961 if (requiredInstructionSet == null) { 8962 requiredInstructionSet = instructionSet; 8963 requirer = ps; 8964 } 8965 } 8966 } 8967 8968 if (requiredInstructionSet != null) { 8969 String adjustedAbi; 8970 if (requirer != null) { 8971 // requirer != null implies that either scannedPackage was null or that scannedPackage 8972 // did not require an ABI, in which case we have to adjust scannedPackage to match 8973 // the ABI of the set (which is the same as requirer's ABI) 8974 adjustedAbi = requirer.primaryCpuAbiString; 8975 if (scannedPackage != null) { 8976 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8977 } 8978 } else { 8979 // requirer == null implies that we're updating all ABIs in the set to 8980 // match scannedPackage. 8981 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8982 } 8983 8984 for (PackageSetting ps : packagesForUser) { 8985 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8986 if (ps.primaryCpuAbiString != null) { 8987 continue; 8988 } 8989 8990 ps.primaryCpuAbiString = adjustedAbi; 8991 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8992 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8993 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8994 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8995 + " (requirer=" 8996 + (requirer == null ? "null" : requirer.pkg.packageName) 8997 + ", scannedPackage=" 8998 + (scannedPackage != null ? scannedPackage.packageName : "null") 8999 + ")"); 9000 try { 9001 mInstaller.rmdex(ps.codePathString, 9002 getDexCodeInstructionSet(getPreferredInstructionSet())); 9003 } catch (InstallerException ignored) { 9004 } 9005 } 9006 } 9007 } 9008 } 9009 } 9010 9011 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9012 synchronized (mPackages) { 9013 mResolverReplaced = true; 9014 // Set up information for custom user intent resolution activity. 9015 mResolveActivity.applicationInfo = pkg.applicationInfo; 9016 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9017 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9018 mResolveActivity.processName = pkg.applicationInfo.packageName; 9019 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9020 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9021 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9022 mResolveActivity.theme = 0; 9023 mResolveActivity.exported = true; 9024 mResolveActivity.enabled = true; 9025 mResolveInfo.activityInfo = mResolveActivity; 9026 mResolveInfo.priority = 0; 9027 mResolveInfo.preferredOrder = 0; 9028 mResolveInfo.match = 0; 9029 mResolveComponentName = mCustomResolverComponentName; 9030 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9031 mResolveComponentName); 9032 } 9033 } 9034 9035 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9036 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9037 9038 // Set up information for ephemeral installer activity 9039 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9040 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9041 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9042 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9043 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9044 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9045 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9046 mEphemeralInstallerActivity.theme = 0; 9047 mEphemeralInstallerActivity.exported = true; 9048 mEphemeralInstallerActivity.enabled = true; 9049 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9050 mEphemeralInstallerInfo.priority = 0; 9051 mEphemeralInstallerInfo.preferredOrder = 0; 9052 mEphemeralInstallerInfo.match = 0; 9053 9054 if (DEBUG_EPHEMERAL) { 9055 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9056 } 9057 } 9058 9059 private static String calculateBundledApkRoot(final String codePathString) { 9060 final File codePath = new File(codePathString); 9061 final File codeRoot; 9062 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9063 codeRoot = Environment.getRootDirectory(); 9064 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9065 codeRoot = Environment.getOemDirectory(); 9066 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9067 codeRoot = Environment.getVendorDirectory(); 9068 } else { 9069 // Unrecognized code path; take its top real segment as the apk root: 9070 // e.g. /something/app/blah.apk => /something 9071 try { 9072 File f = codePath.getCanonicalFile(); 9073 File parent = f.getParentFile(); // non-null because codePath is a file 9074 File tmp; 9075 while ((tmp = parent.getParentFile()) != null) { 9076 f = parent; 9077 parent = tmp; 9078 } 9079 codeRoot = f; 9080 Slog.w(TAG, "Unrecognized code path " 9081 + codePath + " - using " + codeRoot); 9082 } catch (IOException e) { 9083 // Can't canonicalize the code path -- shenanigans? 9084 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9085 return Environment.getRootDirectory().getPath(); 9086 } 9087 } 9088 return codeRoot.getPath(); 9089 } 9090 9091 /** 9092 * Derive and set the location of native libraries for the given package, 9093 * which varies depending on where and how the package was installed. 9094 */ 9095 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9096 final ApplicationInfo info = pkg.applicationInfo; 9097 final String codePath = pkg.codePath; 9098 final File codeFile = new File(codePath); 9099 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9100 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9101 9102 info.nativeLibraryRootDir = null; 9103 info.nativeLibraryRootRequiresIsa = false; 9104 info.nativeLibraryDir = null; 9105 info.secondaryNativeLibraryDir = null; 9106 9107 if (isApkFile(codeFile)) { 9108 // Monolithic install 9109 if (bundledApp) { 9110 // If "/system/lib64/apkname" exists, assume that is the per-package 9111 // native library directory to use; otherwise use "/system/lib/apkname". 9112 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9113 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9114 getPrimaryInstructionSet(info)); 9115 9116 // This is a bundled system app so choose the path based on the ABI. 9117 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9118 // is just the default path. 9119 final String apkName = deriveCodePathName(codePath); 9120 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9121 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9122 apkName).getAbsolutePath(); 9123 9124 if (info.secondaryCpuAbi != null) { 9125 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9126 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9127 secondaryLibDir, apkName).getAbsolutePath(); 9128 } 9129 } else if (asecApp) { 9130 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9131 .getAbsolutePath(); 9132 } else { 9133 final String apkName = deriveCodePathName(codePath); 9134 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9135 .getAbsolutePath(); 9136 } 9137 9138 info.nativeLibraryRootRequiresIsa = false; 9139 info.nativeLibraryDir = info.nativeLibraryRootDir; 9140 } else { 9141 // Cluster install 9142 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9143 info.nativeLibraryRootRequiresIsa = true; 9144 9145 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9146 getPrimaryInstructionSet(info)).getAbsolutePath(); 9147 9148 if (info.secondaryCpuAbi != null) { 9149 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9150 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9151 } 9152 } 9153 } 9154 9155 /** 9156 * Calculate the abis and roots for a bundled app. These can uniquely 9157 * be determined from the contents of the system partition, i.e whether 9158 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9159 * of this information, and instead assume that the system was built 9160 * sensibly. 9161 */ 9162 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9163 PackageSetting pkgSetting) { 9164 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9165 9166 // If "/system/lib64/apkname" exists, assume that is the per-package 9167 // native library directory to use; otherwise use "/system/lib/apkname". 9168 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9169 setBundledAppAbi(pkg, apkRoot, apkName); 9170 // pkgSetting might be null during rescan following uninstall of updates 9171 // to a bundled app, so accommodate that possibility. The settings in 9172 // that case will be established later from the parsed package. 9173 // 9174 // If the settings aren't null, sync them up with what we've just derived. 9175 // note that apkRoot isn't stored in the package settings. 9176 if (pkgSetting != null) { 9177 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9178 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9179 } 9180 } 9181 9182 /** 9183 * Deduces the ABI of a bundled app and sets the relevant fields on the 9184 * parsed pkg object. 9185 * 9186 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9187 * under which system libraries are installed. 9188 * @param apkName the name of the installed package. 9189 */ 9190 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9191 final File codeFile = new File(pkg.codePath); 9192 9193 final boolean has64BitLibs; 9194 final boolean has32BitLibs; 9195 if (isApkFile(codeFile)) { 9196 // Monolithic install 9197 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9198 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9199 } else { 9200 // Cluster install 9201 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9202 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9203 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9204 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9205 has64BitLibs = (new File(rootDir, isa)).exists(); 9206 } else { 9207 has64BitLibs = false; 9208 } 9209 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9210 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9211 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9212 has32BitLibs = (new File(rootDir, isa)).exists(); 9213 } else { 9214 has32BitLibs = false; 9215 } 9216 } 9217 9218 if (has64BitLibs && !has32BitLibs) { 9219 // The package has 64 bit libs, but not 32 bit libs. Its primary 9220 // ABI should be 64 bit. We can safely assume here that the bundled 9221 // native libraries correspond to the most preferred ABI in the list. 9222 9223 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9224 pkg.applicationInfo.secondaryCpuAbi = null; 9225 } else if (has32BitLibs && !has64BitLibs) { 9226 // The package has 32 bit libs but not 64 bit libs. Its primary 9227 // ABI should be 32 bit. 9228 9229 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9230 pkg.applicationInfo.secondaryCpuAbi = null; 9231 } else if (has32BitLibs && has64BitLibs) { 9232 // The application has both 64 and 32 bit bundled libraries. We check 9233 // here that the app declares multiArch support, and warn if it doesn't. 9234 // 9235 // We will be lenient here and record both ABIs. The primary will be the 9236 // ABI that's higher on the list, i.e, a device that's configured to prefer 9237 // 64 bit apps will see a 64 bit primary ABI, 9238 9239 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9240 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9241 } 9242 9243 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9244 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9245 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9246 } else { 9247 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9248 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9249 } 9250 } else { 9251 pkg.applicationInfo.primaryCpuAbi = null; 9252 pkg.applicationInfo.secondaryCpuAbi = null; 9253 } 9254 } 9255 9256 private void killApplication(String pkgName, int appId, String reason) { 9257 // Request the ActivityManager to kill the process(only for existing packages) 9258 // so that we do not end up in a confused state while the user is still using the older 9259 // version of the application while the new one gets installed. 9260 final long token = Binder.clearCallingIdentity(); 9261 try { 9262 IActivityManager am = ActivityManagerNative.getDefault(); 9263 if (am != null) { 9264 try { 9265 am.killApplicationWithAppId(pkgName, appId, reason); 9266 } catch (RemoteException e) { 9267 } 9268 } 9269 } finally { 9270 Binder.restoreCallingIdentity(token); 9271 } 9272 } 9273 9274 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9275 // Remove the parent package setting 9276 PackageSetting ps = (PackageSetting) pkg.mExtras; 9277 if (ps != null) { 9278 removePackageLI(ps, chatty); 9279 } 9280 // Remove the child package setting 9281 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9282 for (int i = 0; i < childCount; i++) { 9283 PackageParser.Package childPkg = pkg.childPackages.get(i); 9284 ps = (PackageSetting) childPkg.mExtras; 9285 if (ps != null) { 9286 removePackageLI(ps, chatty); 9287 } 9288 } 9289 } 9290 9291 void removePackageLI(PackageSetting ps, boolean chatty) { 9292 if (DEBUG_INSTALL) { 9293 if (chatty) 9294 Log.d(TAG, "Removing package " + ps.name); 9295 } 9296 9297 // writer 9298 synchronized (mPackages) { 9299 mPackages.remove(ps.name); 9300 final PackageParser.Package pkg = ps.pkg; 9301 if (pkg != null) { 9302 cleanPackageDataStructuresLILPw(pkg, chatty); 9303 } 9304 } 9305 } 9306 9307 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9308 if (DEBUG_INSTALL) { 9309 if (chatty) 9310 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9311 } 9312 9313 // writer 9314 synchronized (mPackages) { 9315 // Remove the parent package 9316 mPackages.remove(pkg.applicationInfo.packageName); 9317 cleanPackageDataStructuresLILPw(pkg, chatty); 9318 9319 // Remove the child packages 9320 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9321 for (int i = 0; i < childCount; i++) { 9322 PackageParser.Package childPkg = pkg.childPackages.get(i); 9323 mPackages.remove(childPkg.applicationInfo.packageName); 9324 cleanPackageDataStructuresLILPw(childPkg, chatty); 9325 } 9326 } 9327 } 9328 9329 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9330 int N = pkg.providers.size(); 9331 StringBuilder r = null; 9332 int i; 9333 for (i=0; i<N; i++) { 9334 PackageParser.Provider p = pkg.providers.get(i); 9335 mProviders.removeProvider(p); 9336 if (p.info.authority == null) { 9337 9338 /* There was another ContentProvider with this authority when 9339 * this app was installed so this authority is null, 9340 * Ignore it as we don't have to unregister the provider. 9341 */ 9342 continue; 9343 } 9344 String names[] = p.info.authority.split(";"); 9345 for (int j = 0; j < names.length; j++) { 9346 if (mProvidersByAuthority.get(names[j]) == p) { 9347 mProvidersByAuthority.remove(names[j]); 9348 if (DEBUG_REMOVE) { 9349 if (chatty) 9350 Log.d(TAG, "Unregistered content provider: " + names[j] 9351 + ", className = " + p.info.name + ", isSyncable = " 9352 + p.info.isSyncable); 9353 } 9354 } 9355 } 9356 if (DEBUG_REMOVE && chatty) { 9357 if (r == null) { 9358 r = new StringBuilder(256); 9359 } else { 9360 r.append(' '); 9361 } 9362 r.append(p.info.name); 9363 } 9364 } 9365 if (r != null) { 9366 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9367 } 9368 9369 N = pkg.services.size(); 9370 r = null; 9371 for (i=0; i<N; i++) { 9372 PackageParser.Service s = pkg.services.get(i); 9373 mServices.removeService(s); 9374 if (chatty) { 9375 if (r == null) { 9376 r = new StringBuilder(256); 9377 } else { 9378 r.append(' '); 9379 } 9380 r.append(s.info.name); 9381 } 9382 } 9383 if (r != null) { 9384 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9385 } 9386 9387 N = pkg.receivers.size(); 9388 r = null; 9389 for (i=0; i<N; i++) { 9390 PackageParser.Activity a = pkg.receivers.get(i); 9391 mReceivers.removeActivity(a, "receiver"); 9392 if (DEBUG_REMOVE && chatty) { 9393 if (r == null) { 9394 r = new StringBuilder(256); 9395 } else { 9396 r.append(' '); 9397 } 9398 r.append(a.info.name); 9399 } 9400 } 9401 if (r != null) { 9402 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9403 } 9404 9405 N = pkg.activities.size(); 9406 r = null; 9407 for (i=0; i<N; i++) { 9408 PackageParser.Activity a = pkg.activities.get(i); 9409 mActivities.removeActivity(a, "activity"); 9410 if (DEBUG_REMOVE && chatty) { 9411 if (r == null) { 9412 r = new StringBuilder(256); 9413 } else { 9414 r.append(' '); 9415 } 9416 r.append(a.info.name); 9417 } 9418 } 9419 if (r != null) { 9420 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9421 } 9422 9423 N = pkg.permissions.size(); 9424 r = null; 9425 for (i=0; i<N; i++) { 9426 PackageParser.Permission p = pkg.permissions.get(i); 9427 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9428 if (bp == null) { 9429 bp = mSettings.mPermissionTrees.get(p.info.name); 9430 } 9431 if (bp != null && bp.perm == p) { 9432 bp.perm = null; 9433 if (DEBUG_REMOVE && chatty) { 9434 if (r == null) { 9435 r = new StringBuilder(256); 9436 } else { 9437 r.append(' '); 9438 } 9439 r.append(p.info.name); 9440 } 9441 } 9442 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9443 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9444 if (appOpPkgs != null) { 9445 appOpPkgs.remove(pkg.packageName); 9446 } 9447 } 9448 } 9449 if (r != null) { 9450 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9451 } 9452 9453 N = pkg.requestedPermissions.size(); 9454 r = null; 9455 for (i=0; i<N; i++) { 9456 String perm = pkg.requestedPermissions.get(i); 9457 BasePermission bp = mSettings.mPermissions.get(perm); 9458 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9459 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9460 if (appOpPkgs != null) { 9461 appOpPkgs.remove(pkg.packageName); 9462 if (appOpPkgs.isEmpty()) { 9463 mAppOpPermissionPackages.remove(perm); 9464 } 9465 } 9466 } 9467 } 9468 if (r != null) { 9469 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9470 } 9471 9472 N = pkg.instrumentation.size(); 9473 r = null; 9474 for (i=0; i<N; i++) { 9475 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9476 mInstrumentation.remove(a.getComponentName()); 9477 if (DEBUG_REMOVE && chatty) { 9478 if (r == null) { 9479 r = new StringBuilder(256); 9480 } else { 9481 r.append(' '); 9482 } 9483 r.append(a.info.name); 9484 } 9485 } 9486 if (r != null) { 9487 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9488 } 9489 9490 r = null; 9491 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9492 // Only system apps can hold shared libraries. 9493 if (pkg.libraryNames != null) { 9494 for (i=0; i<pkg.libraryNames.size(); i++) { 9495 String name = pkg.libraryNames.get(i); 9496 SharedLibraryEntry cur = mSharedLibraries.get(name); 9497 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9498 mSharedLibraries.remove(name); 9499 if (DEBUG_REMOVE && chatty) { 9500 if (r == null) { 9501 r = new StringBuilder(256); 9502 } else { 9503 r.append(' '); 9504 } 9505 r.append(name); 9506 } 9507 } 9508 } 9509 } 9510 } 9511 if (r != null) { 9512 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9513 } 9514 } 9515 9516 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9517 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9518 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9519 return true; 9520 } 9521 } 9522 return false; 9523 } 9524 9525 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9526 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9527 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9528 9529 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9530 // Update the parent permissions 9531 updatePermissionsLPw(pkg.packageName, pkg, flags); 9532 // Update the child permissions 9533 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9534 for (int i = 0; i < childCount; i++) { 9535 PackageParser.Package childPkg = pkg.childPackages.get(i); 9536 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9537 } 9538 } 9539 9540 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9541 int flags) { 9542 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9543 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9544 } 9545 9546 private void updatePermissionsLPw(String changingPkg, 9547 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9548 // Make sure there are no dangling permission trees. 9549 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9550 while (it.hasNext()) { 9551 final BasePermission bp = it.next(); 9552 if (bp.packageSetting == null) { 9553 // We may not yet have parsed the package, so just see if 9554 // we still know about its settings. 9555 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9556 } 9557 if (bp.packageSetting == null) { 9558 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9559 + " from package " + bp.sourcePackage); 9560 it.remove(); 9561 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9562 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9563 Slog.i(TAG, "Removing old permission tree: " + bp.name 9564 + " from package " + bp.sourcePackage); 9565 flags |= UPDATE_PERMISSIONS_ALL; 9566 it.remove(); 9567 } 9568 } 9569 } 9570 9571 // Make sure all dynamic permissions have been assigned to a package, 9572 // and make sure there are no dangling permissions. 9573 it = mSettings.mPermissions.values().iterator(); 9574 while (it.hasNext()) { 9575 final BasePermission bp = it.next(); 9576 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9577 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9578 + bp.name + " pkg=" + bp.sourcePackage 9579 + " info=" + bp.pendingInfo); 9580 if (bp.packageSetting == null && bp.pendingInfo != null) { 9581 final BasePermission tree = findPermissionTreeLP(bp.name); 9582 if (tree != null && tree.perm != null) { 9583 bp.packageSetting = tree.packageSetting; 9584 bp.perm = new PackageParser.Permission(tree.perm.owner, 9585 new PermissionInfo(bp.pendingInfo)); 9586 bp.perm.info.packageName = tree.perm.info.packageName; 9587 bp.perm.info.name = bp.name; 9588 bp.uid = tree.uid; 9589 } 9590 } 9591 } 9592 if (bp.packageSetting == null) { 9593 // We may not yet have parsed the package, so just see if 9594 // we still know about its settings. 9595 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9596 } 9597 if (bp.packageSetting == null) { 9598 Slog.w(TAG, "Removing dangling permission: " + bp.name 9599 + " from package " + bp.sourcePackage); 9600 it.remove(); 9601 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9602 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9603 Slog.i(TAG, "Removing old permission: " + bp.name 9604 + " from package " + bp.sourcePackage); 9605 flags |= UPDATE_PERMISSIONS_ALL; 9606 it.remove(); 9607 } 9608 } 9609 } 9610 9611 // Now update the permissions for all packages, in particular 9612 // replace the granted permissions of the system packages. 9613 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9614 for (PackageParser.Package pkg : mPackages.values()) { 9615 if (pkg != pkgInfo) { 9616 // Only replace for packages on requested volume 9617 final String volumeUuid = getVolumeUuidForPackage(pkg); 9618 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9619 && Objects.equals(replaceVolumeUuid, volumeUuid); 9620 grantPermissionsLPw(pkg, replace, changingPkg); 9621 } 9622 } 9623 } 9624 9625 if (pkgInfo != null) { 9626 // Only replace for packages on requested volume 9627 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9628 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9629 && Objects.equals(replaceVolumeUuid, volumeUuid); 9630 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9631 } 9632 } 9633 9634 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9635 String packageOfInterest) { 9636 // IMPORTANT: There are two types of permissions: install and runtime. 9637 // Install time permissions are granted when the app is installed to 9638 // all device users and users added in the future. Runtime permissions 9639 // are granted at runtime explicitly to specific users. Normal and signature 9640 // protected permissions are install time permissions. Dangerous permissions 9641 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9642 // otherwise they are runtime permissions. This function does not manage 9643 // runtime permissions except for the case an app targeting Lollipop MR1 9644 // being upgraded to target a newer SDK, in which case dangerous permissions 9645 // are transformed from install time to runtime ones. 9646 9647 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9648 if (ps == null) { 9649 return; 9650 } 9651 9652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9653 9654 PermissionsState permissionsState = ps.getPermissionsState(); 9655 PermissionsState origPermissions = permissionsState; 9656 9657 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9658 9659 boolean runtimePermissionsRevoked = false; 9660 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9661 9662 boolean changedInstallPermission = false; 9663 9664 if (replace) { 9665 ps.installPermissionsFixed = false; 9666 if (!ps.isSharedUser()) { 9667 origPermissions = new PermissionsState(permissionsState); 9668 permissionsState.reset(); 9669 } else { 9670 // We need to know only about runtime permission changes since the 9671 // calling code always writes the install permissions state but 9672 // the runtime ones are written only if changed. The only cases of 9673 // changed runtime permissions here are promotion of an install to 9674 // runtime and revocation of a runtime from a shared user. 9675 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9676 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9677 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9678 runtimePermissionsRevoked = true; 9679 } 9680 } 9681 } 9682 9683 permissionsState.setGlobalGids(mGlobalGids); 9684 9685 final int N = pkg.requestedPermissions.size(); 9686 for (int i=0; i<N; i++) { 9687 final String name = pkg.requestedPermissions.get(i); 9688 final BasePermission bp = mSettings.mPermissions.get(name); 9689 9690 if (DEBUG_INSTALL) { 9691 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9692 } 9693 9694 if (bp == null || bp.packageSetting == null) { 9695 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9696 Slog.w(TAG, "Unknown permission " + name 9697 + " in package " + pkg.packageName); 9698 } 9699 continue; 9700 } 9701 9702 final String perm = bp.name; 9703 boolean allowedSig = false; 9704 int grant = GRANT_DENIED; 9705 9706 // Keep track of app op permissions. 9707 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9708 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9709 if (pkgs == null) { 9710 pkgs = new ArraySet<>(); 9711 mAppOpPermissionPackages.put(bp.name, pkgs); 9712 } 9713 pkgs.add(pkg.packageName); 9714 } 9715 9716 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9717 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9718 >= Build.VERSION_CODES.M; 9719 switch (level) { 9720 case PermissionInfo.PROTECTION_NORMAL: { 9721 // For all apps normal permissions are install time ones. 9722 grant = GRANT_INSTALL; 9723 } break; 9724 9725 case PermissionInfo.PROTECTION_DANGEROUS: { 9726 // If a permission review is required for legacy apps we represent 9727 // their permissions as always granted runtime ones since we need 9728 // to keep the review required permission flag per user while an 9729 // install permission's state is shared across all users. 9730 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9731 // For legacy apps dangerous permissions are install time ones. 9732 grant = GRANT_INSTALL; 9733 } else if (origPermissions.hasInstallPermission(bp.name)) { 9734 // For legacy apps that became modern, install becomes runtime. 9735 grant = GRANT_UPGRADE; 9736 } else if (mPromoteSystemApps 9737 && isSystemApp(ps) 9738 && mExistingSystemPackages.contains(ps.name)) { 9739 // For legacy system apps, install becomes runtime. 9740 // We cannot check hasInstallPermission() for system apps since those 9741 // permissions were granted implicitly and not persisted pre-M. 9742 grant = GRANT_UPGRADE; 9743 } else { 9744 // For modern apps keep runtime permissions unchanged. 9745 grant = GRANT_RUNTIME; 9746 } 9747 } break; 9748 9749 case PermissionInfo.PROTECTION_SIGNATURE: { 9750 // For all apps signature permissions are install time ones. 9751 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9752 if (allowedSig) { 9753 grant = GRANT_INSTALL; 9754 } 9755 } break; 9756 } 9757 9758 if (DEBUG_INSTALL) { 9759 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9760 } 9761 9762 if (grant != GRANT_DENIED) { 9763 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9764 // If this is an existing, non-system package, then 9765 // we can't add any new permissions to it. 9766 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9767 // Except... if this is a permission that was added 9768 // to the platform (note: need to only do this when 9769 // updating the platform). 9770 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9771 grant = GRANT_DENIED; 9772 } 9773 } 9774 } 9775 9776 switch (grant) { 9777 case GRANT_INSTALL: { 9778 // Revoke this as runtime permission to handle the case of 9779 // a runtime permission being downgraded to an install one. 9780 // Also in permission review mode we keep dangerous permissions 9781 // for legacy apps 9782 for (int userId : UserManagerService.getInstance().getUserIds()) { 9783 if (origPermissions.getRuntimePermissionState( 9784 bp.name, userId) != null) { 9785 // Revoke the runtime permission and clear the flags. 9786 origPermissions.revokeRuntimePermission(bp, userId); 9787 origPermissions.updatePermissionFlags(bp, userId, 9788 PackageManager.MASK_PERMISSION_FLAGS, 0); 9789 // If we revoked a permission permission, we have to write. 9790 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9791 changedRuntimePermissionUserIds, userId); 9792 } 9793 } 9794 // Grant an install permission. 9795 if (permissionsState.grantInstallPermission(bp) != 9796 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9797 changedInstallPermission = true; 9798 } 9799 } break; 9800 9801 case GRANT_RUNTIME: { 9802 // Grant previously granted runtime permissions. 9803 for (int userId : UserManagerService.getInstance().getUserIds()) { 9804 PermissionState permissionState = origPermissions 9805 .getRuntimePermissionState(bp.name, userId); 9806 int flags = permissionState != null 9807 ? permissionState.getFlags() : 0; 9808 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9809 if (permissionsState.grantRuntimePermission(bp, userId) == 9810 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9811 // If we cannot put the permission as it was, we have to write. 9812 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9813 changedRuntimePermissionUserIds, userId); 9814 } 9815 // If the app supports runtime permissions no need for a review. 9816 if (Build.PERMISSIONS_REVIEW_REQUIRED 9817 && appSupportsRuntimePermissions 9818 && (flags & PackageManager 9819 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9820 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9821 // Since we changed the flags, we have to write. 9822 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9823 changedRuntimePermissionUserIds, userId); 9824 } 9825 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9826 && !appSupportsRuntimePermissions) { 9827 // For legacy apps that need a permission review, every new 9828 // runtime permission is granted but it is pending a review. 9829 // We also need to review only platform defined runtime 9830 // permissions as these are the only ones the platform knows 9831 // how to disable the API to simulate revocation as legacy 9832 // apps don't expect to run with revoked permissions. 9833 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9834 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9835 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9836 // We changed the flags, hence have to write. 9837 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9838 changedRuntimePermissionUserIds, userId); 9839 } 9840 } 9841 if (permissionsState.grantRuntimePermission(bp, userId) 9842 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9843 // We changed the permission, hence have to write. 9844 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9845 changedRuntimePermissionUserIds, userId); 9846 } 9847 } 9848 // Propagate the permission flags. 9849 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9850 } 9851 } break; 9852 9853 case GRANT_UPGRADE: { 9854 // Grant runtime permissions for a previously held install permission. 9855 PermissionState permissionState = origPermissions 9856 .getInstallPermissionState(bp.name); 9857 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9858 9859 if (origPermissions.revokeInstallPermission(bp) 9860 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9861 // We will be transferring the permission flags, so clear them. 9862 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9863 PackageManager.MASK_PERMISSION_FLAGS, 0); 9864 changedInstallPermission = true; 9865 } 9866 9867 // If the permission is not to be promoted to runtime we ignore it and 9868 // also its other flags as they are not applicable to install permissions. 9869 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9870 for (int userId : currentUserIds) { 9871 if (permissionsState.grantRuntimePermission(bp, userId) != 9872 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9873 // Transfer the permission flags. 9874 permissionsState.updatePermissionFlags(bp, userId, 9875 flags, flags); 9876 // If we granted the permission, we have to write. 9877 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9878 changedRuntimePermissionUserIds, userId); 9879 } 9880 } 9881 } 9882 } break; 9883 9884 default: { 9885 if (packageOfInterest == null 9886 || packageOfInterest.equals(pkg.packageName)) { 9887 Slog.w(TAG, "Not granting permission " + perm 9888 + " to package " + pkg.packageName 9889 + " because it was previously installed without"); 9890 } 9891 } break; 9892 } 9893 } else { 9894 if (permissionsState.revokeInstallPermission(bp) != 9895 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9896 // Also drop the permission flags. 9897 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9898 PackageManager.MASK_PERMISSION_FLAGS, 0); 9899 changedInstallPermission = true; 9900 Slog.i(TAG, "Un-granting permission " + perm 9901 + " from package " + pkg.packageName 9902 + " (protectionLevel=" + bp.protectionLevel 9903 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9904 + ")"); 9905 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9906 // Don't print warning for app op permissions, since it is fine for them 9907 // not to be granted, there is a UI for the user to decide. 9908 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9909 Slog.w(TAG, "Not granting permission " + perm 9910 + " to package " + pkg.packageName 9911 + " (protectionLevel=" + bp.protectionLevel 9912 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9913 + ")"); 9914 } 9915 } 9916 } 9917 } 9918 9919 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9920 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9921 // This is the first that we have heard about this package, so the 9922 // permissions we have now selected are fixed until explicitly 9923 // changed. 9924 ps.installPermissionsFixed = true; 9925 } 9926 9927 // Persist the runtime permissions state for users with changes. If permissions 9928 // were revoked because no app in the shared user declares them we have to 9929 // write synchronously to avoid losing runtime permissions state. 9930 for (int userId : changedRuntimePermissionUserIds) { 9931 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9932 } 9933 9934 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9935 } 9936 9937 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9938 boolean allowed = false; 9939 final int NP = PackageParser.NEW_PERMISSIONS.length; 9940 for (int ip=0; ip<NP; ip++) { 9941 final PackageParser.NewPermissionInfo npi 9942 = PackageParser.NEW_PERMISSIONS[ip]; 9943 if (npi.name.equals(perm) 9944 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9945 allowed = true; 9946 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9947 + pkg.packageName); 9948 break; 9949 } 9950 } 9951 return allowed; 9952 } 9953 9954 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9955 BasePermission bp, PermissionsState origPermissions) { 9956 boolean allowed; 9957 allowed = (compareSignatures( 9958 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9959 == PackageManager.SIGNATURE_MATCH) 9960 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9961 == PackageManager.SIGNATURE_MATCH); 9962 if (!allowed && (bp.protectionLevel 9963 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9964 if (isSystemApp(pkg)) { 9965 // For updated system applications, a system permission 9966 // is granted only if it had been defined by the original application. 9967 if (pkg.isUpdatedSystemApp()) { 9968 final PackageSetting sysPs = mSettings 9969 .getDisabledSystemPkgLPr(pkg.packageName); 9970 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9971 // If the original was granted this permission, we take 9972 // that grant decision as read and propagate it to the 9973 // update. 9974 if (sysPs.isPrivileged()) { 9975 allowed = true; 9976 } 9977 } else { 9978 // The system apk may have been updated with an older 9979 // version of the one on the data partition, but which 9980 // granted a new system permission that it didn't have 9981 // before. In this case we do want to allow the app to 9982 // now get the new permission if the ancestral apk is 9983 // privileged to get it. 9984 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9985 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9986 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9987 allowed = true; 9988 break; 9989 } 9990 } 9991 } 9992 // Also if a privileged parent package on the system image or any of 9993 // its children requested a privileged permission, the updated child 9994 // packages can also get the permission. 9995 if (pkg.parentPackage != null) { 9996 final PackageSetting disabledSysParentPs = mSettings 9997 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9998 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9999 && disabledSysParentPs.isPrivileged()) { 10000 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10001 allowed = true; 10002 } else if (disabledSysParentPs.pkg.childPackages != null) { 10003 final int count = disabledSysParentPs.pkg.childPackages.size(); 10004 for (int i = 0; i < count; i++) { 10005 PackageParser.Package disabledSysChildPkg = 10006 disabledSysParentPs.pkg.childPackages.get(i); 10007 if (isPackageRequestingPermission(disabledSysChildPkg, 10008 perm)) { 10009 allowed = true; 10010 break; 10011 } 10012 } 10013 } 10014 } 10015 } 10016 } 10017 } else { 10018 allowed = isPrivilegedApp(pkg); 10019 } 10020 } 10021 } 10022 if (!allowed) { 10023 if (!allowed && (bp.protectionLevel 10024 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10025 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10026 // If this was a previously normal/dangerous permission that got moved 10027 // to a system permission as part of the runtime permission redesign, then 10028 // we still want to blindly grant it to old apps. 10029 allowed = true; 10030 } 10031 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10032 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10033 // If this permission is to be granted to the system installer and 10034 // this app is an installer, then it gets the permission. 10035 allowed = true; 10036 } 10037 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10038 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10039 // If this permission is to be granted to the system verifier and 10040 // this app is a verifier, then it gets the permission. 10041 allowed = true; 10042 } 10043 if (!allowed && (bp.protectionLevel 10044 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10045 && isSystemApp(pkg)) { 10046 // Any pre-installed system app is allowed to get this permission. 10047 allowed = true; 10048 } 10049 if (!allowed && (bp.protectionLevel 10050 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10051 // For development permissions, a development permission 10052 // is granted only if it was already granted. 10053 allowed = origPermissions.hasInstallPermission(perm); 10054 } 10055 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10056 && pkg.packageName.equals(mSetupWizardPackage)) { 10057 // If this permission is to be granted to the system setup wizard and 10058 // this app is a setup wizard, then it gets the permission. 10059 allowed = true; 10060 } 10061 } 10062 return allowed; 10063 } 10064 10065 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10066 final int permCount = pkg.requestedPermissions.size(); 10067 for (int j = 0; j < permCount; j++) { 10068 String requestedPermission = pkg.requestedPermissions.get(j); 10069 if (permission.equals(requestedPermission)) { 10070 return true; 10071 } 10072 } 10073 return false; 10074 } 10075 10076 final class ActivityIntentResolver 10077 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10078 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10079 boolean defaultOnly, int userId) { 10080 if (!sUserManager.exists(userId)) return null; 10081 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10082 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10083 } 10084 10085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10086 int userId) { 10087 if (!sUserManager.exists(userId)) return null; 10088 mFlags = flags; 10089 return super.queryIntent(intent, resolvedType, 10090 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10091 } 10092 10093 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10094 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10095 if (!sUserManager.exists(userId)) return null; 10096 if (packageActivities == null) { 10097 return null; 10098 } 10099 mFlags = flags; 10100 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10101 final int N = packageActivities.size(); 10102 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10103 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10104 10105 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10106 for (int i = 0; i < N; ++i) { 10107 intentFilters = packageActivities.get(i).intents; 10108 if (intentFilters != null && intentFilters.size() > 0) { 10109 PackageParser.ActivityIntentInfo[] array = 10110 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10111 intentFilters.toArray(array); 10112 listCut.add(array); 10113 } 10114 } 10115 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10116 } 10117 10118 /** 10119 * Finds a privileged activity that matches the specified activity names. 10120 */ 10121 private PackageParser.Activity findMatchingActivity( 10122 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10123 for (PackageParser.Activity sysActivity : activityList) { 10124 if (sysActivity.info.name.equals(activityInfo.name)) { 10125 return sysActivity; 10126 } 10127 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10128 return sysActivity; 10129 } 10130 if (sysActivity.info.targetActivity != null) { 10131 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10132 return sysActivity; 10133 } 10134 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10135 return sysActivity; 10136 } 10137 } 10138 } 10139 return null; 10140 } 10141 10142 public class IterGenerator<E> { 10143 public Iterator<E> generate(ActivityIntentInfo info) { 10144 return null; 10145 } 10146 } 10147 10148 public class ActionIterGenerator extends IterGenerator<String> { 10149 @Override 10150 public Iterator<String> generate(ActivityIntentInfo info) { 10151 return info.actionsIterator(); 10152 } 10153 } 10154 10155 public class CategoriesIterGenerator extends IterGenerator<String> { 10156 @Override 10157 public Iterator<String> generate(ActivityIntentInfo info) { 10158 return info.categoriesIterator(); 10159 } 10160 } 10161 10162 public class SchemesIterGenerator extends IterGenerator<String> { 10163 @Override 10164 public Iterator<String> generate(ActivityIntentInfo info) { 10165 return info.schemesIterator(); 10166 } 10167 } 10168 10169 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10170 @Override 10171 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10172 return info.authoritiesIterator(); 10173 } 10174 } 10175 10176 /** 10177 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10178 * MODIFIED. Do not pass in a list that should not be changed. 10179 */ 10180 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10181 IterGenerator<T> generator, Iterator<T> searchIterator) { 10182 // loop through the set of actions; every one must be found in the intent filter 10183 while (searchIterator.hasNext()) { 10184 // we must have at least one filter in the list to consider a match 10185 if (intentList.size() == 0) { 10186 break; 10187 } 10188 10189 final T searchAction = searchIterator.next(); 10190 10191 // loop through the set of intent filters 10192 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10193 while (intentIter.hasNext()) { 10194 final ActivityIntentInfo intentInfo = intentIter.next(); 10195 boolean selectionFound = false; 10196 10197 // loop through the intent filter's selection criteria; at least one 10198 // of them must match the searched criteria 10199 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10200 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10201 final T intentSelection = intentSelectionIter.next(); 10202 if (intentSelection != null && intentSelection.equals(searchAction)) { 10203 selectionFound = true; 10204 break; 10205 } 10206 } 10207 10208 // the selection criteria wasn't found in this filter's set; this filter 10209 // is not a potential match 10210 if (!selectionFound) { 10211 intentIter.remove(); 10212 } 10213 } 10214 } 10215 } 10216 10217 private boolean isProtectedAction(ActivityIntentInfo filter) { 10218 final Iterator<String> actionsIter = filter.actionsIterator(); 10219 while (actionsIter != null && actionsIter.hasNext()) { 10220 final String filterAction = actionsIter.next(); 10221 if (PROTECTED_ACTIONS.contains(filterAction)) { 10222 return true; 10223 } 10224 } 10225 return false; 10226 } 10227 10228 /** 10229 * Adjusts the priority of the given intent filter according to policy. 10230 * <p> 10231 * <ul> 10232 * <li>The priority for non privileged applications is capped to '0'</li> 10233 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10234 * <li>The priority for unbundled updates to privileged applications is capped to the 10235 * priority defined on the system partition</li> 10236 * </ul> 10237 * <p> 10238 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10239 * allowed to obtain any priority on any action. 10240 */ 10241 private void adjustPriority( 10242 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10243 // nothing to do; priority is fine as-is 10244 if (intent.getPriority() <= 0) { 10245 return; 10246 } 10247 10248 final ActivityInfo activityInfo = intent.activity.info; 10249 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10250 10251 final boolean privilegedApp = 10252 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10253 if (!privilegedApp) { 10254 // non-privileged applications can never define a priority >0 10255 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10256 + " package: " + applicationInfo.packageName 10257 + " activity: " + intent.activity.className 10258 + " origPrio: " + intent.getPriority()); 10259 intent.setPriority(0); 10260 return; 10261 } 10262 10263 if (systemActivities == null) { 10264 // the system package is not disabled; we're parsing the system partition 10265 if (isProtectedAction(intent)) { 10266 if (mDeferProtectedFilters) { 10267 // We can't deal with these just yet. No component should ever obtain a 10268 // >0 priority for a protected actions, with ONE exception -- the setup 10269 // wizard. The setup wizard, however, cannot be known until we're able to 10270 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10271 // until all intent filters have been processed. Chicken, meet egg. 10272 // Let the filter temporarily have a high priority and rectify the 10273 // priorities after all system packages have been scanned. 10274 mProtectedFilters.add(intent); 10275 if (DEBUG_FILTERS) { 10276 Slog.i(TAG, "Protected action; save for later;" 10277 + " package: " + applicationInfo.packageName 10278 + " activity: " + intent.activity.className 10279 + " origPrio: " + intent.getPriority()); 10280 } 10281 return; 10282 } else { 10283 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10284 Slog.i(TAG, "No setup wizard;" 10285 + " All protected intents capped to priority 0"); 10286 } 10287 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10288 if (DEBUG_FILTERS) { 10289 Slog.i(TAG, "Found setup wizard;" 10290 + " allow priority " + intent.getPriority() + ";" 10291 + " package: " + intent.activity.info.packageName 10292 + " activity: " + intent.activity.className 10293 + " priority: " + intent.getPriority()); 10294 } 10295 // setup wizard gets whatever it wants 10296 return; 10297 } 10298 Slog.w(TAG, "Protected action; cap priority to 0;" 10299 + " package: " + intent.activity.info.packageName 10300 + " activity: " + intent.activity.className 10301 + " origPrio: " + intent.getPriority()); 10302 intent.setPriority(0); 10303 return; 10304 } 10305 } 10306 // privileged apps on the system image get whatever priority they request 10307 return; 10308 } 10309 10310 // privileged app unbundled update ... try to find the same activity 10311 final PackageParser.Activity foundActivity = 10312 findMatchingActivity(systemActivities, activityInfo); 10313 if (foundActivity == null) { 10314 // this is a new activity; it cannot obtain >0 priority 10315 if (DEBUG_FILTERS) { 10316 Slog.i(TAG, "New activity; cap priority to 0;" 10317 + " package: " + applicationInfo.packageName 10318 + " activity: " + intent.activity.className 10319 + " origPrio: " + intent.getPriority()); 10320 } 10321 intent.setPriority(0); 10322 return; 10323 } 10324 10325 // found activity, now check for filter equivalence 10326 10327 // a shallow copy is enough; we modify the list, not its contents 10328 final List<ActivityIntentInfo> intentListCopy = 10329 new ArrayList<>(foundActivity.intents); 10330 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10331 10332 // find matching action subsets 10333 final Iterator<String> actionsIterator = intent.actionsIterator(); 10334 if (actionsIterator != null) { 10335 getIntentListSubset( 10336 intentListCopy, new ActionIterGenerator(), actionsIterator); 10337 if (intentListCopy.size() == 0) { 10338 // no more intents to match; we're not equivalent 10339 if (DEBUG_FILTERS) { 10340 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10341 + " package: " + applicationInfo.packageName 10342 + " activity: " + intent.activity.className 10343 + " origPrio: " + intent.getPriority()); 10344 } 10345 intent.setPriority(0); 10346 return; 10347 } 10348 } 10349 10350 // find matching category subsets 10351 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10352 if (categoriesIterator != null) { 10353 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10354 categoriesIterator); 10355 if (intentListCopy.size() == 0) { 10356 // no more intents to match; we're not equivalent 10357 if (DEBUG_FILTERS) { 10358 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10359 + " package: " + applicationInfo.packageName 10360 + " activity: " + intent.activity.className 10361 + " origPrio: " + intent.getPriority()); 10362 } 10363 intent.setPriority(0); 10364 return; 10365 } 10366 } 10367 10368 // find matching schemes subsets 10369 final Iterator<String> schemesIterator = intent.schemesIterator(); 10370 if (schemesIterator != null) { 10371 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10372 schemesIterator); 10373 if (intentListCopy.size() == 0) { 10374 // no more intents to match; we're not equivalent 10375 if (DEBUG_FILTERS) { 10376 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10377 + " package: " + applicationInfo.packageName 10378 + " activity: " + intent.activity.className 10379 + " origPrio: " + intent.getPriority()); 10380 } 10381 intent.setPriority(0); 10382 return; 10383 } 10384 } 10385 10386 // find matching authorities subsets 10387 final Iterator<IntentFilter.AuthorityEntry> 10388 authoritiesIterator = intent.authoritiesIterator(); 10389 if (authoritiesIterator != null) { 10390 getIntentListSubset(intentListCopy, 10391 new AuthoritiesIterGenerator(), 10392 authoritiesIterator); 10393 if (intentListCopy.size() == 0) { 10394 // no more intents to match; we're not equivalent 10395 if (DEBUG_FILTERS) { 10396 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10397 + " package: " + applicationInfo.packageName 10398 + " activity: " + intent.activity.className 10399 + " origPrio: " + intent.getPriority()); 10400 } 10401 intent.setPriority(0); 10402 return; 10403 } 10404 } 10405 10406 // we found matching filter(s); app gets the max priority of all intents 10407 int cappedPriority = 0; 10408 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10409 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10410 } 10411 if (intent.getPriority() > cappedPriority) { 10412 if (DEBUG_FILTERS) { 10413 Slog.i(TAG, "Found matching filter(s);" 10414 + " cap priority to " + cappedPriority + ";" 10415 + " package: " + applicationInfo.packageName 10416 + " activity: " + intent.activity.className 10417 + " origPrio: " + intent.getPriority()); 10418 } 10419 intent.setPriority(cappedPriority); 10420 return; 10421 } 10422 // all this for nothing; the requested priority was <= what was on the system 10423 } 10424 10425 public final void addActivity(PackageParser.Activity a, String type) { 10426 mActivities.put(a.getComponentName(), a); 10427 if (DEBUG_SHOW_INFO) 10428 Log.v( 10429 TAG, " " + type + " " + 10430 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10431 if (DEBUG_SHOW_INFO) 10432 Log.v(TAG, " Class=" + a.info.name); 10433 final int NI = a.intents.size(); 10434 for (int j=0; j<NI; j++) { 10435 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10436 if ("activity".equals(type)) { 10437 final PackageSetting ps = 10438 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10439 final List<PackageParser.Activity> systemActivities = 10440 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10441 adjustPriority(systemActivities, intent); 10442 } 10443 if (DEBUG_SHOW_INFO) { 10444 Log.v(TAG, " IntentFilter:"); 10445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10446 } 10447 if (!intent.debugCheck()) { 10448 Log.w(TAG, "==> For Activity " + a.info.name); 10449 } 10450 addFilter(intent); 10451 } 10452 } 10453 10454 public final void removeActivity(PackageParser.Activity a, String type) { 10455 mActivities.remove(a.getComponentName()); 10456 if (DEBUG_SHOW_INFO) { 10457 Log.v(TAG, " " + type + " " 10458 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10459 : a.info.name) + ":"); 10460 Log.v(TAG, " Class=" + a.info.name); 10461 } 10462 final int NI = a.intents.size(); 10463 for (int j=0; j<NI; j++) { 10464 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10465 if (DEBUG_SHOW_INFO) { 10466 Log.v(TAG, " IntentFilter:"); 10467 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10468 } 10469 removeFilter(intent); 10470 } 10471 } 10472 10473 @Override 10474 protected boolean allowFilterResult( 10475 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10476 ActivityInfo filterAi = filter.activity.info; 10477 for (int i=dest.size()-1; i>=0; i--) { 10478 ActivityInfo destAi = dest.get(i).activityInfo; 10479 if (destAi.name == filterAi.name 10480 && destAi.packageName == filterAi.packageName) { 10481 return false; 10482 } 10483 } 10484 return true; 10485 } 10486 10487 @Override 10488 protected ActivityIntentInfo[] newArray(int size) { 10489 return new ActivityIntentInfo[size]; 10490 } 10491 10492 @Override 10493 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10494 if (!sUserManager.exists(userId)) return true; 10495 PackageParser.Package p = filter.activity.owner; 10496 if (p != null) { 10497 PackageSetting ps = (PackageSetting)p.mExtras; 10498 if (ps != null) { 10499 // System apps are never considered stopped for purposes of 10500 // filtering, because there may be no way for the user to 10501 // actually re-launch them. 10502 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10503 && ps.getStopped(userId); 10504 } 10505 } 10506 return false; 10507 } 10508 10509 @Override 10510 protected boolean isPackageForFilter(String packageName, 10511 PackageParser.ActivityIntentInfo info) { 10512 return packageName.equals(info.activity.owner.packageName); 10513 } 10514 10515 @Override 10516 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10517 int match, int userId) { 10518 if (!sUserManager.exists(userId)) return null; 10519 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10520 return null; 10521 } 10522 final PackageParser.Activity activity = info.activity; 10523 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10524 if (ps == null) { 10525 return null; 10526 } 10527 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10528 ps.readUserState(userId), userId); 10529 if (ai == null) { 10530 return null; 10531 } 10532 final ResolveInfo res = new ResolveInfo(); 10533 res.activityInfo = ai; 10534 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10535 res.filter = info; 10536 } 10537 if (info != null) { 10538 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10539 } 10540 res.priority = info.getPriority(); 10541 res.preferredOrder = activity.owner.mPreferredOrder; 10542 //System.out.println("Result: " + res.activityInfo.className + 10543 // " = " + res.priority); 10544 res.match = match; 10545 res.isDefault = info.hasDefault; 10546 res.labelRes = info.labelRes; 10547 res.nonLocalizedLabel = info.nonLocalizedLabel; 10548 if (userNeedsBadging(userId)) { 10549 res.noResourceId = true; 10550 } else { 10551 res.icon = info.icon; 10552 } 10553 res.iconResourceId = info.icon; 10554 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10555 return res; 10556 } 10557 10558 @Override 10559 protected void sortResults(List<ResolveInfo> results) { 10560 Collections.sort(results, mResolvePrioritySorter); 10561 } 10562 10563 @Override 10564 protected void dumpFilter(PrintWriter out, String prefix, 10565 PackageParser.ActivityIntentInfo filter) { 10566 out.print(prefix); out.print( 10567 Integer.toHexString(System.identityHashCode(filter.activity))); 10568 out.print(' '); 10569 filter.activity.printComponentShortName(out); 10570 out.print(" filter "); 10571 out.println(Integer.toHexString(System.identityHashCode(filter))); 10572 } 10573 10574 @Override 10575 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10576 return filter.activity; 10577 } 10578 10579 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10580 PackageParser.Activity activity = (PackageParser.Activity)label; 10581 out.print(prefix); out.print( 10582 Integer.toHexString(System.identityHashCode(activity))); 10583 out.print(' '); 10584 activity.printComponentShortName(out); 10585 if (count > 1) { 10586 out.print(" ("); out.print(count); out.print(" filters)"); 10587 } 10588 out.println(); 10589 } 10590 10591 // Keys are String (activity class name), values are Activity. 10592 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10593 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10594 private int mFlags; 10595 } 10596 10597 private final class ServiceIntentResolver 10598 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10599 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10600 boolean defaultOnly, int userId) { 10601 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10602 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10603 } 10604 10605 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10606 int userId) { 10607 if (!sUserManager.exists(userId)) return null; 10608 mFlags = flags; 10609 return super.queryIntent(intent, resolvedType, 10610 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10611 } 10612 10613 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10614 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10615 if (!sUserManager.exists(userId)) return null; 10616 if (packageServices == null) { 10617 return null; 10618 } 10619 mFlags = flags; 10620 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10621 final int N = packageServices.size(); 10622 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10623 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10624 10625 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10626 for (int i = 0; i < N; ++i) { 10627 intentFilters = packageServices.get(i).intents; 10628 if (intentFilters != null && intentFilters.size() > 0) { 10629 PackageParser.ServiceIntentInfo[] array = 10630 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10631 intentFilters.toArray(array); 10632 listCut.add(array); 10633 } 10634 } 10635 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10636 } 10637 10638 public final void addService(PackageParser.Service s) { 10639 mServices.put(s.getComponentName(), s); 10640 if (DEBUG_SHOW_INFO) { 10641 Log.v(TAG, " " 10642 + (s.info.nonLocalizedLabel != null 10643 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10644 Log.v(TAG, " Class=" + s.info.name); 10645 } 10646 final int NI = s.intents.size(); 10647 int j; 10648 for (j=0; j<NI; j++) { 10649 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10650 if (DEBUG_SHOW_INFO) { 10651 Log.v(TAG, " IntentFilter:"); 10652 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10653 } 10654 if (!intent.debugCheck()) { 10655 Log.w(TAG, "==> For Service " + s.info.name); 10656 } 10657 addFilter(intent); 10658 } 10659 } 10660 10661 public final void removeService(PackageParser.Service s) { 10662 mServices.remove(s.getComponentName()); 10663 if (DEBUG_SHOW_INFO) { 10664 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10665 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10666 Log.v(TAG, " Class=" + s.info.name); 10667 } 10668 final int NI = s.intents.size(); 10669 int j; 10670 for (j=0; j<NI; j++) { 10671 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10672 if (DEBUG_SHOW_INFO) { 10673 Log.v(TAG, " IntentFilter:"); 10674 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10675 } 10676 removeFilter(intent); 10677 } 10678 } 10679 10680 @Override 10681 protected boolean allowFilterResult( 10682 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10683 ServiceInfo filterSi = filter.service.info; 10684 for (int i=dest.size()-1; i>=0; i--) { 10685 ServiceInfo destAi = dest.get(i).serviceInfo; 10686 if (destAi.name == filterSi.name 10687 && destAi.packageName == filterSi.packageName) { 10688 return false; 10689 } 10690 } 10691 return true; 10692 } 10693 10694 @Override 10695 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10696 return new PackageParser.ServiceIntentInfo[size]; 10697 } 10698 10699 @Override 10700 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10701 if (!sUserManager.exists(userId)) return true; 10702 PackageParser.Package p = filter.service.owner; 10703 if (p != null) { 10704 PackageSetting ps = (PackageSetting)p.mExtras; 10705 if (ps != null) { 10706 // System apps are never considered stopped for purposes of 10707 // filtering, because there may be no way for the user to 10708 // actually re-launch them. 10709 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10710 && ps.getStopped(userId); 10711 } 10712 } 10713 return false; 10714 } 10715 10716 @Override 10717 protected boolean isPackageForFilter(String packageName, 10718 PackageParser.ServiceIntentInfo info) { 10719 return packageName.equals(info.service.owner.packageName); 10720 } 10721 10722 @Override 10723 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10724 int match, int userId) { 10725 if (!sUserManager.exists(userId)) return null; 10726 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10727 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10728 return null; 10729 } 10730 final PackageParser.Service service = info.service; 10731 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10732 if (ps == null) { 10733 return null; 10734 } 10735 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10736 ps.readUserState(userId), userId); 10737 if (si == null) { 10738 return null; 10739 } 10740 final ResolveInfo res = new ResolveInfo(); 10741 res.serviceInfo = si; 10742 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10743 res.filter = filter; 10744 } 10745 res.priority = info.getPriority(); 10746 res.preferredOrder = service.owner.mPreferredOrder; 10747 res.match = match; 10748 res.isDefault = info.hasDefault; 10749 res.labelRes = info.labelRes; 10750 res.nonLocalizedLabel = info.nonLocalizedLabel; 10751 res.icon = info.icon; 10752 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10753 return res; 10754 } 10755 10756 @Override 10757 protected void sortResults(List<ResolveInfo> results) { 10758 Collections.sort(results, mResolvePrioritySorter); 10759 } 10760 10761 @Override 10762 protected void dumpFilter(PrintWriter out, String prefix, 10763 PackageParser.ServiceIntentInfo filter) { 10764 out.print(prefix); out.print( 10765 Integer.toHexString(System.identityHashCode(filter.service))); 10766 out.print(' '); 10767 filter.service.printComponentShortName(out); 10768 out.print(" filter "); 10769 out.println(Integer.toHexString(System.identityHashCode(filter))); 10770 } 10771 10772 @Override 10773 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10774 return filter.service; 10775 } 10776 10777 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10778 PackageParser.Service service = (PackageParser.Service)label; 10779 out.print(prefix); out.print( 10780 Integer.toHexString(System.identityHashCode(service))); 10781 out.print(' '); 10782 service.printComponentShortName(out); 10783 if (count > 1) { 10784 out.print(" ("); out.print(count); out.print(" filters)"); 10785 } 10786 out.println(); 10787 } 10788 10789// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10790// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10791// final List<ResolveInfo> retList = Lists.newArrayList(); 10792// while (i.hasNext()) { 10793// final ResolveInfo resolveInfo = (ResolveInfo) i; 10794// if (isEnabledLP(resolveInfo.serviceInfo)) { 10795// retList.add(resolveInfo); 10796// } 10797// } 10798// return retList; 10799// } 10800 10801 // Keys are String (activity class name), values are Activity. 10802 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10803 = new ArrayMap<ComponentName, PackageParser.Service>(); 10804 private int mFlags; 10805 }; 10806 10807 private final class ProviderIntentResolver 10808 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10809 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10810 boolean defaultOnly, int userId) { 10811 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10812 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10813 } 10814 10815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10816 int userId) { 10817 if (!sUserManager.exists(userId)) 10818 return null; 10819 mFlags = flags; 10820 return super.queryIntent(intent, resolvedType, 10821 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10822 } 10823 10824 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10825 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10826 if (!sUserManager.exists(userId)) 10827 return null; 10828 if (packageProviders == null) { 10829 return null; 10830 } 10831 mFlags = flags; 10832 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10833 final int N = packageProviders.size(); 10834 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10835 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10836 10837 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10838 for (int i = 0; i < N; ++i) { 10839 intentFilters = packageProviders.get(i).intents; 10840 if (intentFilters != null && intentFilters.size() > 0) { 10841 PackageParser.ProviderIntentInfo[] array = 10842 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10843 intentFilters.toArray(array); 10844 listCut.add(array); 10845 } 10846 } 10847 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10848 } 10849 10850 public final void addProvider(PackageParser.Provider p) { 10851 if (mProviders.containsKey(p.getComponentName())) { 10852 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10853 return; 10854 } 10855 10856 mProviders.put(p.getComponentName(), p); 10857 if (DEBUG_SHOW_INFO) { 10858 Log.v(TAG, " " 10859 + (p.info.nonLocalizedLabel != null 10860 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10861 Log.v(TAG, " Class=" + p.info.name); 10862 } 10863 final int NI = p.intents.size(); 10864 int j; 10865 for (j = 0; j < NI; j++) { 10866 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10867 if (DEBUG_SHOW_INFO) { 10868 Log.v(TAG, " IntentFilter:"); 10869 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10870 } 10871 if (!intent.debugCheck()) { 10872 Log.w(TAG, "==> For Provider " + p.info.name); 10873 } 10874 addFilter(intent); 10875 } 10876 } 10877 10878 public final void removeProvider(PackageParser.Provider p) { 10879 mProviders.remove(p.getComponentName()); 10880 if (DEBUG_SHOW_INFO) { 10881 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10882 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10883 Log.v(TAG, " Class=" + p.info.name); 10884 } 10885 final int NI = p.intents.size(); 10886 int j; 10887 for (j = 0; j < NI; j++) { 10888 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10889 if (DEBUG_SHOW_INFO) { 10890 Log.v(TAG, " IntentFilter:"); 10891 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10892 } 10893 removeFilter(intent); 10894 } 10895 } 10896 10897 @Override 10898 protected boolean allowFilterResult( 10899 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10900 ProviderInfo filterPi = filter.provider.info; 10901 for (int i = dest.size() - 1; i >= 0; i--) { 10902 ProviderInfo destPi = dest.get(i).providerInfo; 10903 if (destPi.name == filterPi.name 10904 && destPi.packageName == filterPi.packageName) { 10905 return false; 10906 } 10907 } 10908 return true; 10909 } 10910 10911 @Override 10912 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10913 return new PackageParser.ProviderIntentInfo[size]; 10914 } 10915 10916 @Override 10917 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10918 if (!sUserManager.exists(userId)) 10919 return true; 10920 PackageParser.Package p = filter.provider.owner; 10921 if (p != null) { 10922 PackageSetting ps = (PackageSetting) p.mExtras; 10923 if (ps != null) { 10924 // System apps are never considered stopped for purposes of 10925 // filtering, because there may be no way for the user to 10926 // actually re-launch them. 10927 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10928 && ps.getStopped(userId); 10929 } 10930 } 10931 return false; 10932 } 10933 10934 @Override 10935 protected boolean isPackageForFilter(String packageName, 10936 PackageParser.ProviderIntentInfo info) { 10937 return packageName.equals(info.provider.owner.packageName); 10938 } 10939 10940 @Override 10941 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10942 int match, int userId) { 10943 if (!sUserManager.exists(userId)) 10944 return null; 10945 final PackageParser.ProviderIntentInfo info = filter; 10946 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10947 return null; 10948 } 10949 final PackageParser.Provider provider = info.provider; 10950 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10951 if (ps == null) { 10952 return null; 10953 } 10954 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10955 ps.readUserState(userId), userId); 10956 if (pi == null) { 10957 return null; 10958 } 10959 final ResolveInfo res = new ResolveInfo(); 10960 res.providerInfo = pi; 10961 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10962 res.filter = filter; 10963 } 10964 res.priority = info.getPriority(); 10965 res.preferredOrder = provider.owner.mPreferredOrder; 10966 res.match = match; 10967 res.isDefault = info.hasDefault; 10968 res.labelRes = info.labelRes; 10969 res.nonLocalizedLabel = info.nonLocalizedLabel; 10970 res.icon = info.icon; 10971 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10972 return res; 10973 } 10974 10975 @Override 10976 protected void sortResults(List<ResolveInfo> results) { 10977 Collections.sort(results, mResolvePrioritySorter); 10978 } 10979 10980 @Override 10981 protected void dumpFilter(PrintWriter out, String prefix, 10982 PackageParser.ProviderIntentInfo filter) { 10983 out.print(prefix); 10984 out.print( 10985 Integer.toHexString(System.identityHashCode(filter.provider))); 10986 out.print(' '); 10987 filter.provider.printComponentShortName(out); 10988 out.print(" filter "); 10989 out.println(Integer.toHexString(System.identityHashCode(filter))); 10990 } 10991 10992 @Override 10993 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10994 return filter.provider; 10995 } 10996 10997 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10998 PackageParser.Provider provider = (PackageParser.Provider)label; 10999 out.print(prefix); out.print( 11000 Integer.toHexString(System.identityHashCode(provider))); 11001 out.print(' '); 11002 provider.printComponentShortName(out); 11003 if (count > 1) { 11004 out.print(" ("); out.print(count); out.print(" filters)"); 11005 } 11006 out.println(); 11007 } 11008 11009 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11010 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11011 private int mFlags; 11012 } 11013 11014 private static final class EphemeralIntentResolver 11015 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11016 @Override 11017 protected EphemeralResolveIntentInfo[] newArray(int size) { 11018 return new EphemeralResolveIntentInfo[size]; 11019 } 11020 11021 @Override 11022 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11023 return true; 11024 } 11025 11026 @Override 11027 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11028 int userId) { 11029 if (!sUserManager.exists(userId)) { 11030 return null; 11031 } 11032 return info.getEphemeralResolveInfo(); 11033 } 11034 } 11035 11036 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11037 new Comparator<ResolveInfo>() { 11038 public int compare(ResolveInfo r1, ResolveInfo r2) { 11039 int v1 = r1.priority; 11040 int v2 = r2.priority; 11041 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11042 if (v1 != v2) { 11043 return (v1 > v2) ? -1 : 1; 11044 } 11045 v1 = r1.preferredOrder; 11046 v2 = r2.preferredOrder; 11047 if (v1 != v2) { 11048 return (v1 > v2) ? -1 : 1; 11049 } 11050 if (r1.isDefault != r2.isDefault) { 11051 return r1.isDefault ? -1 : 1; 11052 } 11053 v1 = r1.match; 11054 v2 = r2.match; 11055 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11056 if (v1 != v2) { 11057 return (v1 > v2) ? -1 : 1; 11058 } 11059 if (r1.system != r2.system) { 11060 return r1.system ? -1 : 1; 11061 } 11062 if (r1.activityInfo != null) { 11063 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11064 } 11065 if (r1.serviceInfo != null) { 11066 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11067 } 11068 if (r1.providerInfo != null) { 11069 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11070 } 11071 return 0; 11072 } 11073 }; 11074 11075 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11076 new Comparator<ProviderInfo>() { 11077 public int compare(ProviderInfo p1, ProviderInfo p2) { 11078 final int v1 = p1.initOrder; 11079 final int v2 = p2.initOrder; 11080 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11081 } 11082 }; 11083 11084 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11085 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11086 final int[] userIds) { 11087 mHandler.post(new Runnable() { 11088 @Override 11089 public void run() { 11090 try { 11091 final IActivityManager am = ActivityManagerNative.getDefault(); 11092 if (am == null) return; 11093 final int[] resolvedUserIds; 11094 if (userIds == null) { 11095 resolvedUserIds = am.getRunningUserIds(); 11096 } else { 11097 resolvedUserIds = userIds; 11098 } 11099 for (int id : resolvedUserIds) { 11100 final Intent intent = new Intent(action, 11101 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11102 if (extras != null) { 11103 intent.putExtras(extras); 11104 } 11105 if (targetPkg != null) { 11106 intent.setPackage(targetPkg); 11107 } 11108 // Modify the UID when posting to other users 11109 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11110 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11111 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11112 intent.putExtra(Intent.EXTRA_UID, uid); 11113 } 11114 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11115 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11116 if (DEBUG_BROADCASTS) { 11117 RuntimeException here = new RuntimeException("here"); 11118 here.fillInStackTrace(); 11119 Slog.d(TAG, "Sending to user " + id + ": " 11120 + intent.toShortString(false, true, false, false) 11121 + " " + intent.getExtras(), here); 11122 } 11123 am.broadcastIntent(null, intent, null, finishedReceiver, 11124 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11125 null, finishedReceiver != null, false, id); 11126 } 11127 } catch (RemoteException ex) { 11128 } 11129 } 11130 }); 11131 } 11132 11133 /** 11134 * Check if the external storage media is available. This is true if there 11135 * is a mounted external storage medium or if the external storage is 11136 * emulated. 11137 */ 11138 private boolean isExternalMediaAvailable() { 11139 return mMediaMounted || Environment.isExternalStorageEmulated(); 11140 } 11141 11142 @Override 11143 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11144 // writer 11145 synchronized (mPackages) { 11146 if (!isExternalMediaAvailable()) { 11147 // If the external storage is no longer mounted at this point, 11148 // the caller may not have been able to delete all of this 11149 // packages files and can not delete any more. Bail. 11150 return null; 11151 } 11152 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11153 if (lastPackage != null) { 11154 pkgs.remove(lastPackage); 11155 } 11156 if (pkgs.size() > 0) { 11157 return pkgs.get(0); 11158 } 11159 } 11160 return null; 11161 } 11162 11163 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11164 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11165 userId, andCode ? 1 : 0, packageName); 11166 if (mSystemReady) { 11167 msg.sendToTarget(); 11168 } else { 11169 if (mPostSystemReadyMessages == null) { 11170 mPostSystemReadyMessages = new ArrayList<>(); 11171 } 11172 mPostSystemReadyMessages.add(msg); 11173 } 11174 } 11175 11176 void startCleaningPackages() { 11177 // reader 11178 if (!isExternalMediaAvailable()) { 11179 return; 11180 } 11181 synchronized (mPackages) { 11182 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11183 return; 11184 } 11185 } 11186 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11187 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11188 IActivityManager am = ActivityManagerNative.getDefault(); 11189 if (am != null) { 11190 try { 11191 am.startService(null, intent, null, mContext.getOpPackageName(), 11192 UserHandle.USER_SYSTEM); 11193 } catch (RemoteException e) { 11194 } 11195 } 11196 } 11197 11198 @Override 11199 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11200 int installFlags, String installerPackageName, int userId) { 11201 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11202 11203 final int callingUid = Binder.getCallingUid(); 11204 enforceCrossUserPermission(callingUid, userId, 11205 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11206 11207 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11208 try { 11209 if (observer != null) { 11210 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11211 } 11212 } catch (RemoteException re) { 11213 } 11214 return; 11215 } 11216 11217 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11218 installFlags |= PackageManager.INSTALL_FROM_ADB; 11219 11220 } else { 11221 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11222 // about installerPackageName. 11223 11224 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11225 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11226 } 11227 11228 UserHandle user; 11229 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11230 user = UserHandle.ALL; 11231 } else { 11232 user = new UserHandle(userId); 11233 } 11234 11235 // Only system components can circumvent runtime permissions when installing. 11236 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11237 && mContext.checkCallingOrSelfPermission(Manifest.permission 11238 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11239 throw new SecurityException("You need the " 11240 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11241 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11242 } 11243 11244 final File originFile = new File(originPath); 11245 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11246 11247 final Message msg = mHandler.obtainMessage(INIT_COPY); 11248 final VerificationInfo verificationInfo = new VerificationInfo( 11249 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11250 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11251 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11252 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11253 null /*certificates*/); 11254 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11255 msg.obj = params; 11256 11257 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11258 System.identityHashCode(msg.obj)); 11259 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11260 System.identityHashCode(msg.obj)); 11261 11262 mHandler.sendMessage(msg); 11263 } 11264 11265 void installStage(String packageName, File stagedDir, String stagedCid, 11266 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11267 String installerPackageName, int installerUid, UserHandle user, 11268 Certificate[][] certificates) { 11269 if (DEBUG_EPHEMERAL) { 11270 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11271 Slog.d(TAG, "Ephemeral install of " + packageName); 11272 } 11273 } 11274 final VerificationInfo verificationInfo = new VerificationInfo( 11275 sessionParams.originatingUri, sessionParams.referrerUri, 11276 sessionParams.originatingUid, installerUid); 11277 11278 final OriginInfo origin; 11279 if (stagedDir != null) { 11280 origin = OriginInfo.fromStagedFile(stagedDir); 11281 } else { 11282 origin = OriginInfo.fromStagedContainer(stagedCid); 11283 } 11284 11285 final Message msg = mHandler.obtainMessage(INIT_COPY); 11286 final InstallParams params = new InstallParams(origin, null, observer, 11287 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11288 verificationInfo, user, sessionParams.abiOverride, 11289 sessionParams.grantedRuntimePermissions, certificates); 11290 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11291 msg.obj = params; 11292 11293 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11294 System.identityHashCode(msg.obj)); 11295 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11296 System.identityHashCode(msg.obj)); 11297 11298 mHandler.sendMessage(msg); 11299 } 11300 11301 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11302 int userId) { 11303 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11304 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11305 } 11306 11307 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11308 int appId, int userId) { 11309 Bundle extras = new Bundle(1); 11310 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11311 11312 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11313 packageName, extras, 0, null, null, new int[] {userId}); 11314 try { 11315 IActivityManager am = ActivityManagerNative.getDefault(); 11316 if (isSystem && am.isUserRunning(userId, 0)) { 11317 // The just-installed/enabled app is bundled on the system, so presumed 11318 // to be able to run automatically without needing an explicit launch. 11319 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11320 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11321 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11322 .setPackage(packageName); 11323 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11324 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11325 } 11326 } catch (RemoteException e) { 11327 // shouldn't happen 11328 Slog.w(TAG, "Unable to bootstrap installed package", e); 11329 } 11330 } 11331 11332 @Override 11333 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11334 int userId) { 11335 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11336 PackageSetting pkgSetting; 11337 final int uid = Binder.getCallingUid(); 11338 enforceCrossUserPermission(uid, userId, 11339 true /* requireFullPermission */, true /* checkShell */, 11340 "setApplicationHiddenSetting for user " + userId); 11341 11342 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11343 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11344 return false; 11345 } 11346 11347 long callingId = Binder.clearCallingIdentity(); 11348 try { 11349 boolean sendAdded = false; 11350 boolean sendRemoved = false; 11351 // writer 11352 synchronized (mPackages) { 11353 pkgSetting = mSettings.mPackages.get(packageName); 11354 if (pkgSetting == null) { 11355 return false; 11356 } 11357 if (pkgSetting.getHidden(userId) != hidden) { 11358 pkgSetting.setHidden(hidden, userId); 11359 mSettings.writePackageRestrictionsLPr(userId); 11360 if (hidden) { 11361 sendRemoved = true; 11362 } else { 11363 sendAdded = true; 11364 } 11365 } 11366 } 11367 if (sendAdded) { 11368 sendPackageAddedForUser(packageName, pkgSetting, userId); 11369 return true; 11370 } 11371 if (sendRemoved) { 11372 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11373 "hiding pkg"); 11374 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11375 return true; 11376 } 11377 } finally { 11378 Binder.restoreCallingIdentity(callingId); 11379 } 11380 return false; 11381 } 11382 11383 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11384 int userId) { 11385 final PackageRemovedInfo info = new PackageRemovedInfo(); 11386 info.removedPackage = packageName; 11387 info.removedUsers = new int[] {userId}; 11388 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11389 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11390 } 11391 11392 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11393 if (pkgList.length > 0) { 11394 Bundle extras = new Bundle(1); 11395 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11396 11397 sendPackageBroadcast( 11398 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11399 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11400 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11401 new int[] {userId}); 11402 } 11403 } 11404 11405 /** 11406 * Returns true if application is not found or there was an error. Otherwise it returns 11407 * the hidden state of the package for the given user. 11408 */ 11409 @Override 11410 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11411 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11412 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11413 true /* requireFullPermission */, false /* checkShell */, 11414 "getApplicationHidden for user " + userId); 11415 PackageSetting pkgSetting; 11416 long callingId = Binder.clearCallingIdentity(); 11417 try { 11418 // writer 11419 synchronized (mPackages) { 11420 pkgSetting = mSettings.mPackages.get(packageName); 11421 if (pkgSetting == null) { 11422 return true; 11423 } 11424 return pkgSetting.getHidden(userId); 11425 } 11426 } finally { 11427 Binder.restoreCallingIdentity(callingId); 11428 } 11429 } 11430 11431 /** 11432 * @hide 11433 */ 11434 @Override 11435 public int installExistingPackageAsUser(String packageName, int userId) { 11436 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11437 null); 11438 PackageSetting pkgSetting; 11439 final int uid = Binder.getCallingUid(); 11440 enforceCrossUserPermission(uid, userId, 11441 true /* requireFullPermission */, true /* checkShell */, 11442 "installExistingPackage for user " + userId); 11443 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11444 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11445 } 11446 11447 long callingId = Binder.clearCallingIdentity(); 11448 try { 11449 boolean installed = false; 11450 11451 // writer 11452 synchronized (mPackages) { 11453 pkgSetting = mSettings.mPackages.get(packageName); 11454 if (pkgSetting == null) { 11455 return PackageManager.INSTALL_FAILED_INVALID_URI; 11456 } 11457 if (!pkgSetting.getInstalled(userId)) { 11458 pkgSetting.setInstalled(true, userId); 11459 pkgSetting.setHidden(false, userId); 11460 mSettings.writePackageRestrictionsLPr(userId); 11461 installed = true; 11462 } 11463 } 11464 11465 if (installed) { 11466 if (pkgSetting.pkg != null) { 11467 synchronized (mInstallLock) { 11468 // We don't need to freeze for a brand new install 11469 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11470 } 11471 } 11472 sendPackageAddedForUser(packageName, pkgSetting, userId); 11473 } 11474 } finally { 11475 Binder.restoreCallingIdentity(callingId); 11476 } 11477 11478 return PackageManager.INSTALL_SUCCEEDED; 11479 } 11480 11481 boolean isUserRestricted(int userId, String restrictionKey) { 11482 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11483 if (restrictions.getBoolean(restrictionKey, false)) { 11484 Log.w(TAG, "User is restricted: " + restrictionKey); 11485 return true; 11486 } 11487 return false; 11488 } 11489 11490 @Override 11491 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11492 int userId) { 11493 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11494 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11495 true /* requireFullPermission */, true /* checkShell */, 11496 "setPackagesSuspended for user " + userId); 11497 11498 if (ArrayUtils.isEmpty(packageNames)) { 11499 return packageNames; 11500 } 11501 11502 // List of package names for whom the suspended state has changed. 11503 List<String> changedPackages = new ArrayList<>(packageNames.length); 11504 // List of package names for whom the suspended state is not set as requested in this 11505 // method. 11506 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11507 long callingId = Binder.clearCallingIdentity(); 11508 try { 11509 for (int i = 0; i < packageNames.length; i++) { 11510 String packageName = packageNames[i]; 11511 boolean changed = false; 11512 final int appId; 11513 synchronized (mPackages) { 11514 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11515 if (pkgSetting == null) { 11516 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11517 + "\". Skipping suspending/un-suspending."); 11518 unactionedPackages.add(packageName); 11519 continue; 11520 } 11521 appId = pkgSetting.appId; 11522 if (pkgSetting.getSuspended(userId) != suspended) { 11523 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11524 unactionedPackages.add(packageName); 11525 continue; 11526 } 11527 pkgSetting.setSuspended(suspended, userId); 11528 mSettings.writePackageRestrictionsLPr(userId); 11529 changed = true; 11530 changedPackages.add(packageName); 11531 } 11532 } 11533 11534 if (changed && suspended) { 11535 killApplication(packageName, UserHandle.getUid(userId, appId), 11536 "suspending package"); 11537 } 11538 } 11539 } finally { 11540 Binder.restoreCallingIdentity(callingId); 11541 } 11542 11543 if (!changedPackages.isEmpty()) { 11544 sendPackagesSuspendedForUser(changedPackages.toArray( 11545 new String[changedPackages.size()]), userId, suspended); 11546 } 11547 11548 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11549 } 11550 11551 @Override 11552 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11553 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11554 true /* requireFullPermission */, false /* checkShell */, 11555 "isPackageSuspendedForUser for user " + userId); 11556 synchronized (mPackages) { 11557 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11558 if (pkgSetting == null) { 11559 throw new IllegalArgumentException("Unknown target package: " + packageName); 11560 } 11561 return pkgSetting.getSuspended(userId); 11562 } 11563 } 11564 11565 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11566 if (isPackageDeviceAdmin(packageName, userId)) { 11567 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11568 + "\": has an active device admin"); 11569 return false; 11570 } 11571 11572 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11573 if (packageName.equals(activeLauncherPackageName)) { 11574 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11575 + "\": contains the active launcher"); 11576 return false; 11577 } 11578 11579 if (packageName.equals(mRequiredInstallerPackage)) { 11580 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11581 + "\": required for package installation"); 11582 return false; 11583 } 11584 11585 if (packageName.equals(mRequiredVerifierPackage)) { 11586 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11587 + "\": required for package verification"); 11588 return false; 11589 } 11590 11591 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11592 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11593 + "\": is the default dialer"); 11594 return false; 11595 } 11596 11597 return true; 11598 } 11599 11600 private String getActiveLauncherPackageName(int userId) { 11601 Intent intent = new Intent(Intent.ACTION_MAIN); 11602 intent.addCategory(Intent.CATEGORY_HOME); 11603 ResolveInfo resolveInfo = resolveIntent( 11604 intent, 11605 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11606 PackageManager.MATCH_DEFAULT_ONLY, 11607 userId); 11608 11609 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11610 } 11611 11612 private String getDefaultDialerPackageName(int userId) { 11613 synchronized (mPackages) { 11614 return mSettings.getDefaultDialerPackageNameLPw(userId); 11615 } 11616 } 11617 11618 @Override 11619 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11620 mContext.enforceCallingOrSelfPermission( 11621 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11622 "Only package verification agents can verify applications"); 11623 11624 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11625 final PackageVerificationResponse response = new PackageVerificationResponse( 11626 verificationCode, Binder.getCallingUid()); 11627 msg.arg1 = id; 11628 msg.obj = response; 11629 mHandler.sendMessage(msg); 11630 } 11631 11632 @Override 11633 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11634 long millisecondsToDelay) { 11635 mContext.enforceCallingOrSelfPermission( 11636 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11637 "Only package verification agents can extend verification timeouts"); 11638 11639 final PackageVerificationState state = mPendingVerification.get(id); 11640 final PackageVerificationResponse response = new PackageVerificationResponse( 11641 verificationCodeAtTimeout, Binder.getCallingUid()); 11642 11643 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11644 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11645 } 11646 if (millisecondsToDelay < 0) { 11647 millisecondsToDelay = 0; 11648 } 11649 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11650 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11651 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11652 } 11653 11654 if ((state != null) && !state.timeoutExtended()) { 11655 state.extendTimeout(); 11656 11657 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11658 msg.arg1 = id; 11659 msg.obj = response; 11660 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11661 } 11662 } 11663 11664 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11665 int verificationCode, UserHandle user) { 11666 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11667 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11668 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11669 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11670 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11671 11672 mContext.sendBroadcastAsUser(intent, user, 11673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11674 } 11675 11676 private ComponentName matchComponentForVerifier(String packageName, 11677 List<ResolveInfo> receivers) { 11678 ActivityInfo targetReceiver = null; 11679 11680 final int NR = receivers.size(); 11681 for (int i = 0; i < NR; i++) { 11682 final ResolveInfo info = receivers.get(i); 11683 if (info.activityInfo == null) { 11684 continue; 11685 } 11686 11687 if (packageName.equals(info.activityInfo.packageName)) { 11688 targetReceiver = info.activityInfo; 11689 break; 11690 } 11691 } 11692 11693 if (targetReceiver == null) { 11694 return null; 11695 } 11696 11697 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11698 } 11699 11700 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11701 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11702 if (pkgInfo.verifiers.length == 0) { 11703 return null; 11704 } 11705 11706 final int N = pkgInfo.verifiers.length; 11707 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11708 for (int i = 0; i < N; i++) { 11709 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11710 11711 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11712 receivers); 11713 if (comp == null) { 11714 continue; 11715 } 11716 11717 final int verifierUid = getUidForVerifier(verifierInfo); 11718 if (verifierUid == -1) { 11719 continue; 11720 } 11721 11722 if (DEBUG_VERIFY) { 11723 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11724 + " with the correct signature"); 11725 } 11726 sufficientVerifiers.add(comp); 11727 verificationState.addSufficientVerifier(verifierUid); 11728 } 11729 11730 return sufficientVerifiers; 11731 } 11732 11733 private int getUidForVerifier(VerifierInfo verifierInfo) { 11734 synchronized (mPackages) { 11735 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11736 if (pkg == null) { 11737 return -1; 11738 } else if (pkg.mSignatures.length != 1) { 11739 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11740 + " has more than one signature; ignoring"); 11741 return -1; 11742 } 11743 11744 /* 11745 * If the public key of the package's signature does not match 11746 * our expected public key, then this is a different package and 11747 * we should skip. 11748 */ 11749 11750 final byte[] expectedPublicKey; 11751 try { 11752 final Signature verifierSig = pkg.mSignatures[0]; 11753 final PublicKey publicKey = verifierSig.getPublicKey(); 11754 expectedPublicKey = publicKey.getEncoded(); 11755 } catch (CertificateException e) { 11756 return -1; 11757 } 11758 11759 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11760 11761 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11762 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11763 + " does not have the expected public key; ignoring"); 11764 return -1; 11765 } 11766 11767 return pkg.applicationInfo.uid; 11768 } 11769 } 11770 11771 @Override 11772 public void finishPackageInstall(int token, boolean didLaunch) { 11773 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11774 11775 if (DEBUG_INSTALL) { 11776 Slog.v(TAG, "BM finishing package install for " + token); 11777 } 11778 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11779 11780 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11781 mHandler.sendMessage(msg); 11782 } 11783 11784 /** 11785 * Get the verification agent timeout. 11786 * 11787 * @return verification timeout in milliseconds 11788 */ 11789 private long getVerificationTimeout() { 11790 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11791 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11792 DEFAULT_VERIFICATION_TIMEOUT); 11793 } 11794 11795 /** 11796 * Get the default verification agent response code. 11797 * 11798 * @return default verification response code 11799 */ 11800 private int getDefaultVerificationResponse() { 11801 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11802 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11803 DEFAULT_VERIFICATION_RESPONSE); 11804 } 11805 11806 /** 11807 * Check whether or not package verification has been enabled. 11808 * 11809 * @return true if verification should be performed 11810 */ 11811 private boolean isVerificationEnabled(int userId, int installFlags) { 11812 if (!DEFAULT_VERIFY_ENABLE) { 11813 return false; 11814 } 11815 // Ephemeral apps don't get the full verification treatment 11816 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11817 if (DEBUG_EPHEMERAL) { 11818 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11819 } 11820 return false; 11821 } 11822 11823 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11824 11825 // Check if installing from ADB 11826 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11827 // Do not run verification in a test harness environment 11828 if (ActivityManager.isRunningInTestHarness()) { 11829 return false; 11830 } 11831 if (ensureVerifyAppsEnabled) { 11832 return true; 11833 } 11834 // Check if the developer does not want package verification for ADB installs 11835 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11836 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11837 return false; 11838 } 11839 } 11840 11841 if (ensureVerifyAppsEnabled) { 11842 return true; 11843 } 11844 11845 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11846 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11847 } 11848 11849 @Override 11850 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11851 throws RemoteException { 11852 mContext.enforceCallingOrSelfPermission( 11853 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11854 "Only intentfilter verification agents can verify applications"); 11855 11856 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11857 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11858 Binder.getCallingUid(), verificationCode, failedDomains); 11859 msg.arg1 = id; 11860 msg.obj = response; 11861 mHandler.sendMessage(msg); 11862 } 11863 11864 @Override 11865 public int getIntentVerificationStatus(String packageName, int userId) { 11866 synchronized (mPackages) { 11867 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11868 } 11869 } 11870 11871 @Override 11872 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11873 mContext.enforceCallingOrSelfPermission( 11874 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11875 11876 boolean result = false; 11877 synchronized (mPackages) { 11878 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11879 } 11880 if (result) { 11881 scheduleWritePackageRestrictionsLocked(userId); 11882 } 11883 return result; 11884 } 11885 11886 @Override 11887 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11888 String packageName) { 11889 synchronized (mPackages) { 11890 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11891 } 11892 } 11893 11894 @Override 11895 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11896 if (TextUtils.isEmpty(packageName)) { 11897 return ParceledListSlice.emptyList(); 11898 } 11899 synchronized (mPackages) { 11900 PackageParser.Package pkg = mPackages.get(packageName); 11901 if (pkg == null || pkg.activities == null) { 11902 return ParceledListSlice.emptyList(); 11903 } 11904 final int count = pkg.activities.size(); 11905 ArrayList<IntentFilter> result = new ArrayList<>(); 11906 for (int n=0; n<count; n++) { 11907 PackageParser.Activity activity = pkg.activities.get(n); 11908 if (activity.intents != null && activity.intents.size() > 0) { 11909 result.addAll(activity.intents); 11910 } 11911 } 11912 return new ParceledListSlice<>(result); 11913 } 11914 } 11915 11916 @Override 11917 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11918 mContext.enforceCallingOrSelfPermission( 11919 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11920 11921 synchronized (mPackages) { 11922 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11923 if (packageName != null) { 11924 result |= updateIntentVerificationStatus(packageName, 11925 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11926 userId); 11927 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11928 packageName, userId); 11929 } 11930 return result; 11931 } 11932 } 11933 11934 @Override 11935 public String getDefaultBrowserPackageName(int userId) { 11936 synchronized (mPackages) { 11937 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11938 } 11939 } 11940 11941 /** 11942 * Get the "allow unknown sources" setting. 11943 * 11944 * @return the current "allow unknown sources" setting 11945 */ 11946 private int getUnknownSourcesSettings() { 11947 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11948 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11949 -1); 11950 } 11951 11952 @Override 11953 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11954 final int uid = Binder.getCallingUid(); 11955 // writer 11956 synchronized (mPackages) { 11957 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11958 if (targetPackageSetting == null) { 11959 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11960 } 11961 11962 PackageSetting installerPackageSetting; 11963 if (installerPackageName != null) { 11964 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11965 if (installerPackageSetting == null) { 11966 throw new IllegalArgumentException("Unknown installer package: " 11967 + installerPackageName); 11968 } 11969 } else { 11970 installerPackageSetting = null; 11971 } 11972 11973 Signature[] callerSignature; 11974 Object obj = mSettings.getUserIdLPr(uid); 11975 if (obj != null) { 11976 if (obj instanceof SharedUserSetting) { 11977 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11978 } else if (obj instanceof PackageSetting) { 11979 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11980 } else { 11981 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11982 } 11983 } else { 11984 throw new SecurityException("Unknown calling UID: " + uid); 11985 } 11986 11987 // Verify: can't set installerPackageName to a package that is 11988 // not signed with the same cert as the caller. 11989 if (installerPackageSetting != null) { 11990 if (compareSignatures(callerSignature, 11991 installerPackageSetting.signatures.mSignatures) 11992 != PackageManager.SIGNATURE_MATCH) { 11993 throw new SecurityException( 11994 "Caller does not have same cert as new installer package " 11995 + installerPackageName); 11996 } 11997 } 11998 11999 // Verify: if target already has an installer package, it must 12000 // be signed with the same cert as the caller. 12001 if (targetPackageSetting.installerPackageName != null) { 12002 PackageSetting setting = mSettings.mPackages.get( 12003 targetPackageSetting.installerPackageName); 12004 // If the currently set package isn't valid, then it's always 12005 // okay to change it. 12006 if (setting != null) { 12007 if (compareSignatures(callerSignature, 12008 setting.signatures.mSignatures) 12009 != PackageManager.SIGNATURE_MATCH) { 12010 throw new SecurityException( 12011 "Caller does not have same cert as old installer package " 12012 + targetPackageSetting.installerPackageName); 12013 } 12014 } 12015 } 12016 12017 // Okay! 12018 targetPackageSetting.installerPackageName = installerPackageName; 12019 if (installerPackageName != null) { 12020 mSettings.mInstallerPackages.add(installerPackageName); 12021 } 12022 scheduleWriteSettingsLocked(); 12023 } 12024 } 12025 12026 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12027 // Queue up an async operation since the package installation may take a little while. 12028 mHandler.post(new Runnable() { 12029 public void run() { 12030 mHandler.removeCallbacks(this); 12031 // Result object to be returned 12032 PackageInstalledInfo res = new PackageInstalledInfo(); 12033 res.setReturnCode(currentStatus); 12034 res.uid = -1; 12035 res.pkg = null; 12036 res.removedInfo = null; 12037 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12038 args.doPreInstall(res.returnCode); 12039 synchronized (mInstallLock) { 12040 installPackageTracedLI(args, res); 12041 } 12042 args.doPostInstall(res.returnCode, res.uid); 12043 } 12044 12045 // A restore should be performed at this point if (a) the install 12046 // succeeded, (b) the operation is not an update, and (c) the new 12047 // package has not opted out of backup participation. 12048 final boolean update = res.removedInfo != null 12049 && res.removedInfo.removedPackage != null; 12050 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12051 boolean doRestore = !update 12052 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12053 12054 // Set up the post-install work request bookkeeping. This will be used 12055 // and cleaned up by the post-install event handling regardless of whether 12056 // there's a restore pass performed. Token values are >= 1. 12057 int token; 12058 if (mNextInstallToken < 0) mNextInstallToken = 1; 12059 token = mNextInstallToken++; 12060 12061 PostInstallData data = new PostInstallData(args, res); 12062 mRunningInstalls.put(token, data); 12063 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12064 12065 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12066 // Pass responsibility to the Backup Manager. It will perform a 12067 // restore if appropriate, then pass responsibility back to the 12068 // Package Manager to run the post-install observer callbacks 12069 // and broadcasts. 12070 IBackupManager bm = IBackupManager.Stub.asInterface( 12071 ServiceManager.getService(Context.BACKUP_SERVICE)); 12072 if (bm != null) { 12073 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12074 + " to BM for possible restore"); 12075 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12076 try { 12077 // TODO: http://b/22388012 12078 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12079 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12080 } else { 12081 doRestore = false; 12082 } 12083 } catch (RemoteException e) { 12084 // can't happen; the backup manager is local 12085 } catch (Exception e) { 12086 Slog.e(TAG, "Exception trying to enqueue restore", e); 12087 doRestore = false; 12088 } 12089 } else { 12090 Slog.e(TAG, "Backup Manager not found!"); 12091 doRestore = false; 12092 } 12093 } 12094 12095 if (!doRestore) { 12096 // No restore possible, or the Backup Manager was mysteriously not 12097 // available -- just fire the post-install work request directly. 12098 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12099 12100 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12101 12102 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12103 mHandler.sendMessage(msg); 12104 } 12105 } 12106 }); 12107 } 12108 12109 /** 12110 * Callback from PackageSettings whenever an app is first transitioned out of the 12111 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12112 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12113 * here whether the app is the target of an ongoing install, and only send the 12114 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12115 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12116 * handling. 12117 */ 12118 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12119 // Serialize this with the rest of the install-process message chain. In the 12120 // restore-at-install case, this Runnable will necessarily run before the 12121 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12122 // are coherent. In the non-restore case, the app has already completed install 12123 // and been launched through some other means, so it is not in a problematic 12124 // state for observers to see the FIRST_LAUNCH signal. 12125 mHandler.post(new Runnable() { 12126 @Override 12127 public void run() { 12128 for (int i = 0; i < mRunningInstalls.size(); i++) { 12129 final PostInstallData data = mRunningInstalls.valueAt(i); 12130 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12131 // right package; but is it for the right user? 12132 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12133 if (userId == data.res.newUsers[uIndex]) { 12134 if (DEBUG_BACKUP) { 12135 Slog.i(TAG, "Package " + pkgName 12136 + " being restored so deferring FIRST_LAUNCH"); 12137 } 12138 return; 12139 } 12140 } 12141 } 12142 } 12143 // didn't find it, so not being restored 12144 if (DEBUG_BACKUP) { 12145 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12146 } 12147 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12148 } 12149 }); 12150 } 12151 12152 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12153 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12154 installerPkg, null, userIds); 12155 } 12156 12157 private abstract class HandlerParams { 12158 private static final int MAX_RETRIES = 4; 12159 12160 /** 12161 * Number of times startCopy() has been attempted and had a non-fatal 12162 * error. 12163 */ 12164 private int mRetries = 0; 12165 12166 /** User handle for the user requesting the information or installation. */ 12167 private final UserHandle mUser; 12168 String traceMethod; 12169 int traceCookie; 12170 12171 HandlerParams(UserHandle user) { 12172 mUser = user; 12173 } 12174 12175 UserHandle getUser() { 12176 return mUser; 12177 } 12178 12179 HandlerParams setTraceMethod(String traceMethod) { 12180 this.traceMethod = traceMethod; 12181 return this; 12182 } 12183 12184 HandlerParams setTraceCookie(int traceCookie) { 12185 this.traceCookie = traceCookie; 12186 return this; 12187 } 12188 12189 final boolean startCopy() { 12190 boolean res; 12191 try { 12192 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12193 12194 if (++mRetries > MAX_RETRIES) { 12195 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12196 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12197 handleServiceError(); 12198 return false; 12199 } else { 12200 handleStartCopy(); 12201 res = true; 12202 } 12203 } catch (RemoteException e) { 12204 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12205 mHandler.sendEmptyMessage(MCS_RECONNECT); 12206 res = false; 12207 } 12208 handleReturnCode(); 12209 return res; 12210 } 12211 12212 final void serviceError() { 12213 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12214 handleServiceError(); 12215 handleReturnCode(); 12216 } 12217 12218 abstract void handleStartCopy() throws RemoteException; 12219 abstract void handleServiceError(); 12220 abstract void handleReturnCode(); 12221 } 12222 12223 class MeasureParams extends HandlerParams { 12224 private final PackageStats mStats; 12225 private boolean mSuccess; 12226 12227 private final IPackageStatsObserver mObserver; 12228 12229 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12230 super(new UserHandle(stats.userHandle)); 12231 mObserver = observer; 12232 mStats = stats; 12233 } 12234 12235 @Override 12236 public String toString() { 12237 return "MeasureParams{" 12238 + Integer.toHexString(System.identityHashCode(this)) 12239 + " " + mStats.packageName + "}"; 12240 } 12241 12242 @Override 12243 void handleStartCopy() throws RemoteException { 12244 synchronized (mInstallLock) { 12245 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12246 } 12247 12248 if (mSuccess) { 12249 final boolean mounted; 12250 if (Environment.isExternalStorageEmulated()) { 12251 mounted = true; 12252 } else { 12253 final String status = Environment.getExternalStorageState(); 12254 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12255 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12256 } 12257 12258 if (mounted) { 12259 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12260 12261 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12262 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12263 12264 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12265 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12266 12267 // Always subtract cache size, since it's a subdirectory 12268 mStats.externalDataSize -= mStats.externalCacheSize; 12269 12270 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12271 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12272 12273 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12274 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12275 } 12276 } 12277 } 12278 12279 @Override 12280 void handleReturnCode() { 12281 if (mObserver != null) { 12282 try { 12283 mObserver.onGetStatsCompleted(mStats, mSuccess); 12284 } catch (RemoteException e) { 12285 Slog.i(TAG, "Observer no longer exists."); 12286 } 12287 } 12288 } 12289 12290 @Override 12291 void handleServiceError() { 12292 Slog.e(TAG, "Could not measure application " + mStats.packageName 12293 + " external storage"); 12294 } 12295 } 12296 12297 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12298 throws RemoteException { 12299 long result = 0; 12300 for (File path : paths) { 12301 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12302 } 12303 return result; 12304 } 12305 12306 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12307 for (File path : paths) { 12308 try { 12309 mcs.clearDirectory(path.getAbsolutePath()); 12310 } catch (RemoteException e) { 12311 } 12312 } 12313 } 12314 12315 static class OriginInfo { 12316 /** 12317 * Location where install is coming from, before it has been 12318 * copied/renamed into place. This could be a single monolithic APK 12319 * file, or a cluster directory. This location may be untrusted. 12320 */ 12321 final File file; 12322 final String cid; 12323 12324 /** 12325 * Flag indicating that {@link #file} or {@link #cid} has already been 12326 * staged, meaning downstream users don't need to defensively copy the 12327 * contents. 12328 */ 12329 final boolean staged; 12330 12331 /** 12332 * Flag indicating that {@link #file} or {@link #cid} is an already 12333 * installed app that is being moved. 12334 */ 12335 final boolean existing; 12336 12337 final String resolvedPath; 12338 final File resolvedFile; 12339 12340 static OriginInfo fromNothing() { 12341 return new OriginInfo(null, null, false, false); 12342 } 12343 12344 static OriginInfo fromUntrustedFile(File file) { 12345 return new OriginInfo(file, null, false, false); 12346 } 12347 12348 static OriginInfo fromExistingFile(File file) { 12349 return new OriginInfo(file, null, false, true); 12350 } 12351 12352 static OriginInfo fromStagedFile(File file) { 12353 return new OriginInfo(file, null, true, false); 12354 } 12355 12356 static OriginInfo fromStagedContainer(String cid) { 12357 return new OriginInfo(null, cid, true, false); 12358 } 12359 12360 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12361 this.file = file; 12362 this.cid = cid; 12363 this.staged = staged; 12364 this.existing = existing; 12365 12366 if (cid != null) { 12367 resolvedPath = PackageHelper.getSdDir(cid); 12368 resolvedFile = new File(resolvedPath); 12369 } else if (file != null) { 12370 resolvedPath = file.getAbsolutePath(); 12371 resolvedFile = file; 12372 } else { 12373 resolvedPath = null; 12374 resolvedFile = null; 12375 } 12376 } 12377 } 12378 12379 static class MoveInfo { 12380 final int moveId; 12381 final String fromUuid; 12382 final String toUuid; 12383 final String packageName; 12384 final String dataAppName; 12385 final int appId; 12386 final String seinfo; 12387 final int targetSdkVersion; 12388 12389 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12390 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12391 this.moveId = moveId; 12392 this.fromUuid = fromUuid; 12393 this.toUuid = toUuid; 12394 this.packageName = packageName; 12395 this.dataAppName = dataAppName; 12396 this.appId = appId; 12397 this.seinfo = seinfo; 12398 this.targetSdkVersion = targetSdkVersion; 12399 } 12400 } 12401 12402 static class VerificationInfo { 12403 /** A constant used to indicate that a uid value is not present. */ 12404 public static final int NO_UID = -1; 12405 12406 /** URI referencing where the package was downloaded from. */ 12407 final Uri originatingUri; 12408 12409 /** HTTP referrer URI associated with the originatingURI. */ 12410 final Uri referrer; 12411 12412 /** UID of the application that the install request originated from. */ 12413 final int originatingUid; 12414 12415 /** UID of application requesting the install */ 12416 final int installerUid; 12417 12418 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12419 this.originatingUri = originatingUri; 12420 this.referrer = referrer; 12421 this.originatingUid = originatingUid; 12422 this.installerUid = installerUid; 12423 } 12424 } 12425 12426 class InstallParams extends HandlerParams { 12427 final OriginInfo origin; 12428 final MoveInfo move; 12429 final IPackageInstallObserver2 observer; 12430 int installFlags; 12431 final String installerPackageName; 12432 final String volumeUuid; 12433 private InstallArgs mArgs; 12434 private int mRet; 12435 final String packageAbiOverride; 12436 final String[] grantedRuntimePermissions; 12437 final VerificationInfo verificationInfo; 12438 final Certificate[][] certificates; 12439 12440 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12441 int installFlags, String installerPackageName, String volumeUuid, 12442 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12443 String[] grantedPermissions, Certificate[][] certificates) { 12444 super(user); 12445 this.origin = origin; 12446 this.move = move; 12447 this.observer = observer; 12448 this.installFlags = installFlags; 12449 this.installerPackageName = installerPackageName; 12450 this.volumeUuid = volumeUuid; 12451 this.verificationInfo = verificationInfo; 12452 this.packageAbiOverride = packageAbiOverride; 12453 this.grantedRuntimePermissions = grantedPermissions; 12454 this.certificates = certificates; 12455 } 12456 12457 @Override 12458 public String toString() { 12459 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12460 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12461 } 12462 12463 private int installLocationPolicy(PackageInfoLite pkgLite) { 12464 String packageName = pkgLite.packageName; 12465 int installLocation = pkgLite.installLocation; 12466 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12467 // reader 12468 synchronized (mPackages) { 12469 // Currently installed package which the new package is attempting to replace or 12470 // null if no such package is installed. 12471 PackageParser.Package installedPkg = mPackages.get(packageName); 12472 // Package which currently owns the data which the new package will own if installed. 12473 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12474 // will be null whereas dataOwnerPkg will contain information about the package 12475 // which was uninstalled while keeping its data. 12476 PackageParser.Package dataOwnerPkg = installedPkg; 12477 if (dataOwnerPkg == null) { 12478 PackageSetting ps = mSettings.mPackages.get(packageName); 12479 if (ps != null) { 12480 dataOwnerPkg = ps.pkg; 12481 } 12482 } 12483 12484 if (dataOwnerPkg != null) { 12485 // If installed, the package will get access to data left on the device by its 12486 // predecessor. As a security measure, this is permited only if this is not a 12487 // version downgrade or if the predecessor package is marked as debuggable and 12488 // a downgrade is explicitly requested. 12489 // 12490 // On debuggable platform builds, downgrades are permitted even for 12491 // non-debuggable packages to make testing easier. Debuggable platform builds do 12492 // not offer security guarantees and thus it's OK to disable some security 12493 // mechanisms to make debugging/testing easier on those builds. However, even on 12494 // debuggable builds downgrades of packages are permitted only if requested via 12495 // installFlags. This is because we aim to keep the behavior of debuggable 12496 // platform builds as close as possible to the behavior of non-debuggable 12497 // platform builds. 12498 final boolean downgradeRequested = 12499 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12500 final boolean packageDebuggable = 12501 (dataOwnerPkg.applicationInfo.flags 12502 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12503 final boolean downgradePermitted = 12504 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12505 if (!downgradePermitted) { 12506 try { 12507 checkDowngrade(dataOwnerPkg, pkgLite); 12508 } catch (PackageManagerException e) { 12509 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12510 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12511 } 12512 } 12513 } 12514 12515 if (installedPkg != null) { 12516 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12517 // Check for updated system application. 12518 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12519 if (onSd) { 12520 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12521 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12522 } 12523 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12524 } else { 12525 if (onSd) { 12526 // Install flag overrides everything. 12527 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12528 } 12529 // If current upgrade specifies particular preference 12530 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12531 // Application explicitly specified internal. 12532 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12533 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12534 // App explictly prefers external. Let policy decide 12535 } else { 12536 // Prefer previous location 12537 if (isExternal(installedPkg)) { 12538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12539 } 12540 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12541 } 12542 } 12543 } else { 12544 // Invalid install. Return error code 12545 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12546 } 12547 } 12548 } 12549 // All the special cases have been taken care of. 12550 // Return result based on recommended install location. 12551 if (onSd) { 12552 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12553 } 12554 return pkgLite.recommendedInstallLocation; 12555 } 12556 12557 /* 12558 * Invoke remote method to get package information and install 12559 * location values. Override install location based on default 12560 * policy if needed and then create install arguments based 12561 * on the install location. 12562 */ 12563 public void handleStartCopy() throws RemoteException { 12564 int ret = PackageManager.INSTALL_SUCCEEDED; 12565 12566 // If we're already staged, we've firmly committed to an install location 12567 if (origin.staged) { 12568 if (origin.file != null) { 12569 installFlags |= PackageManager.INSTALL_INTERNAL; 12570 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12571 } else if (origin.cid != null) { 12572 installFlags |= PackageManager.INSTALL_EXTERNAL; 12573 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12574 } else { 12575 throw new IllegalStateException("Invalid stage location"); 12576 } 12577 } 12578 12579 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12580 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12581 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12582 PackageInfoLite pkgLite = null; 12583 12584 if (onInt && onSd) { 12585 // Check if both bits are set. 12586 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12587 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12588 } else if (onSd && ephemeral) { 12589 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12590 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12591 } else { 12592 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12593 packageAbiOverride); 12594 12595 if (DEBUG_EPHEMERAL && ephemeral) { 12596 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12597 } 12598 12599 /* 12600 * If we have too little free space, try to free cache 12601 * before giving up. 12602 */ 12603 if (!origin.staged && pkgLite.recommendedInstallLocation 12604 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12605 // TODO: focus freeing disk space on the target device 12606 final StorageManager storage = StorageManager.from(mContext); 12607 final long lowThreshold = storage.getStorageLowBytes( 12608 Environment.getDataDirectory()); 12609 12610 final long sizeBytes = mContainerService.calculateInstalledSize( 12611 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12612 12613 try { 12614 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12615 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12616 installFlags, packageAbiOverride); 12617 } catch (InstallerException e) { 12618 Slog.w(TAG, "Failed to free cache", e); 12619 } 12620 12621 /* 12622 * The cache free must have deleted the file we 12623 * downloaded to install. 12624 * 12625 * TODO: fix the "freeCache" call to not delete 12626 * the file we care about. 12627 */ 12628 if (pkgLite.recommendedInstallLocation 12629 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12630 pkgLite.recommendedInstallLocation 12631 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12632 } 12633 } 12634 } 12635 12636 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12637 int loc = pkgLite.recommendedInstallLocation; 12638 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12639 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12640 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12641 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12642 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12643 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12644 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12645 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12646 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12647 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12648 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12649 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12650 } else { 12651 // Override with defaults if needed. 12652 loc = installLocationPolicy(pkgLite); 12653 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12654 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12655 } else if (!onSd && !onInt) { 12656 // Override install location with flags 12657 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12658 // Set the flag to install on external media. 12659 installFlags |= PackageManager.INSTALL_EXTERNAL; 12660 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12661 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12662 if (DEBUG_EPHEMERAL) { 12663 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12664 } 12665 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12666 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12667 |PackageManager.INSTALL_INTERNAL); 12668 } else { 12669 // Make sure the flag for installing on external 12670 // media is unset 12671 installFlags |= PackageManager.INSTALL_INTERNAL; 12672 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12673 } 12674 } 12675 } 12676 } 12677 12678 final InstallArgs args = createInstallArgs(this); 12679 mArgs = args; 12680 12681 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12682 // TODO: http://b/22976637 12683 // Apps installed for "all" users use the device owner to verify the app 12684 UserHandle verifierUser = getUser(); 12685 if (verifierUser == UserHandle.ALL) { 12686 verifierUser = UserHandle.SYSTEM; 12687 } 12688 12689 /* 12690 * Determine if we have any installed package verifiers. If we 12691 * do, then we'll defer to them to verify the packages. 12692 */ 12693 final int requiredUid = mRequiredVerifierPackage == null ? -1 12694 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12695 verifierUser.getIdentifier()); 12696 if (!origin.existing && requiredUid != -1 12697 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12698 final Intent verification = new Intent( 12699 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12700 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12701 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12702 PACKAGE_MIME_TYPE); 12703 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12704 12705 // Query all live verifiers based on current user state 12706 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12707 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12708 12709 if (DEBUG_VERIFY) { 12710 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12711 + verification.toString() + " with " + pkgLite.verifiers.length 12712 + " optional verifiers"); 12713 } 12714 12715 final int verificationId = mPendingVerificationToken++; 12716 12717 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12718 12719 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12720 installerPackageName); 12721 12722 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12723 installFlags); 12724 12725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12726 pkgLite.packageName); 12727 12728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12729 pkgLite.versionCode); 12730 12731 if (verificationInfo != null) { 12732 if (verificationInfo.originatingUri != null) { 12733 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12734 verificationInfo.originatingUri); 12735 } 12736 if (verificationInfo.referrer != null) { 12737 verification.putExtra(Intent.EXTRA_REFERRER, 12738 verificationInfo.referrer); 12739 } 12740 if (verificationInfo.originatingUid >= 0) { 12741 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12742 verificationInfo.originatingUid); 12743 } 12744 if (verificationInfo.installerUid >= 0) { 12745 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12746 verificationInfo.installerUid); 12747 } 12748 } 12749 12750 final PackageVerificationState verificationState = new PackageVerificationState( 12751 requiredUid, args); 12752 12753 mPendingVerification.append(verificationId, verificationState); 12754 12755 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12756 receivers, verificationState); 12757 12758 /* 12759 * If any sufficient verifiers were listed in the package 12760 * manifest, attempt to ask them. 12761 */ 12762 if (sufficientVerifiers != null) { 12763 final int N = sufficientVerifiers.size(); 12764 if (N == 0) { 12765 Slog.i(TAG, "Additional verifiers required, but none installed."); 12766 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12767 } else { 12768 for (int i = 0; i < N; i++) { 12769 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12770 12771 final Intent sufficientIntent = new Intent(verification); 12772 sufficientIntent.setComponent(verifierComponent); 12773 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12774 } 12775 } 12776 } 12777 12778 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12779 mRequiredVerifierPackage, receivers); 12780 if (ret == PackageManager.INSTALL_SUCCEEDED 12781 && mRequiredVerifierPackage != null) { 12782 Trace.asyncTraceBegin( 12783 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12784 /* 12785 * Send the intent to the required verification agent, 12786 * but only start the verification timeout after the 12787 * target BroadcastReceivers have run. 12788 */ 12789 verification.setComponent(requiredVerifierComponent); 12790 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12791 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12792 new BroadcastReceiver() { 12793 @Override 12794 public void onReceive(Context context, Intent intent) { 12795 final Message msg = mHandler 12796 .obtainMessage(CHECK_PENDING_VERIFICATION); 12797 msg.arg1 = verificationId; 12798 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12799 } 12800 }, null, 0, null, null); 12801 12802 /* 12803 * We don't want the copy to proceed until verification 12804 * succeeds, so null out this field. 12805 */ 12806 mArgs = null; 12807 } 12808 } else { 12809 /* 12810 * No package verification is enabled, so immediately start 12811 * the remote call to initiate copy using temporary file. 12812 */ 12813 ret = args.copyApk(mContainerService, true); 12814 } 12815 } 12816 12817 mRet = ret; 12818 } 12819 12820 @Override 12821 void handleReturnCode() { 12822 // If mArgs is null, then MCS couldn't be reached. When it 12823 // reconnects, it will try again to install. At that point, this 12824 // will succeed. 12825 if (mArgs != null) { 12826 processPendingInstall(mArgs, mRet); 12827 } 12828 } 12829 12830 @Override 12831 void handleServiceError() { 12832 mArgs = createInstallArgs(this); 12833 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12834 } 12835 12836 public boolean isForwardLocked() { 12837 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12838 } 12839 } 12840 12841 /** 12842 * Used during creation of InstallArgs 12843 * 12844 * @param installFlags package installation flags 12845 * @return true if should be installed on external storage 12846 */ 12847 private static boolean installOnExternalAsec(int installFlags) { 12848 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12849 return false; 12850 } 12851 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12852 return true; 12853 } 12854 return false; 12855 } 12856 12857 /** 12858 * Used during creation of InstallArgs 12859 * 12860 * @param installFlags package installation flags 12861 * @return true if should be installed as forward locked 12862 */ 12863 private static boolean installForwardLocked(int installFlags) { 12864 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12865 } 12866 12867 private InstallArgs createInstallArgs(InstallParams params) { 12868 if (params.move != null) { 12869 return new MoveInstallArgs(params); 12870 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12871 return new AsecInstallArgs(params); 12872 } else { 12873 return new FileInstallArgs(params); 12874 } 12875 } 12876 12877 /** 12878 * Create args that describe an existing installed package. Typically used 12879 * when cleaning up old installs, or used as a move source. 12880 */ 12881 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12882 String resourcePath, String[] instructionSets) { 12883 final boolean isInAsec; 12884 if (installOnExternalAsec(installFlags)) { 12885 /* Apps on SD card are always in ASEC containers. */ 12886 isInAsec = true; 12887 } else if (installForwardLocked(installFlags) 12888 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12889 /* 12890 * Forward-locked apps are only in ASEC containers if they're the 12891 * new style 12892 */ 12893 isInAsec = true; 12894 } else { 12895 isInAsec = false; 12896 } 12897 12898 if (isInAsec) { 12899 return new AsecInstallArgs(codePath, instructionSets, 12900 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12901 } else { 12902 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12903 } 12904 } 12905 12906 static abstract class InstallArgs { 12907 /** @see InstallParams#origin */ 12908 final OriginInfo origin; 12909 /** @see InstallParams#move */ 12910 final MoveInfo move; 12911 12912 final IPackageInstallObserver2 observer; 12913 // Always refers to PackageManager flags only 12914 final int installFlags; 12915 final String installerPackageName; 12916 final String volumeUuid; 12917 final UserHandle user; 12918 final String abiOverride; 12919 final String[] installGrantPermissions; 12920 /** If non-null, drop an async trace when the install completes */ 12921 final String traceMethod; 12922 final int traceCookie; 12923 final Certificate[][] certificates; 12924 12925 // The list of instruction sets supported by this app. This is currently 12926 // only used during the rmdex() phase to clean up resources. We can get rid of this 12927 // if we move dex files under the common app path. 12928 /* nullable */ String[] instructionSets; 12929 12930 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12931 int installFlags, String installerPackageName, String volumeUuid, 12932 UserHandle user, String[] instructionSets, 12933 String abiOverride, String[] installGrantPermissions, 12934 String traceMethod, int traceCookie, Certificate[][] certificates) { 12935 this.origin = origin; 12936 this.move = move; 12937 this.installFlags = installFlags; 12938 this.observer = observer; 12939 this.installerPackageName = installerPackageName; 12940 this.volumeUuid = volumeUuid; 12941 this.user = user; 12942 this.instructionSets = instructionSets; 12943 this.abiOverride = abiOverride; 12944 this.installGrantPermissions = installGrantPermissions; 12945 this.traceMethod = traceMethod; 12946 this.traceCookie = traceCookie; 12947 this.certificates = certificates; 12948 } 12949 12950 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12951 abstract int doPreInstall(int status); 12952 12953 /** 12954 * Rename package into final resting place. All paths on the given 12955 * scanned package should be updated to reflect the rename. 12956 */ 12957 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12958 abstract int doPostInstall(int status, int uid); 12959 12960 /** @see PackageSettingBase#codePathString */ 12961 abstract String getCodePath(); 12962 /** @see PackageSettingBase#resourcePathString */ 12963 abstract String getResourcePath(); 12964 12965 // Need installer lock especially for dex file removal. 12966 abstract void cleanUpResourcesLI(); 12967 abstract boolean doPostDeleteLI(boolean delete); 12968 12969 /** 12970 * Called before the source arguments are copied. This is used mostly 12971 * for MoveParams when it needs to read the source file to put it in the 12972 * destination. 12973 */ 12974 int doPreCopy() { 12975 return PackageManager.INSTALL_SUCCEEDED; 12976 } 12977 12978 /** 12979 * Called after the source arguments are copied. This is used mostly for 12980 * MoveParams when it needs to read the source file to put it in the 12981 * destination. 12982 */ 12983 int doPostCopy(int uid) { 12984 return PackageManager.INSTALL_SUCCEEDED; 12985 } 12986 12987 protected boolean isFwdLocked() { 12988 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12989 } 12990 12991 protected boolean isExternalAsec() { 12992 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12993 } 12994 12995 protected boolean isEphemeral() { 12996 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12997 } 12998 12999 UserHandle getUser() { 13000 return user; 13001 } 13002 } 13003 13004 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13005 if (!allCodePaths.isEmpty()) { 13006 if (instructionSets == null) { 13007 throw new IllegalStateException("instructionSet == null"); 13008 } 13009 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13010 for (String codePath : allCodePaths) { 13011 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13012 try { 13013 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13014 } catch (InstallerException ignored) { 13015 } 13016 } 13017 } 13018 } 13019 } 13020 13021 /** 13022 * Logic to handle installation of non-ASEC applications, including copying 13023 * and renaming logic. 13024 */ 13025 class FileInstallArgs extends InstallArgs { 13026 private File codeFile; 13027 private File resourceFile; 13028 13029 // Example topology: 13030 // /data/app/com.example/base.apk 13031 // /data/app/com.example/split_foo.apk 13032 // /data/app/com.example/lib/arm/libfoo.so 13033 // /data/app/com.example/lib/arm64/libfoo.so 13034 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13035 13036 /** New install */ 13037 FileInstallArgs(InstallParams params) { 13038 super(params.origin, params.move, params.observer, params.installFlags, 13039 params.installerPackageName, params.volumeUuid, 13040 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13041 params.grantedRuntimePermissions, 13042 params.traceMethod, params.traceCookie, params.certificates); 13043 if (isFwdLocked()) { 13044 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13045 } 13046 } 13047 13048 /** Existing install */ 13049 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13050 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13051 null, null, null, 0, null /*certificates*/); 13052 this.codeFile = (codePath != null) ? new File(codePath) : null; 13053 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13054 } 13055 13056 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13057 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13058 try { 13059 return doCopyApk(imcs, temp); 13060 } finally { 13061 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13062 } 13063 } 13064 13065 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13066 if (origin.staged) { 13067 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13068 codeFile = origin.file; 13069 resourceFile = origin.file; 13070 return PackageManager.INSTALL_SUCCEEDED; 13071 } 13072 13073 try { 13074 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13075 final File tempDir = 13076 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13077 codeFile = tempDir; 13078 resourceFile = tempDir; 13079 } catch (IOException e) { 13080 Slog.w(TAG, "Failed to create copy file: " + e); 13081 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13082 } 13083 13084 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13085 @Override 13086 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13087 if (!FileUtils.isValidExtFilename(name)) { 13088 throw new IllegalArgumentException("Invalid filename: " + name); 13089 } 13090 try { 13091 final File file = new File(codeFile, name); 13092 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13093 O_RDWR | O_CREAT, 0644); 13094 Os.chmod(file.getAbsolutePath(), 0644); 13095 return new ParcelFileDescriptor(fd); 13096 } catch (ErrnoException e) { 13097 throw new RemoteException("Failed to open: " + e.getMessage()); 13098 } 13099 } 13100 }; 13101 13102 int ret = PackageManager.INSTALL_SUCCEEDED; 13103 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13104 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13105 Slog.e(TAG, "Failed to copy package"); 13106 return ret; 13107 } 13108 13109 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13110 NativeLibraryHelper.Handle handle = null; 13111 try { 13112 handle = NativeLibraryHelper.Handle.create(codeFile); 13113 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13114 abiOverride); 13115 } catch (IOException e) { 13116 Slog.e(TAG, "Copying native libraries failed", e); 13117 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13118 } finally { 13119 IoUtils.closeQuietly(handle); 13120 } 13121 13122 return ret; 13123 } 13124 13125 int doPreInstall(int status) { 13126 if (status != PackageManager.INSTALL_SUCCEEDED) { 13127 cleanUp(); 13128 } 13129 return status; 13130 } 13131 13132 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13133 if (status != PackageManager.INSTALL_SUCCEEDED) { 13134 cleanUp(); 13135 return false; 13136 } 13137 13138 final File targetDir = codeFile.getParentFile(); 13139 final File beforeCodeFile = codeFile; 13140 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13141 13142 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13143 try { 13144 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13145 } catch (ErrnoException e) { 13146 Slog.w(TAG, "Failed to rename", e); 13147 return false; 13148 } 13149 13150 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13151 Slog.w(TAG, "Failed to restorecon"); 13152 return false; 13153 } 13154 13155 // Reflect the rename internally 13156 codeFile = afterCodeFile; 13157 resourceFile = afterCodeFile; 13158 13159 // Reflect the rename in scanned details 13160 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13161 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13162 afterCodeFile, pkg.baseCodePath)); 13163 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13164 afterCodeFile, pkg.splitCodePaths)); 13165 13166 // Reflect the rename in app info 13167 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13168 pkg.setApplicationInfoCodePath(pkg.codePath); 13169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13171 pkg.setApplicationInfoResourcePath(pkg.codePath); 13172 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13174 13175 return true; 13176 } 13177 13178 int doPostInstall(int status, int uid) { 13179 if (status != PackageManager.INSTALL_SUCCEEDED) { 13180 cleanUp(); 13181 } 13182 return status; 13183 } 13184 13185 @Override 13186 String getCodePath() { 13187 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13188 } 13189 13190 @Override 13191 String getResourcePath() { 13192 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13193 } 13194 13195 private boolean cleanUp() { 13196 if (codeFile == null || !codeFile.exists()) { 13197 return false; 13198 } 13199 13200 removeCodePathLI(codeFile); 13201 13202 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13203 resourceFile.delete(); 13204 } 13205 13206 return true; 13207 } 13208 13209 void cleanUpResourcesLI() { 13210 // Try enumerating all code paths before deleting 13211 List<String> allCodePaths = Collections.EMPTY_LIST; 13212 if (codeFile != null && codeFile.exists()) { 13213 try { 13214 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13215 allCodePaths = pkg.getAllCodePaths(); 13216 } catch (PackageParserException e) { 13217 // Ignored; we tried our best 13218 } 13219 } 13220 13221 cleanUp(); 13222 removeDexFiles(allCodePaths, instructionSets); 13223 } 13224 13225 boolean doPostDeleteLI(boolean delete) { 13226 // XXX err, shouldn't we respect the delete flag? 13227 cleanUpResourcesLI(); 13228 return true; 13229 } 13230 } 13231 13232 private boolean isAsecExternal(String cid) { 13233 final String asecPath = PackageHelper.getSdFilesystem(cid); 13234 return !asecPath.startsWith(mAsecInternalPath); 13235 } 13236 13237 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13238 PackageManagerException { 13239 if (copyRet < 0) { 13240 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13241 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13242 throw new PackageManagerException(copyRet, message); 13243 } 13244 } 13245 } 13246 13247 /** 13248 * Extract the MountService "container ID" from the full code path of an 13249 * .apk. 13250 */ 13251 static String cidFromCodePath(String fullCodePath) { 13252 int eidx = fullCodePath.lastIndexOf("/"); 13253 String subStr1 = fullCodePath.substring(0, eidx); 13254 int sidx = subStr1.lastIndexOf("/"); 13255 return subStr1.substring(sidx+1, eidx); 13256 } 13257 13258 /** 13259 * Logic to handle installation of ASEC applications, including copying and 13260 * renaming logic. 13261 */ 13262 class AsecInstallArgs extends InstallArgs { 13263 static final String RES_FILE_NAME = "pkg.apk"; 13264 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13265 13266 String cid; 13267 String packagePath; 13268 String resourcePath; 13269 13270 /** New install */ 13271 AsecInstallArgs(InstallParams params) { 13272 super(params.origin, params.move, params.observer, params.installFlags, 13273 params.installerPackageName, params.volumeUuid, 13274 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13275 params.grantedRuntimePermissions, 13276 params.traceMethod, params.traceCookie, params.certificates); 13277 } 13278 13279 /** Existing install */ 13280 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13281 boolean isExternal, boolean isForwardLocked) { 13282 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13283 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13284 instructionSets, null, null, null, 0, null /*certificates*/); 13285 // Hackily pretend we're still looking at a full code path 13286 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13287 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13288 } 13289 13290 // Extract cid from fullCodePath 13291 int eidx = fullCodePath.lastIndexOf("/"); 13292 String subStr1 = fullCodePath.substring(0, eidx); 13293 int sidx = subStr1.lastIndexOf("/"); 13294 cid = subStr1.substring(sidx+1, eidx); 13295 setMountPath(subStr1); 13296 } 13297 13298 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13299 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13300 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13301 instructionSets, null, null, null, 0, null /*certificates*/); 13302 this.cid = cid; 13303 setMountPath(PackageHelper.getSdDir(cid)); 13304 } 13305 13306 void createCopyFile() { 13307 cid = mInstallerService.allocateExternalStageCidLegacy(); 13308 } 13309 13310 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13311 if (origin.staged && origin.cid != null) { 13312 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13313 cid = origin.cid; 13314 setMountPath(PackageHelper.getSdDir(cid)); 13315 return PackageManager.INSTALL_SUCCEEDED; 13316 } 13317 13318 if (temp) { 13319 createCopyFile(); 13320 } else { 13321 /* 13322 * Pre-emptively destroy the container since it's destroyed if 13323 * copying fails due to it existing anyway. 13324 */ 13325 PackageHelper.destroySdDir(cid); 13326 } 13327 13328 final String newMountPath = imcs.copyPackageToContainer( 13329 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13330 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13331 13332 if (newMountPath != null) { 13333 setMountPath(newMountPath); 13334 return PackageManager.INSTALL_SUCCEEDED; 13335 } else { 13336 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13337 } 13338 } 13339 13340 @Override 13341 String getCodePath() { 13342 return packagePath; 13343 } 13344 13345 @Override 13346 String getResourcePath() { 13347 return resourcePath; 13348 } 13349 13350 int doPreInstall(int status) { 13351 if (status != PackageManager.INSTALL_SUCCEEDED) { 13352 // Destroy container 13353 PackageHelper.destroySdDir(cid); 13354 } else { 13355 boolean mounted = PackageHelper.isContainerMounted(cid); 13356 if (!mounted) { 13357 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13358 Process.SYSTEM_UID); 13359 if (newMountPath != null) { 13360 setMountPath(newMountPath); 13361 } else { 13362 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13363 } 13364 } 13365 } 13366 return status; 13367 } 13368 13369 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13370 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13371 String newMountPath = null; 13372 if (PackageHelper.isContainerMounted(cid)) { 13373 // Unmount the container 13374 if (!PackageHelper.unMountSdDir(cid)) { 13375 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13376 return false; 13377 } 13378 } 13379 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13380 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13381 " which might be stale. Will try to clean up."); 13382 // Clean up the stale container and proceed to recreate. 13383 if (!PackageHelper.destroySdDir(newCacheId)) { 13384 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13385 return false; 13386 } 13387 // Successfully cleaned up stale container. Try to rename again. 13388 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13389 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13390 + " inspite of cleaning it up."); 13391 return false; 13392 } 13393 } 13394 if (!PackageHelper.isContainerMounted(newCacheId)) { 13395 Slog.w(TAG, "Mounting container " + newCacheId); 13396 newMountPath = PackageHelper.mountSdDir(newCacheId, 13397 getEncryptKey(), Process.SYSTEM_UID); 13398 } else { 13399 newMountPath = PackageHelper.getSdDir(newCacheId); 13400 } 13401 if (newMountPath == null) { 13402 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13403 return false; 13404 } 13405 Log.i(TAG, "Succesfully renamed " + cid + 13406 " to " + newCacheId + 13407 " at new path: " + newMountPath); 13408 cid = newCacheId; 13409 13410 final File beforeCodeFile = new File(packagePath); 13411 setMountPath(newMountPath); 13412 final File afterCodeFile = new File(packagePath); 13413 13414 // Reflect the rename in scanned details 13415 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13416 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13417 afterCodeFile, pkg.baseCodePath)); 13418 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13419 afterCodeFile, pkg.splitCodePaths)); 13420 13421 // Reflect the rename in app info 13422 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13423 pkg.setApplicationInfoCodePath(pkg.codePath); 13424 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13425 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13426 pkg.setApplicationInfoResourcePath(pkg.codePath); 13427 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13428 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13429 13430 return true; 13431 } 13432 13433 private void setMountPath(String mountPath) { 13434 final File mountFile = new File(mountPath); 13435 13436 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13437 if (monolithicFile.exists()) { 13438 packagePath = monolithicFile.getAbsolutePath(); 13439 if (isFwdLocked()) { 13440 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13441 } else { 13442 resourcePath = packagePath; 13443 } 13444 } else { 13445 packagePath = mountFile.getAbsolutePath(); 13446 resourcePath = packagePath; 13447 } 13448 } 13449 13450 int doPostInstall(int status, int uid) { 13451 if (status != PackageManager.INSTALL_SUCCEEDED) { 13452 cleanUp(); 13453 } else { 13454 final int groupOwner; 13455 final String protectedFile; 13456 if (isFwdLocked()) { 13457 groupOwner = UserHandle.getSharedAppGid(uid); 13458 protectedFile = RES_FILE_NAME; 13459 } else { 13460 groupOwner = -1; 13461 protectedFile = null; 13462 } 13463 13464 if (uid < Process.FIRST_APPLICATION_UID 13465 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13466 Slog.e(TAG, "Failed to finalize " + cid); 13467 PackageHelper.destroySdDir(cid); 13468 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13469 } 13470 13471 boolean mounted = PackageHelper.isContainerMounted(cid); 13472 if (!mounted) { 13473 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13474 } 13475 } 13476 return status; 13477 } 13478 13479 private void cleanUp() { 13480 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13481 13482 // Destroy secure container 13483 PackageHelper.destroySdDir(cid); 13484 } 13485 13486 private List<String> getAllCodePaths() { 13487 final File codeFile = new File(getCodePath()); 13488 if (codeFile != null && codeFile.exists()) { 13489 try { 13490 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13491 return pkg.getAllCodePaths(); 13492 } catch (PackageParserException e) { 13493 // Ignored; we tried our best 13494 } 13495 } 13496 return Collections.EMPTY_LIST; 13497 } 13498 13499 void cleanUpResourcesLI() { 13500 // Enumerate all code paths before deleting 13501 cleanUpResourcesLI(getAllCodePaths()); 13502 } 13503 13504 private void cleanUpResourcesLI(List<String> allCodePaths) { 13505 cleanUp(); 13506 removeDexFiles(allCodePaths, instructionSets); 13507 } 13508 13509 String getPackageName() { 13510 return getAsecPackageName(cid); 13511 } 13512 13513 boolean doPostDeleteLI(boolean delete) { 13514 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13515 final List<String> allCodePaths = getAllCodePaths(); 13516 boolean mounted = PackageHelper.isContainerMounted(cid); 13517 if (mounted) { 13518 // Unmount first 13519 if (PackageHelper.unMountSdDir(cid)) { 13520 mounted = false; 13521 } 13522 } 13523 if (!mounted && delete) { 13524 cleanUpResourcesLI(allCodePaths); 13525 } 13526 return !mounted; 13527 } 13528 13529 @Override 13530 int doPreCopy() { 13531 if (isFwdLocked()) { 13532 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13533 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13534 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13535 } 13536 } 13537 13538 return PackageManager.INSTALL_SUCCEEDED; 13539 } 13540 13541 @Override 13542 int doPostCopy(int uid) { 13543 if (isFwdLocked()) { 13544 if (uid < Process.FIRST_APPLICATION_UID 13545 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13546 RES_FILE_NAME)) { 13547 Slog.e(TAG, "Failed to finalize " + cid); 13548 PackageHelper.destroySdDir(cid); 13549 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13550 } 13551 } 13552 13553 return PackageManager.INSTALL_SUCCEEDED; 13554 } 13555 } 13556 13557 /** 13558 * Logic to handle movement of existing installed applications. 13559 */ 13560 class MoveInstallArgs extends InstallArgs { 13561 private File codeFile; 13562 private File resourceFile; 13563 13564 /** New install */ 13565 MoveInstallArgs(InstallParams params) { 13566 super(params.origin, params.move, params.observer, params.installFlags, 13567 params.installerPackageName, params.volumeUuid, 13568 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13569 params.grantedRuntimePermissions, 13570 params.traceMethod, params.traceCookie, params.certificates); 13571 } 13572 13573 int copyApk(IMediaContainerService imcs, boolean temp) { 13574 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13575 + move.fromUuid + " to " + move.toUuid); 13576 synchronized (mInstaller) { 13577 try { 13578 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13579 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13580 } catch (InstallerException e) { 13581 Slog.w(TAG, "Failed to move app", e); 13582 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13583 } 13584 } 13585 13586 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13587 resourceFile = codeFile; 13588 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13589 13590 return PackageManager.INSTALL_SUCCEEDED; 13591 } 13592 13593 int doPreInstall(int status) { 13594 if (status != PackageManager.INSTALL_SUCCEEDED) { 13595 cleanUp(move.toUuid); 13596 } 13597 return status; 13598 } 13599 13600 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13601 if (status != PackageManager.INSTALL_SUCCEEDED) { 13602 cleanUp(move.toUuid); 13603 return false; 13604 } 13605 13606 // Reflect the move in app info 13607 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13608 pkg.setApplicationInfoCodePath(pkg.codePath); 13609 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13610 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13611 pkg.setApplicationInfoResourcePath(pkg.codePath); 13612 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13613 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13614 13615 return true; 13616 } 13617 13618 int doPostInstall(int status, int uid) { 13619 if (status == PackageManager.INSTALL_SUCCEEDED) { 13620 cleanUp(move.fromUuid); 13621 } else { 13622 cleanUp(move.toUuid); 13623 } 13624 return status; 13625 } 13626 13627 @Override 13628 String getCodePath() { 13629 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13630 } 13631 13632 @Override 13633 String getResourcePath() { 13634 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13635 } 13636 13637 private boolean cleanUp(String volumeUuid) { 13638 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13639 move.dataAppName); 13640 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13641 final int[] userIds = sUserManager.getUserIds(); 13642 synchronized (mInstallLock) { 13643 // Clean up both app data and code 13644 // All package moves are frozen until finished 13645 for (int userId : userIds) { 13646 try { 13647 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13648 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13649 } catch (InstallerException e) { 13650 Slog.w(TAG, String.valueOf(e)); 13651 } 13652 } 13653 removeCodePathLI(codeFile); 13654 } 13655 return true; 13656 } 13657 13658 void cleanUpResourcesLI() { 13659 throw new UnsupportedOperationException(); 13660 } 13661 13662 boolean doPostDeleteLI(boolean delete) { 13663 throw new UnsupportedOperationException(); 13664 } 13665 } 13666 13667 static String getAsecPackageName(String packageCid) { 13668 int idx = packageCid.lastIndexOf("-"); 13669 if (idx == -1) { 13670 return packageCid; 13671 } 13672 return packageCid.substring(0, idx); 13673 } 13674 13675 // Utility method used to create code paths based on package name and available index. 13676 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13677 String idxStr = ""; 13678 int idx = 1; 13679 // Fall back to default value of idx=1 if prefix is not 13680 // part of oldCodePath 13681 if (oldCodePath != null) { 13682 String subStr = oldCodePath; 13683 // Drop the suffix right away 13684 if (suffix != null && subStr.endsWith(suffix)) { 13685 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13686 } 13687 // If oldCodePath already contains prefix find out the 13688 // ending index to either increment or decrement. 13689 int sidx = subStr.lastIndexOf(prefix); 13690 if (sidx != -1) { 13691 subStr = subStr.substring(sidx + prefix.length()); 13692 if (subStr != null) { 13693 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13694 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13695 } 13696 try { 13697 idx = Integer.parseInt(subStr); 13698 if (idx <= 1) { 13699 idx++; 13700 } else { 13701 idx--; 13702 } 13703 } catch(NumberFormatException e) { 13704 } 13705 } 13706 } 13707 } 13708 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13709 return prefix + idxStr; 13710 } 13711 13712 private File getNextCodePath(File targetDir, String packageName) { 13713 int suffix = 1; 13714 File result; 13715 do { 13716 result = new File(targetDir, packageName + "-" + suffix); 13717 suffix++; 13718 } while (result.exists()); 13719 return result; 13720 } 13721 13722 // Utility method that returns the relative package path with respect 13723 // to the installation directory. Like say for /data/data/com.test-1.apk 13724 // string com.test-1 is returned. 13725 static String deriveCodePathName(String codePath) { 13726 if (codePath == null) { 13727 return null; 13728 } 13729 final File codeFile = new File(codePath); 13730 final String name = codeFile.getName(); 13731 if (codeFile.isDirectory()) { 13732 return name; 13733 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13734 final int lastDot = name.lastIndexOf('.'); 13735 return name.substring(0, lastDot); 13736 } else { 13737 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13738 return null; 13739 } 13740 } 13741 13742 static class PackageInstalledInfo { 13743 String name; 13744 int uid; 13745 // The set of users that originally had this package installed. 13746 int[] origUsers; 13747 // The set of users that now have this package installed. 13748 int[] newUsers; 13749 PackageParser.Package pkg; 13750 int returnCode; 13751 String returnMsg; 13752 PackageRemovedInfo removedInfo; 13753 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13754 13755 public void setError(int code, String msg) { 13756 setReturnCode(code); 13757 setReturnMessage(msg); 13758 Slog.w(TAG, msg); 13759 } 13760 13761 public void setError(String msg, PackageParserException e) { 13762 setReturnCode(e.error); 13763 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13764 Slog.w(TAG, msg, e); 13765 } 13766 13767 public void setError(String msg, PackageManagerException e) { 13768 returnCode = e.error; 13769 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13770 Slog.w(TAG, msg, e); 13771 } 13772 13773 public void setReturnCode(int returnCode) { 13774 this.returnCode = returnCode; 13775 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13776 for (int i = 0; i < childCount; i++) { 13777 addedChildPackages.valueAt(i).returnCode = returnCode; 13778 } 13779 } 13780 13781 private void setReturnMessage(String returnMsg) { 13782 this.returnMsg = returnMsg; 13783 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13784 for (int i = 0; i < childCount; i++) { 13785 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13786 } 13787 } 13788 13789 // In some error cases we want to convey more info back to the observer 13790 String origPackage; 13791 String origPermission; 13792 } 13793 13794 /* 13795 * Install a non-existing package. 13796 */ 13797 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13798 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13799 PackageInstalledInfo res) { 13800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13801 13802 // Remember this for later, in case we need to rollback this install 13803 String pkgName = pkg.packageName; 13804 13805 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13806 13807 synchronized(mPackages) { 13808 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13809 // A package with the same name is already installed, though 13810 // it has been renamed to an older name. The package we 13811 // are trying to install should be installed as an update to 13812 // the existing one, but that has not been requested, so bail. 13813 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13814 + " without first uninstalling package running as " 13815 + mSettings.mRenamedPackages.get(pkgName)); 13816 return; 13817 } 13818 if (mPackages.containsKey(pkgName)) { 13819 // Don't allow installation over an existing package with the same name. 13820 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13821 + " without first uninstalling."); 13822 return; 13823 } 13824 } 13825 13826 try { 13827 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13828 System.currentTimeMillis(), user); 13829 13830 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13831 13832 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13833 prepareAppDataAfterInstallLIF(newPackage); 13834 13835 } else { 13836 // Remove package from internal structures, but keep around any 13837 // data that might have already existed 13838 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13839 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13840 } 13841 } catch (PackageManagerException e) { 13842 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13843 } 13844 13845 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13846 } 13847 13848 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13849 // Can't rotate keys during boot or if sharedUser. 13850 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13851 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13852 return false; 13853 } 13854 // app is using upgradeKeySets; make sure all are valid 13855 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13856 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13857 for (int i = 0; i < upgradeKeySets.length; i++) { 13858 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13859 Slog.wtf(TAG, "Package " 13860 + (oldPs.name != null ? oldPs.name : "<null>") 13861 + " contains upgrade-key-set reference to unknown key-set: " 13862 + upgradeKeySets[i] 13863 + " reverting to signatures check."); 13864 return false; 13865 } 13866 } 13867 return true; 13868 } 13869 13870 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13871 // Upgrade keysets are being used. Determine if new package has a superset of the 13872 // required keys. 13873 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13874 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13875 for (int i = 0; i < upgradeKeySets.length; i++) { 13876 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13877 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13878 return true; 13879 } 13880 } 13881 return false; 13882 } 13883 13884 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13885 try (DigestInputStream digestStream = 13886 new DigestInputStream(new FileInputStream(file), digest)) { 13887 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13888 } 13889 } 13890 13891 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13892 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13893 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13894 13895 final PackageParser.Package oldPackage; 13896 final String pkgName = pkg.packageName; 13897 final int[] allUsers; 13898 final int[] installedUsers; 13899 13900 synchronized(mPackages) { 13901 oldPackage = mPackages.get(pkgName); 13902 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13903 13904 // don't allow upgrade to target a release SDK from a pre-release SDK 13905 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13906 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13907 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13908 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13909 if (oldTargetsPreRelease 13910 && !newTargetsPreRelease 13911 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13912 Slog.w(TAG, "Can't install package targeting released sdk"); 13913 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13914 return; 13915 } 13916 13917 // don't allow an upgrade from full to ephemeral 13918 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13919 if (isEphemeral && !oldIsEphemeral) { 13920 // can't downgrade from full to ephemeral 13921 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13922 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13923 return; 13924 } 13925 13926 // verify signatures are valid 13927 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13928 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13929 if (!checkUpgradeKeySetLP(ps, pkg)) { 13930 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13931 "New package not signed by keys specified by upgrade-keysets: " 13932 + pkgName); 13933 return; 13934 } 13935 } else { 13936 // default to original signature matching 13937 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13938 != PackageManager.SIGNATURE_MATCH) { 13939 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13940 "New package has a different signature: " + pkgName); 13941 return; 13942 } 13943 } 13944 13945 // don't allow a system upgrade unless the upgrade hash matches 13946 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13947 byte[] digestBytes = null; 13948 try { 13949 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13950 updateDigest(digest, new File(pkg.baseCodePath)); 13951 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13952 for (String path : pkg.splitCodePaths) { 13953 updateDigest(digest, new File(path)); 13954 } 13955 } 13956 digestBytes = digest.digest(); 13957 } catch (NoSuchAlgorithmException | IOException e) { 13958 res.setError(INSTALL_FAILED_INVALID_APK, 13959 "Could not compute hash: " + pkgName); 13960 return; 13961 } 13962 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13963 res.setError(INSTALL_FAILED_INVALID_APK, 13964 "New package fails restrict-update check: " + pkgName); 13965 return; 13966 } 13967 // retain upgrade restriction 13968 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13969 } 13970 13971 // Check for shared user id changes 13972 String invalidPackageName = 13973 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13974 if (invalidPackageName != null) { 13975 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13976 "Package " + invalidPackageName + " tried to change user " 13977 + oldPackage.mSharedUserId); 13978 return; 13979 } 13980 13981 // In case of rollback, remember per-user/profile install state 13982 allUsers = sUserManager.getUserIds(); 13983 installedUsers = ps.queryInstalledUsers(allUsers, true); 13984 } 13985 13986 // Update what is removed 13987 res.removedInfo = new PackageRemovedInfo(); 13988 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13989 res.removedInfo.removedPackage = oldPackage.packageName; 13990 res.removedInfo.isUpdate = true; 13991 res.removedInfo.origUsers = installedUsers; 13992 final int childCount = (oldPackage.childPackages != null) 13993 ? oldPackage.childPackages.size() : 0; 13994 for (int i = 0; i < childCount; i++) { 13995 boolean childPackageUpdated = false; 13996 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13997 if (res.addedChildPackages != null) { 13998 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13999 if (childRes != null) { 14000 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14001 childRes.removedInfo.removedPackage = childPkg.packageName; 14002 childRes.removedInfo.isUpdate = true; 14003 childPackageUpdated = true; 14004 } 14005 } 14006 if (!childPackageUpdated) { 14007 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14008 childRemovedRes.removedPackage = childPkg.packageName; 14009 childRemovedRes.isUpdate = false; 14010 childRemovedRes.dataRemoved = true; 14011 synchronized (mPackages) { 14012 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14013 if (childPs != null) { 14014 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14015 } 14016 } 14017 if (res.removedInfo.removedChildPackages == null) { 14018 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14019 } 14020 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14021 } 14022 } 14023 14024 boolean sysPkg = (isSystemApp(oldPackage)); 14025 if (sysPkg) { 14026 // Set the system/privileged flags as needed 14027 final boolean privileged = 14028 (oldPackage.applicationInfo.privateFlags 14029 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14030 final int systemPolicyFlags = policyFlags 14031 | PackageParser.PARSE_IS_SYSTEM 14032 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14033 14034 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14035 user, allUsers, installerPackageName, res); 14036 } else { 14037 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14038 user, allUsers, installerPackageName, res); 14039 } 14040 } 14041 14042 public List<String> getPreviousCodePaths(String packageName) { 14043 final PackageSetting ps = mSettings.mPackages.get(packageName); 14044 final List<String> result = new ArrayList<String>(); 14045 if (ps != null && ps.oldCodePaths != null) { 14046 result.addAll(ps.oldCodePaths); 14047 } 14048 return result; 14049 } 14050 14051 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14052 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14053 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14054 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14055 + deletedPackage); 14056 14057 String pkgName = deletedPackage.packageName; 14058 boolean deletedPkg = true; 14059 boolean addedPkg = false; 14060 boolean updatedSettings = false; 14061 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14062 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14063 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14064 14065 final long origUpdateTime = (pkg.mExtras != null) 14066 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14067 14068 // First delete the existing package while retaining the data directory 14069 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14070 res.removedInfo, true, pkg)) { 14071 // If the existing package wasn't successfully deleted 14072 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14073 deletedPkg = false; 14074 } else { 14075 // Successfully deleted the old package; proceed with replace. 14076 14077 // If deleted package lived in a container, give users a chance to 14078 // relinquish resources before killing. 14079 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14080 if (DEBUG_INSTALL) { 14081 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14082 } 14083 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14084 final ArrayList<String> pkgList = new ArrayList<String>(1); 14085 pkgList.add(deletedPackage.applicationInfo.packageName); 14086 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14087 } 14088 14089 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14090 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14091 clearAppProfilesLIF(pkg); 14092 14093 try { 14094 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14095 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14096 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14097 14098 // Update the in-memory copy of the previous code paths. 14099 PackageSetting ps = mSettings.mPackages.get(pkgName); 14100 if (!killApp) { 14101 if (ps.oldCodePaths == null) { 14102 ps.oldCodePaths = new ArraySet<>(); 14103 } 14104 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14105 if (deletedPackage.splitCodePaths != null) { 14106 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14107 } 14108 } else { 14109 ps.oldCodePaths = null; 14110 } 14111 if (ps.childPackageNames != null) { 14112 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14113 final String childPkgName = ps.childPackageNames.get(i); 14114 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14115 childPs.oldCodePaths = ps.oldCodePaths; 14116 } 14117 } 14118 prepareAppDataAfterInstallLIF(newPackage); 14119 addedPkg = true; 14120 } catch (PackageManagerException e) { 14121 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14122 } 14123 } 14124 14125 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14126 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14127 14128 // Revert all internal state mutations and added folders for the failed install 14129 if (addedPkg) { 14130 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14131 res.removedInfo, true, null); 14132 } 14133 14134 // Restore the old package 14135 if (deletedPkg) { 14136 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14137 File restoreFile = new File(deletedPackage.codePath); 14138 // Parse old package 14139 boolean oldExternal = isExternal(deletedPackage); 14140 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14141 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14142 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14143 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14144 try { 14145 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14146 null); 14147 } catch (PackageManagerException e) { 14148 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14149 + e.getMessage()); 14150 return; 14151 } 14152 14153 synchronized (mPackages) { 14154 // Ensure the installer package name up to date 14155 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14156 14157 // Update permissions for restored package 14158 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14159 14160 mSettings.writeLPr(); 14161 } 14162 14163 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14164 } 14165 } else { 14166 synchronized (mPackages) { 14167 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14168 if (ps != null) { 14169 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14170 if (res.removedInfo.removedChildPackages != null) { 14171 final int childCount = res.removedInfo.removedChildPackages.size(); 14172 // Iterate in reverse as we may modify the collection 14173 for (int i = childCount - 1; i >= 0; i--) { 14174 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14175 if (res.addedChildPackages.containsKey(childPackageName)) { 14176 res.removedInfo.removedChildPackages.removeAt(i); 14177 } else { 14178 PackageRemovedInfo childInfo = res.removedInfo 14179 .removedChildPackages.valueAt(i); 14180 childInfo.removedForAllUsers = mPackages.get( 14181 childInfo.removedPackage) == null; 14182 } 14183 } 14184 } 14185 } 14186 } 14187 } 14188 } 14189 14190 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14191 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14192 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14193 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14194 + ", old=" + deletedPackage); 14195 14196 final boolean disabledSystem; 14197 14198 // Remove existing system package 14199 removePackageLI(deletedPackage, true); 14200 14201 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14202 if (!disabledSystem) { 14203 // We didn't need to disable the .apk as a current system package, 14204 // which means we are replacing another update that is already 14205 // installed. We need to make sure to delete the older one's .apk. 14206 res.removedInfo.args = createInstallArgsForExisting(0, 14207 deletedPackage.applicationInfo.getCodePath(), 14208 deletedPackage.applicationInfo.getResourcePath(), 14209 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14210 } else { 14211 res.removedInfo.args = null; 14212 } 14213 14214 // Successfully disabled the old package. Now proceed with re-installation 14215 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14216 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14217 clearAppProfilesLIF(pkg); 14218 14219 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14220 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14221 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14222 14223 PackageParser.Package newPackage = null; 14224 try { 14225 // Add the package to the internal data structures 14226 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14227 14228 // Set the update and install times 14229 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14230 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14231 System.currentTimeMillis()); 14232 14233 // Update the package dynamic state if succeeded 14234 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14235 // Now that the install succeeded make sure we remove data 14236 // directories for any child package the update removed. 14237 final int deletedChildCount = (deletedPackage.childPackages != null) 14238 ? deletedPackage.childPackages.size() : 0; 14239 final int newChildCount = (newPackage.childPackages != null) 14240 ? newPackage.childPackages.size() : 0; 14241 for (int i = 0; i < deletedChildCount; i++) { 14242 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14243 boolean childPackageDeleted = true; 14244 for (int j = 0; j < newChildCount; j++) { 14245 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14246 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14247 childPackageDeleted = false; 14248 break; 14249 } 14250 } 14251 if (childPackageDeleted) { 14252 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14253 deletedChildPkg.packageName); 14254 if (ps != null && res.removedInfo.removedChildPackages != null) { 14255 PackageRemovedInfo removedChildRes = res.removedInfo 14256 .removedChildPackages.get(deletedChildPkg.packageName); 14257 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14258 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14259 } 14260 } 14261 } 14262 14263 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14264 prepareAppDataAfterInstallLIF(newPackage); 14265 } 14266 } catch (PackageManagerException e) { 14267 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14268 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14269 } 14270 14271 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14272 // Re installation failed. Restore old information 14273 // Remove new pkg information 14274 if (newPackage != null) { 14275 removeInstalledPackageLI(newPackage, true); 14276 } 14277 // Add back the old system package 14278 try { 14279 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14280 } catch (PackageManagerException e) { 14281 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14282 } 14283 14284 synchronized (mPackages) { 14285 if (disabledSystem) { 14286 enableSystemPackageLPw(deletedPackage); 14287 } 14288 14289 // Ensure the installer package name up to date 14290 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14291 14292 // Update permissions for restored package 14293 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14294 14295 mSettings.writeLPr(); 14296 } 14297 14298 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14299 + " after failed upgrade"); 14300 } 14301 } 14302 14303 /** 14304 * Checks whether the parent or any of the child packages have a change shared 14305 * user. For a package to be a valid update the shred users of the parent and 14306 * the children should match. We may later support changing child shared users. 14307 * @param oldPkg The updated package. 14308 * @param newPkg The update package. 14309 * @return The shared user that change between the versions. 14310 */ 14311 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14312 PackageParser.Package newPkg) { 14313 // Check parent shared user 14314 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14315 return newPkg.packageName; 14316 } 14317 // Check child shared users 14318 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14319 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14320 for (int i = 0; i < newChildCount; i++) { 14321 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14322 // If this child was present, did it have the same shared user? 14323 for (int j = 0; j < oldChildCount; j++) { 14324 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14325 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14326 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14327 return newChildPkg.packageName; 14328 } 14329 } 14330 } 14331 return null; 14332 } 14333 14334 private void removeNativeBinariesLI(PackageSetting ps) { 14335 // Remove the lib path for the parent package 14336 if (ps != null) { 14337 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14338 // Remove the lib path for the child packages 14339 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14340 for (int i = 0; i < childCount; i++) { 14341 PackageSetting childPs = null; 14342 synchronized (mPackages) { 14343 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14344 } 14345 if (childPs != null) { 14346 NativeLibraryHelper.removeNativeBinariesLI(childPs 14347 .legacyNativeLibraryPathString); 14348 } 14349 } 14350 } 14351 } 14352 14353 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14354 // Enable the parent package 14355 mSettings.enableSystemPackageLPw(pkg.packageName); 14356 // Enable the child packages 14357 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14358 for (int i = 0; i < childCount; i++) { 14359 PackageParser.Package childPkg = pkg.childPackages.get(i); 14360 mSettings.enableSystemPackageLPw(childPkg.packageName); 14361 } 14362 } 14363 14364 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14365 PackageParser.Package newPkg) { 14366 // Disable the parent package (parent always replaced) 14367 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14368 // Disable the child packages 14369 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14370 for (int i = 0; i < childCount; i++) { 14371 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14372 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14373 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14374 } 14375 return disabled; 14376 } 14377 14378 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14379 String installerPackageName) { 14380 // Enable the parent package 14381 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14382 // Enable the child packages 14383 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14384 for (int i = 0; i < childCount; i++) { 14385 PackageParser.Package childPkg = pkg.childPackages.get(i); 14386 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14387 } 14388 } 14389 14390 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14391 // Collect all used permissions in the UID 14392 ArraySet<String> usedPermissions = new ArraySet<>(); 14393 final int packageCount = su.packages.size(); 14394 for (int i = 0; i < packageCount; i++) { 14395 PackageSetting ps = su.packages.valueAt(i); 14396 if (ps.pkg == null) { 14397 continue; 14398 } 14399 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14400 for (int j = 0; j < requestedPermCount; j++) { 14401 String permission = ps.pkg.requestedPermissions.get(j); 14402 BasePermission bp = mSettings.mPermissions.get(permission); 14403 if (bp != null) { 14404 usedPermissions.add(permission); 14405 } 14406 } 14407 } 14408 14409 PermissionsState permissionsState = su.getPermissionsState(); 14410 // Prune install permissions 14411 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14412 final int installPermCount = installPermStates.size(); 14413 for (int i = installPermCount - 1; i >= 0; i--) { 14414 PermissionState permissionState = installPermStates.get(i); 14415 if (!usedPermissions.contains(permissionState.getName())) { 14416 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14417 if (bp != null) { 14418 permissionsState.revokeInstallPermission(bp); 14419 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14420 PackageManager.MASK_PERMISSION_FLAGS, 0); 14421 } 14422 } 14423 } 14424 14425 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14426 14427 // Prune runtime permissions 14428 for (int userId : allUserIds) { 14429 List<PermissionState> runtimePermStates = permissionsState 14430 .getRuntimePermissionStates(userId); 14431 final int runtimePermCount = runtimePermStates.size(); 14432 for (int i = runtimePermCount - 1; i >= 0; i--) { 14433 PermissionState permissionState = runtimePermStates.get(i); 14434 if (!usedPermissions.contains(permissionState.getName())) { 14435 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14436 if (bp != null) { 14437 permissionsState.revokeRuntimePermission(bp, userId); 14438 permissionsState.updatePermissionFlags(bp, userId, 14439 PackageManager.MASK_PERMISSION_FLAGS, 0); 14440 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14441 runtimePermissionChangedUserIds, userId); 14442 } 14443 } 14444 } 14445 } 14446 14447 return runtimePermissionChangedUserIds; 14448 } 14449 14450 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14451 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14452 // Update the parent package setting 14453 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14454 res, user); 14455 // Update the child packages setting 14456 final int childCount = (newPackage.childPackages != null) 14457 ? newPackage.childPackages.size() : 0; 14458 for (int i = 0; i < childCount; i++) { 14459 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14460 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14461 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14462 childRes.origUsers, childRes, user); 14463 } 14464 } 14465 14466 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14467 String installerPackageName, int[] allUsers, int[] installedForUsers, 14468 PackageInstalledInfo res, UserHandle user) { 14469 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14470 14471 String pkgName = newPackage.packageName; 14472 synchronized (mPackages) { 14473 //write settings. the installStatus will be incomplete at this stage. 14474 //note that the new package setting would have already been 14475 //added to mPackages. It hasn't been persisted yet. 14476 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14478 mSettings.writeLPr(); 14479 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14480 } 14481 14482 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14483 synchronized (mPackages) { 14484 updatePermissionsLPw(newPackage.packageName, newPackage, 14485 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14486 ? UPDATE_PERMISSIONS_ALL : 0)); 14487 // For system-bundled packages, we assume that installing an upgraded version 14488 // of the package implies that the user actually wants to run that new code, 14489 // so we enable the package. 14490 PackageSetting ps = mSettings.mPackages.get(pkgName); 14491 final int userId = user.getIdentifier(); 14492 if (ps != null) { 14493 if (isSystemApp(newPackage)) { 14494 if (DEBUG_INSTALL) { 14495 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14496 } 14497 // Enable system package for requested users 14498 if (res.origUsers != null) { 14499 for (int origUserId : res.origUsers) { 14500 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14501 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14502 origUserId, installerPackageName); 14503 } 14504 } 14505 } 14506 // Also convey the prior install/uninstall state 14507 if (allUsers != null && installedForUsers != null) { 14508 for (int currentUserId : allUsers) { 14509 final boolean installed = ArrayUtils.contains( 14510 installedForUsers, currentUserId); 14511 if (DEBUG_INSTALL) { 14512 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14513 } 14514 ps.setInstalled(installed, currentUserId); 14515 } 14516 // these install state changes will be persisted in the 14517 // upcoming call to mSettings.writeLPr(). 14518 } 14519 } 14520 // It's implied that when a user requests installation, they want the app to be 14521 // installed and enabled. 14522 if (userId != UserHandle.USER_ALL) { 14523 ps.setInstalled(true, userId); 14524 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14525 } 14526 } 14527 res.name = pkgName; 14528 res.uid = newPackage.applicationInfo.uid; 14529 res.pkg = newPackage; 14530 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14531 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14532 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14533 //to update install status 14534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14535 mSettings.writeLPr(); 14536 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14537 } 14538 14539 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14540 } 14541 14542 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14543 try { 14544 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14545 installPackageLI(args, res); 14546 } finally { 14547 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14548 } 14549 } 14550 14551 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14552 final int installFlags = args.installFlags; 14553 final String installerPackageName = args.installerPackageName; 14554 final String volumeUuid = args.volumeUuid; 14555 final File tmpPackageFile = new File(args.getCodePath()); 14556 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14557 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14558 || (args.volumeUuid != null)); 14559 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14560 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14561 boolean replace = false; 14562 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14563 if (args.move != null) { 14564 // moving a complete application; perform an initial scan on the new install location 14565 scanFlags |= SCAN_INITIAL; 14566 } 14567 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14568 scanFlags |= SCAN_DONT_KILL_APP; 14569 } 14570 14571 // Result object to be returned 14572 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14573 14574 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14575 14576 // Sanity check 14577 if (ephemeral && (forwardLocked || onExternal)) { 14578 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14579 + " external=" + onExternal); 14580 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14581 return; 14582 } 14583 14584 // Retrieve PackageSettings and parse package 14585 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14586 | PackageParser.PARSE_ENFORCE_CODE 14587 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14588 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14589 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14590 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14591 PackageParser pp = new PackageParser(); 14592 pp.setSeparateProcesses(mSeparateProcesses); 14593 pp.setDisplayMetrics(mMetrics); 14594 14595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14596 final PackageParser.Package pkg; 14597 try { 14598 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14599 } catch (PackageParserException e) { 14600 res.setError("Failed parse during installPackageLI", e); 14601 return; 14602 } finally { 14603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14604 } 14605 14606 // If we are installing a clustered package add results for the children 14607 if (pkg.childPackages != null) { 14608 synchronized (mPackages) { 14609 final int childCount = pkg.childPackages.size(); 14610 for (int i = 0; i < childCount; i++) { 14611 PackageParser.Package childPkg = pkg.childPackages.get(i); 14612 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14613 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14614 childRes.pkg = childPkg; 14615 childRes.name = childPkg.packageName; 14616 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14617 if (childPs != null) { 14618 childRes.origUsers = childPs.queryInstalledUsers( 14619 sUserManager.getUserIds(), true); 14620 } 14621 if ((mPackages.containsKey(childPkg.packageName))) { 14622 childRes.removedInfo = new PackageRemovedInfo(); 14623 childRes.removedInfo.removedPackage = childPkg.packageName; 14624 } 14625 if (res.addedChildPackages == null) { 14626 res.addedChildPackages = new ArrayMap<>(); 14627 } 14628 res.addedChildPackages.put(childPkg.packageName, childRes); 14629 } 14630 } 14631 } 14632 14633 // If package doesn't declare API override, mark that we have an install 14634 // time CPU ABI override. 14635 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14636 pkg.cpuAbiOverride = args.abiOverride; 14637 } 14638 14639 String pkgName = res.name = pkg.packageName; 14640 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14641 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14642 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14643 return; 14644 } 14645 } 14646 14647 try { 14648 // either use what we've been given or parse directly from the APK 14649 if (args.certificates != null) { 14650 try { 14651 PackageParser.populateCertificates(pkg, args.certificates); 14652 } catch (PackageParserException e) { 14653 // there was something wrong with the certificates we were given; 14654 // try to pull them from the APK 14655 PackageParser.collectCertificates(pkg, parseFlags); 14656 } 14657 } else { 14658 PackageParser.collectCertificates(pkg, parseFlags); 14659 } 14660 } catch (PackageParserException e) { 14661 res.setError("Failed collect during installPackageLI", e); 14662 return; 14663 } 14664 14665 // Get rid of all references to package scan path via parser. 14666 pp = null; 14667 String oldCodePath = null; 14668 boolean systemApp = false; 14669 synchronized (mPackages) { 14670 // Check if installing already existing package 14671 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14672 String oldName = mSettings.mRenamedPackages.get(pkgName); 14673 if (pkg.mOriginalPackages != null 14674 && pkg.mOriginalPackages.contains(oldName) 14675 && mPackages.containsKey(oldName)) { 14676 // This package is derived from an original package, 14677 // and this device has been updating from that original 14678 // name. We must continue using the original name, so 14679 // rename the new package here. 14680 pkg.setPackageName(oldName); 14681 pkgName = pkg.packageName; 14682 replace = true; 14683 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14684 + oldName + " pkgName=" + pkgName); 14685 } else if (mPackages.containsKey(pkgName)) { 14686 // This package, under its official name, already exists 14687 // on the device; we should replace it. 14688 replace = true; 14689 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14690 } 14691 14692 // Child packages are installed through the parent package 14693 if (pkg.parentPackage != null) { 14694 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14695 "Package " + pkg.packageName + " is child of package " 14696 + pkg.parentPackage.parentPackage + ". Child packages " 14697 + "can be updated only through the parent package."); 14698 return; 14699 } 14700 14701 if (replace) { 14702 // Prevent apps opting out from runtime permissions 14703 PackageParser.Package oldPackage = mPackages.get(pkgName); 14704 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14705 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14706 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14707 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14708 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14709 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14710 + " doesn't support runtime permissions but the old" 14711 + " target SDK " + oldTargetSdk + " does."); 14712 return; 14713 } 14714 14715 // Prevent installing of child packages 14716 if (oldPackage.parentPackage != null) { 14717 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14718 "Package " + pkg.packageName + " is child of package " 14719 + oldPackage.parentPackage + ". Child packages " 14720 + "can be updated only through the parent package."); 14721 return; 14722 } 14723 } 14724 } 14725 14726 PackageSetting ps = mSettings.mPackages.get(pkgName); 14727 if (ps != null) { 14728 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14729 14730 // Quick sanity check that we're signed correctly if updating; 14731 // we'll check this again later when scanning, but we want to 14732 // bail early here before tripping over redefined permissions. 14733 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14734 if (!checkUpgradeKeySetLP(ps, pkg)) { 14735 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14736 + pkg.packageName + " upgrade keys do not match the " 14737 + "previously installed version"); 14738 return; 14739 } 14740 } else { 14741 try { 14742 verifySignaturesLP(ps, pkg); 14743 } catch (PackageManagerException e) { 14744 res.setError(e.error, e.getMessage()); 14745 return; 14746 } 14747 } 14748 14749 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14750 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14751 systemApp = (ps.pkg.applicationInfo.flags & 14752 ApplicationInfo.FLAG_SYSTEM) != 0; 14753 } 14754 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14755 } 14756 14757 // Check whether the newly-scanned package wants to define an already-defined perm 14758 int N = pkg.permissions.size(); 14759 for (int i = N-1; i >= 0; i--) { 14760 PackageParser.Permission perm = pkg.permissions.get(i); 14761 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14762 if (bp != null) { 14763 // If the defining package is signed with our cert, it's okay. This 14764 // also includes the "updating the same package" case, of course. 14765 // "updating same package" could also involve key-rotation. 14766 final boolean sigsOk; 14767 if (bp.sourcePackage.equals(pkg.packageName) 14768 && (bp.packageSetting instanceof PackageSetting) 14769 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14770 scanFlags))) { 14771 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14772 } else { 14773 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14774 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14775 } 14776 if (!sigsOk) { 14777 // If the owning package is the system itself, we log but allow 14778 // install to proceed; we fail the install on all other permission 14779 // redefinitions. 14780 if (!bp.sourcePackage.equals("android")) { 14781 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14782 + pkg.packageName + " attempting to redeclare permission " 14783 + perm.info.name + " already owned by " + bp.sourcePackage); 14784 res.origPermission = perm.info.name; 14785 res.origPackage = bp.sourcePackage; 14786 return; 14787 } else { 14788 Slog.w(TAG, "Package " + pkg.packageName 14789 + " attempting to redeclare system permission " 14790 + perm.info.name + "; ignoring new declaration"); 14791 pkg.permissions.remove(i); 14792 } 14793 } 14794 } 14795 } 14796 } 14797 14798 if (systemApp) { 14799 if (onExternal) { 14800 // Abort update; system app can't be replaced with app on sdcard 14801 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14802 "Cannot install updates to system apps on sdcard"); 14803 return; 14804 } else if (ephemeral) { 14805 // Abort update; system app can't be replaced with an ephemeral app 14806 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14807 "Cannot update a system app with an ephemeral app"); 14808 return; 14809 } 14810 } 14811 14812 if (args.move != null) { 14813 // We did an in-place move, so dex is ready to roll 14814 scanFlags |= SCAN_NO_DEX; 14815 scanFlags |= SCAN_MOVE; 14816 14817 synchronized (mPackages) { 14818 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14819 if (ps == null) { 14820 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14821 "Missing settings for moved package " + pkgName); 14822 } 14823 14824 // We moved the entire application as-is, so bring over the 14825 // previously derived ABI information. 14826 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14827 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14828 } 14829 14830 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14831 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14832 scanFlags |= SCAN_NO_DEX; 14833 14834 try { 14835 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14836 args.abiOverride : pkg.cpuAbiOverride); 14837 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14838 true /* extract libs */); 14839 } catch (PackageManagerException pme) { 14840 Slog.e(TAG, "Error deriving application ABI", pme); 14841 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14842 return; 14843 } 14844 14845 // Shared libraries for the package need to be updated. 14846 synchronized (mPackages) { 14847 try { 14848 updateSharedLibrariesLPw(pkg, null); 14849 } catch (PackageManagerException e) { 14850 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14851 } 14852 } 14853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14854 // Do not run PackageDexOptimizer through the local performDexOpt 14855 // method because `pkg` is not in `mPackages` yet. 14856 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14857 null /* instructionSets */, false /* checkProfiles */, 14858 getCompilerFilterForReason(REASON_INSTALL)); 14859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14860 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14861 String msg = "Extracting package failed for " + pkgName; 14862 res.setError(INSTALL_FAILED_DEXOPT, msg); 14863 return; 14864 } 14865 14866 // Notify BackgroundDexOptService that the package has been changed. 14867 // If this is an update of a package which used to fail to compile, 14868 // BDOS will remove it from its blacklist. 14869 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14870 } 14871 14872 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14873 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14874 return; 14875 } 14876 14877 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14878 14879 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14880 "installPackageLI")) { 14881 if (replace) { 14882 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14883 installerPackageName, res); 14884 } else { 14885 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14886 args.user, installerPackageName, volumeUuid, res); 14887 } 14888 } 14889 synchronized (mPackages) { 14890 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14891 if (ps != null) { 14892 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14893 } 14894 14895 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14896 for (int i = 0; i < childCount; i++) { 14897 PackageParser.Package childPkg = pkg.childPackages.get(i); 14898 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14899 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14900 if (childPs != null) { 14901 childRes.newUsers = childPs.queryInstalledUsers( 14902 sUserManager.getUserIds(), true); 14903 } 14904 } 14905 } 14906 } 14907 14908 private void startIntentFilterVerifications(int userId, boolean replacing, 14909 PackageParser.Package pkg) { 14910 if (mIntentFilterVerifierComponent == null) { 14911 Slog.w(TAG, "No IntentFilter verification will not be done as " 14912 + "there is no IntentFilterVerifier available!"); 14913 return; 14914 } 14915 14916 final int verifierUid = getPackageUid( 14917 mIntentFilterVerifierComponent.getPackageName(), 14918 MATCH_DEBUG_TRIAGED_MISSING, 14919 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14920 14921 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14922 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14923 mHandler.sendMessage(msg); 14924 14925 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14926 for (int i = 0; i < childCount; i++) { 14927 PackageParser.Package childPkg = pkg.childPackages.get(i); 14928 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14929 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14930 mHandler.sendMessage(msg); 14931 } 14932 } 14933 14934 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14935 PackageParser.Package pkg) { 14936 int size = pkg.activities.size(); 14937 if (size == 0) { 14938 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14939 "No activity, so no need to verify any IntentFilter!"); 14940 return; 14941 } 14942 14943 final boolean hasDomainURLs = hasDomainURLs(pkg); 14944 if (!hasDomainURLs) { 14945 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14946 "No domain URLs, so no need to verify any IntentFilter!"); 14947 return; 14948 } 14949 14950 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14951 + " if any IntentFilter from the " + size 14952 + " Activities needs verification ..."); 14953 14954 int count = 0; 14955 final String packageName = pkg.packageName; 14956 14957 synchronized (mPackages) { 14958 // If this is a new install and we see that we've already run verification for this 14959 // package, we have nothing to do: it means the state was restored from backup. 14960 if (!replacing) { 14961 IntentFilterVerificationInfo ivi = 14962 mSettings.getIntentFilterVerificationLPr(packageName); 14963 if (ivi != null) { 14964 if (DEBUG_DOMAIN_VERIFICATION) { 14965 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14966 + ivi.getStatusString()); 14967 } 14968 return; 14969 } 14970 } 14971 14972 // If any filters need to be verified, then all need to be. 14973 boolean needToVerify = false; 14974 for (PackageParser.Activity a : pkg.activities) { 14975 for (ActivityIntentInfo filter : a.intents) { 14976 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14977 if (DEBUG_DOMAIN_VERIFICATION) { 14978 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14979 } 14980 needToVerify = true; 14981 break; 14982 } 14983 } 14984 } 14985 14986 if (needToVerify) { 14987 final int verificationId = mIntentFilterVerificationToken++; 14988 for (PackageParser.Activity a : pkg.activities) { 14989 for (ActivityIntentInfo filter : a.intents) { 14990 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14991 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14992 "Verification needed for IntentFilter:" + filter.toString()); 14993 mIntentFilterVerifier.addOneIntentFilterVerification( 14994 verifierUid, userId, verificationId, filter, packageName); 14995 count++; 14996 } 14997 } 14998 } 14999 } 15000 } 15001 15002 if (count > 0) { 15003 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15004 + " IntentFilter verification" + (count > 1 ? "s" : "") 15005 + " for userId:" + userId); 15006 mIntentFilterVerifier.startVerifications(userId); 15007 } else { 15008 if (DEBUG_DOMAIN_VERIFICATION) { 15009 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15010 } 15011 } 15012 } 15013 15014 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15015 final ComponentName cn = filter.activity.getComponentName(); 15016 final String packageName = cn.getPackageName(); 15017 15018 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15019 packageName); 15020 if (ivi == null) { 15021 return true; 15022 } 15023 int status = ivi.getStatus(); 15024 switch (status) { 15025 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15026 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15027 return true; 15028 15029 default: 15030 // Nothing to do 15031 return false; 15032 } 15033 } 15034 15035 private static boolean isMultiArch(ApplicationInfo info) { 15036 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15037 } 15038 15039 private static boolean isExternal(PackageParser.Package pkg) { 15040 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15041 } 15042 15043 private static boolean isExternal(PackageSetting ps) { 15044 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15045 } 15046 15047 private static boolean isEphemeral(PackageParser.Package pkg) { 15048 return pkg.applicationInfo.isEphemeralApp(); 15049 } 15050 15051 private static boolean isEphemeral(PackageSetting ps) { 15052 return ps.pkg != null && isEphemeral(ps.pkg); 15053 } 15054 15055 private static boolean isSystemApp(PackageParser.Package pkg) { 15056 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15057 } 15058 15059 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15060 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15061 } 15062 15063 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15064 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15065 } 15066 15067 private static boolean isSystemApp(PackageSetting ps) { 15068 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15069 } 15070 15071 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15072 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15073 } 15074 15075 private int packageFlagsToInstallFlags(PackageSetting ps) { 15076 int installFlags = 0; 15077 if (isEphemeral(ps)) { 15078 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15079 } 15080 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15081 // This existing package was an external ASEC install when we have 15082 // the external flag without a UUID 15083 installFlags |= PackageManager.INSTALL_EXTERNAL; 15084 } 15085 if (ps.isForwardLocked()) { 15086 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15087 } 15088 return installFlags; 15089 } 15090 15091 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15092 if (isExternal(pkg)) { 15093 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15094 return StorageManager.UUID_PRIMARY_PHYSICAL; 15095 } else { 15096 return pkg.volumeUuid; 15097 } 15098 } else { 15099 return StorageManager.UUID_PRIVATE_INTERNAL; 15100 } 15101 } 15102 15103 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15104 if (isExternal(pkg)) { 15105 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15106 return mSettings.getExternalVersion(); 15107 } else { 15108 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15109 } 15110 } else { 15111 return mSettings.getInternalVersion(); 15112 } 15113 } 15114 15115 private void deleteTempPackageFiles() { 15116 final FilenameFilter filter = new FilenameFilter() { 15117 public boolean accept(File dir, String name) { 15118 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15119 } 15120 }; 15121 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15122 file.delete(); 15123 } 15124 } 15125 15126 @Override 15127 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15128 int flags) { 15129 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15130 flags); 15131 } 15132 15133 @Override 15134 public void deletePackage(final String packageName, 15135 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15136 mContext.enforceCallingOrSelfPermission( 15137 android.Manifest.permission.DELETE_PACKAGES, null); 15138 Preconditions.checkNotNull(packageName); 15139 Preconditions.checkNotNull(observer); 15140 final int uid = Binder.getCallingUid(); 15141 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15142 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15143 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15144 mContext.enforceCallingOrSelfPermission( 15145 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15146 "deletePackage for user " + userId); 15147 } 15148 15149 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15150 try { 15151 observer.onPackageDeleted(packageName, 15152 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15153 } catch (RemoteException re) { 15154 } 15155 return; 15156 } 15157 15158 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15159 try { 15160 observer.onPackageDeleted(packageName, 15161 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15162 } catch (RemoteException re) { 15163 } 15164 return; 15165 } 15166 15167 if (DEBUG_REMOVE) { 15168 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15169 + " deleteAllUsers: " + deleteAllUsers ); 15170 } 15171 // Queue up an async operation since the package deletion may take a little while. 15172 mHandler.post(new Runnable() { 15173 public void run() { 15174 mHandler.removeCallbacks(this); 15175 int returnCode; 15176 if (!deleteAllUsers) { 15177 returnCode = deletePackageX(packageName, userId, deleteFlags); 15178 } else { 15179 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15180 // If nobody is blocking uninstall, proceed with delete for all users 15181 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15182 returnCode = deletePackageX(packageName, userId, deleteFlags); 15183 } else { 15184 // Otherwise uninstall individually for users with blockUninstalls=false 15185 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15186 for (int userId : users) { 15187 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15188 returnCode = deletePackageX(packageName, userId, userFlags); 15189 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15190 Slog.w(TAG, "Package delete failed for user " + userId 15191 + ", returnCode " + returnCode); 15192 } 15193 } 15194 } 15195 // The app has only been marked uninstalled for certain users. 15196 // We still need to report that delete was blocked 15197 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15198 } 15199 } 15200 try { 15201 observer.onPackageDeleted(packageName, returnCode, null); 15202 } catch (RemoteException e) { 15203 Log.i(TAG, "Observer no longer exists."); 15204 } //end catch 15205 } //end run 15206 }); 15207 } 15208 15209 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15210 int[] result = EMPTY_INT_ARRAY; 15211 for (int userId : userIds) { 15212 if (getBlockUninstallForUser(packageName, userId)) { 15213 result = ArrayUtils.appendInt(result, userId); 15214 } 15215 } 15216 return result; 15217 } 15218 15219 @Override 15220 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15221 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15222 } 15223 15224 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15225 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15226 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15227 try { 15228 if (dpm != null) { 15229 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15230 /* callingUserOnly =*/ false); 15231 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15232 : deviceOwnerComponentName.getPackageName(); 15233 // Does the package contains the device owner? 15234 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15235 // this check is probably not needed, since DO should be registered as a device 15236 // admin on some user too. (Original bug for this: b/17657954) 15237 if (packageName.equals(deviceOwnerPackageName)) { 15238 return true; 15239 } 15240 // Does it contain a device admin for any user? 15241 int[] users; 15242 if (userId == UserHandle.USER_ALL) { 15243 users = sUserManager.getUserIds(); 15244 } else { 15245 users = new int[]{userId}; 15246 } 15247 for (int i = 0; i < users.length; ++i) { 15248 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15249 return true; 15250 } 15251 } 15252 } 15253 } catch (RemoteException e) { 15254 } 15255 return false; 15256 } 15257 15258 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15259 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15260 } 15261 15262 /** 15263 * This method is an internal method that could be get invoked either 15264 * to delete an installed package or to clean up a failed installation. 15265 * After deleting an installed package, a broadcast is sent to notify any 15266 * listeners that the package has been removed. For cleaning up a failed 15267 * installation, the broadcast is not necessary since the package's 15268 * installation wouldn't have sent the initial broadcast either 15269 * The key steps in deleting a package are 15270 * deleting the package information in internal structures like mPackages, 15271 * deleting the packages base directories through installd 15272 * updating mSettings to reflect current status 15273 * persisting settings for later use 15274 * sending a broadcast if necessary 15275 */ 15276 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15277 final PackageRemovedInfo info = new PackageRemovedInfo(); 15278 final boolean res; 15279 15280 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15281 ? UserHandle.ALL : new UserHandle(userId); 15282 15283 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15284 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15285 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15286 } 15287 15288 PackageSetting uninstalledPs = null; 15289 15290 // for the uninstall-updates case and restricted profiles, remember the per- 15291 // user handle installed state 15292 int[] allUsers; 15293 synchronized (mPackages) { 15294 uninstalledPs = mSettings.mPackages.get(packageName); 15295 if (uninstalledPs == null) { 15296 Slog.w(TAG, "Not removing non-existent package " + packageName); 15297 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15298 } 15299 allUsers = sUserManager.getUserIds(); 15300 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15301 } 15302 15303 synchronized (mInstallLock) { 15304 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15305 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15306 "deletePackageX")) { 15307 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15308 deleteFlags | REMOVE_CHATTY, info, true, null); 15309 } 15310 synchronized (mPackages) { 15311 if (res) { 15312 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15313 } 15314 } 15315 } 15316 15317 if (res) { 15318 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15319 info.sendPackageRemovedBroadcasts(killApp); 15320 info.sendSystemPackageUpdatedBroadcasts(); 15321 info.sendSystemPackageAppearedBroadcasts(); 15322 } 15323 // Force a gc here. 15324 Runtime.getRuntime().gc(); 15325 // Delete the resources here after sending the broadcast to let 15326 // other processes clean up before deleting resources. 15327 if (info.args != null) { 15328 synchronized (mInstallLock) { 15329 info.args.doPostDeleteLI(true); 15330 } 15331 } 15332 15333 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15334 } 15335 15336 class PackageRemovedInfo { 15337 String removedPackage; 15338 int uid = -1; 15339 int removedAppId = -1; 15340 int[] origUsers; 15341 int[] removedUsers = null; 15342 boolean isRemovedPackageSystemUpdate = false; 15343 boolean isUpdate; 15344 boolean dataRemoved; 15345 boolean removedForAllUsers; 15346 // Clean up resources deleted packages. 15347 InstallArgs args = null; 15348 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15349 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15350 15351 void sendPackageRemovedBroadcasts(boolean killApp) { 15352 sendPackageRemovedBroadcastInternal(killApp); 15353 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15354 for (int i = 0; i < childCount; i++) { 15355 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15356 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15357 } 15358 } 15359 15360 void sendSystemPackageUpdatedBroadcasts() { 15361 if (isRemovedPackageSystemUpdate) { 15362 sendSystemPackageUpdatedBroadcastsInternal(); 15363 final int childCount = (removedChildPackages != null) 15364 ? removedChildPackages.size() : 0; 15365 for (int i = 0; i < childCount; i++) { 15366 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15367 if (childInfo.isRemovedPackageSystemUpdate) { 15368 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15369 } 15370 } 15371 } 15372 } 15373 15374 void sendSystemPackageAppearedBroadcasts() { 15375 final int packageCount = (appearedChildPackages != null) 15376 ? appearedChildPackages.size() : 0; 15377 for (int i = 0; i < packageCount; i++) { 15378 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15379 for (int userId : installedInfo.newUsers) { 15380 sendPackageAddedForUser(installedInfo.name, true, 15381 UserHandle.getAppId(installedInfo.uid), userId); 15382 } 15383 } 15384 } 15385 15386 private void sendSystemPackageUpdatedBroadcastsInternal() { 15387 Bundle extras = new Bundle(2); 15388 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15389 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15390 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15391 extras, 0, null, null, null); 15392 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15393 extras, 0, null, null, null); 15394 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15395 null, 0, removedPackage, null, null); 15396 } 15397 15398 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15399 Bundle extras = new Bundle(2); 15400 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15401 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15402 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15403 if (isUpdate || isRemovedPackageSystemUpdate) { 15404 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15405 } 15406 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15407 if (removedPackage != null) { 15408 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15409 extras, 0, null, null, removedUsers); 15410 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15411 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15412 removedPackage, extras, 0, null, null, removedUsers); 15413 } 15414 } 15415 if (removedAppId >= 0) { 15416 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15417 removedUsers); 15418 } 15419 } 15420 } 15421 15422 /* 15423 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15424 * flag is not set, the data directory is removed as well. 15425 * make sure this flag is set for partially installed apps. If not its meaningless to 15426 * delete a partially installed application. 15427 */ 15428 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15429 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15430 String packageName = ps.name; 15431 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15432 // Retrieve object to delete permissions for shared user later on 15433 final PackageParser.Package deletedPkg; 15434 final PackageSetting deletedPs; 15435 // reader 15436 synchronized (mPackages) { 15437 deletedPkg = mPackages.get(packageName); 15438 deletedPs = mSettings.mPackages.get(packageName); 15439 if (outInfo != null) { 15440 outInfo.removedPackage = packageName; 15441 outInfo.removedUsers = deletedPs != null 15442 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15443 : null; 15444 } 15445 } 15446 15447 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15448 15449 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15450 final PackageParser.Package resolvedPkg; 15451 if (deletedPkg != null) { 15452 resolvedPkg = deletedPkg; 15453 } else { 15454 // We don't have a parsed package when it lives on an ejected 15455 // adopted storage device, so fake something together 15456 resolvedPkg = new PackageParser.Package(ps.name); 15457 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15458 } 15459 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15460 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15461 destroyAppProfilesLIF(resolvedPkg); 15462 if (outInfo != null) { 15463 outInfo.dataRemoved = true; 15464 } 15465 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15466 } 15467 15468 // writer 15469 synchronized (mPackages) { 15470 if (deletedPs != null) { 15471 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15472 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15473 clearDefaultBrowserIfNeeded(packageName); 15474 if (outInfo != null) { 15475 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15476 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15477 } 15478 updatePermissionsLPw(deletedPs.name, null, 0); 15479 if (deletedPs.sharedUser != null) { 15480 // Remove permissions associated with package. Since runtime 15481 // permissions are per user we have to kill the removed package 15482 // or packages running under the shared user of the removed 15483 // package if revoking the permissions requested only by the removed 15484 // package is successful and this causes a change in gids. 15485 for (int userId : UserManagerService.getInstance().getUserIds()) { 15486 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15487 userId); 15488 if (userIdToKill == UserHandle.USER_ALL 15489 || userIdToKill >= UserHandle.USER_SYSTEM) { 15490 // If gids changed for this user, kill all affected packages. 15491 mHandler.post(new Runnable() { 15492 @Override 15493 public void run() { 15494 // This has to happen with no lock held. 15495 killApplication(deletedPs.name, deletedPs.appId, 15496 KILL_APP_REASON_GIDS_CHANGED); 15497 } 15498 }); 15499 break; 15500 } 15501 } 15502 } 15503 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15504 } 15505 // make sure to preserve per-user disabled state if this removal was just 15506 // a downgrade of a system app to the factory package 15507 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15508 if (DEBUG_REMOVE) { 15509 Slog.d(TAG, "Propagating install state across downgrade"); 15510 } 15511 for (int userId : allUserHandles) { 15512 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15513 if (DEBUG_REMOVE) { 15514 Slog.d(TAG, " user " + userId + " => " + installed); 15515 } 15516 ps.setInstalled(installed, userId); 15517 } 15518 } 15519 } 15520 // can downgrade to reader 15521 if (writeSettings) { 15522 // Save settings now 15523 mSettings.writeLPr(); 15524 } 15525 } 15526 if (outInfo != null) { 15527 // A user ID was deleted here. Go through all users and remove it 15528 // from KeyStore. 15529 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15530 } 15531 } 15532 15533 static boolean locationIsPrivileged(File path) { 15534 try { 15535 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15536 .getCanonicalPath(); 15537 return path.getCanonicalPath().startsWith(privilegedAppDir); 15538 } catch (IOException e) { 15539 Slog.e(TAG, "Unable to access code path " + path); 15540 } 15541 return false; 15542 } 15543 15544 /* 15545 * Tries to delete system package. 15546 */ 15547 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15548 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15549 boolean writeSettings) { 15550 if (deletedPs.parentPackageName != null) { 15551 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15552 return false; 15553 } 15554 15555 final boolean applyUserRestrictions 15556 = (allUserHandles != null) && (outInfo.origUsers != null); 15557 final PackageSetting disabledPs; 15558 // Confirm if the system package has been updated 15559 // An updated system app can be deleted. This will also have to restore 15560 // the system pkg from system partition 15561 // reader 15562 synchronized (mPackages) { 15563 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15564 } 15565 15566 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15567 + " disabledPs=" + disabledPs); 15568 15569 if (disabledPs == null) { 15570 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15571 return false; 15572 } else if (DEBUG_REMOVE) { 15573 Slog.d(TAG, "Deleting system pkg from data partition"); 15574 } 15575 15576 if (DEBUG_REMOVE) { 15577 if (applyUserRestrictions) { 15578 Slog.d(TAG, "Remembering install states:"); 15579 for (int userId : allUserHandles) { 15580 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15581 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15582 } 15583 } 15584 } 15585 15586 // Delete the updated package 15587 outInfo.isRemovedPackageSystemUpdate = true; 15588 if (outInfo.removedChildPackages != null) { 15589 final int childCount = (deletedPs.childPackageNames != null) 15590 ? deletedPs.childPackageNames.size() : 0; 15591 for (int i = 0; i < childCount; i++) { 15592 String childPackageName = deletedPs.childPackageNames.get(i); 15593 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15594 .contains(childPackageName)) { 15595 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15596 childPackageName); 15597 if (childInfo != null) { 15598 childInfo.isRemovedPackageSystemUpdate = true; 15599 } 15600 } 15601 } 15602 } 15603 15604 if (disabledPs.versionCode < deletedPs.versionCode) { 15605 // Delete data for downgrades 15606 flags &= ~PackageManager.DELETE_KEEP_DATA; 15607 } else { 15608 // Preserve data by setting flag 15609 flags |= PackageManager.DELETE_KEEP_DATA; 15610 } 15611 15612 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15613 outInfo, writeSettings, disabledPs.pkg); 15614 if (!ret) { 15615 return false; 15616 } 15617 15618 // writer 15619 synchronized (mPackages) { 15620 // Reinstate the old system package 15621 enableSystemPackageLPw(disabledPs.pkg); 15622 // Remove any native libraries from the upgraded package. 15623 removeNativeBinariesLI(deletedPs); 15624 } 15625 15626 // Install the system package 15627 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15628 int parseFlags = mDefParseFlags 15629 | PackageParser.PARSE_MUST_BE_APK 15630 | PackageParser.PARSE_IS_SYSTEM 15631 | PackageParser.PARSE_IS_SYSTEM_DIR; 15632 if (locationIsPrivileged(disabledPs.codePath)) { 15633 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15634 } 15635 15636 final PackageParser.Package newPkg; 15637 try { 15638 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15639 } catch (PackageManagerException e) { 15640 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15641 + e.getMessage()); 15642 return false; 15643 } 15644 15645 prepareAppDataAfterInstallLIF(newPkg); 15646 15647 // writer 15648 synchronized (mPackages) { 15649 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15650 15651 // Propagate the permissions state as we do not want to drop on the floor 15652 // runtime permissions. The update permissions method below will take 15653 // care of removing obsolete permissions and grant install permissions. 15654 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15655 updatePermissionsLPw(newPkg.packageName, newPkg, 15656 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15657 15658 if (applyUserRestrictions) { 15659 if (DEBUG_REMOVE) { 15660 Slog.d(TAG, "Propagating install state across reinstall"); 15661 } 15662 for (int userId : allUserHandles) { 15663 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15664 if (DEBUG_REMOVE) { 15665 Slog.d(TAG, " user " + userId + " => " + installed); 15666 } 15667 ps.setInstalled(installed, userId); 15668 15669 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15670 } 15671 // Regardless of writeSettings we need to ensure that this restriction 15672 // state propagation is persisted 15673 mSettings.writeAllUsersPackageRestrictionsLPr(); 15674 } 15675 // can downgrade to reader here 15676 if (writeSettings) { 15677 mSettings.writeLPr(); 15678 } 15679 } 15680 return true; 15681 } 15682 15683 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15684 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15685 PackageRemovedInfo outInfo, boolean writeSettings, 15686 PackageParser.Package replacingPackage) { 15687 synchronized (mPackages) { 15688 if (outInfo != null) { 15689 outInfo.uid = ps.appId; 15690 } 15691 15692 if (outInfo != null && outInfo.removedChildPackages != null) { 15693 final int childCount = (ps.childPackageNames != null) 15694 ? ps.childPackageNames.size() : 0; 15695 for (int i = 0; i < childCount; i++) { 15696 String childPackageName = ps.childPackageNames.get(i); 15697 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15698 if (childPs == null) { 15699 return false; 15700 } 15701 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15702 childPackageName); 15703 if (childInfo != null) { 15704 childInfo.uid = childPs.appId; 15705 } 15706 } 15707 } 15708 } 15709 15710 // Delete package data from internal structures and also remove data if flag is set 15711 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15712 15713 // Delete the child packages data 15714 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15715 for (int i = 0; i < childCount; i++) { 15716 PackageSetting childPs; 15717 synchronized (mPackages) { 15718 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15719 } 15720 if (childPs != null) { 15721 PackageRemovedInfo childOutInfo = (outInfo != null 15722 && outInfo.removedChildPackages != null) 15723 ? outInfo.removedChildPackages.get(childPs.name) : null; 15724 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15725 && (replacingPackage != null 15726 && !replacingPackage.hasChildPackage(childPs.name)) 15727 ? flags & ~DELETE_KEEP_DATA : flags; 15728 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15729 deleteFlags, writeSettings); 15730 } 15731 } 15732 15733 // Delete application code and resources only for parent packages 15734 if (ps.parentPackageName == null) { 15735 if (deleteCodeAndResources && (outInfo != null)) { 15736 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15737 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15738 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15739 } 15740 } 15741 15742 return true; 15743 } 15744 15745 @Override 15746 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15747 int userId) { 15748 mContext.enforceCallingOrSelfPermission( 15749 android.Manifest.permission.DELETE_PACKAGES, null); 15750 synchronized (mPackages) { 15751 PackageSetting ps = mSettings.mPackages.get(packageName); 15752 if (ps == null) { 15753 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15754 return false; 15755 } 15756 if (!ps.getInstalled(userId)) { 15757 // Can't block uninstall for an app that is not installed or enabled. 15758 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15759 return false; 15760 } 15761 ps.setBlockUninstall(blockUninstall, userId); 15762 mSettings.writePackageRestrictionsLPr(userId); 15763 } 15764 return true; 15765 } 15766 15767 @Override 15768 public boolean getBlockUninstallForUser(String packageName, int userId) { 15769 synchronized (mPackages) { 15770 PackageSetting ps = mSettings.mPackages.get(packageName); 15771 if (ps == null) { 15772 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15773 return false; 15774 } 15775 return ps.getBlockUninstall(userId); 15776 } 15777 } 15778 15779 @Override 15780 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15781 int callingUid = Binder.getCallingUid(); 15782 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15783 throw new SecurityException( 15784 "setRequiredForSystemUser can only be run by the system or root"); 15785 } 15786 synchronized (mPackages) { 15787 PackageSetting ps = mSettings.mPackages.get(packageName); 15788 if (ps == null) { 15789 Log.w(TAG, "Package doesn't exist: " + packageName); 15790 return false; 15791 } 15792 if (systemUserApp) { 15793 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15794 } else { 15795 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15796 } 15797 mSettings.writeLPr(); 15798 } 15799 return true; 15800 } 15801 15802 /* 15803 * This method handles package deletion in general 15804 */ 15805 private boolean deletePackageLIF(String packageName, UserHandle user, 15806 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15807 PackageRemovedInfo outInfo, boolean writeSettings, 15808 PackageParser.Package replacingPackage) { 15809 if (packageName == null) { 15810 Slog.w(TAG, "Attempt to delete null packageName."); 15811 return false; 15812 } 15813 15814 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15815 15816 PackageSetting ps; 15817 15818 synchronized (mPackages) { 15819 ps = mSettings.mPackages.get(packageName); 15820 if (ps == null) { 15821 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15822 return false; 15823 } 15824 15825 if (ps.parentPackageName != null && (!isSystemApp(ps) 15826 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15827 if (DEBUG_REMOVE) { 15828 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15829 + ((user == null) ? UserHandle.USER_ALL : user)); 15830 } 15831 final int removedUserId = (user != null) ? user.getIdentifier() 15832 : UserHandle.USER_ALL; 15833 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15834 return false; 15835 } 15836 markPackageUninstalledForUserLPw(ps, user); 15837 scheduleWritePackageRestrictionsLocked(user); 15838 return true; 15839 } 15840 } 15841 15842 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15843 && user.getIdentifier() != UserHandle.USER_ALL)) { 15844 // The caller is asking that the package only be deleted for a single 15845 // user. To do this, we just mark its uninstalled state and delete 15846 // its data. If this is a system app, we only allow this to happen if 15847 // they have set the special DELETE_SYSTEM_APP which requests different 15848 // semantics than normal for uninstalling system apps. 15849 markPackageUninstalledForUserLPw(ps, user); 15850 15851 if (!isSystemApp(ps)) { 15852 // Do not uninstall the APK if an app should be cached 15853 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15854 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15855 // Other user still have this package installed, so all 15856 // we need to do is clear this user's data and save that 15857 // it is uninstalled. 15858 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15859 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15860 return false; 15861 } 15862 scheduleWritePackageRestrictionsLocked(user); 15863 return true; 15864 } else { 15865 // We need to set it back to 'installed' so the uninstall 15866 // broadcasts will be sent correctly. 15867 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15868 ps.setInstalled(true, user.getIdentifier()); 15869 } 15870 } else { 15871 // This is a system app, so we assume that the 15872 // other users still have this package installed, so all 15873 // we need to do is clear this user's data and save that 15874 // it is uninstalled. 15875 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15876 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15877 return false; 15878 } 15879 scheduleWritePackageRestrictionsLocked(user); 15880 return true; 15881 } 15882 } 15883 15884 // If we are deleting a composite package for all users, keep track 15885 // of result for each child. 15886 if (ps.childPackageNames != null && outInfo != null) { 15887 synchronized (mPackages) { 15888 final int childCount = ps.childPackageNames.size(); 15889 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15890 for (int i = 0; i < childCount; i++) { 15891 String childPackageName = ps.childPackageNames.get(i); 15892 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15893 childInfo.removedPackage = childPackageName; 15894 outInfo.removedChildPackages.put(childPackageName, childInfo); 15895 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15896 if (childPs != null) { 15897 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15898 } 15899 } 15900 } 15901 } 15902 15903 boolean ret = false; 15904 if (isSystemApp(ps)) { 15905 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15906 // When an updated system application is deleted we delete the existing resources 15907 // as well and fall back to existing code in system partition 15908 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15909 } else { 15910 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15911 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15912 outInfo, writeSettings, replacingPackage); 15913 } 15914 15915 // Take a note whether we deleted the package for all users 15916 if (outInfo != null) { 15917 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15918 if (outInfo.removedChildPackages != null) { 15919 synchronized (mPackages) { 15920 final int childCount = outInfo.removedChildPackages.size(); 15921 for (int i = 0; i < childCount; i++) { 15922 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15923 if (childInfo != null) { 15924 childInfo.removedForAllUsers = mPackages.get( 15925 childInfo.removedPackage) == null; 15926 } 15927 } 15928 } 15929 } 15930 // If we uninstalled an update to a system app there may be some 15931 // child packages that appeared as they are declared in the system 15932 // app but were not declared in the update. 15933 if (isSystemApp(ps)) { 15934 synchronized (mPackages) { 15935 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15936 final int childCount = (updatedPs.childPackageNames != null) 15937 ? updatedPs.childPackageNames.size() : 0; 15938 for (int i = 0; i < childCount; i++) { 15939 String childPackageName = updatedPs.childPackageNames.get(i); 15940 if (outInfo.removedChildPackages == null 15941 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15942 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15943 if (childPs == null) { 15944 continue; 15945 } 15946 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15947 installRes.name = childPackageName; 15948 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15949 installRes.pkg = mPackages.get(childPackageName); 15950 installRes.uid = childPs.pkg.applicationInfo.uid; 15951 if (outInfo.appearedChildPackages == null) { 15952 outInfo.appearedChildPackages = new ArrayMap<>(); 15953 } 15954 outInfo.appearedChildPackages.put(childPackageName, installRes); 15955 } 15956 } 15957 } 15958 } 15959 } 15960 15961 return ret; 15962 } 15963 15964 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15965 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15966 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15967 for (int nextUserId : userIds) { 15968 if (DEBUG_REMOVE) { 15969 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15970 } 15971 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15972 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15973 false /*hidden*/, false /*suspended*/, null, null, null, 15974 false /*blockUninstall*/, 15975 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15976 } 15977 } 15978 15979 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15980 PackageRemovedInfo outInfo) { 15981 final PackageParser.Package pkg; 15982 synchronized (mPackages) { 15983 pkg = mPackages.get(ps.name); 15984 } 15985 15986 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15987 : new int[] {userId}; 15988 for (int nextUserId : userIds) { 15989 if (DEBUG_REMOVE) { 15990 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15991 + nextUserId); 15992 } 15993 15994 destroyAppDataLIF(pkg, userId, 15995 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15996 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15997 schedulePackageCleaning(ps.name, nextUserId, false); 15998 synchronized (mPackages) { 15999 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16000 scheduleWritePackageRestrictionsLocked(nextUserId); 16001 } 16002 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16003 } 16004 } 16005 16006 if (outInfo != null) { 16007 outInfo.removedPackage = ps.name; 16008 outInfo.removedAppId = ps.appId; 16009 outInfo.removedUsers = userIds; 16010 } 16011 16012 return true; 16013 } 16014 16015 private final class ClearStorageConnection implements ServiceConnection { 16016 IMediaContainerService mContainerService; 16017 16018 @Override 16019 public void onServiceConnected(ComponentName name, IBinder service) { 16020 synchronized (this) { 16021 mContainerService = IMediaContainerService.Stub.asInterface(service); 16022 notifyAll(); 16023 } 16024 } 16025 16026 @Override 16027 public void onServiceDisconnected(ComponentName name) { 16028 } 16029 } 16030 16031 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16032 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16033 16034 final boolean mounted; 16035 if (Environment.isExternalStorageEmulated()) { 16036 mounted = true; 16037 } else { 16038 final String status = Environment.getExternalStorageState(); 16039 16040 mounted = status.equals(Environment.MEDIA_MOUNTED) 16041 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16042 } 16043 16044 if (!mounted) { 16045 return; 16046 } 16047 16048 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16049 int[] users; 16050 if (userId == UserHandle.USER_ALL) { 16051 users = sUserManager.getUserIds(); 16052 } else { 16053 users = new int[] { userId }; 16054 } 16055 final ClearStorageConnection conn = new ClearStorageConnection(); 16056 if (mContext.bindServiceAsUser( 16057 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16058 try { 16059 for (int curUser : users) { 16060 long timeout = SystemClock.uptimeMillis() + 5000; 16061 synchronized (conn) { 16062 long now = SystemClock.uptimeMillis(); 16063 while (conn.mContainerService == null && now < timeout) { 16064 try { 16065 conn.wait(timeout - now); 16066 } catch (InterruptedException e) { 16067 } 16068 } 16069 } 16070 if (conn.mContainerService == null) { 16071 return; 16072 } 16073 16074 final UserEnvironment userEnv = new UserEnvironment(curUser); 16075 clearDirectory(conn.mContainerService, 16076 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16077 if (allData) { 16078 clearDirectory(conn.mContainerService, 16079 userEnv.buildExternalStorageAppDataDirs(packageName)); 16080 clearDirectory(conn.mContainerService, 16081 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16082 } 16083 } 16084 } finally { 16085 mContext.unbindService(conn); 16086 } 16087 } 16088 } 16089 16090 @Override 16091 public void clearApplicationProfileData(String packageName) { 16092 enforceSystemOrRoot("Only the system can clear all profile data"); 16093 16094 final PackageParser.Package pkg; 16095 synchronized (mPackages) { 16096 pkg = mPackages.get(packageName); 16097 } 16098 16099 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16100 synchronized (mInstallLock) { 16101 clearAppProfilesLIF(pkg); 16102 } 16103 } 16104 } 16105 16106 @Override 16107 public void clearApplicationUserData(final String packageName, 16108 final IPackageDataObserver observer, final int userId) { 16109 mContext.enforceCallingOrSelfPermission( 16110 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16111 16112 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16113 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16114 16115 final DevicePolicyManagerInternal dpmi = LocalServices 16116 .getService(DevicePolicyManagerInternal.class); 16117 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16118 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16119 } 16120 // Queue up an async operation since the package deletion may take a little while. 16121 mHandler.post(new Runnable() { 16122 public void run() { 16123 mHandler.removeCallbacks(this); 16124 final boolean succeeded; 16125 try (PackageFreezer freezer = freezePackage(packageName, 16126 "clearApplicationUserData")) { 16127 synchronized (mInstallLock) { 16128 succeeded = clearApplicationUserDataLIF(packageName, userId); 16129 } 16130 clearExternalStorageDataSync(packageName, userId, true); 16131 } 16132 if (succeeded) { 16133 // invoke DeviceStorageMonitor's update method to clear any notifications 16134 DeviceStorageMonitorInternal dsm = LocalServices 16135 .getService(DeviceStorageMonitorInternal.class); 16136 if (dsm != null) { 16137 dsm.checkMemory(); 16138 } 16139 } 16140 if(observer != null) { 16141 try { 16142 observer.onRemoveCompleted(packageName, succeeded); 16143 } catch (RemoteException e) { 16144 Log.i(TAG, "Observer no longer exists."); 16145 } 16146 } //end if observer 16147 } //end run 16148 }); 16149 } 16150 16151 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16152 if (packageName == null) { 16153 Slog.w(TAG, "Attempt to delete null packageName."); 16154 return false; 16155 } 16156 16157 // Try finding details about the requested package 16158 PackageParser.Package pkg; 16159 synchronized (mPackages) { 16160 pkg = mPackages.get(packageName); 16161 if (pkg == null) { 16162 final PackageSetting ps = mSettings.mPackages.get(packageName); 16163 if (ps != null) { 16164 pkg = ps.pkg; 16165 } 16166 } 16167 16168 if (pkg == null) { 16169 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16170 return false; 16171 } 16172 16173 PackageSetting ps = (PackageSetting) pkg.mExtras; 16174 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16175 } 16176 16177 clearAppDataLIF(pkg, userId, 16178 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16179 16180 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16181 removeKeystoreDataIfNeeded(userId, appId); 16182 16183 final UserManager um = mContext.getSystemService(UserManager.class); 16184 final int flags; 16185 if (um.isUserUnlockingOrUnlocked(userId)) { 16186 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16187 } else if (um.isUserRunning(userId)) { 16188 flags = StorageManager.FLAG_STORAGE_DE; 16189 } else { 16190 flags = 0; 16191 } 16192 prepareAppDataContentsLIF(pkg, userId, flags); 16193 16194 return true; 16195 } 16196 16197 /** 16198 * Reverts user permission state changes (permissions and flags) in 16199 * all packages for a given user. 16200 * 16201 * @param userId The device user for which to do a reset. 16202 */ 16203 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16204 final int packageCount = mPackages.size(); 16205 for (int i = 0; i < packageCount; i++) { 16206 PackageParser.Package pkg = mPackages.valueAt(i); 16207 PackageSetting ps = (PackageSetting) pkg.mExtras; 16208 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16209 } 16210 } 16211 16212 private void resetNetworkPolicies(int userId) { 16213 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16214 } 16215 16216 /** 16217 * Reverts user permission state changes (permissions and flags). 16218 * 16219 * @param ps The package for which to reset. 16220 * @param userId The device user for which to do a reset. 16221 */ 16222 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16223 final PackageSetting ps, final int userId) { 16224 if (ps.pkg == null) { 16225 return; 16226 } 16227 16228 // These are flags that can change base on user actions. 16229 final int userSettableMask = FLAG_PERMISSION_USER_SET 16230 | FLAG_PERMISSION_USER_FIXED 16231 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16232 | FLAG_PERMISSION_REVIEW_REQUIRED; 16233 16234 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16235 | FLAG_PERMISSION_POLICY_FIXED; 16236 16237 boolean writeInstallPermissions = false; 16238 boolean writeRuntimePermissions = false; 16239 16240 final int permissionCount = ps.pkg.requestedPermissions.size(); 16241 for (int i = 0; i < permissionCount; i++) { 16242 String permission = ps.pkg.requestedPermissions.get(i); 16243 16244 BasePermission bp = mSettings.mPermissions.get(permission); 16245 if (bp == null) { 16246 continue; 16247 } 16248 16249 // If shared user we just reset the state to which only this app contributed. 16250 if (ps.sharedUser != null) { 16251 boolean used = false; 16252 final int packageCount = ps.sharedUser.packages.size(); 16253 for (int j = 0; j < packageCount; j++) { 16254 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16255 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16256 && pkg.pkg.requestedPermissions.contains(permission)) { 16257 used = true; 16258 break; 16259 } 16260 } 16261 if (used) { 16262 continue; 16263 } 16264 } 16265 16266 PermissionsState permissionsState = ps.getPermissionsState(); 16267 16268 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16269 16270 // Always clear the user settable flags. 16271 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16272 bp.name) != null; 16273 // If permission review is enabled and this is a legacy app, mark the 16274 // permission as requiring a review as this is the initial state. 16275 int flags = 0; 16276 if (Build.PERMISSIONS_REVIEW_REQUIRED 16277 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16278 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16279 } 16280 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16281 if (hasInstallState) { 16282 writeInstallPermissions = true; 16283 } else { 16284 writeRuntimePermissions = true; 16285 } 16286 } 16287 16288 // Below is only runtime permission handling. 16289 if (!bp.isRuntime()) { 16290 continue; 16291 } 16292 16293 // Never clobber system or policy. 16294 if ((oldFlags & policyOrSystemFlags) != 0) { 16295 continue; 16296 } 16297 16298 // If this permission was granted by default, make sure it is. 16299 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16300 if (permissionsState.grantRuntimePermission(bp, userId) 16301 != PERMISSION_OPERATION_FAILURE) { 16302 writeRuntimePermissions = true; 16303 } 16304 // If permission review is enabled the permissions for a legacy apps 16305 // are represented as constantly granted runtime ones, so don't revoke. 16306 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16307 // Otherwise, reset the permission. 16308 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16309 switch (revokeResult) { 16310 case PERMISSION_OPERATION_SUCCESS: 16311 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16312 writeRuntimePermissions = true; 16313 final int appId = ps.appId; 16314 mHandler.post(new Runnable() { 16315 @Override 16316 public void run() { 16317 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16318 } 16319 }); 16320 } break; 16321 } 16322 } 16323 } 16324 16325 // Synchronously write as we are taking permissions away. 16326 if (writeRuntimePermissions) { 16327 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16328 } 16329 16330 // Synchronously write as we are taking permissions away. 16331 if (writeInstallPermissions) { 16332 mSettings.writeLPr(); 16333 } 16334 } 16335 16336 /** 16337 * Remove entries from the keystore daemon. Will only remove it if the 16338 * {@code appId} is valid. 16339 */ 16340 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16341 if (appId < 0) { 16342 return; 16343 } 16344 16345 final KeyStore keyStore = KeyStore.getInstance(); 16346 if (keyStore != null) { 16347 if (userId == UserHandle.USER_ALL) { 16348 for (final int individual : sUserManager.getUserIds()) { 16349 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16350 } 16351 } else { 16352 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16353 } 16354 } else { 16355 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16356 } 16357 } 16358 16359 @Override 16360 public void deleteApplicationCacheFiles(final String packageName, 16361 final IPackageDataObserver observer) { 16362 final int userId = UserHandle.getCallingUserId(); 16363 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16364 } 16365 16366 @Override 16367 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16368 final IPackageDataObserver observer) { 16369 mContext.enforceCallingOrSelfPermission( 16370 android.Manifest.permission.DELETE_CACHE_FILES, null); 16371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16372 /* requireFullPermission= */ true, /* checkShell= */ false, 16373 "delete application cache files"); 16374 16375 final PackageParser.Package pkg; 16376 synchronized (mPackages) { 16377 pkg = mPackages.get(packageName); 16378 } 16379 16380 // Queue up an async operation since the package deletion may take a little while. 16381 mHandler.post(new Runnable() { 16382 public void run() { 16383 synchronized (mInstallLock) { 16384 final int flags = StorageManager.FLAG_STORAGE_DE 16385 | StorageManager.FLAG_STORAGE_CE; 16386 // We're only clearing cache files, so we don't care if the 16387 // app is unfrozen and still able to run 16388 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16389 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16390 } 16391 clearExternalStorageDataSync(packageName, userId, false); 16392 if (observer != null) { 16393 try { 16394 observer.onRemoveCompleted(packageName, true); 16395 } catch (RemoteException e) { 16396 Log.i(TAG, "Observer no longer exists."); 16397 } 16398 } 16399 } 16400 }); 16401 } 16402 16403 @Override 16404 public void getPackageSizeInfo(final String packageName, int userHandle, 16405 final IPackageStatsObserver observer) { 16406 mContext.enforceCallingOrSelfPermission( 16407 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16408 if (packageName == null) { 16409 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16410 } 16411 16412 PackageStats stats = new PackageStats(packageName, userHandle); 16413 16414 /* 16415 * Queue up an async operation since the package measurement may take a 16416 * little while. 16417 */ 16418 Message msg = mHandler.obtainMessage(INIT_COPY); 16419 msg.obj = new MeasureParams(stats, observer); 16420 mHandler.sendMessage(msg); 16421 } 16422 16423 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16424 final PackageSetting ps; 16425 synchronized (mPackages) { 16426 ps = mSettings.mPackages.get(packageName); 16427 if (ps == null) { 16428 Slog.w(TAG, "Failed to find settings for " + packageName); 16429 return false; 16430 } 16431 } 16432 try { 16433 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16434 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16435 ps.getCeDataInode(userId), ps.codePathString, stats); 16436 } catch (InstallerException e) { 16437 Slog.w(TAG, String.valueOf(e)); 16438 return false; 16439 } 16440 16441 // For now, ignore code size of packages on system partition 16442 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16443 stats.codeSize = 0; 16444 } 16445 16446 return true; 16447 } 16448 16449 private int getUidTargetSdkVersionLockedLPr(int uid) { 16450 Object obj = mSettings.getUserIdLPr(uid); 16451 if (obj instanceof SharedUserSetting) { 16452 final SharedUserSetting sus = (SharedUserSetting) obj; 16453 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16454 final Iterator<PackageSetting> it = sus.packages.iterator(); 16455 while (it.hasNext()) { 16456 final PackageSetting ps = it.next(); 16457 if (ps.pkg != null) { 16458 int v = ps.pkg.applicationInfo.targetSdkVersion; 16459 if (v < vers) vers = v; 16460 } 16461 } 16462 return vers; 16463 } else if (obj instanceof PackageSetting) { 16464 final PackageSetting ps = (PackageSetting) obj; 16465 if (ps.pkg != null) { 16466 return ps.pkg.applicationInfo.targetSdkVersion; 16467 } 16468 } 16469 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16470 } 16471 16472 @Override 16473 public void addPreferredActivity(IntentFilter filter, int match, 16474 ComponentName[] set, ComponentName activity, int userId) { 16475 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16476 "Adding preferred"); 16477 } 16478 16479 private void addPreferredActivityInternal(IntentFilter filter, int match, 16480 ComponentName[] set, ComponentName activity, boolean always, int userId, 16481 String opname) { 16482 // writer 16483 int callingUid = Binder.getCallingUid(); 16484 enforceCrossUserPermission(callingUid, userId, 16485 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16486 if (filter.countActions() == 0) { 16487 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16488 return; 16489 } 16490 synchronized (mPackages) { 16491 if (mContext.checkCallingOrSelfPermission( 16492 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16493 != PackageManager.PERMISSION_GRANTED) { 16494 if (getUidTargetSdkVersionLockedLPr(callingUid) 16495 < Build.VERSION_CODES.FROYO) { 16496 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16497 + callingUid); 16498 return; 16499 } 16500 mContext.enforceCallingOrSelfPermission( 16501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16502 } 16503 16504 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16505 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16506 + userId + ":"); 16507 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16508 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16509 scheduleWritePackageRestrictionsLocked(userId); 16510 } 16511 } 16512 16513 @Override 16514 public void replacePreferredActivity(IntentFilter filter, int match, 16515 ComponentName[] set, ComponentName activity, int userId) { 16516 if (filter.countActions() != 1) { 16517 throw new IllegalArgumentException( 16518 "replacePreferredActivity expects filter to have only 1 action."); 16519 } 16520 if (filter.countDataAuthorities() != 0 16521 || filter.countDataPaths() != 0 16522 || filter.countDataSchemes() > 1 16523 || filter.countDataTypes() != 0) { 16524 throw new IllegalArgumentException( 16525 "replacePreferredActivity expects filter to have no data authorities, " + 16526 "paths, or types; and at most one scheme."); 16527 } 16528 16529 final int callingUid = Binder.getCallingUid(); 16530 enforceCrossUserPermission(callingUid, userId, 16531 true /* requireFullPermission */, false /* checkShell */, 16532 "replace preferred activity"); 16533 synchronized (mPackages) { 16534 if (mContext.checkCallingOrSelfPermission( 16535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16536 != PackageManager.PERMISSION_GRANTED) { 16537 if (getUidTargetSdkVersionLockedLPr(callingUid) 16538 < Build.VERSION_CODES.FROYO) { 16539 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16540 + Binder.getCallingUid()); 16541 return; 16542 } 16543 mContext.enforceCallingOrSelfPermission( 16544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16545 } 16546 16547 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16548 if (pir != null) { 16549 // Get all of the existing entries that exactly match this filter. 16550 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16551 if (existing != null && existing.size() == 1) { 16552 PreferredActivity cur = existing.get(0); 16553 if (DEBUG_PREFERRED) { 16554 Slog.i(TAG, "Checking replace of preferred:"); 16555 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16556 if (!cur.mPref.mAlways) { 16557 Slog.i(TAG, " -- CUR; not mAlways!"); 16558 } else { 16559 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16560 Slog.i(TAG, " -- CUR: mSet=" 16561 + Arrays.toString(cur.mPref.mSetComponents)); 16562 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16563 Slog.i(TAG, " -- NEW: mMatch=" 16564 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16565 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16566 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16567 } 16568 } 16569 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16570 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16571 && cur.mPref.sameSet(set)) { 16572 // Setting the preferred activity to what it happens to be already 16573 if (DEBUG_PREFERRED) { 16574 Slog.i(TAG, "Replacing with same preferred activity " 16575 + cur.mPref.mShortComponent + " for user " 16576 + userId + ":"); 16577 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16578 } 16579 return; 16580 } 16581 } 16582 16583 if (existing != null) { 16584 if (DEBUG_PREFERRED) { 16585 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16587 } 16588 for (int i = 0; i < existing.size(); i++) { 16589 PreferredActivity pa = existing.get(i); 16590 if (DEBUG_PREFERRED) { 16591 Slog.i(TAG, "Removing existing preferred activity " 16592 + pa.mPref.mComponent + ":"); 16593 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16594 } 16595 pir.removeFilter(pa); 16596 } 16597 } 16598 } 16599 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16600 "Replacing preferred"); 16601 } 16602 } 16603 16604 @Override 16605 public void clearPackagePreferredActivities(String packageName) { 16606 final int uid = Binder.getCallingUid(); 16607 // writer 16608 synchronized (mPackages) { 16609 PackageParser.Package pkg = mPackages.get(packageName); 16610 if (pkg == null || pkg.applicationInfo.uid != uid) { 16611 if (mContext.checkCallingOrSelfPermission( 16612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16613 != PackageManager.PERMISSION_GRANTED) { 16614 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16615 < Build.VERSION_CODES.FROYO) { 16616 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16617 + Binder.getCallingUid()); 16618 return; 16619 } 16620 mContext.enforceCallingOrSelfPermission( 16621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16622 } 16623 } 16624 16625 int user = UserHandle.getCallingUserId(); 16626 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16627 scheduleWritePackageRestrictionsLocked(user); 16628 } 16629 } 16630 } 16631 16632 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16633 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16634 ArrayList<PreferredActivity> removed = null; 16635 boolean changed = false; 16636 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16637 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16638 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16639 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16640 continue; 16641 } 16642 Iterator<PreferredActivity> it = pir.filterIterator(); 16643 while (it.hasNext()) { 16644 PreferredActivity pa = it.next(); 16645 // Mark entry for removal only if it matches the package name 16646 // and the entry is of type "always". 16647 if (packageName == null || 16648 (pa.mPref.mComponent.getPackageName().equals(packageName) 16649 && pa.mPref.mAlways)) { 16650 if (removed == null) { 16651 removed = new ArrayList<PreferredActivity>(); 16652 } 16653 removed.add(pa); 16654 } 16655 } 16656 if (removed != null) { 16657 for (int j=0; j<removed.size(); j++) { 16658 PreferredActivity pa = removed.get(j); 16659 pir.removeFilter(pa); 16660 } 16661 changed = true; 16662 } 16663 } 16664 return changed; 16665 } 16666 16667 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16668 private void clearIntentFilterVerificationsLPw(int userId) { 16669 final int packageCount = mPackages.size(); 16670 for (int i = 0; i < packageCount; i++) { 16671 PackageParser.Package pkg = mPackages.valueAt(i); 16672 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16673 } 16674 } 16675 16676 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16677 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16678 if (userId == UserHandle.USER_ALL) { 16679 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16680 sUserManager.getUserIds())) { 16681 for (int oneUserId : sUserManager.getUserIds()) { 16682 scheduleWritePackageRestrictionsLocked(oneUserId); 16683 } 16684 } 16685 } else { 16686 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16687 scheduleWritePackageRestrictionsLocked(userId); 16688 } 16689 } 16690 } 16691 16692 void clearDefaultBrowserIfNeeded(String packageName) { 16693 for (int oneUserId : sUserManager.getUserIds()) { 16694 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16695 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16696 if (packageName.equals(defaultBrowserPackageName)) { 16697 setDefaultBrowserPackageName(null, oneUserId); 16698 } 16699 } 16700 } 16701 16702 @Override 16703 public void resetApplicationPreferences(int userId) { 16704 mContext.enforceCallingOrSelfPermission( 16705 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16706 final long identity = Binder.clearCallingIdentity(); 16707 // writer 16708 try { 16709 synchronized (mPackages) { 16710 clearPackagePreferredActivitiesLPw(null, userId); 16711 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16712 // TODO: We have to reset the default SMS and Phone. This requires 16713 // significant refactoring to keep all default apps in the package 16714 // manager (cleaner but more work) or have the services provide 16715 // callbacks to the package manager to request a default app reset. 16716 applyFactoryDefaultBrowserLPw(userId); 16717 clearIntentFilterVerificationsLPw(userId); 16718 primeDomainVerificationsLPw(userId); 16719 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16720 scheduleWritePackageRestrictionsLocked(userId); 16721 } 16722 resetNetworkPolicies(userId); 16723 } finally { 16724 Binder.restoreCallingIdentity(identity); 16725 } 16726 } 16727 16728 @Override 16729 public int getPreferredActivities(List<IntentFilter> outFilters, 16730 List<ComponentName> outActivities, String packageName) { 16731 16732 int num = 0; 16733 final int userId = UserHandle.getCallingUserId(); 16734 // reader 16735 synchronized (mPackages) { 16736 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16737 if (pir != null) { 16738 final Iterator<PreferredActivity> it = pir.filterIterator(); 16739 while (it.hasNext()) { 16740 final PreferredActivity pa = it.next(); 16741 if (packageName == null 16742 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16743 && pa.mPref.mAlways)) { 16744 if (outFilters != null) { 16745 outFilters.add(new IntentFilter(pa)); 16746 } 16747 if (outActivities != null) { 16748 outActivities.add(pa.mPref.mComponent); 16749 } 16750 } 16751 } 16752 } 16753 } 16754 16755 return num; 16756 } 16757 16758 @Override 16759 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16760 int userId) { 16761 int callingUid = Binder.getCallingUid(); 16762 if (callingUid != Process.SYSTEM_UID) { 16763 throw new SecurityException( 16764 "addPersistentPreferredActivity can only be run by the system"); 16765 } 16766 if (filter.countActions() == 0) { 16767 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16768 return; 16769 } 16770 synchronized (mPackages) { 16771 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16772 ":"); 16773 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16774 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16775 new PersistentPreferredActivity(filter, activity)); 16776 scheduleWritePackageRestrictionsLocked(userId); 16777 } 16778 } 16779 16780 @Override 16781 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16782 int callingUid = Binder.getCallingUid(); 16783 if (callingUid != Process.SYSTEM_UID) { 16784 throw new SecurityException( 16785 "clearPackagePersistentPreferredActivities can only be run by the system"); 16786 } 16787 ArrayList<PersistentPreferredActivity> removed = null; 16788 boolean changed = false; 16789 synchronized (mPackages) { 16790 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16791 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16792 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16793 .valueAt(i); 16794 if (userId != thisUserId) { 16795 continue; 16796 } 16797 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16798 while (it.hasNext()) { 16799 PersistentPreferredActivity ppa = it.next(); 16800 // Mark entry for removal only if it matches the package name. 16801 if (ppa.mComponent.getPackageName().equals(packageName)) { 16802 if (removed == null) { 16803 removed = new ArrayList<PersistentPreferredActivity>(); 16804 } 16805 removed.add(ppa); 16806 } 16807 } 16808 if (removed != null) { 16809 for (int j=0; j<removed.size(); j++) { 16810 PersistentPreferredActivity ppa = removed.get(j); 16811 ppir.removeFilter(ppa); 16812 } 16813 changed = true; 16814 } 16815 } 16816 16817 if (changed) { 16818 scheduleWritePackageRestrictionsLocked(userId); 16819 } 16820 } 16821 } 16822 16823 /** 16824 * Common machinery for picking apart a restored XML blob and passing 16825 * it to a caller-supplied functor to be applied to the running system. 16826 */ 16827 private void restoreFromXml(XmlPullParser parser, int userId, 16828 String expectedStartTag, BlobXmlRestorer functor) 16829 throws IOException, XmlPullParserException { 16830 int type; 16831 while ((type = parser.next()) != XmlPullParser.START_TAG 16832 && type != XmlPullParser.END_DOCUMENT) { 16833 } 16834 if (type != XmlPullParser.START_TAG) { 16835 // oops didn't find a start tag?! 16836 if (DEBUG_BACKUP) { 16837 Slog.e(TAG, "Didn't find start tag during restore"); 16838 } 16839 return; 16840 } 16841Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16842 // this is supposed to be TAG_PREFERRED_BACKUP 16843 if (!expectedStartTag.equals(parser.getName())) { 16844 if (DEBUG_BACKUP) { 16845 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16846 } 16847 return; 16848 } 16849 16850 // skip interfering stuff, then we're aligned with the backing implementation 16851 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16852Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16853 functor.apply(parser, userId); 16854 } 16855 16856 private interface BlobXmlRestorer { 16857 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16858 } 16859 16860 /** 16861 * Non-Binder method, support for the backup/restore mechanism: write the 16862 * full set of preferred activities in its canonical XML format. Returns the 16863 * XML output as a byte array, or null if there is none. 16864 */ 16865 @Override 16866 public byte[] getPreferredActivityBackup(int userId) { 16867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16868 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16869 } 16870 16871 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16872 try { 16873 final XmlSerializer serializer = new FastXmlSerializer(); 16874 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16875 serializer.startDocument(null, true); 16876 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16877 16878 synchronized (mPackages) { 16879 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16880 } 16881 16882 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16883 serializer.endDocument(); 16884 serializer.flush(); 16885 } catch (Exception e) { 16886 if (DEBUG_BACKUP) { 16887 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16888 } 16889 return null; 16890 } 16891 16892 return dataStream.toByteArray(); 16893 } 16894 16895 @Override 16896 public void restorePreferredActivities(byte[] backup, int userId) { 16897 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16898 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16899 } 16900 16901 try { 16902 final XmlPullParser parser = Xml.newPullParser(); 16903 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16904 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16905 new BlobXmlRestorer() { 16906 @Override 16907 public void apply(XmlPullParser parser, int userId) 16908 throws XmlPullParserException, IOException { 16909 synchronized (mPackages) { 16910 mSettings.readPreferredActivitiesLPw(parser, userId); 16911 } 16912 } 16913 } ); 16914 } catch (Exception e) { 16915 if (DEBUG_BACKUP) { 16916 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16917 } 16918 } 16919 } 16920 16921 /** 16922 * Non-Binder method, support for the backup/restore mechanism: write the 16923 * default browser (etc) settings in its canonical XML format. Returns the default 16924 * browser XML representation as a byte array, or null if there is none. 16925 */ 16926 @Override 16927 public byte[] getDefaultAppsBackup(int userId) { 16928 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16929 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16930 } 16931 16932 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16933 try { 16934 final XmlSerializer serializer = new FastXmlSerializer(); 16935 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16936 serializer.startDocument(null, true); 16937 serializer.startTag(null, TAG_DEFAULT_APPS); 16938 16939 synchronized (mPackages) { 16940 mSettings.writeDefaultAppsLPr(serializer, userId); 16941 } 16942 16943 serializer.endTag(null, TAG_DEFAULT_APPS); 16944 serializer.endDocument(); 16945 serializer.flush(); 16946 } catch (Exception e) { 16947 if (DEBUG_BACKUP) { 16948 Slog.e(TAG, "Unable to write default apps for backup", e); 16949 } 16950 return null; 16951 } 16952 16953 return dataStream.toByteArray(); 16954 } 16955 16956 @Override 16957 public void restoreDefaultApps(byte[] backup, int userId) { 16958 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16959 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16960 } 16961 16962 try { 16963 final XmlPullParser parser = Xml.newPullParser(); 16964 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16965 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16966 new BlobXmlRestorer() { 16967 @Override 16968 public void apply(XmlPullParser parser, int userId) 16969 throws XmlPullParserException, IOException { 16970 synchronized (mPackages) { 16971 mSettings.readDefaultAppsLPw(parser, userId); 16972 } 16973 } 16974 } ); 16975 } catch (Exception e) { 16976 if (DEBUG_BACKUP) { 16977 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16978 } 16979 } 16980 } 16981 16982 @Override 16983 public byte[] getIntentFilterVerificationBackup(int userId) { 16984 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16985 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16986 } 16987 16988 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16989 try { 16990 final XmlSerializer serializer = new FastXmlSerializer(); 16991 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16992 serializer.startDocument(null, true); 16993 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16994 16995 synchronized (mPackages) { 16996 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16997 } 16998 16999 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17000 serializer.endDocument(); 17001 serializer.flush(); 17002 } catch (Exception e) { 17003 if (DEBUG_BACKUP) { 17004 Slog.e(TAG, "Unable to write default apps for backup", e); 17005 } 17006 return null; 17007 } 17008 17009 return dataStream.toByteArray(); 17010 } 17011 17012 @Override 17013 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17014 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17015 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17016 } 17017 17018 try { 17019 final XmlPullParser parser = Xml.newPullParser(); 17020 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17021 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17022 new BlobXmlRestorer() { 17023 @Override 17024 public void apply(XmlPullParser parser, int userId) 17025 throws XmlPullParserException, IOException { 17026 synchronized (mPackages) { 17027 mSettings.readAllDomainVerificationsLPr(parser, userId); 17028 mSettings.writeLPr(); 17029 } 17030 } 17031 } ); 17032 } catch (Exception e) { 17033 if (DEBUG_BACKUP) { 17034 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17035 } 17036 } 17037 } 17038 17039 @Override 17040 public byte[] getPermissionGrantBackup(int userId) { 17041 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17042 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17043 } 17044 17045 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17046 try { 17047 final XmlSerializer serializer = new FastXmlSerializer(); 17048 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17049 serializer.startDocument(null, true); 17050 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17051 17052 synchronized (mPackages) { 17053 serializeRuntimePermissionGrantsLPr(serializer, userId); 17054 } 17055 17056 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17057 serializer.endDocument(); 17058 serializer.flush(); 17059 } catch (Exception e) { 17060 if (DEBUG_BACKUP) { 17061 Slog.e(TAG, "Unable to write default apps for backup", e); 17062 } 17063 return null; 17064 } 17065 17066 return dataStream.toByteArray(); 17067 } 17068 17069 @Override 17070 public void restorePermissionGrants(byte[] backup, int userId) { 17071 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17072 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17073 } 17074 17075 try { 17076 final XmlPullParser parser = Xml.newPullParser(); 17077 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17078 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17079 new BlobXmlRestorer() { 17080 @Override 17081 public void apply(XmlPullParser parser, int userId) 17082 throws XmlPullParserException, IOException { 17083 synchronized (mPackages) { 17084 processRestoredPermissionGrantsLPr(parser, userId); 17085 } 17086 } 17087 } ); 17088 } catch (Exception e) { 17089 if (DEBUG_BACKUP) { 17090 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17091 } 17092 } 17093 } 17094 17095 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17096 throws IOException { 17097 serializer.startTag(null, TAG_ALL_GRANTS); 17098 17099 final int N = mSettings.mPackages.size(); 17100 for (int i = 0; i < N; i++) { 17101 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17102 boolean pkgGrantsKnown = false; 17103 17104 PermissionsState packagePerms = ps.getPermissionsState(); 17105 17106 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17107 final int grantFlags = state.getFlags(); 17108 // only look at grants that are not system/policy fixed 17109 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17110 final boolean isGranted = state.isGranted(); 17111 // And only back up the user-twiddled state bits 17112 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17113 final String packageName = mSettings.mPackages.keyAt(i); 17114 if (!pkgGrantsKnown) { 17115 serializer.startTag(null, TAG_GRANT); 17116 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17117 pkgGrantsKnown = true; 17118 } 17119 17120 final boolean userSet = 17121 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17122 final boolean userFixed = 17123 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17124 final boolean revoke = 17125 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17126 17127 serializer.startTag(null, TAG_PERMISSION); 17128 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17129 if (isGranted) { 17130 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17131 } 17132 if (userSet) { 17133 serializer.attribute(null, ATTR_USER_SET, "true"); 17134 } 17135 if (userFixed) { 17136 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17137 } 17138 if (revoke) { 17139 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17140 } 17141 serializer.endTag(null, TAG_PERMISSION); 17142 } 17143 } 17144 } 17145 17146 if (pkgGrantsKnown) { 17147 serializer.endTag(null, TAG_GRANT); 17148 } 17149 } 17150 17151 serializer.endTag(null, TAG_ALL_GRANTS); 17152 } 17153 17154 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17155 throws XmlPullParserException, IOException { 17156 String pkgName = null; 17157 int outerDepth = parser.getDepth(); 17158 int type; 17159 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17160 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17161 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17162 continue; 17163 } 17164 17165 final String tagName = parser.getName(); 17166 if (tagName.equals(TAG_GRANT)) { 17167 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17168 if (DEBUG_BACKUP) { 17169 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17170 } 17171 } else if (tagName.equals(TAG_PERMISSION)) { 17172 17173 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17174 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17175 17176 int newFlagSet = 0; 17177 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17178 newFlagSet |= FLAG_PERMISSION_USER_SET; 17179 } 17180 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17181 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17182 } 17183 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17184 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17185 } 17186 if (DEBUG_BACKUP) { 17187 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17188 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17189 } 17190 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17191 if (ps != null) { 17192 // Already installed so we apply the grant immediately 17193 if (DEBUG_BACKUP) { 17194 Slog.v(TAG, " + already installed; applying"); 17195 } 17196 PermissionsState perms = ps.getPermissionsState(); 17197 BasePermission bp = mSettings.mPermissions.get(permName); 17198 if (bp != null) { 17199 if (isGranted) { 17200 perms.grantRuntimePermission(bp, userId); 17201 } 17202 if (newFlagSet != 0) { 17203 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17204 } 17205 } 17206 } else { 17207 // Need to wait for post-restore install to apply the grant 17208 if (DEBUG_BACKUP) { 17209 Slog.v(TAG, " - not yet installed; saving for later"); 17210 } 17211 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17212 isGranted, newFlagSet, userId); 17213 } 17214 } else { 17215 PackageManagerService.reportSettingsProblem(Log.WARN, 17216 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17217 XmlUtils.skipCurrentTag(parser); 17218 } 17219 } 17220 17221 scheduleWriteSettingsLocked(); 17222 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17223 } 17224 17225 @Override 17226 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17227 int sourceUserId, int targetUserId, int flags) { 17228 mContext.enforceCallingOrSelfPermission( 17229 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17230 int callingUid = Binder.getCallingUid(); 17231 enforceOwnerRights(ownerPackage, callingUid); 17232 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17233 if (intentFilter.countActions() == 0) { 17234 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17235 return; 17236 } 17237 synchronized (mPackages) { 17238 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17239 ownerPackage, targetUserId, flags); 17240 CrossProfileIntentResolver resolver = 17241 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17242 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17243 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17244 if (existing != null) { 17245 int size = existing.size(); 17246 for (int i = 0; i < size; i++) { 17247 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17248 return; 17249 } 17250 } 17251 } 17252 resolver.addFilter(newFilter); 17253 scheduleWritePackageRestrictionsLocked(sourceUserId); 17254 } 17255 } 17256 17257 @Override 17258 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17259 mContext.enforceCallingOrSelfPermission( 17260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17261 int callingUid = Binder.getCallingUid(); 17262 enforceOwnerRights(ownerPackage, callingUid); 17263 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17264 synchronized (mPackages) { 17265 CrossProfileIntentResolver resolver = 17266 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17267 ArraySet<CrossProfileIntentFilter> set = 17268 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17269 for (CrossProfileIntentFilter filter : set) { 17270 if (filter.getOwnerPackage().equals(ownerPackage)) { 17271 resolver.removeFilter(filter); 17272 } 17273 } 17274 scheduleWritePackageRestrictionsLocked(sourceUserId); 17275 } 17276 } 17277 17278 // Enforcing that callingUid is owning pkg on userId 17279 private void enforceOwnerRights(String pkg, int callingUid) { 17280 // The system owns everything. 17281 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17282 return; 17283 } 17284 int callingUserId = UserHandle.getUserId(callingUid); 17285 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17286 if (pi == null) { 17287 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17288 + callingUserId); 17289 } 17290 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17291 throw new SecurityException("Calling uid " + callingUid 17292 + " does not own package " + pkg); 17293 } 17294 } 17295 17296 @Override 17297 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17298 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17299 } 17300 17301 private Intent getHomeIntent() { 17302 Intent intent = new Intent(Intent.ACTION_MAIN); 17303 intent.addCategory(Intent.CATEGORY_HOME); 17304 return intent; 17305 } 17306 17307 private IntentFilter getHomeFilter() { 17308 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17309 filter.addCategory(Intent.CATEGORY_HOME); 17310 filter.addCategory(Intent.CATEGORY_DEFAULT); 17311 return filter; 17312 } 17313 17314 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17315 int userId) { 17316 Intent intent = getHomeIntent(); 17317 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17318 PackageManager.GET_META_DATA, userId); 17319 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17320 true, false, false, userId); 17321 17322 allHomeCandidates.clear(); 17323 if (list != null) { 17324 for (ResolveInfo ri : list) { 17325 allHomeCandidates.add(ri); 17326 } 17327 } 17328 return (preferred == null || preferred.activityInfo == null) 17329 ? null 17330 : new ComponentName(preferred.activityInfo.packageName, 17331 preferred.activityInfo.name); 17332 } 17333 17334 @Override 17335 public void setHomeActivity(ComponentName comp, int userId) { 17336 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17337 getHomeActivitiesAsUser(homeActivities, userId); 17338 17339 boolean found = false; 17340 17341 final int size = homeActivities.size(); 17342 final ComponentName[] set = new ComponentName[size]; 17343 for (int i = 0; i < size; i++) { 17344 final ResolveInfo candidate = homeActivities.get(i); 17345 final ActivityInfo info = candidate.activityInfo; 17346 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17347 set[i] = activityName; 17348 if (!found && activityName.equals(comp)) { 17349 found = true; 17350 } 17351 } 17352 if (!found) { 17353 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17354 + userId); 17355 } 17356 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17357 set, comp, userId); 17358 } 17359 17360 private @Nullable String getSetupWizardPackageName() { 17361 final Intent intent = new Intent(Intent.ACTION_MAIN); 17362 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17363 17364 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17365 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17366 | MATCH_DISABLED_COMPONENTS, 17367 UserHandle.myUserId()); 17368 if (matches.size() == 1) { 17369 return matches.get(0).getComponentInfo().packageName; 17370 } else { 17371 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17372 + ": matches=" + matches); 17373 return null; 17374 } 17375 } 17376 17377 @Override 17378 public void setApplicationEnabledSetting(String appPackageName, 17379 int newState, int flags, int userId, String callingPackage) { 17380 if (!sUserManager.exists(userId)) return; 17381 if (callingPackage == null) { 17382 callingPackage = Integer.toString(Binder.getCallingUid()); 17383 } 17384 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17385 } 17386 17387 @Override 17388 public void setComponentEnabledSetting(ComponentName componentName, 17389 int newState, int flags, int userId) { 17390 if (!sUserManager.exists(userId)) return; 17391 setEnabledSetting(componentName.getPackageName(), 17392 componentName.getClassName(), newState, flags, userId, null); 17393 } 17394 17395 private void setEnabledSetting(final String packageName, String className, int newState, 17396 final int flags, int userId, String callingPackage) { 17397 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17398 || newState == COMPONENT_ENABLED_STATE_ENABLED 17399 || newState == COMPONENT_ENABLED_STATE_DISABLED 17400 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17401 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17402 throw new IllegalArgumentException("Invalid new component state: " 17403 + newState); 17404 } 17405 PackageSetting pkgSetting; 17406 final int uid = Binder.getCallingUid(); 17407 final int permission; 17408 if (uid == Process.SYSTEM_UID) { 17409 permission = PackageManager.PERMISSION_GRANTED; 17410 } else { 17411 permission = mContext.checkCallingOrSelfPermission( 17412 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17413 } 17414 enforceCrossUserPermission(uid, userId, 17415 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17416 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17417 boolean sendNow = false; 17418 boolean isApp = (className == null); 17419 String componentName = isApp ? packageName : className; 17420 int packageUid = -1; 17421 ArrayList<String> components; 17422 17423 // writer 17424 synchronized (mPackages) { 17425 pkgSetting = mSettings.mPackages.get(packageName); 17426 if (pkgSetting == null) { 17427 if (className == null) { 17428 throw new IllegalArgumentException("Unknown package: " + packageName); 17429 } 17430 throw new IllegalArgumentException( 17431 "Unknown component: " + packageName + "/" + className); 17432 } 17433 // Allow root and verify that userId is not being specified by a different user 17434 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17435 throw new SecurityException( 17436 "Permission Denial: attempt to change component state from pid=" 17437 + Binder.getCallingPid() 17438 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17439 } 17440 if (className == null) { 17441 // We're dealing with an application/package level state change 17442 if (pkgSetting.getEnabled(userId) == newState) { 17443 // Nothing to do 17444 return; 17445 } 17446 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17447 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17448 // Don't care about who enables an app. 17449 callingPackage = null; 17450 } 17451 pkgSetting.setEnabled(newState, userId, callingPackage); 17452 // pkgSetting.pkg.mSetEnabled = newState; 17453 } else { 17454 // We're dealing with a component level state change 17455 // First, verify that this is a valid class name. 17456 PackageParser.Package pkg = pkgSetting.pkg; 17457 if (pkg == null || !pkg.hasComponentClassName(className)) { 17458 if (pkg != null && 17459 pkg.applicationInfo.targetSdkVersion >= 17460 Build.VERSION_CODES.JELLY_BEAN) { 17461 throw new IllegalArgumentException("Component class " + className 17462 + " does not exist in " + packageName); 17463 } else { 17464 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17465 + className + " does not exist in " + packageName); 17466 } 17467 } 17468 switch (newState) { 17469 case COMPONENT_ENABLED_STATE_ENABLED: 17470 if (!pkgSetting.enableComponentLPw(className, userId)) { 17471 return; 17472 } 17473 break; 17474 case COMPONENT_ENABLED_STATE_DISABLED: 17475 if (!pkgSetting.disableComponentLPw(className, userId)) { 17476 return; 17477 } 17478 break; 17479 case COMPONENT_ENABLED_STATE_DEFAULT: 17480 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17481 return; 17482 } 17483 break; 17484 default: 17485 Slog.e(TAG, "Invalid new component state: " + newState); 17486 return; 17487 } 17488 } 17489 scheduleWritePackageRestrictionsLocked(userId); 17490 components = mPendingBroadcasts.get(userId, packageName); 17491 final boolean newPackage = components == null; 17492 if (newPackage) { 17493 components = new ArrayList<String>(); 17494 } 17495 if (!components.contains(componentName)) { 17496 components.add(componentName); 17497 } 17498 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17499 sendNow = true; 17500 // Purge entry from pending broadcast list if another one exists already 17501 // since we are sending one right away. 17502 mPendingBroadcasts.remove(userId, packageName); 17503 } else { 17504 if (newPackage) { 17505 mPendingBroadcasts.put(userId, packageName, components); 17506 } 17507 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17508 // Schedule a message 17509 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17510 } 17511 } 17512 } 17513 17514 long callingId = Binder.clearCallingIdentity(); 17515 try { 17516 if (sendNow) { 17517 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17518 sendPackageChangedBroadcast(packageName, 17519 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17520 } 17521 } finally { 17522 Binder.restoreCallingIdentity(callingId); 17523 } 17524 } 17525 17526 @Override 17527 public void flushPackageRestrictionsAsUser(int userId) { 17528 if (!sUserManager.exists(userId)) { 17529 return; 17530 } 17531 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17532 false /* checkShell */, "flushPackageRestrictions"); 17533 synchronized (mPackages) { 17534 mSettings.writePackageRestrictionsLPr(userId); 17535 mDirtyUsers.remove(userId); 17536 if (mDirtyUsers.isEmpty()) { 17537 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17538 } 17539 } 17540 } 17541 17542 private void sendPackageChangedBroadcast(String packageName, 17543 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17544 if (DEBUG_INSTALL) 17545 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17546 + componentNames); 17547 Bundle extras = new Bundle(4); 17548 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17549 String nameList[] = new String[componentNames.size()]; 17550 componentNames.toArray(nameList); 17551 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17552 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17553 extras.putInt(Intent.EXTRA_UID, packageUid); 17554 // If this is not reporting a change of the overall package, then only send it 17555 // to registered receivers. We don't want to launch a swath of apps for every 17556 // little component state change. 17557 final int flags = !componentNames.contains(packageName) 17558 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17559 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17560 new int[] {UserHandle.getUserId(packageUid)}); 17561 } 17562 17563 @Override 17564 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17565 if (!sUserManager.exists(userId)) return; 17566 final int uid = Binder.getCallingUid(); 17567 final int permission = mContext.checkCallingOrSelfPermission( 17568 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17569 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17570 enforceCrossUserPermission(uid, userId, 17571 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17572 // writer 17573 synchronized (mPackages) { 17574 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17575 allowedByPermission, uid, userId)) { 17576 scheduleWritePackageRestrictionsLocked(userId); 17577 } 17578 } 17579 } 17580 17581 @Override 17582 public String getInstallerPackageName(String packageName) { 17583 // reader 17584 synchronized (mPackages) { 17585 return mSettings.getInstallerPackageNameLPr(packageName); 17586 } 17587 } 17588 17589 public boolean isOrphaned(String packageName) { 17590 // reader 17591 synchronized (mPackages) { 17592 return mSettings.isOrphaned(packageName); 17593 } 17594 } 17595 17596 @Override 17597 public int getApplicationEnabledSetting(String packageName, int userId) { 17598 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17599 int uid = Binder.getCallingUid(); 17600 enforceCrossUserPermission(uid, userId, 17601 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17602 // reader 17603 synchronized (mPackages) { 17604 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17605 } 17606 } 17607 17608 @Override 17609 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17610 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17611 int uid = Binder.getCallingUid(); 17612 enforceCrossUserPermission(uid, userId, 17613 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17614 // reader 17615 synchronized (mPackages) { 17616 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17617 } 17618 } 17619 17620 @Override 17621 public void enterSafeMode() { 17622 enforceSystemOrRoot("Only the system can request entering safe mode"); 17623 17624 if (!mSystemReady) { 17625 mSafeMode = true; 17626 } 17627 } 17628 17629 @Override 17630 public void systemReady() { 17631 mSystemReady = true; 17632 17633 // Read the compatibilty setting when the system is ready. 17634 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17635 mContext.getContentResolver(), 17636 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17637 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17638 if (DEBUG_SETTINGS) { 17639 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17640 } 17641 17642 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17643 17644 synchronized (mPackages) { 17645 // Verify that all of the preferred activity components actually 17646 // exist. It is possible for applications to be updated and at 17647 // that point remove a previously declared activity component that 17648 // had been set as a preferred activity. We try to clean this up 17649 // the next time we encounter that preferred activity, but it is 17650 // possible for the user flow to never be able to return to that 17651 // situation so here we do a sanity check to make sure we haven't 17652 // left any junk around. 17653 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17654 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17655 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17656 removed.clear(); 17657 for (PreferredActivity pa : pir.filterSet()) { 17658 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17659 removed.add(pa); 17660 } 17661 } 17662 if (removed.size() > 0) { 17663 for (int r=0; r<removed.size(); r++) { 17664 PreferredActivity pa = removed.get(r); 17665 Slog.w(TAG, "Removing dangling preferred activity: " 17666 + pa.mPref.mComponent); 17667 pir.removeFilter(pa); 17668 } 17669 mSettings.writePackageRestrictionsLPr( 17670 mSettings.mPreferredActivities.keyAt(i)); 17671 } 17672 } 17673 17674 for (int userId : UserManagerService.getInstance().getUserIds()) { 17675 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17676 grantPermissionsUserIds = ArrayUtils.appendInt( 17677 grantPermissionsUserIds, userId); 17678 } 17679 } 17680 } 17681 sUserManager.systemReady(); 17682 17683 // If we upgraded grant all default permissions before kicking off. 17684 for (int userId : grantPermissionsUserIds) { 17685 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17686 } 17687 17688 // Kick off any messages waiting for system ready 17689 if (mPostSystemReadyMessages != null) { 17690 for (Message msg : mPostSystemReadyMessages) { 17691 msg.sendToTarget(); 17692 } 17693 mPostSystemReadyMessages = null; 17694 } 17695 17696 // Watch for external volumes that come and go over time 17697 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17698 storage.registerListener(mStorageListener); 17699 17700 mInstallerService.systemReady(); 17701 mPackageDexOptimizer.systemReady(); 17702 17703 MountServiceInternal mountServiceInternal = LocalServices.getService( 17704 MountServiceInternal.class); 17705 mountServiceInternal.addExternalStoragePolicy( 17706 new MountServiceInternal.ExternalStorageMountPolicy() { 17707 @Override 17708 public int getMountMode(int uid, String packageName) { 17709 if (Process.isIsolated(uid)) { 17710 return Zygote.MOUNT_EXTERNAL_NONE; 17711 } 17712 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17713 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17714 } 17715 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17716 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17717 } 17718 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17719 return Zygote.MOUNT_EXTERNAL_READ; 17720 } 17721 return Zygote.MOUNT_EXTERNAL_WRITE; 17722 } 17723 17724 @Override 17725 public boolean hasExternalStorage(int uid, String packageName) { 17726 return true; 17727 } 17728 }); 17729 17730 // Now that we're mostly running, clean up stale users and apps 17731 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17732 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17733 } 17734 17735 @Override 17736 public boolean isSafeMode() { 17737 return mSafeMode; 17738 } 17739 17740 @Override 17741 public boolean hasSystemUidErrors() { 17742 return mHasSystemUidErrors; 17743 } 17744 17745 static String arrayToString(int[] array) { 17746 StringBuffer buf = new StringBuffer(128); 17747 buf.append('['); 17748 if (array != null) { 17749 for (int i=0; i<array.length; i++) { 17750 if (i > 0) buf.append(", "); 17751 buf.append(array[i]); 17752 } 17753 } 17754 buf.append(']'); 17755 return buf.toString(); 17756 } 17757 17758 static class DumpState { 17759 public static final int DUMP_LIBS = 1 << 0; 17760 public static final int DUMP_FEATURES = 1 << 1; 17761 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17762 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17763 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17764 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17765 public static final int DUMP_PERMISSIONS = 1 << 6; 17766 public static final int DUMP_PACKAGES = 1 << 7; 17767 public static final int DUMP_SHARED_USERS = 1 << 8; 17768 public static final int DUMP_MESSAGES = 1 << 9; 17769 public static final int DUMP_PROVIDERS = 1 << 10; 17770 public static final int DUMP_VERIFIERS = 1 << 11; 17771 public static final int DUMP_PREFERRED = 1 << 12; 17772 public static final int DUMP_PREFERRED_XML = 1 << 13; 17773 public static final int DUMP_KEYSETS = 1 << 14; 17774 public static final int DUMP_VERSION = 1 << 15; 17775 public static final int DUMP_INSTALLS = 1 << 16; 17776 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17777 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17778 public static final int DUMP_FROZEN = 1 << 19; 17779 public static final int DUMP_DEXOPT = 1 << 20; 17780 17781 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17782 17783 private int mTypes; 17784 17785 private int mOptions; 17786 17787 private boolean mTitlePrinted; 17788 17789 private SharedUserSetting mSharedUser; 17790 17791 public boolean isDumping(int type) { 17792 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17793 return true; 17794 } 17795 17796 return (mTypes & type) != 0; 17797 } 17798 17799 public void setDump(int type) { 17800 mTypes |= type; 17801 } 17802 17803 public boolean isOptionEnabled(int option) { 17804 return (mOptions & option) != 0; 17805 } 17806 17807 public void setOptionEnabled(int option) { 17808 mOptions |= option; 17809 } 17810 17811 public boolean onTitlePrinted() { 17812 final boolean printed = mTitlePrinted; 17813 mTitlePrinted = true; 17814 return printed; 17815 } 17816 17817 public boolean getTitlePrinted() { 17818 return mTitlePrinted; 17819 } 17820 17821 public void setTitlePrinted(boolean enabled) { 17822 mTitlePrinted = enabled; 17823 } 17824 17825 public SharedUserSetting getSharedUser() { 17826 return mSharedUser; 17827 } 17828 17829 public void setSharedUser(SharedUserSetting user) { 17830 mSharedUser = user; 17831 } 17832 } 17833 17834 @Override 17835 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17836 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17837 (new PackageManagerShellCommand(this)).exec( 17838 this, in, out, err, args, resultReceiver); 17839 } 17840 17841 @Override 17842 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17843 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17844 != PackageManager.PERMISSION_GRANTED) { 17845 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17846 + Binder.getCallingPid() 17847 + ", uid=" + Binder.getCallingUid() 17848 + " without permission " 17849 + android.Manifest.permission.DUMP); 17850 return; 17851 } 17852 17853 DumpState dumpState = new DumpState(); 17854 boolean fullPreferred = false; 17855 boolean checkin = false; 17856 17857 String packageName = null; 17858 ArraySet<String> permissionNames = null; 17859 17860 int opti = 0; 17861 while (opti < args.length) { 17862 String opt = args[opti]; 17863 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17864 break; 17865 } 17866 opti++; 17867 17868 if ("-a".equals(opt)) { 17869 // Right now we only know how to print all. 17870 } else if ("-h".equals(opt)) { 17871 pw.println("Package manager dump options:"); 17872 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17873 pw.println(" --checkin: dump for a checkin"); 17874 pw.println(" -f: print details of intent filters"); 17875 pw.println(" -h: print this help"); 17876 pw.println(" cmd may be one of:"); 17877 pw.println(" l[ibraries]: list known shared libraries"); 17878 pw.println(" f[eatures]: list device features"); 17879 pw.println(" k[eysets]: print known keysets"); 17880 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17881 pw.println(" perm[issions]: dump permissions"); 17882 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17883 pw.println(" pref[erred]: print preferred package settings"); 17884 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17885 pw.println(" prov[iders]: dump content providers"); 17886 pw.println(" p[ackages]: dump installed packages"); 17887 pw.println(" s[hared-users]: dump shared user IDs"); 17888 pw.println(" m[essages]: print collected runtime messages"); 17889 pw.println(" v[erifiers]: print package verifier info"); 17890 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17891 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17892 pw.println(" version: print database version info"); 17893 pw.println(" write: write current settings now"); 17894 pw.println(" installs: details about install sessions"); 17895 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17896 pw.println(" dexopt: dump dexopt state"); 17897 pw.println(" <package.name>: info about given package"); 17898 return; 17899 } else if ("--checkin".equals(opt)) { 17900 checkin = true; 17901 } else if ("-f".equals(opt)) { 17902 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17903 } else { 17904 pw.println("Unknown argument: " + opt + "; use -h for help"); 17905 } 17906 } 17907 17908 // Is the caller requesting to dump a particular piece of data? 17909 if (opti < args.length) { 17910 String cmd = args[opti]; 17911 opti++; 17912 // Is this a package name? 17913 if ("android".equals(cmd) || cmd.contains(".")) { 17914 packageName = cmd; 17915 // When dumping a single package, we always dump all of its 17916 // filter information since the amount of data will be reasonable. 17917 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17918 } else if ("check-permission".equals(cmd)) { 17919 if (opti >= args.length) { 17920 pw.println("Error: check-permission missing permission argument"); 17921 return; 17922 } 17923 String perm = args[opti]; 17924 opti++; 17925 if (opti >= args.length) { 17926 pw.println("Error: check-permission missing package argument"); 17927 return; 17928 } 17929 String pkg = args[opti]; 17930 opti++; 17931 int user = UserHandle.getUserId(Binder.getCallingUid()); 17932 if (opti < args.length) { 17933 try { 17934 user = Integer.parseInt(args[opti]); 17935 } catch (NumberFormatException e) { 17936 pw.println("Error: check-permission user argument is not a number: " 17937 + args[opti]); 17938 return; 17939 } 17940 } 17941 pw.println(checkPermission(perm, pkg, user)); 17942 return; 17943 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17944 dumpState.setDump(DumpState.DUMP_LIBS); 17945 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17946 dumpState.setDump(DumpState.DUMP_FEATURES); 17947 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17948 if (opti >= args.length) { 17949 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17950 | DumpState.DUMP_SERVICE_RESOLVERS 17951 | DumpState.DUMP_RECEIVER_RESOLVERS 17952 | DumpState.DUMP_CONTENT_RESOLVERS); 17953 } else { 17954 while (opti < args.length) { 17955 String name = args[opti]; 17956 if ("a".equals(name) || "activity".equals(name)) { 17957 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17958 } else if ("s".equals(name) || "service".equals(name)) { 17959 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17960 } else if ("r".equals(name) || "receiver".equals(name)) { 17961 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17962 } else if ("c".equals(name) || "content".equals(name)) { 17963 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17964 } else { 17965 pw.println("Error: unknown resolver table type: " + name); 17966 return; 17967 } 17968 opti++; 17969 } 17970 } 17971 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17972 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17973 } else if ("permission".equals(cmd)) { 17974 if (opti >= args.length) { 17975 pw.println("Error: permission requires permission name"); 17976 return; 17977 } 17978 permissionNames = new ArraySet<>(); 17979 while (opti < args.length) { 17980 permissionNames.add(args[opti]); 17981 opti++; 17982 } 17983 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17984 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17985 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17986 dumpState.setDump(DumpState.DUMP_PREFERRED); 17987 } else if ("preferred-xml".equals(cmd)) { 17988 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17989 if (opti < args.length && "--full".equals(args[opti])) { 17990 fullPreferred = true; 17991 opti++; 17992 } 17993 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17994 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17995 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17996 dumpState.setDump(DumpState.DUMP_PACKAGES); 17997 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17998 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17999 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18000 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18001 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18002 dumpState.setDump(DumpState.DUMP_MESSAGES); 18003 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18004 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18005 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18006 || "intent-filter-verifiers".equals(cmd)) { 18007 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18008 } else if ("version".equals(cmd)) { 18009 dumpState.setDump(DumpState.DUMP_VERSION); 18010 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18011 dumpState.setDump(DumpState.DUMP_KEYSETS); 18012 } else if ("installs".equals(cmd)) { 18013 dumpState.setDump(DumpState.DUMP_INSTALLS); 18014 } else if ("frozen".equals(cmd)) { 18015 dumpState.setDump(DumpState.DUMP_FROZEN); 18016 } else if ("dexopt".equals(cmd)) { 18017 dumpState.setDump(DumpState.DUMP_DEXOPT); 18018 } else if ("write".equals(cmd)) { 18019 synchronized (mPackages) { 18020 mSettings.writeLPr(); 18021 pw.println("Settings written."); 18022 return; 18023 } 18024 } 18025 } 18026 18027 if (checkin) { 18028 pw.println("vers,1"); 18029 } 18030 18031 // reader 18032 synchronized (mPackages) { 18033 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18034 if (!checkin) { 18035 if (dumpState.onTitlePrinted()) 18036 pw.println(); 18037 pw.println("Database versions:"); 18038 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18039 } 18040 } 18041 18042 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18043 if (!checkin) { 18044 if (dumpState.onTitlePrinted()) 18045 pw.println(); 18046 pw.println("Verifiers:"); 18047 pw.print(" Required: "); 18048 pw.print(mRequiredVerifierPackage); 18049 pw.print(" (uid="); 18050 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18051 UserHandle.USER_SYSTEM)); 18052 pw.println(")"); 18053 } else if (mRequiredVerifierPackage != null) { 18054 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18055 pw.print(","); 18056 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18057 UserHandle.USER_SYSTEM)); 18058 } 18059 } 18060 18061 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18062 packageName == null) { 18063 if (mIntentFilterVerifierComponent != null) { 18064 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18065 if (!checkin) { 18066 if (dumpState.onTitlePrinted()) 18067 pw.println(); 18068 pw.println("Intent Filter Verifier:"); 18069 pw.print(" Using: "); 18070 pw.print(verifierPackageName); 18071 pw.print(" (uid="); 18072 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18073 UserHandle.USER_SYSTEM)); 18074 pw.println(")"); 18075 } else if (verifierPackageName != null) { 18076 pw.print("ifv,"); pw.print(verifierPackageName); 18077 pw.print(","); 18078 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18079 UserHandle.USER_SYSTEM)); 18080 } 18081 } else { 18082 pw.println(); 18083 pw.println("No Intent Filter Verifier available!"); 18084 } 18085 } 18086 18087 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18088 boolean printedHeader = false; 18089 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18090 while (it.hasNext()) { 18091 String name = it.next(); 18092 SharedLibraryEntry ent = mSharedLibraries.get(name); 18093 if (!checkin) { 18094 if (!printedHeader) { 18095 if (dumpState.onTitlePrinted()) 18096 pw.println(); 18097 pw.println("Libraries:"); 18098 printedHeader = true; 18099 } 18100 pw.print(" "); 18101 } else { 18102 pw.print("lib,"); 18103 } 18104 pw.print(name); 18105 if (!checkin) { 18106 pw.print(" -> "); 18107 } 18108 if (ent.path != null) { 18109 if (!checkin) { 18110 pw.print("(jar) "); 18111 pw.print(ent.path); 18112 } else { 18113 pw.print(",jar,"); 18114 pw.print(ent.path); 18115 } 18116 } else { 18117 if (!checkin) { 18118 pw.print("(apk) "); 18119 pw.print(ent.apk); 18120 } else { 18121 pw.print(",apk,"); 18122 pw.print(ent.apk); 18123 } 18124 } 18125 pw.println(); 18126 } 18127 } 18128 18129 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18130 if (dumpState.onTitlePrinted()) 18131 pw.println(); 18132 if (!checkin) { 18133 pw.println("Features:"); 18134 } 18135 18136 for (FeatureInfo feat : mAvailableFeatures.values()) { 18137 if (checkin) { 18138 pw.print("feat,"); 18139 pw.print(feat.name); 18140 pw.print(","); 18141 pw.println(feat.version); 18142 } else { 18143 pw.print(" "); 18144 pw.print(feat.name); 18145 if (feat.version > 0) { 18146 pw.print(" version="); 18147 pw.print(feat.version); 18148 } 18149 pw.println(); 18150 } 18151 } 18152 } 18153 18154 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18155 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18156 : "Activity Resolver Table:", " ", packageName, 18157 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18158 dumpState.setTitlePrinted(true); 18159 } 18160 } 18161 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18162 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18163 : "Receiver Resolver Table:", " ", packageName, 18164 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18165 dumpState.setTitlePrinted(true); 18166 } 18167 } 18168 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18169 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18170 : "Service Resolver Table:", " ", packageName, 18171 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18172 dumpState.setTitlePrinted(true); 18173 } 18174 } 18175 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18176 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18177 : "Provider Resolver Table:", " ", packageName, 18178 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18179 dumpState.setTitlePrinted(true); 18180 } 18181 } 18182 18183 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18184 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18185 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18186 int user = mSettings.mPreferredActivities.keyAt(i); 18187 if (pir.dump(pw, 18188 dumpState.getTitlePrinted() 18189 ? "\nPreferred Activities User " + user + ":" 18190 : "Preferred Activities User " + user + ":", " ", 18191 packageName, true, false)) { 18192 dumpState.setTitlePrinted(true); 18193 } 18194 } 18195 } 18196 18197 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18198 pw.flush(); 18199 FileOutputStream fout = new FileOutputStream(fd); 18200 BufferedOutputStream str = new BufferedOutputStream(fout); 18201 XmlSerializer serializer = new FastXmlSerializer(); 18202 try { 18203 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18204 serializer.startDocument(null, true); 18205 serializer.setFeature( 18206 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18207 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18208 serializer.endDocument(); 18209 serializer.flush(); 18210 } catch (IllegalArgumentException e) { 18211 pw.println("Failed writing: " + e); 18212 } catch (IllegalStateException e) { 18213 pw.println("Failed writing: " + e); 18214 } catch (IOException e) { 18215 pw.println("Failed writing: " + e); 18216 } 18217 } 18218 18219 if (!checkin 18220 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18221 && packageName == null) { 18222 pw.println(); 18223 int count = mSettings.mPackages.size(); 18224 if (count == 0) { 18225 pw.println("No applications!"); 18226 pw.println(); 18227 } else { 18228 final String prefix = " "; 18229 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18230 if (allPackageSettings.size() == 0) { 18231 pw.println("No domain preferred apps!"); 18232 pw.println(); 18233 } else { 18234 pw.println("App verification status:"); 18235 pw.println(); 18236 count = 0; 18237 for (PackageSetting ps : allPackageSettings) { 18238 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18239 if (ivi == null || ivi.getPackageName() == null) continue; 18240 pw.println(prefix + "Package: " + ivi.getPackageName()); 18241 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18242 pw.println(prefix + "Status: " + ivi.getStatusString()); 18243 pw.println(); 18244 count++; 18245 } 18246 if (count == 0) { 18247 pw.println(prefix + "No app verification established."); 18248 pw.println(); 18249 } 18250 for (int userId : sUserManager.getUserIds()) { 18251 pw.println("App linkages for user " + userId + ":"); 18252 pw.println(); 18253 count = 0; 18254 for (PackageSetting ps : allPackageSettings) { 18255 final long status = ps.getDomainVerificationStatusForUser(userId); 18256 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18257 continue; 18258 } 18259 pw.println(prefix + "Package: " + ps.name); 18260 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18261 String statusStr = IntentFilterVerificationInfo. 18262 getStatusStringFromValue(status); 18263 pw.println(prefix + "Status: " + statusStr); 18264 pw.println(); 18265 count++; 18266 } 18267 if (count == 0) { 18268 pw.println(prefix + "No configured app linkages."); 18269 pw.println(); 18270 } 18271 } 18272 } 18273 } 18274 } 18275 18276 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18277 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18278 if (packageName == null && permissionNames == null) { 18279 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18280 if (iperm == 0) { 18281 if (dumpState.onTitlePrinted()) 18282 pw.println(); 18283 pw.println("AppOp Permissions:"); 18284 } 18285 pw.print(" AppOp Permission "); 18286 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18287 pw.println(":"); 18288 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18289 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18290 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18291 } 18292 } 18293 } 18294 } 18295 18296 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18297 boolean printedSomething = false; 18298 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18299 if (packageName != null && !packageName.equals(p.info.packageName)) { 18300 continue; 18301 } 18302 if (!printedSomething) { 18303 if (dumpState.onTitlePrinted()) 18304 pw.println(); 18305 pw.println("Registered ContentProviders:"); 18306 printedSomething = true; 18307 } 18308 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18309 pw.print(" "); pw.println(p.toString()); 18310 } 18311 printedSomething = false; 18312 for (Map.Entry<String, PackageParser.Provider> entry : 18313 mProvidersByAuthority.entrySet()) { 18314 PackageParser.Provider p = entry.getValue(); 18315 if (packageName != null && !packageName.equals(p.info.packageName)) { 18316 continue; 18317 } 18318 if (!printedSomething) { 18319 if (dumpState.onTitlePrinted()) 18320 pw.println(); 18321 pw.println("ContentProvider Authorities:"); 18322 printedSomething = true; 18323 } 18324 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18325 pw.print(" "); pw.println(p.toString()); 18326 if (p.info != null && p.info.applicationInfo != null) { 18327 final String appInfo = p.info.applicationInfo.toString(); 18328 pw.print(" applicationInfo="); pw.println(appInfo); 18329 } 18330 } 18331 } 18332 18333 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18334 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18335 } 18336 18337 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18338 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18339 } 18340 18341 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18342 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18343 } 18344 18345 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18346 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18347 } 18348 18349 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18350 // XXX should handle packageName != null by dumping only install data that 18351 // the given package is involved with. 18352 if (dumpState.onTitlePrinted()) pw.println(); 18353 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18354 } 18355 18356 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18357 // XXX should handle packageName != null by dumping only install data that 18358 // the given package is involved with. 18359 if (dumpState.onTitlePrinted()) pw.println(); 18360 18361 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18362 ipw.println(); 18363 ipw.println("Frozen packages:"); 18364 ipw.increaseIndent(); 18365 if (mFrozenPackages.size() == 0) { 18366 ipw.println("(none)"); 18367 } else { 18368 for (int i = 0; i < mFrozenPackages.size(); i++) { 18369 ipw.println(mFrozenPackages.valueAt(i)); 18370 } 18371 } 18372 ipw.decreaseIndent(); 18373 } 18374 18375 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18376 if (dumpState.onTitlePrinted()) pw.println(); 18377 dumpDexoptStateLPr(pw, packageName); 18378 } 18379 18380 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18381 if (dumpState.onTitlePrinted()) pw.println(); 18382 mSettings.dumpReadMessagesLPr(pw, dumpState); 18383 18384 pw.println(); 18385 pw.println("Package warning messages:"); 18386 BufferedReader in = null; 18387 String line = null; 18388 try { 18389 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18390 while ((line = in.readLine()) != null) { 18391 if (line.contains("ignored: updated version")) continue; 18392 pw.println(line); 18393 } 18394 } catch (IOException ignored) { 18395 } finally { 18396 IoUtils.closeQuietly(in); 18397 } 18398 } 18399 18400 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18401 BufferedReader in = null; 18402 String line = null; 18403 try { 18404 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18405 while ((line = in.readLine()) != null) { 18406 if (line.contains("ignored: updated version")) continue; 18407 pw.print("msg,"); 18408 pw.println(line); 18409 } 18410 } catch (IOException ignored) { 18411 } finally { 18412 IoUtils.closeQuietly(in); 18413 } 18414 } 18415 } 18416 } 18417 18418 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18419 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18420 ipw.println(); 18421 ipw.println("Dexopt state:"); 18422 ipw.increaseIndent(); 18423 Collection<PackageParser.Package> packages = null; 18424 if (packageName != null) { 18425 PackageParser.Package targetPackage = mPackages.get(packageName); 18426 if (targetPackage != null) { 18427 packages = Collections.singletonList(targetPackage); 18428 } else { 18429 ipw.println("Unable to find package: " + packageName); 18430 return; 18431 } 18432 } else { 18433 packages = mPackages.values(); 18434 } 18435 18436 for (PackageParser.Package pkg : packages) { 18437 ipw.println("[" + pkg.packageName + "]"); 18438 ipw.increaseIndent(); 18439 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18440 ipw.decreaseIndent(); 18441 } 18442 } 18443 18444 private String dumpDomainString(String packageName) { 18445 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18446 .getList(); 18447 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18448 18449 ArraySet<String> result = new ArraySet<>(); 18450 if (iviList.size() > 0) { 18451 for (IntentFilterVerificationInfo ivi : iviList) { 18452 for (String host : ivi.getDomains()) { 18453 result.add(host); 18454 } 18455 } 18456 } 18457 if (filters != null && filters.size() > 0) { 18458 for (IntentFilter filter : filters) { 18459 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18460 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18461 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18462 result.addAll(filter.getHostsList()); 18463 } 18464 } 18465 } 18466 18467 StringBuilder sb = new StringBuilder(result.size() * 16); 18468 for (String domain : result) { 18469 if (sb.length() > 0) sb.append(" "); 18470 sb.append(domain); 18471 } 18472 return sb.toString(); 18473 } 18474 18475 // ------- apps on sdcard specific code ------- 18476 static final boolean DEBUG_SD_INSTALL = false; 18477 18478 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18479 18480 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18481 18482 private boolean mMediaMounted = false; 18483 18484 static String getEncryptKey() { 18485 try { 18486 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18487 SD_ENCRYPTION_KEYSTORE_NAME); 18488 if (sdEncKey == null) { 18489 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18490 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18491 if (sdEncKey == null) { 18492 Slog.e(TAG, "Failed to create encryption keys"); 18493 return null; 18494 } 18495 } 18496 return sdEncKey; 18497 } catch (NoSuchAlgorithmException nsae) { 18498 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18499 return null; 18500 } catch (IOException ioe) { 18501 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18502 return null; 18503 } 18504 } 18505 18506 /* 18507 * Update media status on PackageManager. 18508 */ 18509 @Override 18510 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18511 int callingUid = Binder.getCallingUid(); 18512 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18513 throw new SecurityException("Media status can only be updated by the system"); 18514 } 18515 // reader; this apparently protects mMediaMounted, but should probably 18516 // be a different lock in that case. 18517 synchronized (mPackages) { 18518 Log.i(TAG, "Updating external media status from " 18519 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18520 + (mediaStatus ? "mounted" : "unmounted")); 18521 if (DEBUG_SD_INSTALL) 18522 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18523 + ", mMediaMounted=" + mMediaMounted); 18524 if (mediaStatus == mMediaMounted) { 18525 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18526 : 0, -1); 18527 mHandler.sendMessage(msg); 18528 return; 18529 } 18530 mMediaMounted = mediaStatus; 18531 } 18532 // Queue up an async operation since the package installation may take a 18533 // little while. 18534 mHandler.post(new Runnable() { 18535 public void run() { 18536 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18537 } 18538 }); 18539 } 18540 18541 /** 18542 * Called by MountService when the initial ASECs to scan are available. 18543 * Should block until all the ASEC containers are finished being scanned. 18544 */ 18545 public void scanAvailableAsecs() { 18546 updateExternalMediaStatusInner(true, false, false); 18547 } 18548 18549 /* 18550 * Collect information of applications on external media, map them against 18551 * existing containers and update information based on current mount status. 18552 * Please note that we always have to report status if reportStatus has been 18553 * set to true especially when unloading packages. 18554 */ 18555 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18556 boolean externalStorage) { 18557 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18558 int[] uidArr = EmptyArray.INT; 18559 18560 final String[] list = PackageHelper.getSecureContainerList(); 18561 if (ArrayUtils.isEmpty(list)) { 18562 Log.i(TAG, "No secure containers found"); 18563 } else { 18564 // Process list of secure containers and categorize them 18565 // as active or stale based on their package internal state. 18566 18567 // reader 18568 synchronized (mPackages) { 18569 for (String cid : list) { 18570 // Leave stages untouched for now; installer service owns them 18571 if (PackageInstallerService.isStageName(cid)) continue; 18572 18573 if (DEBUG_SD_INSTALL) 18574 Log.i(TAG, "Processing container " + cid); 18575 String pkgName = getAsecPackageName(cid); 18576 if (pkgName == null) { 18577 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18578 continue; 18579 } 18580 if (DEBUG_SD_INSTALL) 18581 Log.i(TAG, "Looking for pkg : " + pkgName); 18582 18583 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18584 if (ps == null) { 18585 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18586 continue; 18587 } 18588 18589 /* 18590 * Skip packages that are not external if we're unmounting 18591 * external storage. 18592 */ 18593 if (externalStorage && !isMounted && !isExternal(ps)) { 18594 continue; 18595 } 18596 18597 final AsecInstallArgs args = new AsecInstallArgs(cid, 18598 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18599 // The package status is changed only if the code path 18600 // matches between settings and the container id. 18601 if (ps.codePathString != null 18602 && ps.codePathString.startsWith(args.getCodePath())) { 18603 if (DEBUG_SD_INSTALL) { 18604 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18605 + " at code path: " + ps.codePathString); 18606 } 18607 18608 // We do have a valid package installed on sdcard 18609 processCids.put(args, ps.codePathString); 18610 final int uid = ps.appId; 18611 if (uid != -1) { 18612 uidArr = ArrayUtils.appendInt(uidArr, uid); 18613 } 18614 } else { 18615 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18616 + ps.codePathString); 18617 } 18618 } 18619 } 18620 18621 Arrays.sort(uidArr); 18622 } 18623 18624 // Process packages with valid entries. 18625 if (isMounted) { 18626 if (DEBUG_SD_INSTALL) 18627 Log.i(TAG, "Loading packages"); 18628 loadMediaPackages(processCids, uidArr, externalStorage); 18629 startCleaningPackages(); 18630 mInstallerService.onSecureContainersAvailable(); 18631 } else { 18632 if (DEBUG_SD_INSTALL) 18633 Log.i(TAG, "Unloading packages"); 18634 unloadMediaPackages(processCids, uidArr, reportStatus); 18635 } 18636 } 18637 18638 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18639 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18640 final int size = infos.size(); 18641 final String[] packageNames = new String[size]; 18642 final int[] packageUids = new int[size]; 18643 for (int i = 0; i < size; i++) { 18644 final ApplicationInfo info = infos.get(i); 18645 packageNames[i] = info.packageName; 18646 packageUids[i] = info.uid; 18647 } 18648 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18649 finishedReceiver); 18650 } 18651 18652 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18653 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18654 sendResourcesChangedBroadcast(mediaStatus, replacing, 18655 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18656 } 18657 18658 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18659 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18660 int size = pkgList.length; 18661 if (size > 0) { 18662 // Send broadcasts here 18663 Bundle extras = new Bundle(); 18664 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18665 if (uidArr != null) { 18666 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18667 } 18668 if (replacing) { 18669 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18670 } 18671 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18672 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18673 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18674 } 18675 } 18676 18677 /* 18678 * Look at potentially valid container ids from processCids If package 18679 * information doesn't match the one on record or package scanning fails, 18680 * the cid is added to list of removeCids. We currently don't delete stale 18681 * containers. 18682 */ 18683 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18684 boolean externalStorage) { 18685 ArrayList<String> pkgList = new ArrayList<String>(); 18686 Set<AsecInstallArgs> keys = processCids.keySet(); 18687 18688 for (AsecInstallArgs args : keys) { 18689 String codePath = processCids.get(args); 18690 if (DEBUG_SD_INSTALL) 18691 Log.i(TAG, "Loading container : " + args.cid); 18692 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18693 try { 18694 // Make sure there are no container errors first. 18695 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18696 Slog.e(TAG, "Failed to mount cid : " + args.cid 18697 + " when installing from sdcard"); 18698 continue; 18699 } 18700 // Check code path here. 18701 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18702 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18703 + " does not match one in settings " + codePath); 18704 continue; 18705 } 18706 // Parse package 18707 int parseFlags = mDefParseFlags; 18708 if (args.isExternalAsec()) { 18709 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18710 } 18711 if (args.isFwdLocked()) { 18712 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18713 } 18714 18715 synchronized (mInstallLock) { 18716 PackageParser.Package pkg = null; 18717 try { 18718 // Sadly we don't know the package name yet to freeze it 18719 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18720 SCAN_IGNORE_FROZEN, 0, null); 18721 } catch (PackageManagerException e) { 18722 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18723 } 18724 // Scan the package 18725 if (pkg != null) { 18726 /* 18727 * TODO why is the lock being held? doPostInstall is 18728 * called in other places without the lock. This needs 18729 * to be straightened out. 18730 */ 18731 // writer 18732 synchronized (mPackages) { 18733 retCode = PackageManager.INSTALL_SUCCEEDED; 18734 pkgList.add(pkg.packageName); 18735 // Post process args 18736 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18737 pkg.applicationInfo.uid); 18738 } 18739 } else { 18740 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18741 } 18742 } 18743 18744 } finally { 18745 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18746 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18747 } 18748 } 18749 } 18750 // writer 18751 synchronized (mPackages) { 18752 // If the platform SDK has changed since the last time we booted, 18753 // we need to re-grant app permission to catch any new ones that 18754 // appear. This is really a hack, and means that apps can in some 18755 // cases get permissions that the user didn't initially explicitly 18756 // allow... it would be nice to have some better way to handle 18757 // this situation. 18758 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18759 : mSettings.getInternalVersion(); 18760 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18761 : StorageManager.UUID_PRIVATE_INTERNAL; 18762 18763 int updateFlags = UPDATE_PERMISSIONS_ALL; 18764 if (ver.sdkVersion != mSdkVersion) { 18765 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18766 + mSdkVersion + "; regranting permissions for external"); 18767 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18768 } 18769 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18770 18771 // Yay, everything is now upgraded 18772 ver.forceCurrent(); 18773 18774 // can downgrade to reader 18775 // Persist settings 18776 mSettings.writeLPr(); 18777 } 18778 // Send a broadcast to let everyone know we are done processing 18779 if (pkgList.size() > 0) { 18780 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18781 } 18782 } 18783 18784 /* 18785 * Utility method to unload a list of specified containers 18786 */ 18787 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18788 // Just unmount all valid containers. 18789 for (AsecInstallArgs arg : cidArgs) { 18790 synchronized (mInstallLock) { 18791 arg.doPostDeleteLI(false); 18792 } 18793 } 18794 } 18795 18796 /* 18797 * Unload packages mounted on external media. This involves deleting package 18798 * data from internal structures, sending broadcasts about disabled packages, 18799 * gc'ing to free up references, unmounting all secure containers 18800 * corresponding to packages on external media, and posting a 18801 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18802 * that we always have to post this message if status has been requested no 18803 * matter what. 18804 */ 18805 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18806 final boolean reportStatus) { 18807 if (DEBUG_SD_INSTALL) 18808 Log.i(TAG, "unloading media packages"); 18809 ArrayList<String> pkgList = new ArrayList<String>(); 18810 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18811 final Set<AsecInstallArgs> keys = processCids.keySet(); 18812 for (AsecInstallArgs args : keys) { 18813 String pkgName = args.getPackageName(); 18814 if (DEBUG_SD_INSTALL) 18815 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18816 // Delete package internally 18817 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18818 synchronized (mInstallLock) { 18819 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18820 final boolean res; 18821 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18822 "unloadMediaPackages")) { 18823 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18824 null); 18825 } 18826 if (res) { 18827 pkgList.add(pkgName); 18828 } else { 18829 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18830 failedList.add(args); 18831 } 18832 } 18833 } 18834 18835 // reader 18836 synchronized (mPackages) { 18837 // We didn't update the settings after removing each package; 18838 // write them now for all packages. 18839 mSettings.writeLPr(); 18840 } 18841 18842 // We have to absolutely send UPDATED_MEDIA_STATUS only 18843 // after confirming that all the receivers processed the ordered 18844 // broadcast when packages get disabled, force a gc to clean things up. 18845 // and unload all the containers. 18846 if (pkgList.size() > 0) { 18847 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18848 new IIntentReceiver.Stub() { 18849 public void performReceive(Intent intent, int resultCode, String data, 18850 Bundle extras, boolean ordered, boolean sticky, 18851 int sendingUser) throws RemoteException { 18852 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18853 reportStatus ? 1 : 0, 1, keys); 18854 mHandler.sendMessage(msg); 18855 } 18856 }); 18857 } else { 18858 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18859 keys); 18860 mHandler.sendMessage(msg); 18861 } 18862 } 18863 18864 private void loadPrivatePackages(final VolumeInfo vol) { 18865 mHandler.post(new Runnable() { 18866 @Override 18867 public void run() { 18868 loadPrivatePackagesInner(vol); 18869 } 18870 }); 18871 } 18872 18873 private void loadPrivatePackagesInner(VolumeInfo vol) { 18874 final String volumeUuid = vol.fsUuid; 18875 if (TextUtils.isEmpty(volumeUuid)) { 18876 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18877 return; 18878 } 18879 18880 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18881 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18882 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18883 18884 final VersionInfo ver; 18885 final List<PackageSetting> packages; 18886 synchronized (mPackages) { 18887 ver = mSettings.findOrCreateVersion(volumeUuid); 18888 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18889 } 18890 18891 for (PackageSetting ps : packages) { 18892 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18893 synchronized (mInstallLock) { 18894 final PackageParser.Package pkg; 18895 try { 18896 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18897 loaded.add(pkg.applicationInfo); 18898 18899 } catch (PackageManagerException e) { 18900 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18901 } 18902 18903 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18904 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18905 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18906 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18907 } 18908 } 18909 } 18910 18911 // Reconcile app data for all started/unlocked users 18912 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18913 final UserManager um = mContext.getSystemService(UserManager.class); 18914 for (UserInfo user : um.getUsers()) { 18915 final int flags; 18916 if (um.isUserUnlockingOrUnlocked(user.id)) { 18917 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18918 } else if (um.isUserRunning(user.id)) { 18919 flags = StorageManager.FLAG_STORAGE_DE; 18920 } else { 18921 continue; 18922 } 18923 18924 try { 18925 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18926 synchronized (mInstallLock) { 18927 reconcileAppsDataLI(volumeUuid, user.id, flags); 18928 } 18929 } catch (IllegalStateException e) { 18930 // Device was probably ejected, and we'll process that event momentarily 18931 Slog.w(TAG, "Failed to prepare storage: " + e); 18932 } 18933 } 18934 18935 synchronized (mPackages) { 18936 int updateFlags = UPDATE_PERMISSIONS_ALL; 18937 if (ver.sdkVersion != mSdkVersion) { 18938 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18939 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18940 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18941 } 18942 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18943 18944 // Yay, everything is now upgraded 18945 ver.forceCurrent(); 18946 18947 mSettings.writeLPr(); 18948 } 18949 18950 for (PackageFreezer freezer : freezers) { 18951 freezer.close(); 18952 } 18953 18954 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18955 sendResourcesChangedBroadcast(true, false, loaded, null); 18956 } 18957 18958 private void unloadPrivatePackages(final VolumeInfo vol) { 18959 mHandler.post(new Runnable() { 18960 @Override 18961 public void run() { 18962 unloadPrivatePackagesInner(vol); 18963 } 18964 }); 18965 } 18966 18967 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18968 final String volumeUuid = vol.fsUuid; 18969 if (TextUtils.isEmpty(volumeUuid)) { 18970 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18971 return; 18972 } 18973 18974 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18975 synchronized (mInstallLock) { 18976 synchronized (mPackages) { 18977 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18978 for (PackageSetting ps : packages) { 18979 if (ps.pkg == null) continue; 18980 18981 final ApplicationInfo info = ps.pkg.applicationInfo; 18982 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18983 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18984 18985 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18986 "unloadPrivatePackagesInner")) { 18987 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18988 false, null)) { 18989 unloaded.add(info); 18990 } else { 18991 Slog.w(TAG, "Failed to unload " + ps.codePath); 18992 } 18993 } 18994 } 18995 18996 mSettings.writeLPr(); 18997 } 18998 } 18999 19000 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19001 sendResourcesChangedBroadcast(false, false, unloaded, null); 19002 } 19003 19004 /** 19005 * Prepare storage areas for given user on all mounted devices. 19006 */ 19007 void prepareUserData(int userId, int userSerial, int flags) { 19008 synchronized (mInstallLock) { 19009 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19010 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19011 final String volumeUuid = vol.getFsUuid(); 19012 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19013 } 19014 } 19015 } 19016 19017 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19018 boolean allowRecover) { 19019 // Prepare storage and verify that serial numbers are consistent; if 19020 // there's a mismatch we need to destroy to avoid leaking data 19021 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19022 try { 19023 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19024 19025 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19026 UserManagerService.enforceSerialNumber( 19027 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19028 } 19029 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19030 UserManagerService.enforceSerialNumber( 19031 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19032 } 19033 19034 synchronized (mInstallLock) { 19035 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19036 } 19037 } catch (Exception e) { 19038 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19039 + " because we failed to prepare: " + e); 19040 destroyUserDataLI(volumeUuid, userId, 19041 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19042 19043 if (allowRecover) { 19044 // Try one last time; if we fail again we're really in trouble 19045 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19046 } 19047 } 19048 } 19049 19050 /** 19051 * Destroy storage areas for given user on all mounted devices. 19052 */ 19053 void destroyUserData(int userId, int flags) { 19054 synchronized (mInstallLock) { 19055 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19056 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19057 final String volumeUuid = vol.getFsUuid(); 19058 destroyUserDataLI(volumeUuid, userId, flags); 19059 } 19060 } 19061 } 19062 19063 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19064 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19065 try { 19066 // Clean up app data, profile data, and media data 19067 mInstaller.destroyUserData(volumeUuid, userId, flags); 19068 19069 // Clean up system data 19070 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19071 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19072 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19073 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19074 } 19075 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19076 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19077 } 19078 } 19079 19080 // Data with special labels is now gone, so finish the job 19081 storage.destroyUserStorage(volumeUuid, userId, flags); 19082 19083 } catch (Exception e) { 19084 logCriticalInfo(Log.WARN, 19085 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19086 } 19087 } 19088 19089 /** 19090 * Examine all users present on given mounted volume, and destroy data 19091 * belonging to users that are no longer valid, or whose user ID has been 19092 * recycled. 19093 */ 19094 private void reconcileUsers(String volumeUuid) { 19095 final List<File> files = new ArrayList<>(); 19096 Collections.addAll(files, FileUtils 19097 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19098 Collections.addAll(files, FileUtils 19099 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19100 for (File file : files) { 19101 if (!file.isDirectory()) continue; 19102 19103 final int userId; 19104 final UserInfo info; 19105 try { 19106 userId = Integer.parseInt(file.getName()); 19107 info = sUserManager.getUserInfo(userId); 19108 } catch (NumberFormatException e) { 19109 Slog.w(TAG, "Invalid user directory " + file); 19110 continue; 19111 } 19112 19113 boolean destroyUser = false; 19114 if (info == null) { 19115 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19116 + " because no matching user was found"); 19117 destroyUser = true; 19118 } else if (!mOnlyCore) { 19119 try { 19120 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19121 } catch (IOException e) { 19122 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19123 + " because we failed to enforce serial number: " + e); 19124 destroyUser = true; 19125 } 19126 } 19127 19128 if (destroyUser) { 19129 synchronized (mInstallLock) { 19130 destroyUserDataLI(volumeUuid, userId, 19131 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19132 } 19133 } 19134 } 19135 } 19136 19137 private void assertPackageKnown(String volumeUuid, String packageName) 19138 throws PackageManagerException { 19139 synchronized (mPackages) { 19140 final PackageSetting ps = mSettings.mPackages.get(packageName); 19141 if (ps == null) { 19142 throw new PackageManagerException("Package " + packageName + " is unknown"); 19143 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19144 throw new PackageManagerException( 19145 "Package " + packageName + " found on unknown volume " + volumeUuid 19146 + "; expected volume " + ps.volumeUuid); 19147 } 19148 } 19149 } 19150 19151 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19152 throws PackageManagerException { 19153 synchronized (mPackages) { 19154 final PackageSetting ps = mSettings.mPackages.get(packageName); 19155 if (ps == null) { 19156 throw new PackageManagerException("Package " + packageName + " is unknown"); 19157 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19158 throw new PackageManagerException( 19159 "Package " + packageName + " found on unknown volume " + volumeUuid 19160 + "; expected volume " + ps.volumeUuid); 19161 } else if (!ps.getInstalled(userId)) { 19162 throw new PackageManagerException( 19163 "Package " + packageName + " not installed for user " + userId); 19164 } 19165 } 19166 } 19167 19168 /** 19169 * Examine all apps present on given mounted volume, and destroy apps that 19170 * aren't expected, either due to uninstallation or reinstallation on 19171 * another volume. 19172 */ 19173 private void reconcileApps(String volumeUuid) { 19174 final File[] files = FileUtils 19175 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19176 for (File file : files) { 19177 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19178 && !PackageInstallerService.isStageName(file.getName()); 19179 if (!isPackage) { 19180 // Ignore entries which are not packages 19181 continue; 19182 } 19183 19184 try { 19185 final PackageLite pkg = PackageParser.parsePackageLite(file, 19186 PackageParser.PARSE_MUST_BE_APK); 19187 assertPackageKnown(volumeUuid, pkg.packageName); 19188 19189 } catch (PackageParserException | PackageManagerException e) { 19190 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19191 synchronized (mInstallLock) { 19192 removeCodePathLI(file); 19193 } 19194 } 19195 } 19196 } 19197 19198 /** 19199 * Reconcile all app data for the given user. 19200 * <p> 19201 * Verifies that directories exist and that ownership and labeling is 19202 * correct for all installed apps on all mounted volumes. 19203 */ 19204 void reconcileAppsData(int userId, int flags) { 19205 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19206 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19207 final String volumeUuid = vol.getFsUuid(); 19208 synchronized (mInstallLock) { 19209 reconcileAppsDataLI(volumeUuid, userId, flags); 19210 } 19211 } 19212 } 19213 19214 /** 19215 * Reconcile all app data on given mounted volume. 19216 * <p> 19217 * Destroys app data that isn't expected, either due to uninstallation or 19218 * reinstallation on another volume. 19219 * <p> 19220 * Verifies that directories exist and that ownership and labeling is 19221 * correct for all installed apps. 19222 */ 19223 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19224 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19225 + Integer.toHexString(flags)); 19226 19227 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19228 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19229 19230 boolean restoreconNeeded = false; 19231 19232 // First look for stale data that doesn't belong, and check if things 19233 // have changed since we did our last restorecon 19234 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19235 if (StorageManager.isFileEncryptedNativeOrEmulated() 19236 && !StorageManager.isUserKeyUnlocked(userId)) { 19237 throw new RuntimeException( 19238 "Yikes, someone asked us to reconcile CE storage while " + userId 19239 + " was still locked; this would have caused massive data loss!"); 19240 } 19241 19242 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19243 19244 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19245 for (File file : files) { 19246 final String packageName = file.getName(); 19247 try { 19248 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19249 } catch (PackageManagerException e) { 19250 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19251 try { 19252 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19253 StorageManager.FLAG_STORAGE_CE, 0); 19254 } catch (InstallerException e2) { 19255 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19256 } 19257 } 19258 } 19259 } 19260 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19261 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19262 19263 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19264 for (File file : files) { 19265 final String packageName = file.getName(); 19266 try { 19267 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19268 } catch (PackageManagerException e) { 19269 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19270 try { 19271 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19272 StorageManager.FLAG_STORAGE_DE, 0); 19273 } catch (InstallerException e2) { 19274 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19275 } 19276 } 19277 } 19278 } 19279 19280 // Ensure that data directories are ready to roll for all packages 19281 // installed for this volume and user 19282 final List<PackageSetting> packages; 19283 synchronized (mPackages) { 19284 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19285 } 19286 int preparedCount = 0; 19287 for (PackageSetting ps : packages) { 19288 final String packageName = ps.name; 19289 if (ps.pkg == null) { 19290 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19291 // TODO: might be due to legacy ASEC apps; we should circle back 19292 // and reconcile again once they're scanned 19293 continue; 19294 } 19295 19296 if (ps.getInstalled(userId)) { 19297 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19298 19299 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19300 // We may have just shuffled around app data directories, so 19301 // prepare them one more time 19302 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19303 } 19304 19305 preparedCount++; 19306 } 19307 } 19308 19309 if (restoreconNeeded) { 19310 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19311 SELinuxMMAC.setRestoreconDone(ceDir); 19312 } 19313 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19314 SELinuxMMAC.setRestoreconDone(deDir); 19315 } 19316 } 19317 19318 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19319 + " packages; restoreconNeeded was " + restoreconNeeded); 19320 } 19321 19322 /** 19323 * Prepare app data for the given app just after it was installed or 19324 * upgraded. This method carefully only touches users that it's installed 19325 * for, and it forces a restorecon to handle any seinfo changes. 19326 * <p> 19327 * Verifies that directories exist and that ownership and labeling is 19328 * correct for all installed apps. If there is an ownership mismatch, it 19329 * will try recovering system apps by wiping data; third-party app data is 19330 * left intact. 19331 * <p> 19332 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19333 */ 19334 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19335 final PackageSetting ps; 19336 synchronized (mPackages) { 19337 ps = mSettings.mPackages.get(pkg.packageName); 19338 mSettings.writeKernelMappingLPr(ps); 19339 } 19340 19341 final UserManager um = mContext.getSystemService(UserManager.class); 19342 for (UserInfo user : um.getUsers()) { 19343 final int flags; 19344 if (um.isUserUnlockingOrUnlocked(user.id)) { 19345 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19346 } else if (um.isUserRunning(user.id)) { 19347 flags = StorageManager.FLAG_STORAGE_DE; 19348 } else { 19349 continue; 19350 } 19351 19352 if (ps.getInstalled(user.id)) { 19353 // Whenever an app changes, force a restorecon of its data 19354 // TODO: when user data is locked, mark that we're still dirty 19355 prepareAppDataLIF(pkg, user.id, flags, true); 19356 } 19357 } 19358 } 19359 19360 /** 19361 * Prepare app data for the given app. 19362 * <p> 19363 * Verifies that directories exist and that ownership and labeling is 19364 * correct for all installed apps. If there is an ownership mismatch, this 19365 * will try recovering system apps by wiping data; third-party app data is 19366 * left intact. 19367 */ 19368 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19369 boolean restoreconNeeded) { 19370 if (pkg == null) { 19371 Slog.wtf(TAG, "Package was null!", new Throwable()); 19372 return; 19373 } 19374 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19375 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19376 for (int i = 0; i < childCount; i++) { 19377 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19378 } 19379 } 19380 19381 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19382 boolean restoreconNeeded) { 19383 if (DEBUG_APP_DATA) { 19384 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19385 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19386 } 19387 19388 final String volumeUuid = pkg.volumeUuid; 19389 final String packageName = pkg.packageName; 19390 final ApplicationInfo app = pkg.applicationInfo; 19391 final int appId = UserHandle.getAppId(app.uid); 19392 19393 Preconditions.checkNotNull(app.seinfo); 19394 19395 try { 19396 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19397 appId, app.seinfo, app.targetSdkVersion); 19398 } catch (InstallerException e) { 19399 if (app.isSystemApp()) { 19400 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19401 + ", but trying to recover: " + e); 19402 destroyAppDataLeafLIF(pkg, userId, flags); 19403 try { 19404 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19405 appId, app.seinfo, app.targetSdkVersion); 19406 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19407 } catch (InstallerException e2) { 19408 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19409 } 19410 } else { 19411 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19412 } 19413 } 19414 19415 if (restoreconNeeded) { 19416 try { 19417 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19418 app.seinfo); 19419 } catch (InstallerException e) { 19420 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19421 } 19422 } 19423 19424 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19425 try { 19426 // CE storage is unlocked right now, so read out the inode and 19427 // remember for use later when it's locked 19428 // TODO: mark this structure as dirty so we persist it! 19429 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19430 StorageManager.FLAG_STORAGE_CE); 19431 synchronized (mPackages) { 19432 final PackageSetting ps = mSettings.mPackages.get(packageName); 19433 if (ps != null) { 19434 ps.setCeDataInode(ceDataInode, userId); 19435 } 19436 } 19437 } catch (InstallerException e) { 19438 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19439 } 19440 } 19441 19442 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19443 } 19444 19445 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19446 if (pkg == null) { 19447 Slog.wtf(TAG, "Package was null!", new Throwable()); 19448 return; 19449 } 19450 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19451 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19452 for (int i = 0; i < childCount; i++) { 19453 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19454 } 19455 } 19456 19457 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19458 final String volumeUuid = pkg.volumeUuid; 19459 final String packageName = pkg.packageName; 19460 final ApplicationInfo app = pkg.applicationInfo; 19461 19462 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19463 // Create a native library symlink only if we have native libraries 19464 // and if the native libraries are 32 bit libraries. We do not provide 19465 // this symlink for 64 bit libraries. 19466 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19467 final String nativeLibPath = app.nativeLibraryDir; 19468 try { 19469 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19470 nativeLibPath, userId); 19471 } catch (InstallerException e) { 19472 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19473 } 19474 } 19475 } 19476 } 19477 19478 /** 19479 * For system apps on non-FBE devices, this method migrates any existing 19480 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19481 * requested by the app. 19482 */ 19483 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19484 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19485 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19486 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19487 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19488 try { 19489 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19490 storageTarget); 19491 } catch (InstallerException e) { 19492 logCriticalInfo(Log.WARN, 19493 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19494 } 19495 return true; 19496 } else { 19497 return false; 19498 } 19499 } 19500 19501 public PackageFreezer freezePackage(String packageName, String killReason) { 19502 return new PackageFreezer(packageName, killReason); 19503 } 19504 19505 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19506 String killReason) { 19507 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19508 return new PackageFreezer(); 19509 } else { 19510 return freezePackage(packageName, killReason); 19511 } 19512 } 19513 19514 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19515 String killReason) { 19516 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19517 return new PackageFreezer(); 19518 } else { 19519 return freezePackage(packageName, killReason); 19520 } 19521 } 19522 19523 /** 19524 * Class that freezes and kills the given package upon creation, and 19525 * unfreezes it upon closing. This is typically used when doing surgery on 19526 * app code/data to prevent the app from running while you're working. 19527 */ 19528 private class PackageFreezer implements AutoCloseable { 19529 private final String mPackageName; 19530 private final PackageFreezer[] mChildren; 19531 19532 private final boolean mWeFroze; 19533 19534 private final AtomicBoolean mClosed = new AtomicBoolean(); 19535 private final CloseGuard mCloseGuard = CloseGuard.get(); 19536 19537 /** 19538 * Create and return a stub freezer that doesn't actually do anything, 19539 * typically used when someone requested 19540 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19541 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19542 */ 19543 public PackageFreezer() { 19544 mPackageName = null; 19545 mChildren = null; 19546 mWeFroze = false; 19547 mCloseGuard.open("close"); 19548 } 19549 19550 public PackageFreezer(String packageName, String killReason) { 19551 synchronized (mPackages) { 19552 mPackageName = packageName; 19553 mWeFroze = mFrozenPackages.add(mPackageName); 19554 19555 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19556 if (ps != null) { 19557 killApplication(ps.name, ps.appId, killReason); 19558 } 19559 19560 final PackageParser.Package p = mPackages.get(packageName); 19561 if (p != null && p.childPackages != null) { 19562 final int N = p.childPackages.size(); 19563 mChildren = new PackageFreezer[N]; 19564 for (int i = 0; i < N; i++) { 19565 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19566 killReason); 19567 } 19568 } else { 19569 mChildren = null; 19570 } 19571 } 19572 mCloseGuard.open("close"); 19573 } 19574 19575 @Override 19576 protected void finalize() throws Throwable { 19577 try { 19578 mCloseGuard.warnIfOpen(); 19579 close(); 19580 } finally { 19581 super.finalize(); 19582 } 19583 } 19584 19585 @Override 19586 public void close() { 19587 mCloseGuard.close(); 19588 if (mClosed.compareAndSet(false, true)) { 19589 synchronized (mPackages) { 19590 if (mWeFroze) { 19591 mFrozenPackages.remove(mPackageName); 19592 } 19593 19594 if (mChildren != null) { 19595 for (PackageFreezer freezer : mChildren) { 19596 freezer.close(); 19597 } 19598 } 19599 } 19600 } 19601 } 19602 } 19603 19604 /** 19605 * Verify that given package is currently frozen. 19606 */ 19607 private void checkPackageFrozen(String packageName) { 19608 synchronized (mPackages) { 19609 if (!mFrozenPackages.contains(packageName)) { 19610 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19611 } 19612 } 19613 } 19614 19615 @Override 19616 public int movePackage(final String packageName, final String volumeUuid) { 19617 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19618 19619 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19620 final int moveId = mNextMoveId.getAndIncrement(); 19621 mHandler.post(new Runnable() { 19622 @Override 19623 public void run() { 19624 try { 19625 movePackageInternal(packageName, volumeUuid, moveId, user); 19626 } catch (PackageManagerException e) { 19627 Slog.w(TAG, "Failed to move " + packageName, e); 19628 mMoveCallbacks.notifyStatusChanged(moveId, 19629 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19630 } 19631 } 19632 }); 19633 return moveId; 19634 } 19635 19636 private void movePackageInternal(final String packageName, final String volumeUuid, 19637 final int moveId, UserHandle user) throws PackageManagerException { 19638 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19639 final PackageManager pm = mContext.getPackageManager(); 19640 19641 final boolean currentAsec; 19642 final String currentVolumeUuid; 19643 final File codeFile; 19644 final String installerPackageName; 19645 final String packageAbiOverride; 19646 final int appId; 19647 final String seinfo; 19648 final String label; 19649 final int targetSdkVersion; 19650 final PackageFreezer freezer; 19651 final int[] installedUserIds; 19652 19653 // reader 19654 synchronized (mPackages) { 19655 final PackageParser.Package pkg = mPackages.get(packageName); 19656 final PackageSetting ps = mSettings.mPackages.get(packageName); 19657 if (pkg == null || ps == null) { 19658 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19659 } 19660 19661 if (pkg.applicationInfo.isSystemApp()) { 19662 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19663 "Cannot move system application"); 19664 } 19665 19666 if (pkg.applicationInfo.isExternalAsec()) { 19667 currentAsec = true; 19668 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19669 } else if (pkg.applicationInfo.isForwardLocked()) { 19670 currentAsec = true; 19671 currentVolumeUuid = "forward_locked"; 19672 } else { 19673 currentAsec = false; 19674 currentVolumeUuid = ps.volumeUuid; 19675 19676 final File probe = new File(pkg.codePath); 19677 final File probeOat = new File(probe, "oat"); 19678 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19679 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19680 "Move only supported for modern cluster style installs"); 19681 } 19682 } 19683 19684 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19685 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19686 "Package already moved to " + volumeUuid); 19687 } 19688 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19689 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19690 "Device admin cannot be moved"); 19691 } 19692 19693 if (mFrozenPackages.contains(packageName)) { 19694 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19695 "Failed to move already frozen package"); 19696 } 19697 19698 codeFile = new File(pkg.codePath); 19699 installerPackageName = ps.installerPackageName; 19700 packageAbiOverride = ps.cpuAbiOverrideString; 19701 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19702 seinfo = pkg.applicationInfo.seinfo; 19703 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19704 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19705 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19706 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19707 } 19708 19709 final Bundle extras = new Bundle(); 19710 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19711 extras.putString(Intent.EXTRA_TITLE, label); 19712 mMoveCallbacks.notifyCreated(moveId, extras); 19713 19714 int installFlags; 19715 final boolean moveCompleteApp; 19716 final File measurePath; 19717 19718 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19719 installFlags = INSTALL_INTERNAL; 19720 moveCompleteApp = !currentAsec; 19721 measurePath = Environment.getDataAppDirectory(volumeUuid); 19722 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19723 installFlags = INSTALL_EXTERNAL; 19724 moveCompleteApp = false; 19725 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19726 } else { 19727 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19728 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19729 || !volume.isMountedWritable()) { 19730 freezer.close(); 19731 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19732 "Move location not mounted private volume"); 19733 } 19734 19735 Preconditions.checkState(!currentAsec); 19736 19737 installFlags = INSTALL_INTERNAL; 19738 moveCompleteApp = true; 19739 measurePath = Environment.getDataAppDirectory(volumeUuid); 19740 } 19741 19742 final PackageStats stats = new PackageStats(null, -1); 19743 synchronized (mInstaller) { 19744 for (int userId : installedUserIds) { 19745 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19746 freezer.close(); 19747 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19748 "Failed to measure package size"); 19749 } 19750 } 19751 } 19752 19753 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19754 + stats.dataSize); 19755 19756 final long startFreeBytes = measurePath.getFreeSpace(); 19757 final long sizeBytes; 19758 if (moveCompleteApp) { 19759 sizeBytes = stats.codeSize + stats.dataSize; 19760 } else { 19761 sizeBytes = stats.codeSize; 19762 } 19763 19764 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19765 freezer.close(); 19766 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19767 "Not enough free space to move"); 19768 } 19769 19770 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19771 19772 final CountDownLatch installedLatch = new CountDownLatch(1); 19773 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19774 @Override 19775 public void onUserActionRequired(Intent intent) throws RemoteException { 19776 throw new IllegalStateException(); 19777 } 19778 19779 @Override 19780 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19781 Bundle extras) throws RemoteException { 19782 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19783 + PackageManager.installStatusToString(returnCode, msg)); 19784 19785 installedLatch.countDown(); 19786 freezer.close(); 19787 19788 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19789 switch (status) { 19790 case PackageInstaller.STATUS_SUCCESS: 19791 mMoveCallbacks.notifyStatusChanged(moveId, 19792 PackageManager.MOVE_SUCCEEDED); 19793 break; 19794 case PackageInstaller.STATUS_FAILURE_STORAGE: 19795 mMoveCallbacks.notifyStatusChanged(moveId, 19796 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19797 break; 19798 default: 19799 mMoveCallbacks.notifyStatusChanged(moveId, 19800 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19801 break; 19802 } 19803 } 19804 }; 19805 19806 final MoveInfo move; 19807 if (moveCompleteApp) { 19808 // Kick off a thread to report progress estimates 19809 new Thread() { 19810 @Override 19811 public void run() { 19812 while (true) { 19813 try { 19814 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19815 break; 19816 } 19817 } catch (InterruptedException ignored) { 19818 } 19819 19820 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19821 final int progress = 10 + (int) MathUtils.constrain( 19822 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19823 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19824 } 19825 } 19826 }.start(); 19827 19828 final String dataAppName = codeFile.getName(); 19829 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19830 dataAppName, appId, seinfo, targetSdkVersion); 19831 } else { 19832 move = null; 19833 } 19834 19835 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19836 19837 final Message msg = mHandler.obtainMessage(INIT_COPY); 19838 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19839 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19840 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19841 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19842 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19843 msg.obj = params; 19844 19845 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19846 System.identityHashCode(msg.obj)); 19847 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19848 System.identityHashCode(msg.obj)); 19849 19850 mHandler.sendMessage(msg); 19851 } 19852 19853 @Override 19854 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19855 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19856 19857 final int realMoveId = mNextMoveId.getAndIncrement(); 19858 final Bundle extras = new Bundle(); 19859 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19860 mMoveCallbacks.notifyCreated(realMoveId, extras); 19861 19862 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19863 @Override 19864 public void onCreated(int moveId, Bundle extras) { 19865 // Ignored 19866 } 19867 19868 @Override 19869 public void onStatusChanged(int moveId, int status, long estMillis) { 19870 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19871 } 19872 }; 19873 19874 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19875 storage.setPrimaryStorageUuid(volumeUuid, callback); 19876 return realMoveId; 19877 } 19878 19879 @Override 19880 public int getMoveStatus(int moveId) { 19881 mContext.enforceCallingOrSelfPermission( 19882 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19883 return mMoveCallbacks.mLastStatus.get(moveId); 19884 } 19885 19886 @Override 19887 public void registerMoveCallback(IPackageMoveObserver callback) { 19888 mContext.enforceCallingOrSelfPermission( 19889 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19890 mMoveCallbacks.register(callback); 19891 } 19892 19893 @Override 19894 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19895 mContext.enforceCallingOrSelfPermission( 19896 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19897 mMoveCallbacks.unregister(callback); 19898 } 19899 19900 @Override 19901 public boolean setInstallLocation(int loc) { 19902 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19903 null); 19904 if (getInstallLocation() == loc) { 19905 return true; 19906 } 19907 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19908 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19909 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19910 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19911 return true; 19912 } 19913 return false; 19914 } 19915 19916 @Override 19917 public int getInstallLocation() { 19918 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19919 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19920 PackageHelper.APP_INSTALL_AUTO); 19921 } 19922 19923 /** Called by UserManagerService */ 19924 void cleanUpUser(UserManagerService userManager, int userHandle) { 19925 synchronized (mPackages) { 19926 mDirtyUsers.remove(userHandle); 19927 mUserNeedsBadging.delete(userHandle); 19928 mSettings.removeUserLPw(userHandle); 19929 mPendingBroadcasts.remove(userHandle); 19930 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19931 removeUnusedPackagesLPw(userManager, userHandle); 19932 } 19933 } 19934 19935 /** 19936 * We're removing userHandle and would like to remove any downloaded packages 19937 * that are no longer in use by any other user. 19938 * @param userHandle the user being removed 19939 */ 19940 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19941 final boolean DEBUG_CLEAN_APKS = false; 19942 int [] users = userManager.getUserIds(); 19943 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19944 while (psit.hasNext()) { 19945 PackageSetting ps = psit.next(); 19946 if (ps.pkg == null) { 19947 continue; 19948 } 19949 final String packageName = ps.pkg.packageName; 19950 // Skip over if system app 19951 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19952 continue; 19953 } 19954 if (DEBUG_CLEAN_APKS) { 19955 Slog.i(TAG, "Checking package " + packageName); 19956 } 19957 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19958 if (keep) { 19959 if (DEBUG_CLEAN_APKS) { 19960 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19961 } 19962 } else { 19963 for (int i = 0; i < users.length; i++) { 19964 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19965 keep = true; 19966 if (DEBUG_CLEAN_APKS) { 19967 Slog.i(TAG, " Keeping package " + packageName + " for user " 19968 + users[i]); 19969 } 19970 break; 19971 } 19972 } 19973 } 19974 if (!keep) { 19975 if (DEBUG_CLEAN_APKS) { 19976 Slog.i(TAG, " Removing package " + packageName); 19977 } 19978 mHandler.post(new Runnable() { 19979 public void run() { 19980 deletePackageX(packageName, userHandle, 0); 19981 } //end run 19982 }); 19983 } 19984 } 19985 } 19986 19987 /** Called by UserManagerService */ 19988 void createNewUser(int userHandle) { 19989 synchronized (mInstallLock) { 19990 mSettings.createNewUserLI(this, mInstaller, userHandle); 19991 } 19992 synchronized (mPackages) { 19993 applyFactoryDefaultBrowserLPw(userHandle); 19994 primeDomainVerificationsLPw(userHandle); 19995 } 19996 } 19997 19998 void newUserCreated(final int userHandle) { 19999 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20000 // If permission review for legacy apps is required, we represent 20001 // dagerous permissions for such apps as always granted runtime 20002 // permissions to keep per user flag state whether review is needed. 20003 // Hence, if a new user is added we have to propagate dangerous 20004 // permission grants for these legacy apps. 20005 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20006 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20007 | UPDATE_PERMISSIONS_REPLACE_ALL); 20008 } 20009 } 20010 20011 @Override 20012 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20013 mContext.enforceCallingOrSelfPermission( 20014 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20015 "Only package verification agents can read the verifier device identity"); 20016 20017 synchronized (mPackages) { 20018 return mSettings.getVerifierDeviceIdentityLPw(); 20019 } 20020 } 20021 20022 @Override 20023 public void setPermissionEnforced(String permission, boolean enforced) { 20024 // TODO: Now that we no longer change GID for storage, this should to away. 20025 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20026 "setPermissionEnforced"); 20027 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20028 synchronized (mPackages) { 20029 if (mSettings.mReadExternalStorageEnforced == null 20030 || mSettings.mReadExternalStorageEnforced != enforced) { 20031 mSettings.mReadExternalStorageEnforced = enforced; 20032 mSettings.writeLPr(); 20033 } 20034 } 20035 // kill any non-foreground processes so we restart them and 20036 // grant/revoke the GID. 20037 final IActivityManager am = ActivityManagerNative.getDefault(); 20038 if (am != null) { 20039 final long token = Binder.clearCallingIdentity(); 20040 try { 20041 am.killProcessesBelowForeground("setPermissionEnforcement"); 20042 } catch (RemoteException e) { 20043 } finally { 20044 Binder.restoreCallingIdentity(token); 20045 } 20046 } 20047 } else { 20048 throw new IllegalArgumentException("No selective enforcement for " + permission); 20049 } 20050 } 20051 20052 @Override 20053 @Deprecated 20054 public boolean isPermissionEnforced(String permission) { 20055 return true; 20056 } 20057 20058 @Override 20059 public boolean isStorageLow() { 20060 final long token = Binder.clearCallingIdentity(); 20061 try { 20062 final DeviceStorageMonitorInternal 20063 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20064 if (dsm != null) { 20065 return dsm.isMemoryLow(); 20066 } else { 20067 return false; 20068 } 20069 } finally { 20070 Binder.restoreCallingIdentity(token); 20071 } 20072 } 20073 20074 @Override 20075 public IPackageInstaller getPackageInstaller() { 20076 return mInstallerService; 20077 } 20078 20079 private boolean userNeedsBadging(int userId) { 20080 int index = mUserNeedsBadging.indexOfKey(userId); 20081 if (index < 0) { 20082 final UserInfo userInfo; 20083 final long token = Binder.clearCallingIdentity(); 20084 try { 20085 userInfo = sUserManager.getUserInfo(userId); 20086 } finally { 20087 Binder.restoreCallingIdentity(token); 20088 } 20089 final boolean b; 20090 if (userInfo != null && userInfo.isManagedProfile()) { 20091 b = true; 20092 } else { 20093 b = false; 20094 } 20095 mUserNeedsBadging.put(userId, b); 20096 return b; 20097 } 20098 return mUserNeedsBadging.valueAt(index); 20099 } 20100 20101 @Override 20102 public KeySet getKeySetByAlias(String packageName, String alias) { 20103 if (packageName == null || alias == null) { 20104 return null; 20105 } 20106 synchronized(mPackages) { 20107 final PackageParser.Package pkg = mPackages.get(packageName); 20108 if (pkg == null) { 20109 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20110 throw new IllegalArgumentException("Unknown package: " + packageName); 20111 } 20112 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20113 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20114 } 20115 } 20116 20117 @Override 20118 public KeySet getSigningKeySet(String packageName) { 20119 if (packageName == null) { 20120 return null; 20121 } 20122 synchronized(mPackages) { 20123 final PackageParser.Package pkg = mPackages.get(packageName); 20124 if (pkg == null) { 20125 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20126 throw new IllegalArgumentException("Unknown package: " + packageName); 20127 } 20128 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20129 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20130 throw new SecurityException("May not access signing KeySet of other apps."); 20131 } 20132 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20133 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20134 } 20135 } 20136 20137 @Override 20138 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20139 if (packageName == null || ks == null) { 20140 return false; 20141 } 20142 synchronized(mPackages) { 20143 final PackageParser.Package pkg = mPackages.get(packageName); 20144 if (pkg == null) { 20145 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20146 throw new IllegalArgumentException("Unknown package: " + packageName); 20147 } 20148 IBinder ksh = ks.getToken(); 20149 if (ksh instanceof KeySetHandle) { 20150 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20151 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20152 } 20153 return false; 20154 } 20155 } 20156 20157 @Override 20158 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20159 if (packageName == null || ks == null) { 20160 return false; 20161 } 20162 synchronized(mPackages) { 20163 final PackageParser.Package pkg = mPackages.get(packageName); 20164 if (pkg == null) { 20165 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20166 throw new IllegalArgumentException("Unknown package: " + packageName); 20167 } 20168 IBinder ksh = ks.getToken(); 20169 if (ksh instanceof KeySetHandle) { 20170 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20171 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20172 } 20173 return false; 20174 } 20175 } 20176 20177 private void deletePackageIfUnusedLPr(final String packageName) { 20178 PackageSetting ps = mSettings.mPackages.get(packageName); 20179 if (ps == null) { 20180 return; 20181 } 20182 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20183 // TODO Implement atomic delete if package is unused 20184 // It is currently possible that the package will be deleted even if it is installed 20185 // after this method returns. 20186 mHandler.post(new Runnable() { 20187 public void run() { 20188 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20189 } 20190 }); 20191 } 20192 } 20193 20194 /** 20195 * Check and throw if the given before/after packages would be considered a 20196 * downgrade. 20197 */ 20198 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20199 throws PackageManagerException { 20200 if (after.versionCode < before.mVersionCode) { 20201 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20202 "Update version code " + after.versionCode + " is older than current " 20203 + before.mVersionCode); 20204 } else if (after.versionCode == before.mVersionCode) { 20205 if (after.baseRevisionCode < before.baseRevisionCode) { 20206 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20207 "Update base revision code " + after.baseRevisionCode 20208 + " is older than current " + before.baseRevisionCode); 20209 } 20210 20211 if (!ArrayUtils.isEmpty(after.splitNames)) { 20212 for (int i = 0; i < after.splitNames.length; i++) { 20213 final String splitName = after.splitNames[i]; 20214 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20215 if (j != -1) { 20216 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20217 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20218 "Update split " + splitName + " revision code " 20219 + after.splitRevisionCodes[i] + " is older than current " 20220 + before.splitRevisionCodes[j]); 20221 } 20222 } 20223 } 20224 } 20225 } 20226 } 20227 20228 private static class MoveCallbacks extends Handler { 20229 private static final int MSG_CREATED = 1; 20230 private static final int MSG_STATUS_CHANGED = 2; 20231 20232 private final RemoteCallbackList<IPackageMoveObserver> 20233 mCallbacks = new RemoteCallbackList<>(); 20234 20235 private final SparseIntArray mLastStatus = new SparseIntArray(); 20236 20237 public MoveCallbacks(Looper looper) { 20238 super(looper); 20239 } 20240 20241 public void register(IPackageMoveObserver callback) { 20242 mCallbacks.register(callback); 20243 } 20244 20245 public void unregister(IPackageMoveObserver callback) { 20246 mCallbacks.unregister(callback); 20247 } 20248 20249 @Override 20250 public void handleMessage(Message msg) { 20251 final SomeArgs args = (SomeArgs) msg.obj; 20252 final int n = mCallbacks.beginBroadcast(); 20253 for (int i = 0; i < n; i++) { 20254 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20255 try { 20256 invokeCallback(callback, msg.what, args); 20257 } catch (RemoteException ignored) { 20258 } 20259 } 20260 mCallbacks.finishBroadcast(); 20261 args.recycle(); 20262 } 20263 20264 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20265 throws RemoteException { 20266 switch (what) { 20267 case MSG_CREATED: { 20268 callback.onCreated(args.argi1, (Bundle) args.arg2); 20269 break; 20270 } 20271 case MSG_STATUS_CHANGED: { 20272 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20273 break; 20274 } 20275 } 20276 } 20277 20278 private void notifyCreated(int moveId, Bundle extras) { 20279 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20280 20281 final SomeArgs args = SomeArgs.obtain(); 20282 args.argi1 = moveId; 20283 args.arg2 = extras; 20284 obtainMessage(MSG_CREATED, args).sendToTarget(); 20285 } 20286 20287 private void notifyStatusChanged(int moveId, int status) { 20288 notifyStatusChanged(moveId, status, -1); 20289 } 20290 20291 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20292 Slog.v(TAG, "Move " + moveId + " status " + status); 20293 20294 final SomeArgs args = SomeArgs.obtain(); 20295 args.argi1 = moveId; 20296 args.argi2 = status; 20297 args.arg3 = estMillis; 20298 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20299 20300 synchronized (mLastStatus) { 20301 mLastStatus.put(moveId, status); 20302 } 20303 } 20304 } 20305 20306 private final static class OnPermissionChangeListeners extends Handler { 20307 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20308 20309 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20310 new RemoteCallbackList<>(); 20311 20312 public OnPermissionChangeListeners(Looper looper) { 20313 super(looper); 20314 } 20315 20316 @Override 20317 public void handleMessage(Message msg) { 20318 switch (msg.what) { 20319 case MSG_ON_PERMISSIONS_CHANGED: { 20320 final int uid = msg.arg1; 20321 handleOnPermissionsChanged(uid); 20322 } break; 20323 } 20324 } 20325 20326 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20327 mPermissionListeners.register(listener); 20328 20329 } 20330 20331 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20332 mPermissionListeners.unregister(listener); 20333 } 20334 20335 public void onPermissionsChanged(int uid) { 20336 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20337 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20338 } 20339 } 20340 20341 private void handleOnPermissionsChanged(int uid) { 20342 final int count = mPermissionListeners.beginBroadcast(); 20343 try { 20344 for (int i = 0; i < count; i++) { 20345 IOnPermissionsChangeListener callback = mPermissionListeners 20346 .getBroadcastItem(i); 20347 try { 20348 callback.onPermissionsChanged(uid); 20349 } catch (RemoteException e) { 20350 Log.e(TAG, "Permission listener is dead", e); 20351 } 20352 } 20353 } finally { 20354 mPermissionListeners.finishBroadcast(); 20355 } 20356 } 20357 } 20358 20359 private class PackageManagerInternalImpl extends PackageManagerInternal { 20360 @Override 20361 public void setLocationPackagesProvider(PackagesProvider provider) { 20362 synchronized (mPackages) { 20363 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20364 } 20365 } 20366 20367 @Override 20368 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20369 synchronized (mPackages) { 20370 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20371 } 20372 } 20373 20374 @Override 20375 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20376 synchronized (mPackages) { 20377 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20378 } 20379 } 20380 20381 @Override 20382 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20383 synchronized (mPackages) { 20384 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20385 } 20386 } 20387 20388 @Override 20389 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20390 synchronized (mPackages) { 20391 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20392 } 20393 } 20394 20395 @Override 20396 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20397 synchronized (mPackages) { 20398 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20399 } 20400 } 20401 20402 @Override 20403 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20404 synchronized (mPackages) { 20405 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20406 packageName, userId); 20407 } 20408 } 20409 20410 @Override 20411 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20412 synchronized (mPackages) { 20413 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20414 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20415 packageName, userId); 20416 } 20417 } 20418 20419 @Override 20420 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20421 synchronized (mPackages) { 20422 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20423 packageName, userId); 20424 } 20425 } 20426 20427 @Override 20428 public void setKeepUninstalledPackages(final List<String> packageList) { 20429 Preconditions.checkNotNull(packageList); 20430 List<String> removedFromList = null; 20431 synchronized (mPackages) { 20432 if (mKeepUninstalledPackages != null) { 20433 final int packagesCount = mKeepUninstalledPackages.size(); 20434 for (int i = 0; i < packagesCount; i++) { 20435 String oldPackage = mKeepUninstalledPackages.get(i); 20436 if (packageList != null && packageList.contains(oldPackage)) { 20437 continue; 20438 } 20439 if (removedFromList == null) { 20440 removedFromList = new ArrayList<>(); 20441 } 20442 removedFromList.add(oldPackage); 20443 } 20444 } 20445 mKeepUninstalledPackages = new ArrayList<>(packageList); 20446 if (removedFromList != null) { 20447 final int removedCount = removedFromList.size(); 20448 for (int i = 0; i < removedCount; i++) { 20449 deletePackageIfUnusedLPr(removedFromList.get(i)); 20450 } 20451 } 20452 } 20453 } 20454 20455 @Override 20456 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20457 synchronized (mPackages) { 20458 // If we do not support permission review, done. 20459 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20460 return false; 20461 } 20462 20463 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20464 if (packageSetting == null) { 20465 return false; 20466 } 20467 20468 // Permission review applies only to apps not supporting the new permission model. 20469 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20470 return false; 20471 } 20472 20473 // Legacy apps have the permission and get user consent on launch. 20474 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20475 return permissionsState.isPermissionReviewRequired(userId); 20476 } 20477 } 20478 20479 @Override 20480 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20481 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20482 } 20483 20484 @Override 20485 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20486 int userId) { 20487 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20488 } 20489 } 20490 20491 @Override 20492 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20493 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20494 synchronized (mPackages) { 20495 final long identity = Binder.clearCallingIdentity(); 20496 try { 20497 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20498 packageNames, userId); 20499 } finally { 20500 Binder.restoreCallingIdentity(identity); 20501 } 20502 } 20503 } 20504 20505 private static void enforceSystemOrPhoneCaller(String tag) { 20506 int callingUid = Binder.getCallingUid(); 20507 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20508 throw new SecurityException( 20509 "Cannot call " + tag + " from UID " + callingUid); 20510 } 20511 } 20512 20513 boolean isHistoricalPackageUsageAvailable() { 20514 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20515 } 20516 20517 /** 20518 * Return a <b>copy</b> of the collection of packages known to the package manager. 20519 * @return A copy of the values of mPackages. 20520 */ 20521 Collection<PackageParser.Package> getPackages() { 20522 synchronized (mPackages) { 20523 return new ArrayList<>(mPackages.values()); 20524 } 20525 } 20526 20527 /** 20528 * Logs process start information (including base APK hash) to the security log. 20529 * @hide 20530 */ 20531 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20532 String apkFile, int pid) { 20533 if (!SecurityLog.isLoggingEnabled()) { 20534 return; 20535 } 20536 Bundle data = new Bundle(); 20537 data.putLong("startTimestamp", System.currentTimeMillis()); 20538 data.putString("processName", processName); 20539 data.putInt("uid", uid); 20540 data.putString("seinfo", seinfo); 20541 data.putString("apkFile", apkFile); 20542 data.putInt("pid", pid); 20543 Message msg = mProcessLoggingHandler.obtainMessage( 20544 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20545 msg.setData(data); 20546 mProcessLoggingHandler.sendMessage(msg); 20547 } 20548} 20549