PackageManagerService.java revision ac063d64ea133461338a1bf89f949bc5b3825565
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.ResourcesManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedInputStream; 268import java.io.BufferedOutputStream; 269import java.io.BufferedReader; 270import java.io.ByteArrayInputStream; 271import java.io.ByteArrayOutputStream; 272import java.io.File; 273import java.io.FileDescriptor; 274import java.io.FileInputStream; 275import java.io.FileNotFoundException; 276import java.io.FileOutputStream; 277import java.io.FileReader; 278import java.io.FilenameFilter; 279import java.io.IOException; 280import java.io.InputStream; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307import java.util.concurrent.atomic.AtomicLong; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = false; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 370 371 private static final boolean DISABLE_EPHEMERAL_APPS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 public static final int REASON_CORE_APP = 8; 508 509 public static final int REASON_LAST = REASON_CORE_APP; 510 511 /** Special library name that skips shared libraries check during compilation. */ 512 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 513 514 final ServiceThread mHandlerThread; 515 516 final PackageHandler mHandler; 517 518 private final ProcessLoggingHandler mProcessLoggingHandler; 519 520 /** 521 * Messages for {@link #mHandler} that need to wait for system ready before 522 * being dispatched. 523 */ 524 private ArrayList<Message> mPostSystemReadyMessages; 525 526 final int mSdkVersion = Build.VERSION.SDK_INT; 527 528 final Context mContext; 529 final boolean mFactoryTest; 530 final boolean mOnlyCore; 531 final DisplayMetrics mMetrics; 532 final int mDefParseFlags; 533 final String[] mSeparateProcesses; 534 final boolean mIsUpgrade; 535 final boolean mIsPreNUpgrade; 536 537 /** The location for ASEC container files on internal storage. */ 538 final String mAsecInternalPath; 539 540 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 541 // LOCK HELD. Can be called with mInstallLock held. 542 @GuardedBy("mInstallLock") 543 final Installer mInstaller; 544 545 /** Directory where installed third-party apps stored */ 546 final File mAppInstallDir; 547 final File mEphemeralInstallDir; 548 549 /** 550 * Directory to which applications installed internally have their 551 * 32 bit native libraries copied. 552 */ 553 private File mAppLib32InstallDir; 554 555 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 556 // apps. 557 final File mDrmAppPrivateInstallDir; 558 559 // ---------------------------------------------------------------- 560 561 // Lock for state used when installing and doing other long running 562 // operations. Methods that must be called with this lock held have 563 // the suffix "LI". 564 final Object mInstallLock = new Object(); 565 566 // ---------------------------------------------------------------- 567 568 // Keys are String (package name), values are Package. This also serves 569 // as the lock for the global state. Methods that must be called with 570 // this lock held have the prefix "LP". 571 @GuardedBy("mPackages") 572 final ArrayMap<String, PackageParser.Package> mPackages = 573 new ArrayMap<String, PackageParser.Package>(); 574 575 final ArrayMap<String, Set<String>> mKnownCodebase = 576 new ArrayMap<String, Set<String>>(); 577 578 // Tracks available target package names -> overlay package paths. 579 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 580 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 581 582 /** 583 * Tracks new system packages [received in an OTA] that we expect to 584 * find updated user-installed versions. Keys are package name, values 585 * are package location. 586 */ 587 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 588 /** 589 * Tracks high priority intent filters for protected actions. During boot, certain 590 * filter actions are protected and should never be allowed to have a high priority 591 * intent filter for them. However, there is one, and only one exception -- the 592 * setup wizard. It must be able to define a high priority intent filter for these 593 * actions to ensure there are no escapes from the wizard. We need to delay processing 594 * of these during boot as we need to look at all of the system packages in order 595 * to know which component is the setup wizard. 596 */ 597 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 598 /** 599 * Whether or not processing protected filters should be deferred. 600 */ 601 private boolean mDeferProtectedFilters = true; 602 603 /** 604 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 605 */ 606 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 607 /** 608 * Whether or not system app permissions should be promoted from install to runtime. 609 */ 610 boolean mPromoteSystemApps; 611 612 @GuardedBy("mPackages") 613 final Settings mSettings; 614 615 /** 616 * Set of package names that are currently "frozen", which means active 617 * surgery is being done on the code/data for that package. The platform 618 * will refuse to launch frozen packages to avoid race conditions. 619 * 620 * @see PackageFreezer 621 */ 622 @GuardedBy("mPackages") 623 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 624 625 boolean mRestoredSettings; 626 627 // System configuration read by SystemConfig. 628 final int[] mGlobalGids; 629 final SparseArray<ArraySet<String>> mSystemPermissions; 630 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 631 632 // If mac_permissions.xml was found for seinfo labeling. 633 boolean mFoundPolicyFile; 634 635 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 636 637 public static final class SharedLibraryEntry { 638 public final String path; 639 public final String apk; 640 641 SharedLibraryEntry(String _path, String _apk) { 642 path = _path; 643 apk = _apk; 644 } 645 } 646 647 // Currently known shared libraries. 648 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 649 new ArrayMap<String, SharedLibraryEntry>(); 650 651 // All available activities, for your resolving pleasure. 652 final ActivityIntentResolver mActivities = 653 new ActivityIntentResolver(); 654 655 // All available receivers, for your resolving pleasure. 656 final ActivityIntentResolver mReceivers = 657 new ActivityIntentResolver(); 658 659 // All available services, for your resolving pleasure. 660 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 661 662 // All available providers, for your resolving pleasure. 663 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 664 665 // Mapping from provider base names (first directory in content URI codePath) 666 // to the provider information. 667 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 668 new ArrayMap<String, PackageParser.Provider>(); 669 670 // Mapping from instrumentation class names to info about them. 671 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 672 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 673 674 // Mapping from permission names to info about them. 675 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 676 new ArrayMap<String, PackageParser.PermissionGroup>(); 677 678 // Packages whose data we have transfered into another package, thus 679 // should no longer exist. 680 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 681 682 // Broadcast actions that are only available to the system. 683 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 684 685 /** List of packages waiting for verification. */ 686 final SparseArray<PackageVerificationState> mPendingVerification 687 = new SparseArray<PackageVerificationState>(); 688 689 /** Set of packages associated with each app op permission. */ 690 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 691 692 final PackageInstallerService mInstallerService; 693 694 private final PackageDexOptimizer mPackageDexOptimizer; 695 696 private AtomicInteger mNextMoveId = new AtomicInteger(); 697 private final MoveCallbacks mMoveCallbacks; 698 699 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 700 701 // Cache of users who need badging. 702 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 703 704 /** Token for keys in mPendingVerification. */ 705 private int mPendingVerificationToken = 0; 706 707 volatile boolean mSystemReady; 708 volatile boolean mSafeMode; 709 volatile boolean mHasSystemUidErrors; 710 711 ApplicationInfo mAndroidApplication; 712 final ActivityInfo mResolveActivity = new ActivityInfo(); 713 final ResolveInfo mResolveInfo = new ResolveInfo(); 714 ComponentName mResolveComponentName; 715 PackageParser.Package mPlatformPackage; 716 ComponentName mCustomResolverComponentName; 717 718 boolean mResolverReplaced = false; 719 720 private final @Nullable ComponentName mIntentFilterVerifierComponent; 721 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 722 723 private int mIntentFilterVerificationToken = 0; 724 725 /** Component that knows whether or not an ephemeral application exists */ 726 final ComponentName mEphemeralResolverComponent; 727 /** The service connection to the ephemeral resolver */ 728 final EphemeralResolverConnection mEphemeralResolverConnection; 729 730 /** Component used to install ephemeral applications */ 731 final ComponentName mEphemeralInstallerComponent; 732 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 733 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 734 735 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 736 = new SparseArray<IntentFilterVerificationState>(); 737 738 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 739 new DefaultPermissionGrantPolicy(this); 740 741 // List of packages names to keep cached, even if they are uninstalled for all users 742 private List<String> mKeepUninstalledPackages; 743 744 private UserManagerInternal mUserManagerInternal; 745 746 private static class IFVerificationParams { 747 PackageParser.Package pkg; 748 boolean replacing; 749 int userId; 750 int verifierUid; 751 752 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 753 int _userId, int _verifierUid) { 754 pkg = _pkg; 755 replacing = _replacing; 756 userId = _userId; 757 replacing = _replacing; 758 verifierUid = _verifierUid; 759 } 760 } 761 762 private interface IntentFilterVerifier<T extends IntentFilter> { 763 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 764 T filter, String packageName); 765 void startVerifications(int userId); 766 void receiveVerificationResponse(int verificationId); 767 } 768 769 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 770 private Context mContext; 771 private ComponentName mIntentFilterVerifierComponent; 772 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 773 774 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 775 mContext = context; 776 mIntentFilterVerifierComponent = verifierComponent; 777 } 778 779 private String getDefaultScheme() { 780 return IntentFilter.SCHEME_HTTPS; 781 } 782 783 @Override 784 public void startVerifications(int userId) { 785 // Launch verifications requests 786 int count = mCurrentIntentFilterVerifications.size(); 787 for (int n=0; n<count; n++) { 788 int verificationId = mCurrentIntentFilterVerifications.get(n); 789 final IntentFilterVerificationState ivs = 790 mIntentFilterVerificationStates.get(verificationId); 791 792 String packageName = ivs.getPackageName(); 793 794 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 795 final int filterCount = filters.size(); 796 ArraySet<String> domainsSet = new ArraySet<>(); 797 for (int m=0; m<filterCount; m++) { 798 PackageParser.ActivityIntentInfo filter = filters.get(m); 799 domainsSet.addAll(filter.getHostsList()); 800 } 801 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 802 synchronized (mPackages) { 803 if (mSettings.createIntentFilterVerificationIfNeededLPw( 804 packageName, domainsList) != null) { 805 scheduleWriteSettingsLocked(); 806 } 807 } 808 sendVerificationRequest(userId, verificationId, ivs); 809 } 810 mCurrentIntentFilterVerifications.clear(); 811 } 812 813 private void sendVerificationRequest(int userId, int verificationId, 814 IntentFilterVerificationState ivs) { 815 816 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 819 verificationId); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 822 getDefaultScheme()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 825 ivs.getHostsString()); 826 verificationIntent.putExtra( 827 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 828 ivs.getPackageName()); 829 verificationIntent.setComponent(mIntentFilterVerifierComponent); 830 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 831 832 UserHandle user = new UserHandle(userId); 833 mContext.sendBroadcastAsUser(verificationIntent, user); 834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 835 "Sending IntentFilter verification broadcast"); 836 } 837 838 public void receiveVerificationResponse(int verificationId) { 839 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 840 841 final boolean verified = ivs.isVerified(); 842 843 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 844 final int count = filters.size(); 845 if (DEBUG_DOMAIN_VERIFICATION) { 846 Slog.i(TAG, "Received verification response " + verificationId 847 + " for " + count + " filters, verified=" + verified); 848 } 849 for (int n=0; n<count; n++) { 850 PackageParser.ActivityIntentInfo filter = filters.get(n); 851 filter.setVerified(verified); 852 853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 854 + " verified with result:" + verified + " and hosts:" 855 + ivs.getHostsString()); 856 } 857 858 mIntentFilterVerificationStates.remove(verificationId); 859 860 final String packageName = ivs.getPackageName(); 861 IntentFilterVerificationInfo ivi = null; 862 863 synchronized (mPackages) { 864 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 865 } 866 if (ivi == null) { 867 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 868 + verificationId + " packageName:" + packageName); 869 return; 870 } 871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 872 "Updating IntentFilterVerificationInfo for package " + packageName 873 +" verificationId:" + verificationId); 874 875 synchronized (mPackages) { 876 if (verified) { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 878 } else { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 880 } 881 scheduleWriteSettingsLocked(); 882 883 final int userId = ivs.getUserId(); 884 if (userId != UserHandle.USER_ALL) { 885 final int userStatus = 886 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 887 888 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 889 boolean needUpdate = false; 890 891 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 892 // already been set by the User thru the Disambiguation dialog 893 switch (userStatus) { 894 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 895 if (verified) { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 897 } else { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 899 } 900 needUpdate = true; 901 break; 902 903 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 904 if (verified) { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 906 needUpdate = true; 907 } 908 break; 909 910 default: 911 // Nothing to do 912 } 913 914 if (needUpdate) { 915 mSettings.updateIntentFilterVerificationStatusLPw( 916 packageName, updatedStatus, userId); 917 scheduleWritePackageRestrictionsLocked(userId); 918 } 919 } 920 } 921 } 922 923 @Override 924 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 925 ActivityIntentInfo filter, String packageName) { 926 if (!hasValidDomains(filter)) { 927 return false; 928 } 929 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 930 if (ivs == null) { 931 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 932 packageName); 933 } 934 if (DEBUG_DOMAIN_VERIFICATION) { 935 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 936 } 937 ivs.addFilter(filter); 938 return true; 939 } 940 941 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 942 int userId, int verificationId, String packageName) { 943 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 944 verifierUid, userId, packageName); 945 ivs.setPendingState(); 946 synchronized (mPackages) { 947 mIntentFilterVerificationStates.append(verificationId, ivs); 948 mCurrentIntentFilterVerifications.add(verificationId); 949 } 950 return ivs; 951 } 952 } 953 954 private static boolean hasValidDomains(ActivityIntentInfo filter) { 955 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 956 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 957 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 958 } 959 960 // Set of pending broadcasts for aggregating enable/disable of components. 961 static class PendingPackageBroadcasts { 962 // for each user id, a map of <package name -> components within that package> 963 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 964 965 public PendingPackageBroadcasts() { 966 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 967 } 968 969 public ArrayList<String> get(int userId, String packageName) { 970 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 971 return packages.get(packageName); 972 } 973 974 public void put(int userId, String packageName, ArrayList<String> components) { 975 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 976 packages.put(packageName, components); 977 } 978 979 public void remove(int userId, String packageName) { 980 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 981 if (packages != null) { 982 packages.remove(packageName); 983 } 984 } 985 986 public void remove(int userId) { 987 mUidMap.remove(userId); 988 } 989 990 public int userIdCount() { 991 return mUidMap.size(); 992 } 993 994 public int userIdAt(int n) { 995 return mUidMap.keyAt(n); 996 } 997 998 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 999 return mUidMap.get(userId); 1000 } 1001 1002 public int size() { 1003 // total number of pending broadcast entries across all userIds 1004 int num = 0; 1005 for (int i = 0; i< mUidMap.size(); i++) { 1006 num += mUidMap.valueAt(i).size(); 1007 } 1008 return num; 1009 } 1010 1011 public void clear() { 1012 mUidMap.clear(); 1013 } 1014 1015 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1016 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1017 if (map == null) { 1018 map = new ArrayMap<String, ArrayList<String>>(); 1019 mUidMap.put(userId, map); 1020 } 1021 return map; 1022 } 1023 } 1024 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1025 1026 // Service Connection to remote media container service to copy 1027 // package uri's from external media onto secure containers 1028 // or internal storage. 1029 private IMediaContainerService mContainerService = null; 1030 1031 static final int SEND_PENDING_BROADCAST = 1; 1032 static final int MCS_BOUND = 3; 1033 static final int END_COPY = 4; 1034 static final int INIT_COPY = 5; 1035 static final int MCS_UNBIND = 6; 1036 static final int START_CLEANING_PACKAGE = 7; 1037 static final int FIND_INSTALL_LOC = 8; 1038 static final int POST_INSTALL = 9; 1039 static final int MCS_RECONNECT = 10; 1040 static final int MCS_GIVE_UP = 11; 1041 static final int UPDATED_MEDIA_STATUS = 12; 1042 static final int WRITE_SETTINGS = 13; 1043 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1044 static final int PACKAGE_VERIFIED = 15; 1045 static final int CHECK_PENDING_VERIFICATION = 16; 1046 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1047 static final int INTENT_FILTER_VERIFIED = 18; 1048 static final int WRITE_PACKAGE_LIST = 19; 1049 1050 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1051 1052 // Delay time in millisecs 1053 static final int BROADCAST_DELAY = 10 * 1000; 1054 1055 static UserManagerService sUserManager; 1056 1057 // Stores a list of users whose package restrictions file needs to be updated 1058 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1059 1060 final private DefaultContainerConnection mDefContainerConn = 1061 new DefaultContainerConnection(); 1062 class DefaultContainerConnection implements ServiceConnection { 1063 public void onServiceConnected(ComponentName name, IBinder service) { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1065 IMediaContainerService imcs = 1066 IMediaContainerService.Stub.asInterface(service); 1067 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1068 } 1069 1070 public void onServiceDisconnected(ComponentName name) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1072 } 1073 } 1074 1075 // Recordkeeping of restore-after-install operations that are currently in flight 1076 // between the Package Manager and the Backup Manager 1077 static class PostInstallData { 1078 public InstallArgs args; 1079 public PackageInstalledInfo res; 1080 1081 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1082 args = _a; 1083 res = _r; 1084 } 1085 } 1086 1087 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1088 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1089 1090 // XML tags for backup/restore of various bits of state 1091 private static final String TAG_PREFERRED_BACKUP = "pa"; 1092 private static final String TAG_DEFAULT_APPS = "da"; 1093 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1094 1095 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1096 private static final String TAG_ALL_GRANTS = "rt-grants"; 1097 private static final String TAG_GRANT = "grant"; 1098 private static final String ATTR_PACKAGE_NAME = "pkg"; 1099 1100 private static final String TAG_PERMISSION = "perm"; 1101 private static final String ATTR_PERMISSION_NAME = "name"; 1102 private static final String ATTR_IS_GRANTED = "g"; 1103 private static final String ATTR_USER_SET = "set"; 1104 private static final String ATTR_USER_FIXED = "fixed"; 1105 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1106 1107 // System/policy permission grants are not backed up 1108 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1109 FLAG_PERMISSION_POLICY_FIXED 1110 | FLAG_PERMISSION_SYSTEM_FIXED 1111 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1112 1113 // And we back up these user-adjusted states 1114 private static final int USER_RUNTIME_GRANT_MASK = 1115 FLAG_PERMISSION_USER_SET 1116 | FLAG_PERMISSION_USER_FIXED 1117 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1118 1119 final @Nullable String mRequiredVerifierPackage; 1120 final @NonNull String mRequiredInstallerPackage; 1121 final @Nullable String mSetupWizardPackage; 1122 final @NonNull String mServicesSystemSharedLibraryPackageName; 1123 final @NonNull String mSharedSystemSharedLibraryPackageName; 1124 1125 private final PackageUsage mPackageUsage = new PackageUsage(); 1126 1127 private class PackageUsage { 1128 private static final int WRITE_INTERVAL 1129 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1130 1131 private final Object mFileLock = new Object(); 1132 private final AtomicLong mLastWritten = new AtomicLong(0); 1133 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1134 1135 private boolean mIsHistoricalPackageUsageAvailable = true; 1136 1137 boolean isHistoricalPackageUsageAvailable() { 1138 return mIsHistoricalPackageUsageAvailable; 1139 } 1140 1141 void write(boolean force) { 1142 if (force) { 1143 writeInternal(); 1144 return; 1145 } 1146 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1147 && !DEBUG_DEXOPT) { 1148 return; 1149 } 1150 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1151 new Thread("PackageUsage_DiskWriter") { 1152 @Override 1153 public void run() { 1154 try { 1155 writeInternal(); 1156 } finally { 1157 mBackgroundWriteRunning.set(false); 1158 } 1159 } 1160 }.start(); 1161 } 1162 } 1163 1164 private void writeInternal() { 1165 synchronized (mPackages) { 1166 synchronized (mFileLock) { 1167 AtomicFile file = getFile(); 1168 FileOutputStream f = null; 1169 try { 1170 f = file.startWrite(); 1171 BufferedOutputStream out = new BufferedOutputStream(f); 1172 FileUtils.setPermissions(file.getBaseFile().getPath(), 1173 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1174 StringBuilder sb = new StringBuilder(); 1175 1176 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1177 sb.append('\n'); 1178 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1179 1180 for (PackageParser.Package pkg : mPackages.values()) { 1181 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1182 continue; 1183 } 1184 sb.setLength(0); 1185 sb.append(pkg.packageName); 1186 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1187 sb.append(' '); 1188 sb.append(usageTimeInMillis); 1189 } 1190 sb.append('\n'); 1191 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1192 } 1193 out.flush(); 1194 file.finishWrite(f); 1195 } catch (IOException e) { 1196 if (f != null) { 1197 file.failWrite(f); 1198 } 1199 Log.e(TAG, "Failed to write package usage times", e); 1200 } 1201 } 1202 } 1203 mLastWritten.set(SystemClock.elapsedRealtime()); 1204 } 1205 1206 void readLP() { 1207 synchronized (mFileLock) { 1208 AtomicFile file = getFile(); 1209 BufferedInputStream in = null; 1210 try { 1211 in = new BufferedInputStream(file.openRead()); 1212 StringBuffer sb = new StringBuffer(); 1213 1214 String firstLine = readLine(in, sb); 1215 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1216 readVersion1LP(in, sb); 1217 } else { 1218 readVersion0LP(in, sb, firstLine); 1219 } 1220 } catch (FileNotFoundException expected) { 1221 mIsHistoricalPackageUsageAvailable = false; 1222 } catch (IOException e) { 1223 Log.w(TAG, "Failed to read package usage times", e); 1224 } finally { 1225 IoUtils.closeQuietly(in); 1226 } 1227 } 1228 mLastWritten.set(SystemClock.elapsedRealtime()); 1229 } 1230 1231 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1232 throws IOException { 1233 // Initial version of the file had no version number and stored one 1234 // package-timestamp pair per line. 1235 // Note that the first line has already been read from the InputStream. 1236 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1237 String[] tokens = line.split(" "); 1238 if (tokens.length != 2) { 1239 throw new IOException("Failed to parse " + line + 1240 " as package-timestamp pair."); 1241 } 1242 1243 String packageName = tokens[0]; 1244 PackageParser.Package pkg = mPackages.get(packageName); 1245 if (pkg == null) { 1246 continue; 1247 } 1248 1249 long timestamp = parseAsLong(tokens[1]); 1250 for (int reason = 0; 1251 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1252 reason++) { 1253 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1254 } 1255 } 1256 } 1257 1258 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1259 // Version 1 of the file started with the corresponding version 1260 // number and then stored a package name and eight timestamps per line. 1261 String line; 1262 while ((line = readLine(in, sb)) != null) { 1263 String[] tokens = line.split(" "); 1264 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1265 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1266 } 1267 1268 String packageName = tokens[0]; 1269 PackageParser.Package pkg = mPackages.get(packageName); 1270 if (pkg == null) { 1271 continue; 1272 } 1273 1274 for (int reason = 0; 1275 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1276 reason++) { 1277 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1278 } 1279 } 1280 } 1281 1282 private long parseAsLong(String token) throws IOException { 1283 try { 1284 return Long.parseLong(token); 1285 } catch (NumberFormatException e) { 1286 throw new IOException("Failed to parse " + token + " as a long.", e); 1287 } 1288 } 1289 1290 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1291 return readToken(in, sb, '\n'); 1292 } 1293 1294 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1295 throws IOException { 1296 sb.setLength(0); 1297 while (true) { 1298 int ch = in.read(); 1299 if (ch == -1) { 1300 if (sb.length() == 0) { 1301 return null; 1302 } 1303 throw new IOException("Unexpected EOF"); 1304 } 1305 if (ch == endOfToken) { 1306 return sb.toString(); 1307 } 1308 sb.append((char)ch); 1309 } 1310 } 1311 1312 private AtomicFile getFile() { 1313 File dataDir = Environment.getDataDirectory(); 1314 File systemDir = new File(dataDir, "system"); 1315 File fname = new File(systemDir, "package-usage.list"); 1316 return new AtomicFile(fname); 1317 } 1318 1319 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1320 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1321 } 1322 1323 class PackageHandler extends Handler { 1324 private boolean mBound = false; 1325 final ArrayList<HandlerParams> mPendingInstalls = 1326 new ArrayList<HandlerParams>(); 1327 1328 private boolean connectToService() { 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1330 " DefaultContainerService"); 1331 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1333 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1334 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 mBound = true; 1337 return true; 1338 } 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 return false; 1341 } 1342 1343 private void disconnectService() { 1344 mContainerService = null; 1345 mBound = false; 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1347 mContext.unbindService(mDefContainerConn); 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 } 1350 1351 PackageHandler(Looper looper) { 1352 super(looper); 1353 } 1354 1355 public void handleMessage(Message msg) { 1356 try { 1357 doHandleMessage(msg); 1358 } finally { 1359 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1360 } 1361 } 1362 1363 void doHandleMessage(Message msg) { 1364 switch (msg.what) { 1365 case INIT_COPY: { 1366 HandlerParams params = (HandlerParams) msg.obj; 1367 int idx = mPendingInstalls.size(); 1368 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1369 // If a bind was already initiated we dont really 1370 // need to do anything. The pending install 1371 // will be processed later on. 1372 if (!mBound) { 1373 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1374 System.identityHashCode(mHandler)); 1375 // If this is the only one pending we might 1376 // have to bind to the service again. 1377 if (!connectToService()) { 1378 Slog.e(TAG, "Failed to bind to media container service"); 1379 params.serviceError(); 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1381 System.identityHashCode(mHandler)); 1382 if (params.traceMethod != null) { 1383 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1384 params.traceCookie); 1385 } 1386 return; 1387 } else { 1388 // Once we bind to the service, the first 1389 // pending request will be processed. 1390 mPendingInstalls.add(idx, params); 1391 } 1392 } else { 1393 mPendingInstalls.add(idx, params); 1394 // Already bound to the service. Just make 1395 // sure we trigger off processing the first request. 1396 if (idx == 0) { 1397 mHandler.sendEmptyMessage(MCS_BOUND); 1398 } 1399 } 1400 break; 1401 } 1402 case MCS_BOUND: { 1403 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1404 if (msg.obj != null) { 1405 mContainerService = (IMediaContainerService) msg.obj; 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1407 System.identityHashCode(mHandler)); 1408 } 1409 if (mContainerService == null) { 1410 if (!mBound) { 1411 // Something seriously wrong since we are not bound and we are not 1412 // waiting for connection. Bail out. 1413 Slog.e(TAG, "Cannot bind to media container service"); 1414 for (HandlerParams params : mPendingInstalls) { 1415 // Indicate service bind error 1416 params.serviceError(); 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1418 System.identityHashCode(params)); 1419 if (params.traceMethod != null) { 1420 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1421 params.traceMethod, params.traceCookie); 1422 } 1423 return; 1424 } 1425 mPendingInstalls.clear(); 1426 } else { 1427 Slog.w(TAG, "Waiting to connect to media container service"); 1428 } 1429 } else if (mPendingInstalls.size() > 0) { 1430 HandlerParams params = mPendingInstalls.get(0); 1431 if (params != null) { 1432 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1433 System.identityHashCode(params)); 1434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1435 if (params.startCopy()) { 1436 // We are done... look for more work or to 1437 // go idle. 1438 if (DEBUG_SD_INSTALL) Log.i(TAG, 1439 "Checking for more work or unbind..."); 1440 // Delete pending install 1441 if (mPendingInstalls.size() > 0) { 1442 mPendingInstalls.remove(0); 1443 } 1444 if (mPendingInstalls.size() == 0) { 1445 if (mBound) { 1446 if (DEBUG_SD_INSTALL) Log.i(TAG, 1447 "Posting delayed MCS_UNBIND"); 1448 removeMessages(MCS_UNBIND); 1449 Message ubmsg = obtainMessage(MCS_UNBIND); 1450 // Unbind after a little delay, to avoid 1451 // continual thrashing. 1452 sendMessageDelayed(ubmsg, 10000); 1453 } 1454 } else { 1455 // There are more pending requests in queue. 1456 // Just post MCS_BOUND message to trigger processing 1457 // of next pending install. 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, 1459 "Posting MCS_BOUND for next work"); 1460 mHandler.sendEmptyMessage(MCS_BOUND); 1461 } 1462 } 1463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1464 } 1465 } else { 1466 // Should never happen ideally. 1467 Slog.w(TAG, "Empty queue"); 1468 } 1469 break; 1470 } 1471 case MCS_RECONNECT: { 1472 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1473 if (mPendingInstalls.size() > 0) { 1474 if (mBound) { 1475 disconnectService(); 1476 } 1477 if (!connectToService()) { 1478 Slog.e(TAG, "Failed to bind to media container service"); 1479 for (HandlerParams params : mPendingInstalls) { 1480 // Indicate service bind error 1481 params.serviceError(); 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1483 System.identityHashCode(params)); 1484 } 1485 mPendingInstalls.clear(); 1486 } 1487 } 1488 break; 1489 } 1490 case MCS_UNBIND: { 1491 // If there is no actual work left, then time to unbind. 1492 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1493 1494 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1495 if (mBound) { 1496 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1497 1498 disconnectService(); 1499 } 1500 } else if (mPendingInstalls.size() > 0) { 1501 // There are more pending requests in queue. 1502 // Just post MCS_BOUND message to trigger processing 1503 // of next pending install. 1504 mHandler.sendEmptyMessage(MCS_BOUND); 1505 } 1506 1507 break; 1508 } 1509 case MCS_GIVE_UP: { 1510 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1511 HandlerParams params = mPendingInstalls.remove(0); 1512 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1513 System.identityHashCode(params)); 1514 break; 1515 } 1516 case SEND_PENDING_BROADCAST: { 1517 String packages[]; 1518 ArrayList<String> components[]; 1519 int size = 0; 1520 int uids[]; 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1522 synchronized (mPackages) { 1523 if (mPendingBroadcasts == null) { 1524 return; 1525 } 1526 size = mPendingBroadcasts.size(); 1527 if (size <= 0) { 1528 // Nothing to be done. Just return 1529 return; 1530 } 1531 packages = new String[size]; 1532 components = new ArrayList[size]; 1533 uids = new int[size]; 1534 int i = 0; // filling out the above arrays 1535 1536 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1537 int packageUserId = mPendingBroadcasts.userIdAt(n); 1538 Iterator<Map.Entry<String, ArrayList<String>>> it 1539 = mPendingBroadcasts.packagesForUserId(packageUserId) 1540 .entrySet().iterator(); 1541 while (it.hasNext() && i < size) { 1542 Map.Entry<String, ArrayList<String>> ent = it.next(); 1543 packages[i] = ent.getKey(); 1544 components[i] = ent.getValue(); 1545 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1546 uids[i] = (ps != null) 1547 ? UserHandle.getUid(packageUserId, ps.appId) 1548 : -1; 1549 i++; 1550 } 1551 } 1552 size = i; 1553 mPendingBroadcasts.clear(); 1554 } 1555 // Send broadcasts 1556 for (int i = 0; i < size; i++) { 1557 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1558 } 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1560 break; 1561 } 1562 case START_CLEANING_PACKAGE: { 1563 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1564 final String packageName = (String)msg.obj; 1565 final int userId = msg.arg1; 1566 final boolean andCode = msg.arg2 != 0; 1567 synchronized (mPackages) { 1568 if (userId == UserHandle.USER_ALL) { 1569 int[] users = sUserManager.getUserIds(); 1570 for (int user : users) { 1571 mSettings.addPackageToCleanLPw( 1572 new PackageCleanItem(user, packageName, andCode)); 1573 } 1574 } else { 1575 mSettings.addPackageToCleanLPw( 1576 new PackageCleanItem(userId, packageName, andCode)); 1577 } 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 startCleaningPackages(); 1581 } break; 1582 case POST_INSTALL: { 1583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1584 1585 PostInstallData data = mRunningInstalls.get(msg.arg1); 1586 final boolean didRestore = (msg.arg2 != 0); 1587 mRunningInstalls.delete(msg.arg1); 1588 1589 if (data != null) { 1590 InstallArgs args = data.args; 1591 PackageInstalledInfo parentRes = data.res; 1592 1593 final boolean grantPermissions = (args.installFlags 1594 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1595 final boolean killApp = (args.installFlags 1596 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1597 final String[] grantedPermissions = args.installGrantPermissions; 1598 1599 // Handle the parent package 1600 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1601 grantedPermissions, didRestore, args.installerPackageName, 1602 args.observer); 1603 1604 // Handle the child packages 1605 final int childCount = (parentRes.addedChildPackages != null) 1606 ? parentRes.addedChildPackages.size() : 0; 1607 for (int i = 0; i < childCount; i++) { 1608 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1609 handlePackagePostInstall(childRes, grantPermissions, killApp, 1610 grantedPermissions, false, args.installerPackageName, 1611 args.observer); 1612 } 1613 1614 // Log tracing if needed 1615 if (args.traceMethod != null) { 1616 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1617 args.traceCookie); 1618 } 1619 } else { 1620 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1621 } 1622 1623 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1624 } break; 1625 case UPDATED_MEDIA_STATUS: { 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1627 boolean reportStatus = msg.arg1 == 1; 1628 boolean doGc = msg.arg2 == 1; 1629 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1630 if (doGc) { 1631 // Force a gc to clear up stale containers. 1632 Runtime.getRuntime().gc(); 1633 } 1634 if (msg.obj != null) { 1635 @SuppressWarnings("unchecked") 1636 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1638 // Unload containers 1639 unloadAllContainers(args); 1640 } 1641 if (reportStatus) { 1642 try { 1643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1644 PackageHelper.getMountService().finishMediaUpdate(); 1645 } catch (RemoteException e) { 1646 Log.e(TAG, "MountService not running?"); 1647 } 1648 } 1649 } break; 1650 case WRITE_SETTINGS: { 1651 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1652 synchronized (mPackages) { 1653 removeMessages(WRITE_SETTINGS); 1654 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1655 mSettings.writeLPr(); 1656 mDirtyUsers.clear(); 1657 } 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1659 } break; 1660 case WRITE_PACKAGE_RESTRICTIONS: { 1661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1662 synchronized (mPackages) { 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 for (int userId : mDirtyUsers) { 1665 mSettings.writePackageRestrictionsLPr(userId); 1666 } 1667 mDirtyUsers.clear(); 1668 } 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1670 } break; 1671 case WRITE_PACKAGE_LIST: { 1672 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1673 synchronized (mPackages) { 1674 removeMessages(WRITE_PACKAGE_LIST); 1675 mSettings.writePackageListLPr(msg.arg1); 1676 } 1677 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1678 } break; 1679 case CHECK_PENDING_VERIFICATION: { 1680 final int verificationId = msg.arg1; 1681 final PackageVerificationState state = mPendingVerification.get(verificationId); 1682 1683 if ((state != null) && !state.timeoutExtended()) { 1684 final InstallArgs args = state.getInstallArgs(); 1685 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1686 1687 Slog.i(TAG, "Verification timed out for " + originUri); 1688 mPendingVerification.remove(verificationId); 1689 1690 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1691 1692 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1693 Slog.i(TAG, "Continuing with installation of " + originUri); 1694 state.setVerifierResponse(Binder.getCallingUid(), 1695 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1696 broadcastPackageVerified(verificationId, originUri, 1697 PackageManager.VERIFICATION_ALLOW, 1698 state.getInstallArgs().getUser()); 1699 try { 1700 ret = args.copyApk(mContainerService, true); 1701 } catch (RemoteException e) { 1702 Slog.e(TAG, "Could not contact the ContainerService"); 1703 } 1704 } else { 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_REJECT, 1707 state.getInstallArgs().getUser()); 1708 } 1709 1710 Trace.asyncTraceEnd( 1711 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1712 1713 processPendingInstall(args, ret); 1714 mHandler.sendEmptyMessage(MCS_UNBIND); 1715 } 1716 break; 1717 } 1718 case PACKAGE_VERIFIED: { 1719 final int verificationId = msg.arg1; 1720 1721 final PackageVerificationState state = mPendingVerification.get(verificationId); 1722 if (state == null) { 1723 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1724 break; 1725 } 1726 1727 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1728 1729 state.setVerifierResponse(response.callerUid, response.code); 1730 1731 if (state.isVerificationComplete()) { 1732 mPendingVerification.remove(verificationId); 1733 1734 final InstallArgs args = state.getInstallArgs(); 1735 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1736 1737 int ret; 1738 if (state.isInstallAllowed()) { 1739 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1740 broadcastPackageVerified(verificationId, originUri, 1741 response.code, state.getInstallArgs().getUser()); 1742 try { 1743 ret = args.copyApk(mContainerService, true); 1744 } catch (RemoteException e) { 1745 Slog.e(TAG, "Could not contact the ContainerService"); 1746 } 1747 } else { 1748 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1749 } 1750 1751 Trace.asyncTraceEnd( 1752 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1753 1754 processPendingInstall(args, ret); 1755 mHandler.sendEmptyMessage(MCS_UNBIND); 1756 } 1757 1758 break; 1759 } 1760 case START_INTENT_FILTER_VERIFICATIONS: { 1761 IFVerificationParams params = (IFVerificationParams) msg.obj; 1762 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1763 params.replacing, params.pkg); 1764 break; 1765 } 1766 case INTENT_FILTER_VERIFIED: { 1767 final int verificationId = msg.arg1; 1768 1769 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1770 verificationId); 1771 if (state == null) { 1772 Slog.w(TAG, "Invalid IntentFilter verification token " 1773 + verificationId + " received"); 1774 break; 1775 } 1776 1777 final int userId = state.getUserId(); 1778 1779 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1780 "Processing IntentFilter verification with token:" 1781 + verificationId + " and userId:" + userId); 1782 1783 final IntentFilterVerificationResponse response = 1784 (IntentFilterVerificationResponse) msg.obj; 1785 1786 state.setVerifierResponse(response.callerUid, response.code); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "IntentFilter verification with token:" + verificationId 1790 + " and userId:" + userId 1791 + " is settings verifier response with response code:" 1792 + response.code); 1793 1794 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1795 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1796 + response.getFailedDomainsString()); 1797 } 1798 1799 if (state.isVerificationComplete()) { 1800 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1801 } else { 1802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1803 "IntentFilter verification with token:" + verificationId 1804 + " was not said to be complete"); 1805 } 1806 1807 break; 1808 } 1809 } 1810 } 1811 } 1812 1813 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1814 boolean killApp, String[] grantedPermissions, 1815 boolean launchedForRestore, String installerPackage, 1816 IPackageInstallObserver2 installObserver) { 1817 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1818 // Send the removed broadcasts 1819 if (res.removedInfo != null) { 1820 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1821 } 1822 1823 // Now that we successfully installed the package, grant runtime 1824 // permissions if requested before broadcasting the install. 1825 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1826 >= Build.VERSION_CODES.M) { 1827 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1828 } 1829 1830 final boolean update = res.removedInfo != null 1831 && res.removedInfo.removedPackage != null; 1832 1833 // If this is the first time we have child packages for a disabled privileged 1834 // app that had no children, we grant requested runtime permissions to the new 1835 // children if the parent on the system image had them already granted. 1836 if (res.pkg.parentPackage != null) { 1837 synchronized (mPackages) { 1838 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1839 } 1840 } 1841 1842 synchronized (mPackages) { 1843 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1844 } 1845 1846 final String packageName = res.pkg.applicationInfo.packageName; 1847 Bundle extras = new Bundle(1); 1848 extras.putInt(Intent.EXTRA_UID, res.uid); 1849 1850 // Determine the set of users who are adding this package for 1851 // the first time vs. those who are seeing an update. 1852 int[] firstUsers = EMPTY_INT_ARRAY; 1853 int[] updateUsers = EMPTY_INT_ARRAY; 1854 if (res.origUsers == null || res.origUsers.length == 0) { 1855 firstUsers = res.newUsers; 1856 } else { 1857 for (int newUser : res.newUsers) { 1858 boolean isNew = true; 1859 for (int origUser : res.origUsers) { 1860 if (origUser == newUser) { 1861 isNew = false; 1862 break; 1863 } 1864 } 1865 if (isNew) { 1866 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1867 } else { 1868 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1869 } 1870 } 1871 } 1872 1873 // Send installed broadcasts if the install/update is not ephemeral 1874 if (!isEphemeral(res.pkg)) { 1875 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1876 1877 // Send added for users that see the package for the first time 1878 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1879 extras, 0 /*flags*/, null /*targetPackage*/, 1880 null /*finishedReceiver*/, firstUsers); 1881 1882 // Send added for users that don't see the package for the first time 1883 if (update) { 1884 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1885 } 1886 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1887 extras, 0 /*flags*/, null /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 1890 // Send replaced for users that don't see the package for the first time 1891 if (update) { 1892 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1893 packageName, extras, 0 /*flags*/, 1894 null /*targetPackage*/, null /*finishedReceiver*/, 1895 updateUsers); 1896 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1897 null /*package*/, null /*extras*/, 0 /*flags*/, 1898 packageName /*targetPackage*/, 1899 null /*finishedReceiver*/, updateUsers); 1900 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1901 // First-install and we did a restore, so we're responsible for the 1902 // first-launch broadcast. 1903 if (DEBUG_BACKUP) { 1904 Slog.i(TAG, "Post-restore of " + packageName 1905 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1906 } 1907 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1908 } 1909 1910 // Send broadcast package appeared if forward locked/external for all users 1911 // treat asec-hosted packages like removable media on upgrade 1912 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1913 if (DEBUG_INSTALL) { 1914 Slog.i(TAG, "upgrading pkg " + res.pkg 1915 + " is ASEC-hosted -> AVAILABLE"); 1916 } 1917 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1918 ArrayList<String> pkgList = new ArrayList<>(1); 1919 pkgList.add(packageName); 1920 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1921 } 1922 } 1923 1924 // Work that needs to happen on first install within each user 1925 if (firstUsers != null && firstUsers.length > 0) { 1926 synchronized (mPackages) { 1927 for (int userId : firstUsers) { 1928 // If this app is a browser and it's newly-installed for some 1929 // users, clear any default-browser state in those users. The 1930 // app's nature doesn't depend on the user, so we can just check 1931 // its browser nature in any user and generalize. 1932 if (packageIsBrowser(packageName, userId)) { 1933 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1934 } 1935 1936 // We may also need to apply pending (restored) runtime 1937 // permission grants within these users. 1938 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1939 } 1940 } 1941 } 1942 1943 // Log current value of "unknown sources" setting 1944 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1945 getUnknownSourcesSettings()); 1946 1947 // Force a gc to clear up things 1948 Runtime.getRuntime().gc(); 1949 1950 // Remove the replaced package's older resources safely now 1951 // We delete after a gc for applications on sdcard. 1952 if (res.removedInfo != null && res.removedInfo.args != null) { 1953 synchronized (mInstallLock) { 1954 res.removedInfo.args.doPostDeleteLI(true); 1955 } 1956 } 1957 } 1958 1959 // If someone is watching installs - notify them 1960 if (installObserver != null) { 1961 try { 1962 Bundle extras = extrasForInstallResult(res); 1963 installObserver.onPackageInstalled(res.name, res.returnCode, 1964 res.returnMsg, extras); 1965 } catch (RemoteException e) { 1966 Slog.i(TAG, "Observer no longer exists."); 1967 } 1968 } 1969 } 1970 1971 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1972 PackageParser.Package pkg) { 1973 if (pkg.parentPackage == null) { 1974 return; 1975 } 1976 if (pkg.requestedPermissions == null) { 1977 return; 1978 } 1979 final PackageSetting disabledSysParentPs = mSettings 1980 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1981 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1982 || !disabledSysParentPs.isPrivileged() 1983 || (disabledSysParentPs.childPackageNames != null 1984 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1985 return; 1986 } 1987 final int[] allUserIds = sUserManager.getUserIds(); 1988 final int permCount = pkg.requestedPermissions.size(); 1989 for (int i = 0; i < permCount; i++) { 1990 String permission = pkg.requestedPermissions.get(i); 1991 BasePermission bp = mSettings.mPermissions.get(permission); 1992 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1993 continue; 1994 } 1995 for (int userId : allUserIds) { 1996 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1997 permission, userId)) { 1998 grantRuntimePermission(pkg.packageName, permission, userId); 1999 } 2000 } 2001 } 2002 } 2003 2004 private StorageEventListener mStorageListener = new StorageEventListener() { 2005 @Override 2006 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2007 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2008 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2009 final String volumeUuid = vol.getFsUuid(); 2010 2011 // Clean up any users or apps that were removed or recreated 2012 // while this volume was missing 2013 reconcileUsers(volumeUuid); 2014 reconcileApps(volumeUuid); 2015 2016 // Clean up any install sessions that expired or were 2017 // cancelled while this volume was missing 2018 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2019 2020 loadPrivatePackages(vol); 2021 2022 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2023 unloadPrivatePackages(vol); 2024 } 2025 } 2026 2027 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2028 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2029 updateExternalMediaStatus(true, false); 2030 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2031 updateExternalMediaStatus(false, false); 2032 } 2033 } 2034 } 2035 2036 @Override 2037 public void onVolumeForgotten(String fsUuid) { 2038 if (TextUtils.isEmpty(fsUuid)) { 2039 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2040 return; 2041 } 2042 2043 // Remove any apps installed on the forgotten volume 2044 synchronized (mPackages) { 2045 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2046 for (PackageSetting ps : packages) { 2047 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2048 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2049 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2050 } 2051 2052 mSettings.onVolumeForgotten(fsUuid); 2053 mSettings.writeLPr(); 2054 } 2055 } 2056 }; 2057 2058 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2059 String[] grantedPermissions) { 2060 for (int userId : userIds) { 2061 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2062 } 2063 2064 // We could have touched GID membership, so flush out packages.list 2065 synchronized (mPackages) { 2066 mSettings.writePackageListLPr(); 2067 } 2068 } 2069 2070 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2071 String[] grantedPermissions) { 2072 SettingBase sb = (SettingBase) pkg.mExtras; 2073 if (sb == null) { 2074 return; 2075 } 2076 2077 PermissionsState permissionsState = sb.getPermissionsState(); 2078 2079 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2080 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2081 2082 for (String permission : pkg.requestedPermissions) { 2083 final BasePermission bp; 2084 synchronized (mPackages) { 2085 bp = mSettings.mPermissions.get(permission); 2086 } 2087 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2088 && (grantedPermissions == null 2089 || ArrayUtils.contains(grantedPermissions, permission))) { 2090 final int flags = permissionsState.getPermissionFlags(permission, userId); 2091 // Installer cannot change immutable permissions. 2092 if ((flags & immutableFlags) == 0) { 2093 grantRuntimePermission(pkg.packageName, permission, userId); 2094 } 2095 } 2096 } 2097 } 2098 2099 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2100 Bundle extras = null; 2101 switch (res.returnCode) { 2102 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2103 extras = new Bundle(); 2104 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2105 res.origPermission); 2106 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2107 res.origPackage); 2108 break; 2109 } 2110 case PackageManager.INSTALL_SUCCEEDED: { 2111 extras = new Bundle(); 2112 extras.putBoolean(Intent.EXTRA_REPLACING, 2113 res.removedInfo != null && res.removedInfo.removedPackage != null); 2114 break; 2115 } 2116 } 2117 return extras; 2118 } 2119 2120 void scheduleWriteSettingsLocked() { 2121 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2122 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2123 } 2124 } 2125 2126 void scheduleWritePackageListLocked(int userId) { 2127 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2128 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2129 msg.arg1 = userId; 2130 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2131 } 2132 } 2133 2134 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2135 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2136 scheduleWritePackageRestrictionsLocked(userId); 2137 } 2138 2139 void scheduleWritePackageRestrictionsLocked(int userId) { 2140 final int[] userIds = (userId == UserHandle.USER_ALL) 2141 ? sUserManager.getUserIds() : new int[]{userId}; 2142 for (int nextUserId : userIds) { 2143 if (!sUserManager.exists(nextUserId)) return; 2144 mDirtyUsers.add(nextUserId); 2145 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2146 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2147 } 2148 } 2149 } 2150 2151 public static PackageManagerService main(Context context, Installer installer, 2152 boolean factoryTest, boolean onlyCore) { 2153 // Self-check for initial settings. 2154 PackageManagerServiceCompilerMapping.checkProperties(); 2155 2156 PackageManagerService m = new PackageManagerService(context, installer, 2157 factoryTest, onlyCore); 2158 m.enableSystemUserPackages(); 2159 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2160 // disabled after already being started. 2161 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2162 UserHandle.USER_SYSTEM); 2163 ServiceManager.addService("package", m); 2164 return m; 2165 } 2166 2167 private void enableSystemUserPackages() { 2168 if (!UserManager.isSplitSystemUser()) { 2169 return; 2170 } 2171 // For system user, enable apps based on the following conditions: 2172 // - app is whitelisted or belong to one of these groups: 2173 // -- system app which has no launcher icons 2174 // -- system app which has INTERACT_ACROSS_USERS permission 2175 // -- system IME app 2176 // - app is not in the blacklist 2177 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2178 Set<String> enableApps = new ArraySet<>(); 2179 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2180 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2181 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2182 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2183 enableApps.addAll(wlApps); 2184 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2185 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2186 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2187 enableApps.removeAll(blApps); 2188 Log.i(TAG, "Applications installed for system user: " + enableApps); 2189 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2190 UserHandle.SYSTEM); 2191 final int allAppsSize = allAps.size(); 2192 synchronized (mPackages) { 2193 for (int i = 0; i < allAppsSize; i++) { 2194 String pName = allAps.get(i); 2195 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2196 // Should not happen, but we shouldn't be failing if it does 2197 if (pkgSetting == null) { 2198 continue; 2199 } 2200 boolean install = enableApps.contains(pName); 2201 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2202 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2203 + " for system user"); 2204 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2205 } 2206 } 2207 } 2208 } 2209 2210 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2211 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2212 Context.DISPLAY_SERVICE); 2213 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2214 } 2215 2216 public PackageManagerService(Context context, Installer installer, 2217 boolean factoryTest, boolean onlyCore) { 2218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2219 SystemClock.uptimeMillis()); 2220 2221 if (mSdkVersion <= 0) { 2222 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2223 } 2224 2225 mContext = context; 2226 mFactoryTest = factoryTest; 2227 mOnlyCore = onlyCore; 2228 mMetrics = new DisplayMetrics(); 2229 mSettings = new Settings(mPackages); 2230 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2231 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2232 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 2243 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2244 if (separateProcesses != null && separateProcesses.length() > 0) { 2245 if ("*".equals(separateProcesses)) { 2246 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2247 mSeparateProcesses = null; 2248 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2249 } else { 2250 mDefParseFlags = 0; 2251 mSeparateProcesses = separateProcesses.split(","); 2252 Slog.w(TAG, "Running with debug.separate_processes: " 2253 + separateProcesses); 2254 } 2255 } else { 2256 mDefParseFlags = 0; 2257 mSeparateProcesses = null; 2258 } 2259 2260 mInstaller = installer; 2261 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2262 "*dexopt*"); 2263 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2264 2265 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2266 FgThread.get().getLooper()); 2267 2268 getDefaultDisplayMetrics(context, mMetrics); 2269 2270 SystemConfig systemConfig = SystemConfig.getInstance(); 2271 mGlobalGids = systemConfig.getGlobalGids(); 2272 mSystemPermissions = systemConfig.getSystemPermissions(); 2273 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2274 2275 synchronized (mInstallLock) { 2276 // writer 2277 synchronized (mPackages) { 2278 mHandlerThread = new ServiceThread(TAG, 2279 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2280 mHandlerThread.start(); 2281 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2282 mProcessLoggingHandler = new ProcessLoggingHandler(); 2283 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2284 2285 File dataDir = Environment.getDataDirectory(); 2286 mAppInstallDir = new File(dataDir, "app"); 2287 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2288 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2289 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2290 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2291 2292 sUserManager = new UserManagerService(context, this, mPackages); 2293 2294 // Propagate permission configuration in to package manager. 2295 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2296 = systemConfig.getPermissions(); 2297 for (int i=0; i<permConfig.size(); i++) { 2298 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2299 BasePermission bp = mSettings.mPermissions.get(perm.name); 2300 if (bp == null) { 2301 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2302 mSettings.mPermissions.put(perm.name, bp); 2303 } 2304 if (perm.gids != null) { 2305 bp.setGids(perm.gids, perm.perUser); 2306 } 2307 } 2308 2309 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2310 for (int i=0; i<libConfig.size(); i++) { 2311 mSharedLibraries.put(libConfig.keyAt(i), 2312 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2313 } 2314 2315 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2316 2317 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2318 2319 String customResolverActivity = Resources.getSystem().getString( 2320 R.string.config_customResolverActivity); 2321 if (TextUtils.isEmpty(customResolverActivity)) { 2322 customResolverActivity = null; 2323 } else { 2324 mCustomResolverComponentName = ComponentName.unflattenFromString( 2325 customResolverActivity); 2326 } 2327 2328 long startTime = SystemClock.uptimeMillis(); 2329 2330 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2331 startTime); 2332 2333 // Set flag to monitor and not change apk file paths when 2334 // scanning install directories. 2335 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2336 2337 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2338 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2339 2340 if (bootClassPath == null) { 2341 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2342 } 2343 2344 if (systemServerClassPath == null) { 2345 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2346 } 2347 2348 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2349 final String[] dexCodeInstructionSets = 2350 getDexCodeInstructionSets( 2351 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2352 2353 /** 2354 * Ensure all external libraries have had dexopt run on them. 2355 */ 2356 if (mSharedLibraries.size() > 0) { 2357 // NOTE: For now, we're compiling these system "shared libraries" 2358 // (and framework jars) into all available architectures. It's possible 2359 // to compile them only when we come across an app that uses them (there's 2360 // already logic for that in scanPackageLI) but that adds some complexity. 2361 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2362 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2363 final String lib = libEntry.path; 2364 if (lib == null) { 2365 continue; 2366 } 2367 2368 try { 2369 // Shared libraries do not have profiles so we perform a full 2370 // AOT compilation (if needed). 2371 int dexoptNeeded = DexFile.getDexOptNeeded( 2372 lib, dexCodeInstructionSet, 2373 getCompilerFilterForReason(REASON_SHARED_APK), 2374 false /* newProfile */); 2375 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2376 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2377 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2378 getCompilerFilterForReason(REASON_SHARED_APK), 2379 StorageManager.UUID_PRIVATE_INTERNAL, 2380 SKIP_SHARED_LIBRARY_CHECK); 2381 } 2382 } catch (FileNotFoundException e) { 2383 Slog.w(TAG, "Library not found: " + lib); 2384 } catch (IOException | InstallerException e) { 2385 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2386 + e.getMessage()); 2387 } 2388 } 2389 } 2390 } 2391 2392 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2393 2394 final VersionInfo ver = mSettings.getInternalVersion(); 2395 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2396 2397 // when upgrading from pre-M, promote system app permissions from install to runtime 2398 mPromoteSystemApps = 2399 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2400 2401 // When upgrading from pre-N, we need to handle package extraction like first boot, 2402 // as there is no profiling data available. 2403 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2404 2405 // save off the names of pre-existing system packages prior to scanning; we don't 2406 // want to automatically grant runtime permissions for new system apps 2407 if (mPromoteSystemApps) { 2408 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2409 while (pkgSettingIter.hasNext()) { 2410 PackageSetting ps = pkgSettingIter.next(); 2411 if (isSystemApp(ps)) { 2412 mExistingSystemPackages.add(ps.name); 2413 } 2414 } 2415 } 2416 2417 // Collect vendor overlay packages. 2418 // (Do this before scanning any apps.) 2419 // For security and version matching reason, only consider 2420 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2421 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2422 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR 2425 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2426 2427 // Find base frameworks (resource packages without code). 2428 scanDirTracedLI(frameworkDir, mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_IS_PRIVILEGED, 2432 scanFlags | SCAN_NO_DEX, 0); 2433 2434 // Collected privileged system packages. 2435 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2436 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2440 2441 // Collect ordinary system packages. 2442 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2443 scanDirTracedLI(systemAppDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2446 2447 // Collect all vendor packages. 2448 File vendorAppDir = new File("/vendor/app"); 2449 try { 2450 vendorAppDir = vendorAppDir.getCanonicalFile(); 2451 } catch (IOException e) { 2452 // failed to look up canonical path, continue with original one 2453 } 2454 scanDirTracedLI(vendorAppDir, mDefParseFlags 2455 | PackageParser.PARSE_IS_SYSTEM 2456 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2457 2458 // Collect all OEM packages. 2459 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2460 scanDirTracedLI(oemAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Prune any system packages that no longer exist. 2465 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2466 if (!mOnlyCore) { 2467 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2468 while (psit.hasNext()) { 2469 PackageSetting ps = psit.next(); 2470 2471 /* 2472 * If this is not a system app, it can't be a 2473 * disable system app. 2474 */ 2475 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2476 continue; 2477 } 2478 2479 /* 2480 * If the package is scanned, it's not erased. 2481 */ 2482 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2483 if (scannedPkg != null) { 2484 /* 2485 * If the system app is both scanned and in the 2486 * disabled packages list, then it must have been 2487 * added via OTA. Remove it from the currently 2488 * scanned package so the previously user-installed 2489 * application can be scanned. 2490 */ 2491 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2492 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2493 + ps.name + "; removing system app. Last known codePath=" 2494 + ps.codePathString + ", installStatus=" + ps.installStatus 2495 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2496 + scannedPkg.mVersionCode); 2497 removePackageLI(scannedPkg, true); 2498 mExpectingBetter.put(ps.name, ps.codePath); 2499 } 2500 2501 continue; 2502 } 2503 2504 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2505 psit.remove(); 2506 logCriticalInfo(Log.WARN, "System package " + ps.name 2507 + " no longer exists; it's data will be wiped"); 2508 // Actual deletion of code and data will be handled by later 2509 // reconciliation step 2510 } else { 2511 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2512 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2513 possiblyDeletedUpdatedSystemApps.add(ps.name); 2514 } 2515 } 2516 } 2517 } 2518 2519 //look for any incomplete package installations 2520 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2521 for (int i = 0; i < deletePkgsList.size(); i++) { 2522 // Actual deletion of code and data will be handled by later 2523 // reconciliation step 2524 final String packageName = deletePkgsList.get(i).name; 2525 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2526 synchronized (mPackages) { 2527 mSettings.removePackageLPw(packageName); 2528 } 2529 } 2530 2531 //delete tmp files 2532 deleteTempPackageFiles(); 2533 2534 // Remove any shared userIDs that have no associated packages 2535 mSettings.pruneSharedUsersLPw(); 2536 2537 if (!mOnlyCore) { 2538 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2539 SystemClock.uptimeMillis()); 2540 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2541 2542 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2543 | PackageParser.PARSE_FORWARD_LOCK, 2544 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2545 2546 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2547 | PackageParser.PARSE_IS_EPHEMERAL, 2548 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2549 2550 /** 2551 * Remove disable package settings for any updated system 2552 * apps that were removed via an OTA. If they're not a 2553 * previously-updated app, remove them completely. 2554 * Otherwise, just revoke their system-level permissions. 2555 */ 2556 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2557 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2558 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2559 2560 String msg; 2561 if (deletedPkg == null) { 2562 msg = "Updated system package " + deletedAppName 2563 + " no longer exists; it's data will be wiped"; 2564 // Actual deletion of code and data will be handled by later 2565 // reconciliation step 2566 } else { 2567 msg = "Updated system app + " + deletedAppName 2568 + " no longer present; removing system privileges for " 2569 + deletedAppName; 2570 2571 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2572 2573 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2574 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2575 } 2576 logCriticalInfo(Log.WARN, msg); 2577 } 2578 2579 /** 2580 * Make sure all system apps that we expected to appear on 2581 * the userdata partition actually showed up. If they never 2582 * appeared, crawl back and revive the system version. 2583 */ 2584 for (int i = 0; i < mExpectingBetter.size(); i++) { 2585 final String packageName = mExpectingBetter.keyAt(i); 2586 if (!mPackages.containsKey(packageName)) { 2587 final File scanFile = mExpectingBetter.valueAt(i); 2588 2589 logCriticalInfo(Log.WARN, "Expected better " + packageName 2590 + " but never showed up; reverting to system"); 2591 2592 int reparseFlags = mDefParseFlags; 2593 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2594 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2595 | PackageParser.PARSE_IS_SYSTEM_DIR 2596 | PackageParser.PARSE_IS_PRIVILEGED; 2597 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2598 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2599 | PackageParser.PARSE_IS_SYSTEM_DIR; 2600 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2601 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2602 | PackageParser.PARSE_IS_SYSTEM_DIR; 2603 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR; 2606 } else { 2607 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2608 continue; 2609 } 2610 2611 mSettings.enableSystemPackageLPw(packageName); 2612 2613 try { 2614 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2615 } catch (PackageManagerException e) { 2616 Slog.e(TAG, "Failed to parse original system package: " 2617 + e.getMessage()); 2618 } 2619 } 2620 } 2621 } 2622 mExpectingBetter.clear(); 2623 2624 // Resolve protected action filters. Only the setup wizard is allowed to 2625 // have a high priority filter for these actions. 2626 mSetupWizardPackage = getSetupWizardPackageName(); 2627 if (mProtectedFilters.size() > 0) { 2628 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2629 Slog.i(TAG, "No setup wizard;" 2630 + " All protected intents capped to priority 0"); 2631 } 2632 for (ActivityIntentInfo filter : mProtectedFilters) { 2633 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2634 if (DEBUG_FILTERS) { 2635 Slog.i(TAG, "Found setup wizard;" 2636 + " allow priority " + filter.getPriority() + ";" 2637 + " package: " + filter.activity.info.packageName 2638 + " activity: " + filter.activity.className 2639 + " priority: " + filter.getPriority()); 2640 } 2641 // skip setup wizard; allow it to keep the high priority filter 2642 continue; 2643 } 2644 Slog.w(TAG, "Protected action; cap priority to 0;" 2645 + " package: " + filter.activity.info.packageName 2646 + " activity: " + filter.activity.className 2647 + " origPrio: " + filter.getPriority()); 2648 filter.setPriority(0); 2649 } 2650 } 2651 mDeferProtectedFilters = false; 2652 mProtectedFilters.clear(); 2653 2654 // Now that we know all of the shared libraries, update all clients to have 2655 // the correct library paths. 2656 updateAllSharedLibrariesLPw(); 2657 2658 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2659 // NOTE: We ignore potential failures here during a system scan (like 2660 // the rest of the commands above) because there's precious little we 2661 // can do about it. A settings error is reported, though. 2662 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2663 false /* boot complete */); 2664 } 2665 2666 // Now that we know all the packages we are keeping, 2667 // read and update their last usage times. 2668 mPackageUsage.readLP(); 2669 2670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2671 SystemClock.uptimeMillis()); 2672 Slog.i(TAG, "Time to scan packages: " 2673 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2674 + " seconds"); 2675 2676 // If the platform SDK has changed since the last time we booted, 2677 // we need to re-grant app permission to catch any new ones that 2678 // appear. This is really a hack, and means that apps can in some 2679 // cases get permissions that the user didn't initially explicitly 2680 // allow... it would be nice to have some better way to handle 2681 // this situation. 2682 int updateFlags = UPDATE_PERMISSIONS_ALL; 2683 if (ver.sdkVersion != mSdkVersion) { 2684 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2685 + mSdkVersion + "; regranting permissions for internal storage"); 2686 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2687 } 2688 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2689 ver.sdkVersion = mSdkVersion; 2690 2691 // If this is the first boot or an update from pre-M, and it is a normal 2692 // boot, then we need to initialize the default preferred apps across 2693 // all defined users. 2694 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2695 for (UserInfo user : sUserManager.getUsers(true)) { 2696 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2697 applyFactoryDefaultBrowserLPw(user.id); 2698 primeDomainVerificationsLPw(user.id); 2699 } 2700 } 2701 2702 // Prepare storage for system user really early during boot, 2703 // since core system apps like SettingsProvider and SystemUI 2704 // can't wait for user to start 2705 final int storageFlags; 2706 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE; 2708 } else { 2709 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2710 } 2711 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2712 storageFlags); 2713 2714 // If this is first boot after an OTA, and a normal boot, then 2715 // we need to clear code cache directories. 2716 // Note that we do *not* clear the application profiles. These remain valid 2717 // across OTAs and are used to drive profile verification (post OTA) and 2718 // profile compilation (without waiting to collect a fresh set of profiles). 2719 if (mIsUpgrade && !onlyCore) { 2720 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2721 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2722 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2723 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2724 // No apps are running this early, so no need to freeze 2725 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2726 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2727 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2728 } 2729 } 2730 ver.fingerprint = Build.FINGERPRINT; 2731 } 2732 2733 checkDefaultBrowser(); 2734 2735 // clear only after permissions and other defaults have been updated 2736 mExistingSystemPackages.clear(); 2737 mPromoteSystemApps = false; 2738 2739 // All the changes are done during package scanning. 2740 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2741 2742 // can downgrade to reader 2743 mSettings.writeLPr(); 2744 2745 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2746 // early on (before the package manager declares itself as early) because other 2747 // components in the system server might ask for package contexts for these apps. 2748 // 2749 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2750 // (i.e, that the data partition is unavailable). 2751 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2752 long start = System.nanoTime(); 2753 List<PackageParser.Package> coreApps = new ArrayList<>(); 2754 for (PackageParser.Package pkg : mPackages.values()) { 2755 if (pkg.coreApp) { 2756 coreApps.add(pkg); 2757 } 2758 } 2759 2760 int[] stats = performDexOpt(coreApps, false, 2761 getCompilerFilterForReason(REASON_CORE_APP)); 2762 2763 final int elapsedTimeSeconds = 2764 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2765 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2766 2767 if (DEBUG_DEXOPT) { 2768 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2769 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2770 } 2771 2772 2773 // TODO: Should we log these stats to tron too ? 2774 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2775 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2776 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2777 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2778 } 2779 2780 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2781 SystemClock.uptimeMillis()); 2782 2783 if (!mOnlyCore) { 2784 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2785 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2786 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2787 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2788 mIntentFilterVerifierComponent); 2789 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2790 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2791 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2792 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2793 } else { 2794 mRequiredVerifierPackage = null; 2795 mRequiredInstallerPackage = null; 2796 mIntentFilterVerifierComponent = null; 2797 mIntentFilterVerifier = null; 2798 mServicesSystemSharedLibraryPackageName = null; 2799 mSharedSystemSharedLibraryPackageName = null; 2800 } 2801 2802 mInstallerService = new PackageInstallerService(context, this); 2803 2804 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2805 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2806 // both the installer and resolver must be present to enable ephemeral 2807 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2808 if (DEBUG_EPHEMERAL) { 2809 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2810 + " installer:" + ephemeralInstallerComponent); 2811 } 2812 mEphemeralResolverComponent = ephemeralResolverComponent; 2813 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2814 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2815 mEphemeralResolverConnection = 2816 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2817 } else { 2818 if (DEBUG_EPHEMERAL) { 2819 final String missingComponent = 2820 (ephemeralResolverComponent == null) 2821 ? (ephemeralInstallerComponent == null) 2822 ? "resolver and installer" 2823 : "resolver" 2824 : "installer"; 2825 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2826 } 2827 mEphemeralResolverComponent = null; 2828 mEphemeralInstallerComponent = null; 2829 mEphemeralResolverConnection = null; 2830 } 2831 2832 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2833 } // synchronized (mPackages) 2834 } // synchronized (mInstallLock) 2835 2836 // Now after opening every single application zip, make sure they 2837 // are all flushed. Not really needed, but keeps things nice and 2838 // tidy. 2839 Runtime.getRuntime().gc(); 2840 2841 // The initial scanning above does many calls into installd while 2842 // holding the mPackages lock, but we're mostly interested in yelling 2843 // once we have a booted system. 2844 mInstaller.setWarnIfHeld(mPackages); 2845 2846 // Expose private service for system components to use. 2847 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2848 } 2849 2850 @Override 2851 public boolean isFirstBoot() { 2852 return !mRestoredSettings; 2853 } 2854 2855 @Override 2856 public boolean isOnlyCoreApps() { 2857 return mOnlyCore; 2858 } 2859 2860 @Override 2861 public boolean isUpgrade() { 2862 return mIsUpgrade; 2863 } 2864 2865 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2866 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2867 2868 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2869 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2870 UserHandle.USER_SYSTEM); 2871 if (matches.size() == 1) { 2872 return matches.get(0).getComponentInfo().packageName; 2873 } else { 2874 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2875 return null; 2876 } 2877 } 2878 2879 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2880 synchronized (mPackages) { 2881 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2882 if (libraryEntry == null) { 2883 throw new IllegalStateException("Missing required shared library:" + libraryName); 2884 } 2885 return libraryEntry.apk; 2886 } 2887 } 2888 2889 private @NonNull String getRequiredInstallerLPr() { 2890 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2891 intent.addCategory(Intent.CATEGORY_DEFAULT); 2892 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2893 2894 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2895 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2896 UserHandle.USER_SYSTEM); 2897 if (matches.size() == 1) { 2898 ResolveInfo resolveInfo = matches.get(0); 2899 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2900 throw new RuntimeException("The installer must be a privileged app"); 2901 } 2902 return matches.get(0).getComponentInfo().packageName; 2903 } else { 2904 throw new RuntimeException("There must be exactly one installer; found " + matches); 2905 } 2906 } 2907 2908 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2909 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2910 2911 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 ResolveInfo best = null; 2915 final int N = matches.size(); 2916 for (int i = 0; i < N; i++) { 2917 final ResolveInfo cur = matches.get(i); 2918 final String packageName = cur.getComponentInfo().packageName; 2919 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2920 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2921 continue; 2922 } 2923 2924 if (best == null || cur.priority > best.priority) { 2925 best = cur; 2926 } 2927 } 2928 2929 if (best != null) { 2930 return best.getComponentInfo().getComponentName(); 2931 } else { 2932 throw new RuntimeException("There must be at least one intent filter verifier"); 2933 } 2934 } 2935 2936 private @Nullable ComponentName getEphemeralResolverLPr() { 2937 final String[] packageArray = 2938 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2939 if (packageArray.length == 0) { 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2942 } 2943 return null; 2944 } 2945 2946 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2947 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2948 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2949 UserHandle.USER_SYSTEM); 2950 2951 final int N = resolvers.size(); 2952 if (N == 0) { 2953 if (DEBUG_EPHEMERAL) { 2954 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2955 } 2956 return null; 2957 } 2958 2959 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2960 for (int i = 0; i < N; i++) { 2961 final ResolveInfo info = resolvers.get(i); 2962 2963 if (info.serviceInfo == null) { 2964 continue; 2965 } 2966 2967 final String packageName = info.serviceInfo.packageName; 2968 if (!possiblePackages.contains(packageName)) { 2969 if (DEBUG_EPHEMERAL) { 2970 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2971 + " pkg: " + packageName + ", info:" + info); 2972 } 2973 continue; 2974 } 2975 2976 if (DEBUG_EPHEMERAL) { 2977 Slog.v(TAG, "Ephemeral resolver found;" 2978 + " pkg: " + packageName + ", info:" + info); 2979 } 2980 return new ComponentName(packageName, info.serviceInfo.name); 2981 } 2982 if (DEBUG_EPHEMERAL) { 2983 Slog.v(TAG, "Ephemeral resolver NOT found"); 2984 } 2985 return null; 2986 } 2987 2988 private @Nullable ComponentName getEphemeralInstallerLPr() { 2989 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2990 intent.addCategory(Intent.CATEGORY_DEFAULT); 2991 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2992 2993 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2994 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2995 UserHandle.USER_SYSTEM); 2996 if (matches.size() == 0) { 2997 return null; 2998 } else if (matches.size() == 1) { 2999 return matches.get(0).getComponentInfo().getComponentName(); 3000 } else { 3001 throw new RuntimeException( 3002 "There must be at most one ephemeral installer; found " + matches); 3003 } 3004 } 3005 3006 private void primeDomainVerificationsLPw(int userId) { 3007 if (DEBUG_DOMAIN_VERIFICATION) { 3008 Slog.d(TAG, "Priming domain verifications in user " + userId); 3009 } 3010 3011 SystemConfig systemConfig = SystemConfig.getInstance(); 3012 ArraySet<String> packages = systemConfig.getLinkedApps(); 3013 ArraySet<String> domains = new ArraySet<String>(); 3014 3015 for (String packageName : packages) { 3016 PackageParser.Package pkg = mPackages.get(packageName); 3017 if (pkg != null) { 3018 if (!pkg.isSystemApp()) { 3019 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3020 continue; 3021 } 3022 3023 domains.clear(); 3024 for (PackageParser.Activity a : pkg.activities) { 3025 for (ActivityIntentInfo filter : a.intents) { 3026 if (hasValidDomains(filter)) { 3027 domains.addAll(filter.getHostsList()); 3028 } 3029 } 3030 } 3031 3032 if (domains.size() > 0) { 3033 if (DEBUG_DOMAIN_VERIFICATION) { 3034 Slog.v(TAG, " + " + packageName); 3035 } 3036 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3037 // state w.r.t. the formal app-linkage "no verification attempted" state; 3038 // and then 'always' in the per-user state actually used for intent resolution. 3039 final IntentFilterVerificationInfo ivi; 3040 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3041 new ArrayList<String>(domains)); 3042 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3043 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3044 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3045 } else { 3046 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3047 + "' does not handle web links"); 3048 } 3049 } else { 3050 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3051 } 3052 } 3053 3054 scheduleWritePackageRestrictionsLocked(userId); 3055 scheduleWriteSettingsLocked(); 3056 } 3057 3058 private void applyFactoryDefaultBrowserLPw(int userId) { 3059 // The default browser app's package name is stored in a string resource, 3060 // with a product-specific overlay used for vendor customization. 3061 String browserPkg = mContext.getResources().getString( 3062 com.android.internal.R.string.default_browser); 3063 if (!TextUtils.isEmpty(browserPkg)) { 3064 // non-empty string => required to be a known package 3065 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3066 if (ps == null) { 3067 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3068 browserPkg = null; 3069 } else { 3070 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3071 } 3072 } 3073 3074 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3075 // default. If there's more than one, just leave everything alone. 3076 if (browserPkg == null) { 3077 calculateDefaultBrowserLPw(userId); 3078 } 3079 } 3080 3081 private void calculateDefaultBrowserLPw(int userId) { 3082 List<String> allBrowsers = resolveAllBrowserApps(userId); 3083 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3084 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3085 } 3086 3087 private List<String> resolveAllBrowserApps(int userId) { 3088 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3089 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3090 PackageManager.MATCH_ALL, userId); 3091 3092 final int count = list.size(); 3093 List<String> result = new ArrayList<String>(count); 3094 for (int i=0; i<count; i++) { 3095 ResolveInfo info = list.get(i); 3096 if (info.activityInfo == null 3097 || !info.handleAllWebDataURI 3098 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3099 || result.contains(info.activityInfo.packageName)) { 3100 continue; 3101 } 3102 result.add(info.activityInfo.packageName); 3103 } 3104 3105 return result; 3106 } 3107 3108 private boolean packageIsBrowser(String packageName, int userId) { 3109 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3110 PackageManager.MATCH_ALL, userId); 3111 final int N = list.size(); 3112 for (int i = 0; i < N; i++) { 3113 ResolveInfo info = list.get(i); 3114 if (packageName.equals(info.activityInfo.packageName)) { 3115 return true; 3116 } 3117 } 3118 return false; 3119 } 3120 3121 private void checkDefaultBrowser() { 3122 final int myUserId = UserHandle.myUserId(); 3123 final String packageName = getDefaultBrowserPackageName(myUserId); 3124 if (packageName != null) { 3125 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3126 if (info == null) { 3127 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3128 synchronized (mPackages) { 3129 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3130 } 3131 } 3132 } 3133 } 3134 3135 @Override 3136 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3137 throws RemoteException { 3138 try { 3139 return super.onTransact(code, data, reply, flags); 3140 } catch (RuntimeException e) { 3141 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3142 Slog.wtf(TAG, "Package Manager Crash", e); 3143 } 3144 throw e; 3145 } 3146 } 3147 3148 static int[] appendInts(int[] cur, int[] add) { 3149 if (add == null) return cur; 3150 if (cur == null) return add; 3151 final int N = add.length; 3152 for (int i=0; i<N; i++) { 3153 cur = appendInt(cur, add[i]); 3154 } 3155 return cur; 3156 } 3157 3158 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3159 if (!sUserManager.exists(userId)) return null; 3160 if (ps == null) { 3161 return null; 3162 } 3163 final PackageParser.Package p = ps.pkg; 3164 if (p == null) { 3165 return null; 3166 } 3167 3168 final PermissionsState permissionsState = ps.getPermissionsState(); 3169 3170 final int[] gids = permissionsState.computeGids(userId); 3171 final Set<String> permissions = permissionsState.getPermissions(userId); 3172 final PackageUserState state = ps.readUserState(userId); 3173 3174 return PackageParser.generatePackageInfo(p, gids, flags, 3175 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3176 } 3177 3178 @Override 3179 public void checkPackageStartable(String packageName, int userId) { 3180 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3181 3182 synchronized (mPackages) { 3183 final PackageSetting ps = mSettings.mPackages.get(packageName); 3184 if (ps == null) { 3185 throw new SecurityException("Package " + packageName + " was not found!"); 3186 } 3187 3188 if (!ps.getInstalled(userId)) { 3189 throw new SecurityException( 3190 "Package " + packageName + " was not installed for user " + userId + "!"); 3191 } 3192 3193 if (mSafeMode && !ps.isSystem()) { 3194 throw new SecurityException("Package " + packageName + " not a system app!"); 3195 } 3196 3197 if (mFrozenPackages.contains(packageName)) { 3198 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3199 } 3200 3201 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3202 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3203 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3204 } 3205 } 3206 } 3207 3208 @Override 3209 public boolean isPackageAvailable(String packageName, int userId) { 3210 if (!sUserManager.exists(userId)) return false; 3211 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3212 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3213 synchronized (mPackages) { 3214 PackageParser.Package p = mPackages.get(packageName); 3215 if (p != null) { 3216 final PackageSetting ps = (PackageSetting) p.mExtras; 3217 if (ps != null) { 3218 final PackageUserState state = ps.readUserState(userId); 3219 if (state != null) { 3220 return PackageParser.isAvailable(state); 3221 } 3222 } 3223 } 3224 } 3225 return false; 3226 } 3227 3228 @Override 3229 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return null; 3231 flags = updateFlagsForPackage(flags, userId, packageName); 3232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3233 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3234 // reader 3235 synchronized (mPackages) { 3236 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3237 PackageParser.Package p = null; 3238 if (matchFactoryOnly) { 3239 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3240 if (ps != null) { 3241 return generatePackageInfo(ps, flags, userId); 3242 } 3243 } 3244 if (p == null) { 3245 p = mPackages.get(packageName); 3246 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3247 return null; 3248 } 3249 } 3250 if (DEBUG_PACKAGE_INFO) 3251 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3252 if (p != null) { 3253 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3254 } 3255 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3256 final PackageSetting ps = mSettings.mPackages.get(packageName); 3257 return generatePackageInfo(ps, flags, userId); 3258 } 3259 } 3260 return null; 3261 } 3262 3263 @Override 3264 public String[] currentToCanonicalPackageNames(String[] names) { 3265 String[] out = new String[names.length]; 3266 // reader 3267 synchronized (mPackages) { 3268 for (int i=names.length-1; i>=0; i--) { 3269 PackageSetting ps = mSettings.mPackages.get(names[i]); 3270 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3271 } 3272 } 3273 return out; 3274 } 3275 3276 @Override 3277 public String[] canonicalToCurrentPackageNames(String[] names) { 3278 String[] out = new String[names.length]; 3279 // reader 3280 synchronized (mPackages) { 3281 for (int i=names.length-1; i>=0; i--) { 3282 String cur = mSettings.mRenamedPackages.get(names[i]); 3283 out[i] = cur != null ? cur : names[i]; 3284 } 3285 } 3286 return out; 3287 } 3288 3289 @Override 3290 public int getPackageUid(String packageName, int flags, int userId) { 3291 if (!sUserManager.exists(userId)) return -1; 3292 flags = updateFlagsForPackage(flags, userId, packageName); 3293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3294 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3295 3296 // reader 3297 synchronized (mPackages) { 3298 final PackageParser.Package p = mPackages.get(packageName); 3299 if (p != null && p.isMatch(flags)) { 3300 return UserHandle.getUid(userId, p.applicationInfo.uid); 3301 } 3302 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3303 final PackageSetting ps = mSettings.mPackages.get(packageName); 3304 if (ps != null && ps.isMatch(flags)) { 3305 return UserHandle.getUid(userId, ps.appId); 3306 } 3307 } 3308 } 3309 3310 return -1; 3311 } 3312 3313 @Override 3314 public int[] getPackageGids(String packageName, int flags, int userId) { 3315 if (!sUserManager.exists(userId)) return null; 3316 flags = updateFlagsForPackage(flags, userId, packageName); 3317 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3318 false /* requireFullPermission */, false /* checkShell */, 3319 "getPackageGids"); 3320 3321 // reader 3322 synchronized (mPackages) { 3323 final PackageParser.Package p = mPackages.get(packageName); 3324 if (p != null && p.isMatch(flags)) { 3325 PackageSetting ps = (PackageSetting) p.mExtras; 3326 return ps.getPermissionsState().computeGids(userId); 3327 } 3328 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3329 final PackageSetting ps = mSettings.mPackages.get(packageName); 3330 if (ps != null && ps.isMatch(flags)) { 3331 return ps.getPermissionsState().computeGids(userId); 3332 } 3333 } 3334 } 3335 3336 return null; 3337 } 3338 3339 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3340 if (bp.perm != null) { 3341 return PackageParser.generatePermissionInfo(bp.perm, flags); 3342 } 3343 PermissionInfo pi = new PermissionInfo(); 3344 pi.name = bp.name; 3345 pi.packageName = bp.sourcePackage; 3346 pi.nonLocalizedLabel = bp.name; 3347 pi.protectionLevel = bp.protectionLevel; 3348 return pi; 3349 } 3350 3351 @Override 3352 public PermissionInfo getPermissionInfo(String name, int flags) { 3353 // reader 3354 synchronized (mPackages) { 3355 final BasePermission p = mSettings.mPermissions.get(name); 3356 if (p != null) { 3357 return generatePermissionInfo(p, flags); 3358 } 3359 return null; 3360 } 3361 } 3362 3363 @Override 3364 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3365 int flags) { 3366 // reader 3367 synchronized (mPackages) { 3368 if (group != null && !mPermissionGroups.containsKey(group)) { 3369 // This is thrown as NameNotFoundException 3370 return null; 3371 } 3372 3373 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3374 for (BasePermission p : mSettings.mPermissions.values()) { 3375 if (group == null) { 3376 if (p.perm == null || p.perm.info.group == null) { 3377 out.add(generatePermissionInfo(p, flags)); 3378 } 3379 } else { 3380 if (p.perm != null && group.equals(p.perm.info.group)) { 3381 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3382 } 3383 } 3384 } 3385 return new ParceledListSlice<>(out); 3386 } 3387 } 3388 3389 @Override 3390 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3391 // reader 3392 synchronized (mPackages) { 3393 return PackageParser.generatePermissionGroupInfo( 3394 mPermissionGroups.get(name), flags); 3395 } 3396 } 3397 3398 @Override 3399 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3400 // reader 3401 synchronized (mPackages) { 3402 final int N = mPermissionGroups.size(); 3403 ArrayList<PermissionGroupInfo> out 3404 = new ArrayList<PermissionGroupInfo>(N); 3405 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3406 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3407 } 3408 return new ParceledListSlice<>(out); 3409 } 3410 } 3411 3412 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3413 int userId) { 3414 if (!sUserManager.exists(userId)) return null; 3415 PackageSetting ps = mSettings.mPackages.get(packageName); 3416 if (ps != null) { 3417 if (ps.pkg == null) { 3418 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3419 if (pInfo != null) { 3420 return pInfo.applicationInfo; 3421 } 3422 return null; 3423 } 3424 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3425 ps.readUserState(userId), userId); 3426 } 3427 return null; 3428 } 3429 3430 @Override 3431 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3432 if (!sUserManager.exists(userId)) return null; 3433 flags = updateFlagsForApplication(flags, userId, packageName); 3434 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3435 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3436 // writer 3437 synchronized (mPackages) { 3438 PackageParser.Package p = mPackages.get(packageName); 3439 if (DEBUG_PACKAGE_INFO) Log.v( 3440 TAG, "getApplicationInfo " + packageName 3441 + ": " + p); 3442 if (p != null) { 3443 PackageSetting ps = mSettings.mPackages.get(packageName); 3444 if (ps == null) return null; 3445 // Note: isEnabledLP() does not apply here - always return info 3446 return PackageParser.generateApplicationInfo( 3447 p, flags, ps.readUserState(userId), userId); 3448 } 3449 if ("android".equals(packageName)||"system".equals(packageName)) { 3450 return mAndroidApplication; 3451 } 3452 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3453 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3454 } 3455 } 3456 return null; 3457 } 3458 3459 @Override 3460 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3461 final IPackageDataObserver observer) { 3462 mContext.enforceCallingOrSelfPermission( 3463 android.Manifest.permission.CLEAR_APP_CACHE, null); 3464 // Queue up an async operation since clearing cache may take a little while. 3465 mHandler.post(new Runnable() { 3466 public void run() { 3467 mHandler.removeCallbacks(this); 3468 boolean success = true; 3469 synchronized (mInstallLock) { 3470 try { 3471 mInstaller.freeCache(volumeUuid, freeStorageSize); 3472 } catch (InstallerException e) { 3473 Slog.w(TAG, "Couldn't clear application caches: " + e); 3474 success = false; 3475 } 3476 } 3477 if (observer != null) { 3478 try { 3479 observer.onRemoveCompleted(null, success); 3480 } catch (RemoteException e) { 3481 Slog.w(TAG, "RemoveException when invoking call back"); 3482 } 3483 } 3484 } 3485 }); 3486 } 3487 3488 @Override 3489 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3490 final IntentSender pi) { 3491 mContext.enforceCallingOrSelfPermission( 3492 android.Manifest.permission.CLEAR_APP_CACHE, null); 3493 // Queue up an async operation since clearing cache may take a little while. 3494 mHandler.post(new Runnable() { 3495 public void run() { 3496 mHandler.removeCallbacks(this); 3497 boolean success = true; 3498 synchronized (mInstallLock) { 3499 try { 3500 mInstaller.freeCache(volumeUuid, freeStorageSize); 3501 } catch (InstallerException e) { 3502 Slog.w(TAG, "Couldn't clear application caches: " + e); 3503 success = false; 3504 } 3505 } 3506 if(pi != null) { 3507 try { 3508 // Callback via pending intent 3509 int code = success ? 1 : 0; 3510 pi.sendIntent(null, code, null, 3511 null, null); 3512 } catch (SendIntentException e1) { 3513 Slog.i(TAG, "Failed to send pending intent"); 3514 } 3515 } 3516 } 3517 }); 3518 } 3519 3520 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3521 synchronized (mInstallLock) { 3522 try { 3523 mInstaller.freeCache(volumeUuid, freeStorageSize); 3524 } catch (InstallerException e) { 3525 throw new IOException("Failed to free enough space", e); 3526 } 3527 } 3528 } 3529 3530 /** 3531 * Update given flags based on encryption status of current user. 3532 */ 3533 private int updateFlags(int flags, int userId) { 3534 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3535 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3536 // Caller expressed an explicit opinion about what encryption 3537 // aware/unaware components they want to see, so fall through and 3538 // give them what they want 3539 } else { 3540 // Caller expressed no opinion, so match based on user state 3541 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3542 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3543 } else { 3544 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3545 } 3546 } 3547 return flags; 3548 } 3549 3550 private UserManagerInternal getUserManagerInternal() { 3551 if (mUserManagerInternal == null) { 3552 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3553 } 3554 return mUserManagerInternal; 3555 } 3556 3557 /** 3558 * Update given flags when being used to request {@link PackageInfo}. 3559 */ 3560 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3561 boolean triaged = true; 3562 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3563 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3564 // Caller is asking for component details, so they'd better be 3565 // asking for specific encryption matching behavior, or be triaged 3566 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3567 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3568 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3569 triaged = false; 3570 } 3571 } 3572 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3573 | PackageManager.MATCH_SYSTEM_ONLY 3574 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3575 triaged = false; 3576 } 3577 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3578 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3579 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3580 } 3581 return updateFlags(flags, userId); 3582 } 3583 3584 /** 3585 * Update given flags when being used to request {@link ApplicationInfo}. 3586 */ 3587 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3588 return updateFlagsForPackage(flags, userId, cookie); 3589 } 3590 3591 /** 3592 * Update given flags when being used to request {@link ComponentInfo}. 3593 */ 3594 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3595 if (cookie instanceof Intent) { 3596 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3597 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3598 } 3599 } 3600 3601 boolean triaged = true; 3602 // Caller is asking for component details, so they'd better be 3603 // asking for specific encryption matching behavior, or be triaged 3604 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3605 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3606 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3607 triaged = false; 3608 } 3609 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3610 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3611 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3612 } 3613 3614 return updateFlags(flags, userId); 3615 } 3616 3617 /** 3618 * Update given flags when being used to request {@link ResolveInfo}. 3619 */ 3620 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3621 // Safe mode means we shouldn't match any third-party components 3622 if (mSafeMode) { 3623 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3624 } 3625 3626 return updateFlagsForComponent(flags, userId, cookie); 3627 } 3628 3629 @Override 3630 public ActivityInfo getActivityInfo(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 activity info"); 3635 synchronized (mPackages) { 3636 PackageParser.Activity a = mActivities.mActivities.get(component); 3637 3638 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3639 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3640 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3641 if (ps == null) return null; 3642 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3643 userId); 3644 } 3645 if (mResolveComponentName.equals(component)) { 3646 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3647 new PackageUserState(), userId); 3648 } 3649 } 3650 return null; 3651 } 3652 3653 @Override 3654 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3655 String resolvedType) { 3656 synchronized (mPackages) { 3657 if (component.equals(mResolveComponentName)) { 3658 // The resolver supports EVERYTHING! 3659 return true; 3660 } 3661 PackageParser.Activity a = mActivities.mActivities.get(component); 3662 if (a == null) { 3663 return false; 3664 } 3665 for (int i=0; i<a.intents.size(); i++) { 3666 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3667 intent.getData(), intent.getCategories(), TAG) >= 0) { 3668 return true; 3669 } 3670 } 3671 return false; 3672 } 3673 } 3674 3675 @Override 3676 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3677 if (!sUserManager.exists(userId)) return null; 3678 flags = updateFlagsForComponent(flags, userId, component); 3679 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3680 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3681 synchronized (mPackages) { 3682 PackageParser.Activity a = mReceivers.mActivities.get(component); 3683 if (DEBUG_PACKAGE_INFO) Log.v( 3684 TAG, "getReceiverInfo " + component + ": " + a); 3685 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3686 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3687 if (ps == null) return null; 3688 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3689 userId); 3690 } 3691 } 3692 return null; 3693 } 3694 3695 @Override 3696 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3697 if (!sUserManager.exists(userId)) return null; 3698 flags = updateFlagsForComponent(flags, userId, component); 3699 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3700 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3701 synchronized (mPackages) { 3702 PackageParser.Service s = mServices.mServices.get(component); 3703 if (DEBUG_PACKAGE_INFO) Log.v( 3704 TAG, "getServiceInfo " + component + ": " + s); 3705 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3706 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3707 if (ps == null) return null; 3708 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3709 userId); 3710 } 3711 } 3712 return null; 3713 } 3714 3715 @Override 3716 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3717 if (!sUserManager.exists(userId)) return null; 3718 flags = updateFlagsForComponent(flags, userId, component); 3719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3720 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3721 synchronized (mPackages) { 3722 PackageParser.Provider p = mProviders.mProviders.get(component); 3723 if (DEBUG_PACKAGE_INFO) Log.v( 3724 TAG, "getProviderInfo " + component + ": " + p); 3725 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3726 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3727 if (ps == null) return null; 3728 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3729 userId); 3730 } 3731 } 3732 return null; 3733 } 3734 3735 @Override 3736 public String[] getSystemSharedLibraryNames() { 3737 Set<String> libSet; 3738 synchronized (mPackages) { 3739 libSet = mSharedLibraries.keySet(); 3740 int size = libSet.size(); 3741 if (size > 0) { 3742 String[] libs = new String[size]; 3743 libSet.toArray(libs); 3744 return libs; 3745 } 3746 } 3747 return null; 3748 } 3749 3750 @Override 3751 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3752 synchronized (mPackages) { 3753 return mServicesSystemSharedLibraryPackageName; 3754 } 3755 } 3756 3757 @Override 3758 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3759 synchronized (mPackages) { 3760 return mSharedSystemSharedLibraryPackageName; 3761 } 3762 } 3763 3764 @Override 3765 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3766 synchronized (mPackages) { 3767 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3768 3769 final FeatureInfo fi = new FeatureInfo(); 3770 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3771 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3772 res.add(fi); 3773 3774 return new ParceledListSlice<>(res); 3775 } 3776 } 3777 3778 @Override 3779 public boolean hasSystemFeature(String name, int version) { 3780 synchronized (mPackages) { 3781 final FeatureInfo feat = mAvailableFeatures.get(name); 3782 if (feat == null) { 3783 return false; 3784 } else { 3785 return feat.version >= version; 3786 } 3787 } 3788 } 3789 3790 @Override 3791 public int checkPermission(String permName, String pkgName, int userId) { 3792 if (!sUserManager.exists(userId)) { 3793 return PackageManager.PERMISSION_DENIED; 3794 } 3795 3796 synchronized (mPackages) { 3797 final PackageParser.Package p = mPackages.get(pkgName); 3798 if (p != null && p.mExtras != null) { 3799 final PackageSetting ps = (PackageSetting) p.mExtras; 3800 final PermissionsState permissionsState = ps.getPermissionsState(); 3801 if (permissionsState.hasPermission(permName, userId)) { 3802 return PackageManager.PERMISSION_GRANTED; 3803 } 3804 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3805 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3806 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3807 return PackageManager.PERMISSION_GRANTED; 3808 } 3809 } 3810 } 3811 3812 return PackageManager.PERMISSION_DENIED; 3813 } 3814 3815 @Override 3816 public int checkUidPermission(String permName, int uid) { 3817 final int userId = UserHandle.getUserId(uid); 3818 3819 if (!sUserManager.exists(userId)) { 3820 return PackageManager.PERMISSION_DENIED; 3821 } 3822 3823 synchronized (mPackages) { 3824 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3825 if (obj != null) { 3826 final SettingBase ps = (SettingBase) obj; 3827 final PermissionsState permissionsState = ps.getPermissionsState(); 3828 if (permissionsState.hasPermission(permName, userId)) { 3829 return PackageManager.PERMISSION_GRANTED; 3830 } 3831 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3832 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3833 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3834 return PackageManager.PERMISSION_GRANTED; 3835 } 3836 } else { 3837 ArraySet<String> perms = mSystemPermissions.get(uid); 3838 if (perms != null) { 3839 if (perms.contains(permName)) { 3840 return PackageManager.PERMISSION_GRANTED; 3841 } 3842 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3843 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3844 return PackageManager.PERMISSION_GRANTED; 3845 } 3846 } 3847 } 3848 } 3849 3850 return PackageManager.PERMISSION_DENIED; 3851 } 3852 3853 @Override 3854 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3855 if (UserHandle.getCallingUserId() != userId) { 3856 mContext.enforceCallingPermission( 3857 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3858 "isPermissionRevokedByPolicy for user " + userId); 3859 } 3860 3861 if (checkPermission(permission, packageName, userId) 3862 == PackageManager.PERMISSION_GRANTED) { 3863 return false; 3864 } 3865 3866 final long identity = Binder.clearCallingIdentity(); 3867 try { 3868 final int flags = getPermissionFlags(permission, packageName, userId); 3869 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3870 } finally { 3871 Binder.restoreCallingIdentity(identity); 3872 } 3873 } 3874 3875 @Override 3876 public String getPermissionControllerPackageName() { 3877 synchronized (mPackages) { 3878 return mRequiredInstallerPackage; 3879 } 3880 } 3881 3882 /** 3883 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3884 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3885 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3886 * @param message the message to log on security exception 3887 */ 3888 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3889 boolean checkShell, String message) { 3890 if (userId < 0) { 3891 throw new IllegalArgumentException("Invalid userId " + userId); 3892 } 3893 if (checkShell) { 3894 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3895 } 3896 if (userId == UserHandle.getUserId(callingUid)) return; 3897 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3898 if (requireFullPermission) { 3899 mContext.enforceCallingOrSelfPermission( 3900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3901 } else { 3902 try { 3903 mContext.enforceCallingOrSelfPermission( 3904 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3905 } catch (SecurityException se) { 3906 mContext.enforceCallingOrSelfPermission( 3907 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3908 } 3909 } 3910 } 3911 } 3912 3913 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3914 if (callingUid == Process.SHELL_UID) { 3915 if (userHandle >= 0 3916 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3917 throw new SecurityException("Shell does not have permission to access user " 3918 + userHandle); 3919 } else if (userHandle < 0) { 3920 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3921 + Debug.getCallers(3)); 3922 } 3923 } 3924 } 3925 3926 private BasePermission findPermissionTreeLP(String permName) { 3927 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3928 if (permName.startsWith(bp.name) && 3929 permName.length() > bp.name.length() && 3930 permName.charAt(bp.name.length()) == '.') { 3931 return bp; 3932 } 3933 } 3934 return null; 3935 } 3936 3937 private BasePermission checkPermissionTreeLP(String permName) { 3938 if (permName != null) { 3939 BasePermission bp = findPermissionTreeLP(permName); 3940 if (bp != null) { 3941 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3942 return bp; 3943 } 3944 throw new SecurityException("Calling uid " 3945 + Binder.getCallingUid() 3946 + " is not allowed to add to permission tree " 3947 + bp.name + " owned by uid " + bp.uid); 3948 } 3949 } 3950 throw new SecurityException("No permission tree found for " + permName); 3951 } 3952 3953 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3954 if (s1 == null) { 3955 return s2 == null; 3956 } 3957 if (s2 == null) { 3958 return false; 3959 } 3960 if (s1.getClass() != s2.getClass()) { 3961 return false; 3962 } 3963 return s1.equals(s2); 3964 } 3965 3966 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3967 if (pi1.icon != pi2.icon) return false; 3968 if (pi1.logo != pi2.logo) return false; 3969 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3970 if (!compareStrings(pi1.name, pi2.name)) return false; 3971 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3972 // We'll take care of setting this one. 3973 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3974 // These are not currently stored in settings. 3975 //if (!compareStrings(pi1.group, pi2.group)) return false; 3976 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3977 //if (pi1.labelRes != pi2.labelRes) return false; 3978 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3979 return true; 3980 } 3981 3982 int permissionInfoFootprint(PermissionInfo info) { 3983 int size = info.name.length(); 3984 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3985 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3986 return size; 3987 } 3988 3989 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3990 int size = 0; 3991 for (BasePermission perm : mSettings.mPermissions.values()) { 3992 if (perm.uid == tree.uid) { 3993 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3994 } 3995 } 3996 return size; 3997 } 3998 3999 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4000 // We calculate the max size of permissions defined by this uid and throw 4001 // if that plus the size of 'info' would exceed our stated maximum. 4002 if (tree.uid != Process.SYSTEM_UID) { 4003 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4004 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4005 throw new SecurityException("Permission tree size cap exceeded"); 4006 } 4007 } 4008 } 4009 4010 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4011 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4012 throw new SecurityException("Label must be specified in permission"); 4013 } 4014 BasePermission tree = checkPermissionTreeLP(info.name); 4015 BasePermission bp = mSettings.mPermissions.get(info.name); 4016 boolean added = bp == null; 4017 boolean changed = true; 4018 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4019 if (added) { 4020 enforcePermissionCapLocked(info, tree); 4021 bp = new BasePermission(info.name, tree.sourcePackage, 4022 BasePermission.TYPE_DYNAMIC); 4023 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4024 throw new SecurityException( 4025 "Not allowed to modify non-dynamic permission " 4026 + info.name); 4027 } else { 4028 if (bp.protectionLevel == fixedLevel 4029 && bp.perm.owner.equals(tree.perm.owner) 4030 && bp.uid == tree.uid 4031 && comparePermissionInfos(bp.perm.info, info)) { 4032 changed = false; 4033 } 4034 } 4035 bp.protectionLevel = fixedLevel; 4036 info = new PermissionInfo(info); 4037 info.protectionLevel = fixedLevel; 4038 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4039 bp.perm.info.packageName = tree.perm.info.packageName; 4040 bp.uid = tree.uid; 4041 if (added) { 4042 mSettings.mPermissions.put(info.name, bp); 4043 } 4044 if (changed) { 4045 if (!async) { 4046 mSettings.writeLPr(); 4047 } else { 4048 scheduleWriteSettingsLocked(); 4049 } 4050 } 4051 return added; 4052 } 4053 4054 @Override 4055 public boolean addPermission(PermissionInfo info) { 4056 synchronized (mPackages) { 4057 return addPermissionLocked(info, false); 4058 } 4059 } 4060 4061 @Override 4062 public boolean addPermissionAsync(PermissionInfo info) { 4063 synchronized (mPackages) { 4064 return addPermissionLocked(info, true); 4065 } 4066 } 4067 4068 @Override 4069 public void removePermission(String name) { 4070 synchronized (mPackages) { 4071 checkPermissionTreeLP(name); 4072 BasePermission bp = mSettings.mPermissions.get(name); 4073 if (bp != null) { 4074 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4075 throw new SecurityException( 4076 "Not allowed to modify non-dynamic permission " 4077 + name); 4078 } 4079 mSettings.mPermissions.remove(name); 4080 mSettings.writeLPr(); 4081 } 4082 } 4083 } 4084 4085 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4086 BasePermission bp) { 4087 int index = pkg.requestedPermissions.indexOf(bp.name); 4088 if (index == -1) { 4089 throw new SecurityException("Package " + pkg.packageName 4090 + " has not requested permission " + bp.name); 4091 } 4092 if (!bp.isRuntime() && !bp.isDevelopment()) { 4093 throw new SecurityException("Permission " + bp.name 4094 + " is not a changeable permission type"); 4095 } 4096 } 4097 4098 @Override 4099 public void grantRuntimePermission(String packageName, String name, final int userId) { 4100 if (!sUserManager.exists(userId)) { 4101 Log.e(TAG, "No such user:" + userId); 4102 return; 4103 } 4104 4105 mContext.enforceCallingOrSelfPermission( 4106 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4107 "grantRuntimePermission"); 4108 4109 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4110 true /* requireFullPermission */, true /* checkShell */, 4111 "grantRuntimePermission"); 4112 4113 final int uid; 4114 final SettingBase sb; 4115 4116 synchronized (mPackages) { 4117 final PackageParser.Package pkg = mPackages.get(packageName); 4118 if (pkg == null) { 4119 throw new IllegalArgumentException("Unknown package: " + packageName); 4120 } 4121 4122 final BasePermission bp = mSettings.mPermissions.get(name); 4123 if (bp == null) { 4124 throw new IllegalArgumentException("Unknown permission: " + name); 4125 } 4126 4127 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4128 4129 // If a permission review is required for legacy apps we represent 4130 // their permissions as always granted runtime ones since we need 4131 // to keep the review required permission flag per user while an 4132 // install permission's state is shared across all users. 4133 if (Build.PERMISSIONS_REVIEW_REQUIRED 4134 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4135 && bp.isRuntime()) { 4136 return; 4137 } 4138 4139 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4140 sb = (SettingBase) pkg.mExtras; 4141 if (sb == null) { 4142 throw new IllegalArgumentException("Unknown package: " + packageName); 4143 } 4144 4145 final PermissionsState permissionsState = sb.getPermissionsState(); 4146 4147 final int flags = permissionsState.getPermissionFlags(name, userId); 4148 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4149 throw new SecurityException("Cannot grant system fixed permission " 4150 + name + " for package " + packageName); 4151 } 4152 4153 if (bp.isDevelopment()) { 4154 // Development permissions must be handled specially, since they are not 4155 // normal runtime permissions. For now they apply to all users. 4156 if (permissionsState.grantInstallPermission(bp) != 4157 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4158 scheduleWriteSettingsLocked(); 4159 } 4160 return; 4161 } 4162 4163 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4164 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4165 return; 4166 } 4167 4168 final int result = permissionsState.grantRuntimePermission(bp, userId); 4169 switch (result) { 4170 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4171 return; 4172 } 4173 4174 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4175 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4176 mHandler.post(new Runnable() { 4177 @Override 4178 public void run() { 4179 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4180 } 4181 }); 4182 } 4183 break; 4184 } 4185 4186 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4187 4188 // Not critical if that is lost - app has to request again. 4189 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4190 } 4191 4192 // Only need to do this if user is initialized. Otherwise it's a new user 4193 // and there are no processes running as the user yet and there's no need 4194 // to make an expensive call to remount processes for the changed permissions. 4195 if (READ_EXTERNAL_STORAGE.equals(name) 4196 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4197 final long token = Binder.clearCallingIdentity(); 4198 try { 4199 if (sUserManager.isInitialized(userId)) { 4200 MountServiceInternal mountServiceInternal = LocalServices.getService( 4201 MountServiceInternal.class); 4202 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4203 } 4204 } finally { 4205 Binder.restoreCallingIdentity(token); 4206 } 4207 } 4208 } 4209 4210 @Override 4211 public void revokeRuntimePermission(String packageName, String name, int userId) { 4212 if (!sUserManager.exists(userId)) { 4213 Log.e(TAG, "No such user:" + userId); 4214 return; 4215 } 4216 4217 mContext.enforceCallingOrSelfPermission( 4218 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4219 "revokeRuntimePermission"); 4220 4221 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4222 true /* requireFullPermission */, true /* checkShell */, 4223 "revokeRuntimePermission"); 4224 4225 final int appId; 4226 4227 synchronized (mPackages) { 4228 final PackageParser.Package pkg = mPackages.get(packageName); 4229 if (pkg == null) { 4230 throw new IllegalArgumentException("Unknown package: " + packageName); 4231 } 4232 4233 final BasePermission bp = mSettings.mPermissions.get(name); 4234 if (bp == null) { 4235 throw new IllegalArgumentException("Unknown permission: " + name); 4236 } 4237 4238 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4239 4240 // If a permission review is required for legacy apps we represent 4241 // their permissions as always granted runtime ones since we need 4242 // to keep the review required permission flag per user while an 4243 // install permission's state is shared across all users. 4244 if (Build.PERMISSIONS_REVIEW_REQUIRED 4245 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4246 && bp.isRuntime()) { 4247 return; 4248 } 4249 4250 SettingBase sb = (SettingBase) pkg.mExtras; 4251 if (sb == null) { 4252 throw new IllegalArgumentException("Unknown package: " + packageName); 4253 } 4254 4255 final PermissionsState permissionsState = sb.getPermissionsState(); 4256 4257 final int flags = permissionsState.getPermissionFlags(name, userId); 4258 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4259 throw new SecurityException("Cannot revoke system fixed permission " 4260 + name + " for package " + packageName); 4261 } 4262 4263 if (bp.isDevelopment()) { 4264 // Development permissions must be handled specially, since they are not 4265 // normal runtime permissions. For now they apply to all users. 4266 if (permissionsState.revokeInstallPermission(bp) != 4267 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4268 scheduleWriteSettingsLocked(); 4269 } 4270 return; 4271 } 4272 4273 if (permissionsState.revokeRuntimePermission(bp, userId) == 4274 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4275 return; 4276 } 4277 4278 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4279 4280 // Critical, after this call app should never have the permission. 4281 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4282 4283 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4284 } 4285 4286 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4287 } 4288 4289 @Override 4290 public void resetRuntimePermissions() { 4291 mContext.enforceCallingOrSelfPermission( 4292 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4293 "revokeRuntimePermission"); 4294 4295 int callingUid = Binder.getCallingUid(); 4296 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4297 mContext.enforceCallingOrSelfPermission( 4298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4299 "resetRuntimePermissions"); 4300 } 4301 4302 synchronized (mPackages) { 4303 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4304 for (int userId : UserManagerService.getInstance().getUserIds()) { 4305 final int packageCount = mPackages.size(); 4306 for (int i = 0; i < packageCount; i++) { 4307 PackageParser.Package pkg = mPackages.valueAt(i); 4308 if (!(pkg.mExtras instanceof PackageSetting)) { 4309 continue; 4310 } 4311 PackageSetting ps = (PackageSetting) pkg.mExtras; 4312 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4313 } 4314 } 4315 } 4316 } 4317 4318 @Override 4319 public int getPermissionFlags(String name, String packageName, int userId) { 4320 if (!sUserManager.exists(userId)) { 4321 return 0; 4322 } 4323 4324 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4325 4326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4327 true /* requireFullPermission */, false /* checkShell */, 4328 "getPermissionFlags"); 4329 4330 synchronized (mPackages) { 4331 final PackageParser.Package pkg = mPackages.get(packageName); 4332 if (pkg == null) { 4333 return 0; 4334 } 4335 4336 final BasePermission bp = mSettings.mPermissions.get(name); 4337 if (bp == null) { 4338 return 0; 4339 } 4340 4341 SettingBase sb = (SettingBase) pkg.mExtras; 4342 if (sb == null) { 4343 return 0; 4344 } 4345 4346 PermissionsState permissionsState = sb.getPermissionsState(); 4347 return permissionsState.getPermissionFlags(name, userId); 4348 } 4349 } 4350 4351 @Override 4352 public void updatePermissionFlags(String name, String packageName, int flagMask, 4353 int flagValues, int userId) { 4354 if (!sUserManager.exists(userId)) { 4355 return; 4356 } 4357 4358 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4359 4360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4361 true /* requireFullPermission */, true /* checkShell */, 4362 "updatePermissionFlags"); 4363 4364 // Only the system can change these flags and nothing else. 4365 if (getCallingUid() != Process.SYSTEM_UID) { 4366 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4367 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4368 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4369 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4370 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4371 } 4372 4373 synchronized (mPackages) { 4374 final PackageParser.Package pkg = mPackages.get(packageName); 4375 if (pkg == null) { 4376 throw new IllegalArgumentException("Unknown package: " + packageName); 4377 } 4378 4379 final BasePermission bp = mSettings.mPermissions.get(name); 4380 if (bp == null) { 4381 throw new IllegalArgumentException("Unknown permission: " + name); 4382 } 4383 4384 SettingBase sb = (SettingBase) pkg.mExtras; 4385 if (sb == null) { 4386 throw new IllegalArgumentException("Unknown package: " + packageName); 4387 } 4388 4389 PermissionsState permissionsState = sb.getPermissionsState(); 4390 4391 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4392 4393 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4394 // Install and runtime permissions are stored in different places, 4395 // so figure out what permission changed and persist the change. 4396 if (permissionsState.getInstallPermissionState(name) != null) { 4397 scheduleWriteSettingsLocked(); 4398 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4399 || hadState) { 4400 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4401 } 4402 } 4403 } 4404 } 4405 4406 /** 4407 * Update the permission flags for all packages and runtime permissions of a user in order 4408 * to allow device or profile owner to remove POLICY_FIXED. 4409 */ 4410 @Override 4411 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4412 if (!sUserManager.exists(userId)) { 4413 return; 4414 } 4415 4416 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4417 4418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4419 true /* requireFullPermission */, true /* checkShell */, 4420 "updatePermissionFlagsForAllApps"); 4421 4422 // Only the system can change system fixed flags. 4423 if (getCallingUid() != Process.SYSTEM_UID) { 4424 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4425 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4426 } 4427 4428 synchronized (mPackages) { 4429 boolean changed = false; 4430 final int packageCount = mPackages.size(); 4431 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4432 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4433 SettingBase sb = (SettingBase) pkg.mExtras; 4434 if (sb == null) { 4435 continue; 4436 } 4437 PermissionsState permissionsState = sb.getPermissionsState(); 4438 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4439 userId, flagMask, flagValues); 4440 } 4441 if (changed) { 4442 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4443 } 4444 } 4445 } 4446 4447 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4448 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4449 != PackageManager.PERMISSION_GRANTED 4450 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4451 != PackageManager.PERMISSION_GRANTED) { 4452 throw new SecurityException(message + " requires " 4453 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4454 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4455 } 4456 } 4457 4458 @Override 4459 public boolean shouldShowRequestPermissionRationale(String permissionName, 4460 String packageName, int userId) { 4461 if (UserHandle.getCallingUserId() != userId) { 4462 mContext.enforceCallingPermission( 4463 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4464 "canShowRequestPermissionRationale for user " + userId); 4465 } 4466 4467 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4468 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4469 return false; 4470 } 4471 4472 if (checkPermission(permissionName, packageName, userId) 4473 == PackageManager.PERMISSION_GRANTED) { 4474 return false; 4475 } 4476 4477 final int flags; 4478 4479 final long identity = Binder.clearCallingIdentity(); 4480 try { 4481 flags = getPermissionFlags(permissionName, 4482 packageName, userId); 4483 } finally { 4484 Binder.restoreCallingIdentity(identity); 4485 } 4486 4487 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4488 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4489 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4490 4491 if ((flags & fixedFlags) != 0) { 4492 return false; 4493 } 4494 4495 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4496 } 4497 4498 @Override 4499 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4500 mContext.enforceCallingOrSelfPermission( 4501 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4502 "addOnPermissionsChangeListener"); 4503 4504 synchronized (mPackages) { 4505 mOnPermissionChangeListeners.addListenerLocked(listener); 4506 } 4507 } 4508 4509 @Override 4510 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4511 synchronized (mPackages) { 4512 mOnPermissionChangeListeners.removeListenerLocked(listener); 4513 } 4514 } 4515 4516 @Override 4517 public boolean isProtectedBroadcast(String actionName) { 4518 synchronized (mPackages) { 4519 if (mProtectedBroadcasts.contains(actionName)) { 4520 return true; 4521 } else if (actionName != null) { 4522 // TODO: remove these terrible hacks 4523 if (actionName.startsWith("android.net.netmon.lingerExpired") 4524 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4525 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4526 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4527 return true; 4528 } 4529 } 4530 } 4531 return false; 4532 } 4533 4534 @Override 4535 public int checkSignatures(String pkg1, String pkg2) { 4536 synchronized (mPackages) { 4537 final PackageParser.Package p1 = mPackages.get(pkg1); 4538 final PackageParser.Package p2 = mPackages.get(pkg2); 4539 if (p1 == null || p1.mExtras == null 4540 || p2 == null || p2.mExtras == null) { 4541 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4542 } 4543 return compareSignatures(p1.mSignatures, p2.mSignatures); 4544 } 4545 } 4546 4547 @Override 4548 public int checkUidSignatures(int uid1, int uid2) { 4549 // Map to base uids. 4550 uid1 = UserHandle.getAppId(uid1); 4551 uid2 = UserHandle.getAppId(uid2); 4552 // reader 4553 synchronized (mPackages) { 4554 Signature[] s1; 4555 Signature[] s2; 4556 Object obj = mSettings.getUserIdLPr(uid1); 4557 if (obj != null) { 4558 if (obj instanceof SharedUserSetting) { 4559 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4560 } else if (obj instanceof PackageSetting) { 4561 s1 = ((PackageSetting)obj).signatures.mSignatures; 4562 } else { 4563 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4564 } 4565 } else { 4566 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4567 } 4568 obj = mSettings.getUserIdLPr(uid2); 4569 if (obj != null) { 4570 if (obj instanceof SharedUserSetting) { 4571 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4572 } else if (obj instanceof PackageSetting) { 4573 s2 = ((PackageSetting)obj).signatures.mSignatures; 4574 } else { 4575 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4576 } 4577 } else { 4578 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4579 } 4580 return compareSignatures(s1, s2); 4581 } 4582 } 4583 4584 /** 4585 * This method should typically only be used when granting or revoking 4586 * permissions, since the app may immediately restart after this call. 4587 * <p> 4588 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4589 * guard your work against the app being relaunched. 4590 */ 4591 private void killUid(int appId, int userId, String reason) { 4592 final long identity = Binder.clearCallingIdentity(); 4593 try { 4594 IActivityManager am = ActivityManagerNative.getDefault(); 4595 if (am != null) { 4596 try { 4597 am.killUid(appId, userId, reason); 4598 } catch (RemoteException e) { 4599 /* ignore - same process */ 4600 } 4601 } 4602 } finally { 4603 Binder.restoreCallingIdentity(identity); 4604 } 4605 } 4606 4607 /** 4608 * Compares two sets of signatures. Returns: 4609 * <br /> 4610 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4611 * <br /> 4612 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4613 * <br /> 4614 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4615 * <br /> 4616 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4617 * <br /> 4618 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4619 */ 4620 static int compareSignatures(Signature[] s1, Signature[] s2) { 4621 if (s1 == null) { 4622 return s2 == null 4623 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4624 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4625 } 4626 4627 if (s2 == null) { 4628 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4629 } 4630 4631 if (s1.length != s2.length) { 4632 return PackageManager.SIGNATURE_NO_MATCH; 4633 } 4634 4635 // Since both signature sets are of size 1, we can compare without HashSets. 4636 if (s1.length == 1) { 4637 return s1[0].equals(s2[0]) ? 4638 PackageManager.SIGNATURE_MATCH : 4639 PackageManager.SIGNATURE_NO_MATCH; 4640 } 4641 4642 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4643 for (Signature sig : s1) { 4644 set1.add(sig); 4645 } 4646 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4647 for (Signature sig : s2) { 4648 set2.add(sig); 4649 } 4650 // Make sure s2 contains all signatures in s1. 4651 if (set1.equals(set2)) { 4652 return PackageManager.SIGNATURE_MATCH; 4653 } 4654 return PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 /** 4658 * If the database version for this type of package (internal storage or 4659 * external storage) is less than the version where package signatures 4660 * were updated, return true. 4661 */ 4662 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4663 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4664 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4665 } 4666 4667 /** 4668 * Used for backward compatibility to make sure any packages with 4669 * certificate chains get upgraded to the new style. {@code existingSigs} 4670 * will be in the old format (since they were stored on disk from before the 4671 * system upgrade) and {@code scannedSigs} will be in the newer format. 4672 */ 4673 private int compareSignaturesCompat(PackageSignatures existingSigs, 4674 PackageParser.Package scannedPkg) { 4675 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4676 return PackageManager.SIGNATURE_NO_MATCH; 4677 } 4678 4679 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4680 for (Signature sig : existingSigs.mSignatures) { 4681 existingSet.add(sig); 4682 } 4683 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4684 for (Signature sig : scannedPkg.mSignatures) { 4685 try { 4686 Signature[] chainSignatures = sig.getChainSignatures(); 4687 for (Signature chainSig : chainSignatures) { 4688 scannedCompatSet.add(chainSig); 4689 } 4690 } catch (CertificateEncodingException e) { 4691 scannedCompatSet.add(sig); 4692 } 4693 } 4694 /* 4695 * Make sure the expanded scanned set contains all signatures in the 4696 * existing one. 4697 */ 4698 if (scannedCompatSet.equals(existingSet)) { 4699 // Migrate the old signatures to the new scheme. 4700 existingSigs.assignSignatures(scannedPkg.mSignatures); 4701 // The new KeySets will be re-added later in the scanning process. 4702 synchronized (mPackages) { 4703 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4704 } 4705 return PackageManager.SIGNATURE_MATCH; 4706 } 4707 return PackageManager.SIGNATURE_NO_MATCH; 4708 } 4709 4710 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4711 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4712 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4713 } 4714 4715 private int compareSignaturesRecover(PackageSignatures existingSigs, 4716 PackageParser.Package scannedPkg) { 4717 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4718 return PackageManager.SIGNATURE_NO_MATCH; 4719 } 4720 4721 String msg = null; 4722 try { 4723 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4724 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4725 + scannedPkg.packageName); 4726 return PackageManager.SIGNATURE_MATCH; 4727 } 4728 } catch (CertificateException e) { 4729 msg = e.getMessage(); 4730 } 4731 4732 logCriticalInfo(Log.INFO, 4733 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4734 return PackageManager.SIGNATURE_NO_MATCH; 4735 } 4736 4737 @Override 4738 public List<String> getAllPackages() { 4739 synchronized (mPackages) { 4740 return new ArrayList<String>(mPackages.keySet()); 4741 } 4742 } 4743 4744 @Override 4745 public String[] getPackagesForUid(int uid) { 4746 uid = UserHandle.getAppId(uid); 4747 // reader 4748 synchronized (mPackages) { 4749 Object obj = mSettings.getUserIdLPr(uid); 4750 if (obj instanceof SharedUserSetting) { 4751 final SharedUserSetting sus = (SharedUserSetting) obj; 4752 final int N = sus.packages.size(); 4753 final String[] res = new String[N]; 4754 final Iterator<PackageSetting> it = sus.packages.iterator(); 4755 int i = 0; 4756 while (it.hasNext()) { 4757 res[i++] = it.next().name; 4758 } 4759 return res; 4760 } else if (obj instanceof PackageSetting) { 4761 final PackageSetting ps = (PackageSetting) obj; 4762 return new String[] { ps.name }; 4763 } 4764 } 4765 return null; 4766 } 4767 4768 @Override 4769 public String getNameForUid(int uid) { 4770 // reader 4771 synchronized (mPackages) { 4772 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4773 if (obj instanceof SharedUserSetting) { 4774 final SharedUserSetting sus = (SharedUserSetting) obj; 4775 return sus.name + ":" + sus.userId; 4776 } else if (obj instanceof PackageSetting) { 4777 final PackageSetting ps = (PackageSetting) obj; 4778 return ps.name; 4779 } 4780 } 4781 return null; 4782 } 4783 4784 @Override 4785 public int getUidForSharedUser(String sharedUserName) { 4786 if(sharedUserName == null) { 4787 return -1; 4788 } 4789 // reader 4790 synchronized (mPackages) { 4791 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4792 if (suid == null) { 4793 return -1; 4794 } 4795 return suid.userId; 4796 } 4797 } 4798 4799 @Override 4800 public int getFlagsForUid(int uid) { 4801 synchronized (mPackages) { 4802 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4803 if (obj instanceof SharedUserSetting) { 4804 final SharedUserSetting sus = (SharedUserSetting) obj; 4805 return sus.pkgFlags; 4806 } else if (obj instanceof PackageSetting) { 4807 final PackageSetting ps = (PackageSetting) obj; 4808 return ps.pkgFlags; 4809 } 4810 } 4811 return 0; 4812 } 4813 4814 @Override 4815 public int getPrivateFlagsForUid(int uid) { 4816 synchronized (mPackages) { 4817 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4818 if (obj instanceof SharedUserSetting) { 4819 final SharedUserSetting sus = (SharedUserSetting) obj; 4820 return sus.pkgPrivateFlags; 4821 } else if (obj instanceof PackageSetting) { 4822 final PackageSetting ps = (PackageSetting) obj; 4823 return ps.pkgPrivateFlags; 4824 } 4825 } 4826 return 0; 4827 } 4828 4829 @Override 4830 public boolean isUidPrivileged(int uid) { 4831 uid = UserHandle.getAppId(uid); 4832 // reader 4833 synchronized (mPackages) { 4834 Object obj = mSettings.getUserIdLPr(uid); 4835 if (obj instanceof SharedUserSetting) { 4836 final SharedUserSetting sus = (SharedUserSetting) obj; 4837 final Iterator<PackageSetting> it = sus.packages.iterator(); 4838 while (it.hasNext()) { 4839 if (it.next().isPrivileged()) { 4840 return true; 4841 } 4842 } 4843 } else if (obj instanceof PackageSetting) { 4844 final PackageSetting ps = (PackageSetting) obj; 4845 return ps.isPrivileged(); 4846 } 4847 } 4848 return false; 4849 } 4850 4851 @Override 4852 public String[] getAppOpPermissionPackages(String permissionName) { 4853 synchronized (mPackages) { 4854 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4855 if (pkgs == null) { 4856 return null; 4857 } 4858 return pkgs.toArray(new String[pkgs.size()]); 4859 } 4860 } 4861 4862 @Override 4863 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4864 int flags, int userId) { 4865 try { 4866 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4867 4868 if (!sUserManager.exists(userId)) return null; 4869 flags = updateFlagsForResolve(flags, userId, intent); 4870 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4871 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4872 4873 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4874 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4875 flags, userId); 4876 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4877 4878 final ResolveInfo bestChoice = 4879 chooseBestActivity(intent, resolvedType, flags, query, userId); 4880 4881 if (isEphemeralAllowed(intent, query, userId)) { 4882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4883 final EphemeralResolveInfo ai = 4884 getEphemeralResolveInfo(intent, resolvedType, userId); 4885 if (ai != null) { 4886 if (DEBUG_EPHEMERAL) { 4887 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4888 } 4889 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4890 bestChoice.ephemeralResolveInfo = ai; 4891 } 4892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4893 } 4894 return bestChoice; 4895 } finally { 4896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4897 } 4898 } 4899 4900 @Override 4901 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4902 IntentFilter filter, int match, ComponentName activity) { 4903 final int userId = UserHandle.getCallingUserId(); 4904 if (DEBUG_PREFERRED) { 4905 Log.v(TAG, "setLastChosenActivity intent=" + intent 4906 + " resolvedType=" + resolvedType 4907 + " flags=" + flags 4908 + " filter=" + filter 4909 + " match=" + match 4910 + " activity=" + activity); 4911 filter.dump(new PrintStreamPrinter(System.out), " "); 4912 } 4913 intent.setComponent(null); 4914 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4915 userId); 4916 // Find any earlier preferred or last chosen entries and nuke them 4917 findPreferredActivity(intent, resolvedType, 4918 flags, query, 0, false, true, false, userId); 4919 // Add the new activity as the last chosen for this filter 4920 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4921 "Setting last chosen"); 4922 } 4923 4924 @Override 4925 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4926 final int userId = UserHandle.getCallingUserId(); 4927 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4928 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4929 userId); 4930 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4931 false, false, false, userId); 4932 } 4933 4934 4935 private boolean isEphemeralAllowed( 4936 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4937 // Short circuit and return early if possible. 4938 if (DISABLE_EPHEMERAL_APPS) { 4939 return false; 4940 } 4941 final int callingUser = UserHandle.getCallingUserId(); 4942 if (callingUser != UserHandle.USER_SYSTEM) { 4943 return false; 4944 } 4945 if (mEphemeralResolverConnection == null) { 4946 return false; 4947 } 4948 if (intent.getComponent() != null) { 4949 return false; 4950 } 4951 if (intent.getPackage() != null) { 4952 return false; 4953 } 4954 final boolean isWebUri = hasWebURI(intent); 4955 if (!isWebUri) { 4956 return false; 4957 } 4958 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4959 synchronized (mPackages) { 4960 final int count = resolvedActivites.size(); 4961 for (int n = 0; n < count; n++) { 4962 ResolveInfo info = resolvedActivites.get(n); 4963 String packageName = info.activityInfo.packageName; 4964 PackageSetting ps = mSettings.mPackages.get(packageName); 4965 if (ps != null) { 4966 // Try to get the status from User settings first 4967 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4968 int status = (int) (packedStatus >> 32); 4969 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4970 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4971 if (DEBUG_EPHEMERAL) { 4972 Slog.v(TAG, "DENY ephemeral apps;" 4973 + " pkg: " + packageName + ", status: " + status); 4974 } 4975 return false; 4976 } 4977 } 4978 } 4979 } 4980 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4981 return true; 4982 } 4983 4984 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4985 int userId) { 4986 MessageDigest digest = null; 4987 try { 4988 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4989 } catch (NoSuchAlgorithmException e) { 4990 // If we can't create a digest, ignore ephemeral apps. 4991 return null; 4992 } 4993 4994 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4995 final byte[] digestBytes = digest.digest(hostBytes); 4996 int shaPrefix = 4997 digestBytes[0] << 24 4998 | digestBytes[1] << 16 4999 | digestBytes[2] << 8 5000 | digestBytes[3] << 0; 5001 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5002 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 5003 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5004 // No hash prefix match; there are no ephemeral apps for this domain. 5005 return null; 5006 } 5007 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 5008 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 5009 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 5010 continue; 5011 } 5012 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5013 // No filters; this should never happen. 5014 if (filters.isEmpty()) { 5015 continue; 5016 } 5017 // We have a domain match; resolve the filters to see if anything matches. 5018 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5019 for (int j = filters.size() - 1; j >= 0; --j) { 5020 final EphemeralResolveIntentInfo intentInfo = 5021 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5022 ephemeralResolver.addFilter(intentInfo); 5023 } 5024 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5025 intent, resolvedType, false /*defaultOnly*/, userId); 5026 if (!matchedResolveInfoList.isEmpty()) { 5027 return matchedResolveInfoList.get(0); 5028 } 5029 } 5030 // Hash or filter mis-match; no ephemeral apps for this domain. 5031 return null; 5032 } 5033 5034 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5035 int flags, List<ResolveInfo> query, int userId) { 5036 if (query != null) { 5037 final int N = query.size(); 5038 if (N == 1) { 5039 return query.get(0); 5040 } else if (N > 1) { 5041 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5042 // If there is more than one activity with the same priority, 5043 // then let the user decide between them. 5044 ResolveInfo r0 = query.get(0); 5045 ResolveInfo r1 = query.get(1); 5046 if (DEBUG_INTENT_MATCHING || debug) { 5047 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5048 + r1.activityInfo.name + "=" + r1.priority); 5049 } 5050 // If the first activity has a higher priority, or a different 5051 // default, then it is always desirable to pick it. 5052 if (r0.priority != r1.priority 5053 || r0.preferredOrder != r1.preferredOrder 5054 || r0.isDefault != r1.isDefault) { 5055 return query.get(0); 5056 } 5057 // If we have saved a preference for a preferred activity for 5058 // this Intent, use that. 5059 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5060 flags, query, r0.priority, true, false, debug, userId); 5061 if (ri != null) { 5062 return ri; 5063 } 5064 ri = new ResolveInfo(mResolveInfo); 5065 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5066 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5067 // If all of the options come from the same package, show the application's 5068 // label and icon instead of the generic resolver's. 5069 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5070 // and then throw away the ResolveInfo itself, meaning that the caller loses 5071 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5072 // a fallback for this case; we only set the target package's resources on 5073 // the ResolveInfo, not the ActivityInfo. 5074 final String intentPackage = intent.getPackage(); 5075 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5076 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5077 ri.resolvePackageName = intentPackage; 5078 if (userNeedsBadging(userId)) { 5079 ri.noResourceId = true; 5080 } else { 5081 ri.icon = appi.icon; 5082 } 5083 ri.iconResourceId = appi.icon; 5084 ri.labelRes = appi.labelRes; 5085 } 5086 ri.activityInfo.applicationInfo = new ApplicationInfo( 5087 ri.activityInfo.applicationInfo); 5088 if (userId != 0) { 5089 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5090 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5091 } 5092 // Make sure that the resolver is displayable in car mode 5093 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5094 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5095 return ri; 5096 } 5097 } 5098 return null; 5099 } 5100 5101 /** 5102 * Return true if the given list is not empty and all of its contents have 5103 * an activityInfo with the given package name. 5104 */ 5105 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5106 if (ArrayUtils.isEmpty(list)) { 5107 return false; 5108 } 5109 for (int i = 0, N = list.size(); i < N; i++) { 5110 final ResolveInfo ri = list.get(i); 5111 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5112 if (ai == null || !packageName.equals(ai.packageName)) { 5113 return false; 5114 } 5115 } 5116 return true; 5117 } 5118 5119 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5120 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5121 final int N = query.size(); 5122 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5123 .get(userId); 5124 // Get the list of persistent preferred activities that handle the intent 5125 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5126 List<PersistentPreferredActivity> pprefs = ppir != null 5127 ? ppir.queryIntent(intent, resolvedType, 5128 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5129 : null; 5130 if (pprefs != null && pprefs.size() > 0) { 5131 final int M = pprefs.size(); 5132 for (int i=0; i<M; i++) { 5133 final PersistentPreferredActivity ppa = pprefs.get(i); 5134 if (DEBUG_PREFERRED || debug) { 5135 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5136 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5137 + "\n component=" + ppa.mComponent); 5138 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5139 } 5140 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5141 flags | MATCH_DISABLED_COMPONENTS, userId); 5142 if (DEBUG_PREFERRED || debug) { 5143 Slog.v(TAG, "Found persistent preferred activity:"); 5144 if (ai != null) { 5145 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5146 } else { 5147 Slog.v(TAG, " null"); 5148 } 5149 } 5150 if (ai == null) { 5151 // This previously registered persistent preferred activity 5152 // component is no longer known. Ignore it and do NOT remove it. 5153 continue; 5154 } 5155 for (int j=0; j<N; j++) { 5156 final ResolveInfo ri = query.get(j); 5157 if (!ri.activityInfo.applicationInfo.packageName 5158 .equals(ai.applicationInfo.packageName)) { 5159 continue; 5160 } 5161 if (!ri.activityInfo.name.equals(ai.name)) { 5162 continue; 5163 } 5164 // Found a persistent preference that can handle the intent. 5165 if (DEBUG_PREFERRED || debug) { 5166 Slog.v(TAG, "Returning persistent preferred activity: " + 5167 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5168 } 5169 return ri; 5170 } 5171 } 5172 } 5173 return null; 5174 } 5175 5176 // TODO: handle preferred activities missing while user has amnesia 5177 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5178 List<ResolveInfo> query, int priority, boolean always, 5179 boolean removeMatches, boolean debug, int userId) { 5180 if (!sUserManager.exists(userId)) return null; 5181 flags = updateFlagsForResolve(flags, userId, intent); 5182 // writer 5183 synchronized (mPackages) { 5184 if (intent.getSelector() != null) { 5185 intent = intent.getSelector(); 5186 } 5187 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5188 5189 // Try to find a matching persistent preferred activity. 5190 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5191 debug, userId); 5192 5193 // If a persistent preferred activity matched, use it. 5194 if (pri != null) { 5195 return pri; 5196 } 5197 5198 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5199 // Get the list of preferred activities that handle the intent 5200 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5201 List<PreferredActivity> prefs = pir != null 5202 ? pir.queryIntent(intent, resolvedType, 5203 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5204 : null; 5205 if (prefs != null && prefs.size() > 0) { 5206 boolean changed = false; 5207 try { 5208 // First figure out how good the original match set is. 5209 // We will only allow preferred activities that came 5210 // from the same match quality. 5211 int match = 0; 5212 5213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5214 5215 final int N = query.size(); 5216 for (int j=0; j<N; j++) { 5217 final ResolveInfo ri = query.get(j); 5218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5219 + ": 0x" + Integer.toHexString(match)); 5220 if (ri.match > match) { 5221 match = ri.match; 5222 } 5223 } 5224 5225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5226 + Integer.toHexString(match)); 5227 5228 match &= IntentFilter.MATCH_CATEGORY_MASK; 5229 final int M = prefs.size(); 5230 for (int i=0; i<M; i++) { 5231 final PreferredActivity pa = prefs.get(i); 5232 if (DEBUG_PREFERRED || debug) { 5233 Slog.v(TAG, "Checking PreferredActivity ds=" 5234 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5235 + "\n component=" + pa.mPref.mComponent); 5236 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5237 } 5238 if (pa.mPref.mMatch != match) { 5239 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5240 + Integer.toHexString(pa.mPref.mMatch)); 5241 continue; 5242 } 5243 // If it's not an "always" type preferred activity and that's what we're 5244 // looking for, skip it. 5245 if (always && !pa.mPref.mAlways) { 5246 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5247 continue; 5248 } 5249 final ActivityInfo ai = getActivityInfo( 5250 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5251 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5252 userId); 5253 if (DEBUG_PREFERRED || debug) { 5254 Slog.v(TAG, "Found preferred activity:"); 5255 if (ai != null) { 5256 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5257 } else { 5258 Slog.v(TAG, " null"); 5259 } 5260 } 5261 if (ai == null) { 5262 // This previously registered preferred activity 5263 // component is no longer known. Most likely an update 5264 // to the app was installed and in the new version this 5265 // component no longer exists. Clean it up by removing 5266 // it from the preferred activities list, and skip it. 5267 Slog.w(TAG, "Removing dangling preferred activity: " 5268 + pa.mPref.mComponent); 5269 pir.removeFilter(pa); 5270 changed = true; 5271 continue; 5272 } 5273 for (int j=0; j<N; j++) { 5274 final ResolveInfo ri = query.get(j); 5275 if (!ri.activityInfo.applicationInfo.packageName 5276 .equals(ai.applicationInfo.packageName)) { 5277 continue; 5278 } 5279 if (!ri.activityInfo.name.equals(ai.name)) { 5280 continue; 5281 } 5282 5283 if (removeMatches) { 5284 pir.removeFilter(pa); 5285 changed = true; 5286 if (DEBUG_PREFERRED) { 5287 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5288 } 5289 break; 5290 } 5291 5292 // Okay we found a previously set preferred or last chosen app. 5293 // If the result set is different from when this 5294 // was created, we need to clear it and re-ask the 5295 // user their preference, if we're looking for an "always" type entry. 5296 if (always && !pa.mPref.sameSet(query)) { 5297 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5298 + intent + " type " + resolvedType); 5299 if (DEBUG_PREFERRED) { 5300 Slog.v(TAG, "Removing preferred activity since set changed " 5301 + pa.mPref.mComponent); 5302 } 5303 pir.removeFilter(pa); 5304 // Re-add the filter as a "last chosen" entry (!always) 5305 PreferredActivity lastChosen = new PreferredActivity( 5306 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5307 pir.addFilter(lastChosen); 5308 changed = true; 5309 return null; 5310 } 5311 5312 // Yay! Either the set matched or we're looking for the last chosen 5313 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5314 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5315 return ri; 5316 } 5317 } 5318 } finally { 5319 if (changed) { 5320 if (DEBUG_PREFERRED) { 5321 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5322 } 5323 scheduleWritePackageRestrictionsLocked(userId); 5324 } 5325 } 5326 } 5327 } 5328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5329 return null; 5330 } 5331 5332 /* 5333 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5334 */ 5335 @Override 5336 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5337 int targetUserId) { 5338 mContext.enforceCallingOrSelfPermission( 5339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5340 List<CrossProfileIntentFilter> matches = 5341 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5342 if (matches != null) { 5343 int size = matches.size(); 5344 for (int i = 0; i < size; i++) { 5345 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5346 } 5347 } 5348 if (hasWebURI(intent)) { 5349 // cross-profile app linking works only towards the parent. 5350 final UserInfo parent = getProfileParent(sourceUserId); 5351 synchronized(mPackages) { 5352 int flags = updateFlagsForResolve(0, parent.id, intent); 5353 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5354 intent, resolvedType, flags, sourceUserId, parent.id); 5355 return xpDomainInfo != null; 5356 } 5357 } 5358 return false; 5359 } 5360 5361 private UserInfo getProfileParent(int userId) { 5362 final long identity = Binder.clearCallingIdentity(); 5363 try { 5364 return sUserManager.getProfileParent(userId); 5365 } finally { 5366 Binder.restoreCallingIdentity(identity); 5367 } 5368 } 5369 5370 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5371 String resolvedType, int userId) { 5372 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5373 if (resolver != null) { 5374 return resolver.queryIntent(intent, resolvedType, false, userId); 5375 } 5376 return null; 5377 } 5378 5379 @Override 5380 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5381 String resolvedType, int flags, int userId) { 5382 try { 5383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5384 5385 return new ParceledListSlice<>( 5386 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5387 } finally { 5388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5389 } 5390 } 5391 5392 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5393 String resolvedType, int flags, int userId) { 5394 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5395 flags = updateFlagsForResolve(flags, userId, intent); 5396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5397 false /* requireFullPermission */, false /* checkShell */, 5398 "query intent activities"); 5399 ComponentName comp = intent.getComponent(); 5400 if (comp == null) { 5401 if (intent.getSelector() != null) { 5402 intent = intent.getSelector(); 5403 comp = intent.getComponent(); 5404 } 5405 } 5406 5407 if (comp != null) { 5408 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5409 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5410 if (ai != null) { 5411 final ResolveInfo ri = new ResolveInfo(); 5412 ri.activityInfo = ai; 5413 list.add(ri); 5414 } 5415 return list; 5416 } 5417 5418 // reader 5419 synchronized (mPackages) { 5420 final String pkgName = intent.getPackage(); 5421 if (pkgName == null) { 5422 List<CrossProfileIntentFilter> matchingFilters = 5423 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5424 // Check for results that need to skip the current profile. 5425 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5426 resolvedType, flags, userId); 5427 if (xpResolveInfo != null) { 5428 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5429 result.add(xpResolveInfo); 5430 return filterIfNotSystemUser(result, userId); 5431 } 5432 5433 // Check for results in the current profile. 5434 List<ResolveInfo> result = mActivities.queryIntent( 5435 intent, resolvedType, flags, userId); 5436 result = filterIfNotSystemUser(result, userId); 5437 5438 // Check for cross profile results. 5439 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5440 xpResolveInfo = queryCrossProfileIntents( 5441 matchingFilters, intent, resolvedType, flags, userId, 5442 hasNonNegativePriorityResult); 5443 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5444 boolean isVisibleToUser = filterIfNotSystemUser( 5445 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5446 if (isVisibleToUser) { 5447 result.add(xpResolveInfo); 5448 Collections.sort(result, mResolvePrioritySorter); 5449 } 5450 } 5451 if (hasWebURI(intent)) { 5452 CrossProfileDomainInfo xpDomainInfo = null; 5453 final UserInfo parent = getProfileParent(userId); 5454 if (parent != null) { 5455 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5456 flags, userId, parent.id); 5457 } 5458 if (xpDomainInfo != null) { 5459 if (xpResolveInfo != null) { 5460 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5461 // in the result. 5462 result.remove(xpResolveInfo); 5463 } 5464 if (result.size() == 0) { 5465 result.add(xpDomainInfo.resolveInfo); 5466 return result; 5467 } 5468 } else if (result.size() <= 1) { 5469 return result; 5470 } 5471 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5472 xpDomainInfo, userId); 5473 Collections.sort(result, mResolvePrioritySorter); 5474 } 5475 return result; 5476 } 5477 final PackageParser.Package pkg = mPackages.get(pkgName); 5478 if (pkg != null) { 5479 return filterIfNotSystemUser( 5480 mActivities.queryIntentForPackage( 5481 intent, resolvedType, flags, pkg.activities, userId), 5482 userId); 5483 } 5484 return new ArrayList<ResolveInfo>(); 5485 } 5486 } 5487 5488 private static class CrossProfileDomainInfo { 5489 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5490 ResolveInfo resolveInfo; 5491 /* Best domain verification status of the activities found in the other profile */ 5492 int bestDomainVerificationStatus; 5493 } 5494 5495 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5496 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5497 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5498 sourceUserId)) { 5499 return null; 5500 } 5501 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5502 resolvedType, flags, parentUserId); 5503 5504 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5505 return null; 5506 } 5507 CrossProfileDomainInfo result = null; 5508 int size = resultTargetUser.size(); 5509 for (int i = 0; i < size; i++) { 5510 ResolveInfo riTargetUser = resultTargetUser.get(i); 5511 // Intent filter verification is only for filters that specify a host. So don't return 5512 // those that handle all web uris. 5513 if (riTargetUser.handleAllWebDataURI) { 5514 continue; 5515 } 5516 String packageName = riTargetUser.activityInfo.packageName; 5517 PackageSetting ps = mSettings.mPackages.get(packageName); 5518 if (ps == null) { 5519 continue; 5520 } 5521 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5522 int status = (int)(verificationState >> 32); 5523 if (result == null) { 5524 result = new CrossProfileDomainInfo(); 5525 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5526 sourceUserId, parentUserId); 5527 result.bestDomainVerificationStatus = status; 5528 } else { 5529 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5530 result.bestDomainVerificationStatus); 5531 } 5532 } 5533 // Don't consider matches with status NEVER across profiles. 5534 if (result != null && result.bestDomainVerificationStatus 5535 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5536 return null; 5537 } 5538 return result; 5539 } 5540 5541 /** 5542 * Verification statuses are ordered from the worse to the best, except for 5543 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5544 */ 5545 private int bestDomainVerificationStatus(int status1, int status2) { 5546 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5547 return status2; 5548 } 5549 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5550 return status1; 5551 } 5552 return (int) MathUtils.max(status1, status2); 5553 } 5554 5555 private boolean isUserEnabled(int userId) { 5556 long callingId = Binder.clearCallingIdentity(); 5557 try { 5558 UserInfo userInfo = sUserManager.getUserInfo(userId); 5559 return userInfo != null && userInfo.isEnabled(); 5560 } finally { 5561 Binder.restoreCallingIdentity(callingId); 5562 } 5563 } 5564 5565 /** 5566 * Filter out activities with systemUserOnly flag set, when current user is not System. 5567 * 5568 * @return filtered list 5569 */ 5570 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5571 if (userId == UserHandle.USER_SYSTEM) { 5572 return resolveInfos; 5573 } 5574 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5575 ResolveInfo info = resolveInfos.get(i); 5576 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5577 resolveInfos.remove(i); 5578 } 5579 } 5580 return resolveInfos; 5581 } 5582 5583 /** 5584 * @param resolveInfos list of resolve infos in descending priority order 5585 * @return if the list contains a resolve info with non-negative priority 5586 */ 5587 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5588 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5589 } 5590 5591 private static boolean hasWebURI(Intent intent) { 5592 if (intent.getData() == null) { 5593 return false; 5594 } 5595 final String scheme = intent.getScheme(); 5596 if (TextUtils.isEmpty(scheme)) { 5597 return false; 5598 } 5599 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5600 } 5601 5602 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5603 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5604 int userId) { 5605 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5606 5607 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5608 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5609 candidates.size()); 5610 } 5611 5612 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5613 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5614 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5615 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5616 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5617 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5618 5619 synchronized (mPackages) { 5620 final int count = candidates.size(); 5621 // First, try to use linked apps. Partition the candidates into four lists: 5622 // one for the final results, one for the "do not use ever", one for "undefined status" 5623 // and finally one for "browser app type". 5624 for (int n=0; n<count; n++) { 5625 ResolveInfo info = candidates.get(n); 5626 String packageName = info.activityInfo.packageName; 5627 PackageSetting ps = mSettings.mPackages.get(packageName); 5628 if (ps != null) { 5629 // Add to the special match all list (Browser use case) 5630 if (info.handleAllWebDataURI) { 5631 matchAllList.add(info); 5632 continue; 5633 } 5634 // Try to get the status from User settings first 5635 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5636 int status = (int)(packedStatus >> 32); 5637 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5638 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5639 if (DEBUG_DOMAIN_VERIFICATION) { 5640 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5641 + " : linkgen=" + linkGeneration); 5642 } 5643 // Use link-enabled generation as preferredOrder, i.e. 5644 // prefer newly-enabled over earlier-enabled. 5645 info.preferredOrder = linkGeneration; 5646 alwaysList.add(info); 5647 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5648 if (DEBUG_DOMAIN_VERIFICATION) { 5649 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5650 } 5651 neverList.add(info); 5652 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5653 if (DEBUG_DOMAIN_VERIFICATION) { 5654 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5655 } 5656 alwaysAskList.add(info); 5657 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5658 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5659 if (DEBUG_DOMAIN_VERIFICATION) { 5660 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5661 } 5662 undefinedList.add(info); 5663 } 5664 } 5665 } 5666 5667 // We'll want to include browser possibilities in a few cases 5668 boolean includeBrowser = false; 5669 5670 // First try to add the "always" resolution(s) for the current user, if any 5671 if (alwaysList.size() > 0) { 5672 result.addAll(alwaysList); 5673 } else { 5674 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5675 result.addAll(undefinedList); 5676 // Maybe add one for the other profile. 5677 if (xpDomainInfo != null && ( 5678 xpDomainInfo.bestDomainVerificationStatus 5679 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5680 result.add(xpDomainInfo.resolveInfo); 5681 } 5682 includeBrowser = true; 5683 } 5684 5685 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5686 // If there were 'always' entries their preferred order has been set, so we also 5687 // back that off to make the alternatives equivalent 5688 if (alwaysAskList.size() > 0) { 5689 for (ResolveInfo i : result) { 5690 i.preferredOrder = 0; 5691 } 5692 result.addAll(alwaysAskList); 5693 includeBrowser = true; 5694 } 5695 5696 if (includeBrowser) { 5697 // Also add browsers (all of them or only the default one) 5698 if (DEBUG_DOMAIN_VERIFICATION) { 5699 Slog.v(TAG, " ...including browsers in candidate set"); 5700 } 5701 if ((matchFlags & MATCH_ALL) != 0) { 5702 result.addAll(matchAllList); 5703 } else { 5704 // Browser/generic handling case. If there's a default browser, go straight 5705 // to that (but only if there is no other higher-priority match). 5706 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5707 int maxMatchPrio = 0; 5708 ResolveInfo defaultBrowserMatch = null; 5709 final int numCandidates = matchAllList.size(); 5710 for (int n = 0; n < numCandidates; n++) { 5711 ResolveInfo info = matchAllList.get(n); 5712 // track the highest overall match priority... 5713 if (info.priority > maxMatchPrio) { 5714 maxMatchPrio = info.priority; 5715 } 5716 // ...and the highest-priority default browser match 5717 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5718 if (defaultBrowserMatch == null 5719 || (defaultBrowserMatch.priority < info.priority)) { 5720 if (debug) { 5721 Slog.v(TAG, "Considering default browser match " + info); 5722 } 5723 defaultBrowserMatch = info; 5724 } 5725 } 5726 } 5727 if (defaultBrowserMatch != null 5728 && defaultBrowserMatch.priority >= maxMatchPrio 5729 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5730 { 5731 if (debug) { 5732 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5733 } 5734 result.add(defaultBrowserMatch); 5735 } else { 5736 result.addAll(matchAllList); 5737 } 5738 } 5739 5740 // If there is nothing selected, add all candidates and remove the ones that the user 5741 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5742 if (result.size() == 0) { 5743 result.addAll(candidates); 5744 result.removeAll(neverList); 5745 } 5746 } 5747 } 5748 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5749 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5750 result.size()); 5751 for (ResolveInfo info : result) { 5752 Slog.v(TAG, " + " + info.activityInfo); 5753 } 5754 } 5755 return result; 5756 } 5757 5758 // Returns a packed value as a long: 5759 // 5760 // high 'int'-sized word: link status: undefined/ask/never/always. 5761 // low 'int'-sized word: relative priority among 'always' results. 5762 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5763 long result = ps.getDomainVerificationStatusForUser(userId); 5764 // if none available, get the master status 5765 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5766 if (ps.getIntentFilterVerificationInfo() != null) { 5767 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5768 } 5769 } 5770 return result; 5771 } 5772 5773 private ResolveInfo querySkipCurrentProfileIntents( 5774 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5775 int flags, int sourceUserId) { 5776 if (matchingFilters != null) { 5777 int size = matchingFilters.size(); 5778 for (int i = 0; i < size; i ++) { 5779 CrossProfileIntentFilter filter = matchingFilters.get(i); 5780 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5781 // Checking if there are activities in the target user that can handle the 5782 // intent. 5783 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5784 resolvedType, flags, sourceUserId); 5785 if (resolveInfo != null) { 5786 return resolveInfo; 5787 } 5788 } 5789 } 5790 } 5791 return null; 5792 } 5793 5794 // Return matching ResolveInfo in target user if any. 5795 private ResolveInfo queryCrossProfileIntents( 5796 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5797 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5798 if (matchingFilters != null) { 5799 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5800 // match the same intent. For performance reasons, it is better not to 5801 // run queryIntent twice for the same userId 5802 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5803 int size = matchingFilters.size(); 5804 for (int i = 0; i < size; i++) { 5805 CrossProfileIntentFilter filter = matchingFilters.get(i); 5806 int targetUserId = filter.getTargetUserId(); 5807 boolean skipCurrentProfile = 5808 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5809 boolean skipCurrentProfileIfNoMatchFound = 5810 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5811 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5812 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5813 // Checking if there are activities in the target user that can handle the 5814 // intent. 5815 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5816 resolvedType, flags, sourceUserId); 5817 if (resolveInfo != null) return resolveInfo; 5818 alreadyTriedUserIds.put(targetUserId, true); 5819 } 5820 } 5821 } 5822 return null; 5823 } 5824 5825 /** 5826 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5827 * will forward the intent to the filter's target user. 5828 * Otherwise, returns null. 5829 */ 5830 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5831 String resolvedType, int flags, int sourceUserId) { 5832 int targetUserId = filter.getTargetUserId(); 5833 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5834 resolvedType, flags, targetUserId); 5835 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5836 // If all the matches in the target profile are suspended, return null. 5837 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5838 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5839 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5840 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5841 targetUserId); 5842 } 5843 } 5844 } 5845 return null; 5846 } 5847 5848 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5849 int sourceUserId, int targetUserId) { 5850 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5851 long ident = Binder.clearCallingIdentity(); 5852 boolean targetIsProfile; 5853 try { 5854 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5855 } finally { 5856 Binder.restoreCallingIdentity(ident); 5857 } 5858 String className; 5859 if (targetIsProfile) { 5860 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5861 } else { 5862 className = FORWARD_INTENT_TO_PARENT; 5863 } 5864 ComponentName forwardingActivityComponentName = new ComponentName( 5865 mAndroidApplication.packageName, className); 5866 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5867 sourceUserId); 5868 if (!targetIsProfile) { 5869 forwardingActivityInfo.showUserIcon = targetUserId; 5870 forwardingResolveInfo.noResourceId = true; 5871 } 5872 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5873 forwardingResolveInfo.priority = 0; 5874 forwardingResolveInfo.preferredOrder = 0; 5875 forwardingResolveInfo.match = 0; 5876 forwardingResolveInfo.isDefault = true; 5877 forwardingResolveInfo.filter = filter; 5878 forwardingResolveInfo.targetUserId = targetUserId; 5879 return forwardingResolveInfo; 5880 } 5881 5882 @Override 5883 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5884 Intent[] specifics, String[] specificTypes, Intent intent, 5885 String resolvedType, int flags, int userId) { 5886 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5887 specificTypes, intent, resolvedType, flags, userId)); 5888 } 5889 5890 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5891 Intent[] specifics, String[] specificTypes, Intent intent, 5892 String resolvedType, int flags, int userId) { 5893 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5894 flags = updateFlagsForResolve(flags, userId, intent); 5895 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5896 false /* requireFullPermission */, false /* checkShell */, 5897 "query intent activity options"); 5898 final String resultsAction = intent.getAction(); 5899 5900 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5901 | PackageManager.GET_RESOLVED_FILTER, userId); 5902 5903 if (DEBUG_INTENT_MATCHING) { 5904 Log.v(TAG, "Query " + intent + ": " + results); 5905 } 5906 5907 int specificsPos = 0; 5908 int N; 5909 5910 // todo: note that the algorithm used here is O(N^2). This 5911 // isn't a problem in our current environment, but if we start running 5912 // into situations where we have more than 5 or 10 matches then this 5913 // should probably be changed to something smarter... 5914 5915 // First we go through and resolve each of the specific items 5916 // that were supplied, taking care of removing any corresponding 5917 // duplicate items in the generic resolve list. 5918 if (specifics != null) { 5919 for (int i=0; i<specifics.length; i++) { 5920 final Intent sintent = specifics[i]; 5921 if (sintent == null) { 5922 continue; 5923 } 5924 5925 if (DEBUG_INTENT_MATCHING) { 5926 Log.v(TAG, "Specific #" + i + ": " + sintent); 5927 } 5928 5929 String action = sintent.getAction(); 5930 if (resultsAction != null && resultsAction.equals(action)) { 5931 // If this action was explicitly requested, then don't 5932 // remove things that have it. 5933 action = null; 5934 } 5935 5936 ResolveInfo ri = null; 5937 ActivityInfo ai = null; 5938 5939 ComponentName comp = sintent.getComponent(); 5940 if (comp == null) { 5941 ri = resolveIntent( 5942 sintent, 5943 specificTypes != null ? specificTypes[i] : null, 5944 flags, userId); 5945 if (ri == null) { 5946 continue; 5947 } 5948 if (ri == mResolveInfo) { 5949 // ACK! Must do something better with this. 5950 } 5951 ai = ri.activityInfo; 5952 comp = new ComponentName(ai.applicationInfo.packageName, 5953 ai.name); 5954 } else { 5955 ai = getActivityInfo(comp, flags, userId); 5956 if (ai == null) { 5957 continue; 5958 } 5959 } 5960 5961 // Look for any generic query activities that are duplicates 5962 // of this specific one, and remove them from the results. 5963 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5964 N = results.size(); 5965 int j; 5966 for (j=specificsPos; j<N; j++) { 5967 ResolveInfo sri = results.get(j); 5968 if ((sri.activityInfo.name.equals(comp.getClassName()) 5969 && sri.activityInfo.applicationInfo.packageName.equals( 5970 comp.getPackageName())) 5971 || (action != null && sri.filter.matchAction(action))) { 5972 results.remove(j); 5973 if (DEBUG_INTENT_MATCHING) Log.v( 5974 TAG, "Removing duplicate item from " + j 5975 + " due to specific " + specificsPos); 5976 if (ri == null) { 5977 ri = sri; 5978 } 5979 j--; 5980 N--; 5981 } 5982 } 5983 5984 // Add this specific item to its proper place. 5985 if (ri == null) { 5986 ri = new ResolveInfo(); 5987 ri.activityInfo = ai; 5988 } 5989 results.add(specificsPos, ri); 5990 ri.specificIndex = i; 5991 specificsPos++; 5992 } 5993 } 5994 5995 // Now we go through the remaining generic results and remove any 5996 // duplicate actions that are found here. 5997 N = results.size(); 5998 for (int i=specificsPos; i<N-1; i++) { 5999 final ResolveInfo rii = results.get(i); 6000 if (rii.filter == null) { 6001 continue; 6002 } 6003 6004 // Iterate over all of the actions of this result's intent 6005 // filter... typically this should be just one. 6006 final Iterator<String> it = rii.filter.actionsIterator(); 6007 if (it == null) { 6008 continue; 6009 } 6010 while (it.hasNext()) { 6011 final String action = it.next(); 6012 if (resultsAction != null && resultsAction.equals(action)) { 6013 // If this action was explicitly requested, then don't 6014 // remove things that have it. 6015 continue; 6016 } 6017 for (int j=i+1; j<N; j++) { 6018 final ResolveInfo rij = results.get(j); 6019 if (rij.filter != null && rij.filter.hasAction(action)) { 6020 results.remove(j); 6021 if (DEBUG_INTENT_MATCHING) Log.v( 6022 TAG, "Removing duplicate item from " + j 6023 + " due to action " + action + " at " + i); 6024 j--; 6025 N--; 6026 } 6027 } 6028 } 6029 6030 // If the caller didn't request filter information, drop it now 6031 // so we don't have to marshall/unmarshall it. 6032 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6033 rii.filter = null; 6034 } 6035 } 6036 6037 // Filter out the caller activity if so requested. 6038 if (caller != null) { 6039 N = results.size(); 6040 for (int i=0; i<N; i++) { 6041 ActivityInfo ainfo = results.get(i).activityInfo; 6042 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6043 && caller.getClassName().equals(ainfo.name)) { 6044 results.remove(i); 6045 break; 6046 } 6047 } 6048 } 6049 6050 // If the caller didn't request filter information, 6051 // drop them now so we don't have to 6052 // marshall/unmarshall it. 6053 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6054 N = results.size(); 6055 for (int i=0; i<N; i++) { 6056 results.get(i).filter = null; 6057 } 6058 } 6059 6060 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6061 return results; 6062 } 6063 6064 @Override 6065 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6066 String resolvedType, int flags, int userId) { 6067 return new ParceledListSlice<>( 6068 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6069 } 6070 6071 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6072 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 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6084 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6085 if (ai != null) { 6086 ResolveInfo ri = new ResolveInfo(); 6087 ri.activityInfo = ai; 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 mReceivers.queryIntent(intent, resolvedType, flags, userId); 6098 } 6099 final PackageParser.Package pkg = mPackages.get(pkgName); 6100 if (pkg != null) { 6101 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6102 userId); 6103 } 6104 return Collections.emptyList(); 6105 } 6106 } 6107 6108 @Override 6109 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6110 if (!sUserManager.exists(userId)) return null; 6111 flags = updateFlagsForResolve(flags, userId, intent); 6112 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6113 if (query != null) { 6114 if (query.size() >= 1) { 6115 // If there is more than one service with the same priority, 6116 // just arbitrarily pick the first one. 6117 return query.get(0); 6118 } 6119 } 6120 return null; 6121 } 6122 6123 @Override 6124 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6125 String resolvedType, int flags, int userId) { 6126 return new ParceledListSlice<>( 6127 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6128 } 6129 6130 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6131 String resolvedType, int flags, int userId) { 6132 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6133 flags = updateFlagsForResolve(flags, userId, intent); 6134 ComponentName comp = intent.getComponent(); 6135 if (comp == null) { 6136 if (intent.getSelector() != null) { 6137 intent = intent.getSelector(); 6138 comp = intent.getComponent(); 6139 } 6140 } 6141 if (comp != null) { 6142 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6143 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6144 if (si != null) { 6145 final ResolveInfo ri = new ResolveInfo(); 6146 ri.serviceInfo = si; 6147 list.add(ri); 6148 } 6149 return list; 6150 } 6151 6152 // reader 6153 synchronized (mPackages) { 6154 String pkgName = intent.getPackage(); 6155 if (pkgName == null) { 6156 return mServices.queryIntent(intent, resolvedType, flags, userId); 6157 } 6158 final PackageParser.Package pkg = mPackages.get(pkgName); 6159 if (pkg != null) { 6160 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6161 userId); 6162 } 6163 return Collections.emptyList(); 6164 } 6165 } 6166 6167 @Override 6168 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6169 String resolvedType, int flags, int userId) { 6170 return new ParceledListSlice<>( 6171 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6172 } 6173 6174 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6175 Intent intent, String resolvedType, int flags, int userId) { 6176 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6177 flags = updateFlagsForResolve(flags, userId, intent); 6178 ComponentName comp = intent.getComponent(); 6179 if (comp == null) { 6180 if (intent.getSelector() != null) { 6181 intent = intent.getSelector(); 6182 comp = intent.getComponent(); 6183 } 6184 } 6185 if (comp != null) { 6186 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6187 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6188 if (pi != null) { 6189 final ResolveInfo ri = new ResolveInfo(); 6190 ri.providerInfo = pi; 6191 list.add(ri); 6192 } 6193 return list; 6194 } 6195 6196 // reader 6197 synchronized (mPackages) { 6198 String pkgName = intent.getPackage(); 6199 if (pkgName == null) { 6200 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6201 } 6202 final PackageParser.Package pkg = mPackages.get(pkgName); 6203 if (pkg != null) { 6204 return mProviders.queryIntentForPackage( 6205 intent, resolvedType, flags, pkg.providers, userId); 6206 } 6207 return Collections.emptyList(); 6208 } 6209 } 6210 6211 @Override 6212 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6213 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6214 flags = updateFlagsForPackage(flags, userId, null); 6215 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6217 true /* requireFullPermission */, false /* checkShell */, 6218 "get installed packages"); 6219 6220 // writer 6221 synchronized (mPackages) { 6222 ArrayList<PackageInfo> list; 6223 if (listUninstalled) { 6224 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6225 for (PackageSetting ps : mSettings.mPackages.values()) { 6226 final PackageInfo pi; 6227 if (ps.pkg != null) { 6228 pi = generatePackageInfo(ps, flags, userId); 6229 } else { 6230 pi = generatePackageInfo(ps, flags, userId); 6231 } 6232 if (pi != null) { 6233 list.add(pi); 6234 } 6235 } 6236 } else { 6237 list = new ArrayList<PackageInfo>(mPackages.size()); 6238 for (PackageParser.Package p : mPackages.values()) { 6239 final PackageInfo pi = 6240 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6241 if (pi != null) { 6242 list.add(pi); 6243 } 6244 } 6245 } 6246 6247 return new ParceledListSlice<PackageInfo>(list); 6248 } 6249 } 6250 6251 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6252 String[] permissions, boolean[] tmp, int flags, int userId) { 6253 int numMatch = 0; 6254 final PermissionsState permissionsState = ps.getPermissionsState(); 6255 for (int i=0; i<permissions.length; i++) { 6256 final String permission = permissions[i]; 6257 if (permissionsState.hasPermission(permission, userId)) { 6258 tmp[i] = true; 6259 numMatch++; 6260 } else { 6261 tmp[i] = false; 6262 } 6263 } 6264 if (numMatch == 0) { 6265 return; 6266 } 6267 final PackageInfo pi; 6268 if (ps.pkg != null) { 6269 pi = generatePackageInfo(ps, flags, userId); 6270 } else { 6271 pi = generatePackageInfo(ps, flags, userId); 6272 } 6273 // The above might return null in cases of uninstalled apps or install-state 6274 // skew across users/profiles. 6275 if (pi != null) { 6276 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6277 if (numMatch == permissions.length) { 6278 pi.requestedPermissions = permissions; 6279 } else { 6280 pi.requestedPermissions = new String[numMatch]; 6281 numMatch = 0; 6282 for (int i=0; i<permissions.length; i++) { 6283 if (tmp[i]) { 6284 pi.requestedPermissions[numMatch] = permissions[i]; 6285 numMatch++; 6286 } 6287 } 6288 } 6289 } 6290 list.add(pi); 6291 } 6292 } 6293 6294 @Override 6295 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6296 String[] permissions, int flags, int userId) { 6297 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6298 flags = updateFlagsForPackage(flags, userId, permissions); 6299 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6300 6301 // writer 6302 synchronized (mPackages) { 6303 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6304 boolean[] tmpBools = new boolean[permissions.length]; 6305 if (listUninstalled) { 6306 for (PackageSetting ps : mSettings.mPackages.values()) { 6307 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6308 } 6309 } else { 6310 for (PackageParser.Package pkg : mPackages.values()) { 6311 PackageSetting ps = (PackageSetting)pkg.mExtras; 6312 if (ps != null) { 6313 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6314 userId); 6315 } 6316 } 6317 } 6318 6319 return new ParceledListSlice<PackageInfo>(list); 6320 } 6321 } 6322 6323 @Override 6324 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6325 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6326 flags = updateFlagsForApplication(flags, userId, null); 6327 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6328 6329 // writer 6330 synchronized (mPackages) { 6331 ArrayList<ApplicationInfo> list; 6332 if (listUninstalled) { 6333 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6334 for (PackageSetting ps : mSettings.mPackages.values()) { 6335 ApplicationInfo ai; 6336 if (ps.pkg != null) { 6337 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6338 ps.readUserState(userId), userId); 6339 } else { 6340 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6341 } 6342 if (ai != null) { 6343 list.add(ai); 6344 } 6345 } 6346 } else { 6347 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6348 for (PackageParser.Package p : mPackages.values()) { 6349 if (p.mExtras != null) { 6350 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6351 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6352 if (ai != null) { 6353 list.add(ai); 6354 } 6355 } 6356 } 6357 } 6358 6359 return new ParceledListSlice<ApplicationInfo>(list); 6360 } 6361 } 6362 6363 @Override 6364 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6365 if (DISABLE_EPHEMERAL_APPS) { 6366 return null; 6367 } 6368 6369 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6370 "getEphemeralApplications"); 6371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6372 true /* requireFullPermission */, false /* checkShell */, 6373 "getEphemeralApplications"); 6374 synchronized (mPackages) { 6375 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6376 .getEphemeralApplicationsLPw(userId); 6377 if (ephemeralApps != null) { 6378 return new ParceledListSlice<>(ephemeralApps); 6379 } 6380 } 6381 return null; 6382 } 6383 6384 @Override 6385 public boolean isEphemeralApplication(String packageName, int userId) { 6386 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6387 true /* requireFullPermission */, false /* checkShell */, 6388 "isEphemeral"); 6389 if (DISABLE_EPHEMERAL_APPS) { 6390 return false; 6391 } 6392 6393 if (!isCallerSameApp(packageName)) { 6394 return false; 6395 } 6396 synchronized (mPackages) { 6397 PackageParser.Package pkg = mPackages.get(packageName); 6398 if (pkg != null) { 6399 return pkg.applicationInfo.isEphemeralApp(); 6400 } 6401 } 6402 return false; 6403 } 6404 6405 @Override 6406 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6407 if (DISABLE_EPHEMERAL_APPS) { 6408 return null; 6409 } 6410 6411 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6412 true /* requireFullPermission */, false /* checkShell */, 6413 "getCookie"); 6414 if (!isCallerSameApp(packageName)) { 6415 return null; 6416 } 6417 synchronized (mPackages) { 6418 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6419 packageName, userId); 6420 } 6421 } 6422 6423 @Override 6424 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6425 if (DISABLE_EPHEMERAL_APPS) { 6426 return true; 6427 } 6428 6429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6430 true /* requireFullPermission */, true /* checkShell */, 6431 "setCookie"); 6432 if (!isCallerSameApp(packageName)) { 6433 return false; 6434 } 6435 synchronized (mPackages) { 6436 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6437 packageName, cookie, userId); 6438 } 6439 } 6440 6441 @Override 6442 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6443 if (DISABLE_EPHEMERAL_APPS) { 6444 return null; 6445 } 6446 6447 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6448 "getEphemeralApplicationIcon"); 6449 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6450 true /* requireFullPermission */, false /* checkShell */, 6451 "getEphemeralApplicationIcon"); 6452 synchronized (mPackages) { 6453 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6454 packageName, userId); 6455 } 6456 } 6457 6458 private boolean isCallerSameApp(String packageName) { 6459 PackageParser.Package pkg = mPackages.get(packageName); 6460 return pkg != null 6461 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6462 } 6463 6464 @Override 6465 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6466 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6467 } 6468 6469 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6470 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6471 6472 // reader 6473 synchronized (mPackages) { 6474 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6475 final int userId = UserHandle.getCallingUserId(); 6476 while (i.hasNext()) { 6477 final PackageParser.Package p = i.next(); 6478 if (p.applicationInfo == null) continue; 6479 6480 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6481 && !p.applicationInfo.isDirectBootAware(); 6482 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6483 && p.applicationInfo.isDirectBootAware(); 6484 6485 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6486 && (!mSafeMode || isSystemApp(p)) 6487 && (matchesUnaware || matchesAware)) { 6488 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6489 if (ps != null) { 6490 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6491 ps.readUserState(userId), userId); 6492 if (ai != null) { 6493 finalList.add(ai); 6494 } 6495 } 6496 } 6497 } 6498 } 6499 6500 return finalList; 6501 } 6502 6503 @Override 6504 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6505 if (!sUserManager.exists(userId)) return null; 6506 flags = updateFlagsForComponent(flags, userId, name); 6507 // reader 6508 synchronized (mPackages) { 6509 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6510 PackageSetting ps = provider != null 6511 ? mSettings.mPackages.get(provider.owner.packageName) 6512 : null; 6513 return ps != null 6514 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6515 ? PackageParser.generateProviderInfo(provider, flags, 6516 ps.readUserState(userId), userId) 6517 : null; 6518 } 6519 } 6520 6521 /** 6522 * @deprecated 6523 */ 6524 @Deprecated 6525 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6526 // reader 6527 synchronized (mPackages) { 6528 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6529 .entrySet().iterator(); 6530 final int userId = UserHandle.getCallingUserId(); 6531 while (i.hasNext()) { 6532 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6533 PackageParser.Provider p = entry.getValue(); 6534 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6535 6536 if (ps != null && p.syncable 6537 && (!mSafeMode || (p.info.applicationInfo.flags 6538 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6539 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6540 ps.readUserState(userId), userId); 6541 if (info != null) { 6542 outNames.add(entry.getKey()); 6543 outInfo.add(info); 6544 } 6545 } 6546 } 6547 } 6548 } 6549 6550 @Override 6551 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6552 int uid, int flags) { 6553 final int userId = processName != null ? UserHandle.getUserId(uid) 6554 : UserHandle.getCallingUserId(); 6555 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6556 flags = updateFlagsForComponent(flags, userId, processName); 6557 6558 ArrayList<ProviderInfo> finalList = null; 6559 // reader 6560 synchronized (mPackages) { 6561 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6562 while (i.hasNext()) { 6563 final PackageParser.Provider p = i.next(); 6564 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6565 if (ps != null && p.info.authority != null 6566 && (processName == null 6567 || (p.info.processName.equals(processName) 6568 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6569 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6570 if (finalList == null) { 6571 finalList = new ArrayList<ProviderInfo>(3); 6572 } 6573 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6574 ps.readUserState(userId), userId); 6575 if (info != null) { 6576 finalList.add(info); 6577 } 6578 } 6579 } 6580 } 6581 6582 if (finalList != null) { 6583 Collections.sort(finalList, mProviderInitOrderSorter); 6584 return new ParceledListSlice<ProviderInfo>(finalList); 6585 } 6586 6587 return ParceledListSlice.emptyList(); 6588 } 6589 6590 @Override 6591 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6592 // reader 6593 synchronized (mPackages) { 6594 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6595 return PackageParser.generateInstrumentationInfo(i, flags); 6596 } 6597 } 6598 6599 @Override 6600 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6601 String targetPackage, int flags) { 6602 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6603 } 6604 6605 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6606 int flags) { 6607 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6608 6609 // reader 6610 synchronized (mPackages) { 6611 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6612 while (i.hasNext()) { 6613 final PackageParser.Instrumentation p = i.next(); 6614 if (targetPackage == null 6615 || targetPackage.equals(p.info.targetPackage)) { 6616 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6617 flags); 6618 if (ii != null) { 6619 finalList.add(ii); 6620 } 6621 } 6622 } 6623 } 6624 6625 return finalList; 6626 } 6627 6628 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6629 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6630 if (overlays == null) { 6631 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6632 return; 6633 } 6634 for (PackageParser.Package opkg : overlays.values()) { 6635 // Not much to do if idmap fails: we already logged the error 6636 // and we certainly don't want to abort installation of pkg simply 6637 // because an overlay didn't fit properly. For these reasons, 6638 // ignore the return value of createIdmapForPackagePairLI. 6639 createIdmapForPackagePairLI(pkg, opkg); 6640 } 6641 } 6642 6643 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6644 PackageParser.Package opkg) { 6645 if (!opkg.mTrustedOverlay) { 6646 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6647 opkg.baseCodePath + ": overlay not trusted"); 6648 return false; 6649 } 6650 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6651 if (overlaySet == null) { 6652 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6653 opkg.baseCodePath + " but target package has no known overlays"); 6654 return false; 6655 } 6656 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6657 // TODO: generate idmap for split APKs 6658 try { 6659 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6660 } catch (InstallerException e) { 6661 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6662 + opkg.baseCodePath); 6663 return false; 6664 } 6665 PackageParser.Package[] overlayArray = 6666 overlaySet.values().toArray(new PackageParser.Package[0]); 6667 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6668 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6669 return p1.mOverlayPriority - p2.mOverlayPriority; 6670 } 6671 }; 6672 Arrays.sort(overlayArray, cmp); 6673 6674 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6675 int i = 0; 6676 for (PackageParser.Package p : overlayArray) { 6677 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6678 } 6679 return true; 6680 } 6681 6682 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6684 try { 6685 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6686 } finally { 6687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6688 } 6689 } 6690 6691 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6692 final File[] files = dir.listFiles(); 6693 if (ArrayUtils.isEmpty(files)) { 6694 Log.d(TAG, "No files in app dir " + dir); 6695 return; 6696 } 6697 6698 if (DEBUG_PACKAGE_SCANNING) { 6699 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6700 + " flags=0x" + Integer.toHexString(parseFlags)); 6701 } 6702 6703 for (File file : files) { 6704 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6705 && !PackageInstallerService.isStageName(file.getName()); 6706 if (!isPackage) { 6707 // Ignore entries which are not packages 6708 continue; 6709 } 6710 try { 6711 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6712 scanFlags, currentTime, null); 6713 } catch (PackageManagerException e) { 6714 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6715 6716 // Delete invalid userdata apps 6717 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6718 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6719 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6720 removeCodePathLI(file); 6721 } 6722 } 6723 } 6724 } 6725 6726 private static File getSettingsProblemFile() { 6727 File dataDir = Environment.getDataDirectory(); 6728 File systemDir = new File(dataDir, "system"); 6729 File fname = new File(systemDir, "uiderrors.txt"); 6730 return fname; 6731 } 6732 6733 static void reportSettingsProblem(int priority, String msg) { 6734 logCriticalInfo(priority, msg); 6735 } 6736 6737 static void logCriticalInfo(int priority, String msg) { 6738 Slog.println(priority, TAG, msg); 6739 EventLogTags.writePmCriticalInfo(msg); 6740 try { 6741 File fname = getSettingsProblemFile(); 6742 FileOutputStream out = new FileOutputStream(fname, true); 6743 PrintWriter pw = new FastPrintWriter(out); 6744 SimpleDateFormat formatter = new SimpleDateFormat(); 6745 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6746 pw.println(dateString + ": " + msg); 6747 pw.close(); 6748 FileUtils.setPermissions( 6749 fname.toString(), 6750 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6751 -1, -1); 6752 } catch (java.io.IOException e) { 6753 } 6754 } 6755 6756 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6757 final int policyFlags) throws PackageManagerException { 6758 if (ps != null 6759 && ps.codePath.equals(srcFile) 6760 && ps.timeStamp == srcFile.lastModified() 6761 && !isCompatSignatureUpdateNeeded(pkg) 6762 && !isRecoverSignatureUpdateNeeded(pkg)) { 6763 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6764 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6765 ArraySet<PublicKey> signingKs; 6766 synchronized (mPackages) { 6767 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6768 } 6769 if (ps.signatures.mSignatures != null 6770 && ps.signatures.mSignatures.length != 0 6771 && signingKs != null) { 6772 // Optimization: reuse the existing cached certificates 6773 // if the package appears to be unchanged. 6774 pkg.mSignatures = ps.signatures.mSignatures; 6775 pkg.mSigningKeys = signingKs; 6776 return; 6777 } 6778 6779 Slog.w(TAG, "PackageSetting for " + ps.name 6780 + " is missing signatures. Collecting certs again to recover them."); 6781 } else { 6782 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6783 } 6784 6785 try { 6786 PackageParser.collectCertificates(pkg, policyFlags); 6787 } catch (PackageParserException e) { 6788 throw PackageManagerException.from(e); 6789 } 6790 } 6791 6792 /** 6793 * Traces a package scan. 6794 * @see #scanPackageLI(File, int, int, long, UserHandle) 6795 */ 6796 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6797 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6799 try { 6800 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6801 } finally { 6802 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6803 } 6804 } 6805 6806 /** 6807 * Scans a package and returns the newly parsed package. 6808 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6809 */ 6810 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6811 long currentTime, UserHandle user) throws PackageManagerException { 6812 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6813 PackageParser pp = new PackageParser(); 6814 pp.setSeparateProcesses(mSeparateProcesses); 6815 pp.setOnlyCoreApps(mOnlyCore); 6816 pp.setDisplayMetrics(mMetrics); 6817 6818 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6819 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6820 } 6821 6822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6823 final PackageParser.Package pkg; 6824 try { 6825 pkg = pp.parsePackage(scanFile, parseFlags); 6826 } catch (PackageParserException e) { 6827 throw PackageManagerException.from(e); 6828 } finally { 6829 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6830 } 6831 6832 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6833 } 6834 6835 /** 6836 * Scans a package and returns the newly parsed package. 6837 * @throws PackageManagerException on a parse error. 6838 */ 6839 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6840 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6841 throws PackageManagerException { 6842 // If the package has children and this is the first dive in the function 6843 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6844 // packages (parent and children) would be successfully scanned before the 6845 // actual scan since scanning mutates internal state and we want to atomically 6846 // install the package and its children. 6847 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6848 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6849 scanFlags |= SCAN_CHECK_ONLY; 6850 } 6851 } else { 6852 scanFlags &= ~SCAN_CHECK_ONLY; 6853 } 6854 6855 // Scan the parent 6856 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6857 scanFlags, currentTime, user); 6858 6859 // Scan the children 6860 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6861 for (int i = 0; i < childCount; i++) { 6862 PackageParser.Package childPackage = pkg.childPackages.get(i); 6863 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6864 currentTime, user); 6865 } 6866 6867 6868 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6869 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6870 } 6871 6872 return scannedPkg; 6873 } 6874 6875 /** 6876 * Scans a package and returns the newly parsed package. 6877 * @throws PackageManagerException on a parse error. 6878 */ 6879 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6880 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6881 throws PackageManagerException { 6882 PackageSetting ps = null; 6883 PackageSetting updatedPkg; 6884 // reader 6885 synchronized (mPackages) { 6886 // Look to see if we already know about this package. 6887 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6888 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6889 // This package has been renamed to its original name. Let's 6890 // use that. 6891 ps = mSettings.peekPackageLPr(oldName); 6892 } 6893 // If there was no original package, see one for the real package name. 6894 if (ps == null) { 6895 ps = mSettings.peekPackageLPr(pkg.packageName); 6896 } 6897 // Check to see if this package could be hiding/updating a system 6898 // package. Must look for it either under the original or real 6899 // package name depending on our state. 6900 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6901 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6902 6903 // If this is a package we don't know about on the system partition, we 6904 // may need to remove disabled child packages on the system partition 6905 // or may need to not add child packages if the parent apk is updated 6906 // on the data partition and no longer defines this child package. 6907 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6908 // If this is a parent package for an updated system app and this system 6909 // app got an OTA update which no longer defines some of the child packages 6910 // we have to prune them from the disabled system packages. 6911 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6912 if (disabledPs != null) { 6913 final int scannedChildCount = (pkg.childPackages != null) 6914 ? pkg.childPackages.size() : 0; 6915 final int disabledChildCount = disabledPs.childPackageNames != null 6916 ? disabledPs.childPackageNames.size() : 0; 6917 for (int i = 0; i < disabledChildCount; i++) { 6918 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6919 boolean disabledPackageAvailable = false; 6920 for (int j = 0; j < scannedChildCount; j++) { 6921 PackageParser.Package childPkg = pkg.childPackages.get(j); 6922 if (childPkg.packageName.equals(disabledChildPackageName)) { 6923 disabledPackageAvailable = true; 6924 break; 6925 } 6926 } 6927 if (!disabledPackageAvailable) { 6928 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6929 } 6930 } 6931 } 6932 } 6933 } 6934 6935 boolean updatedPkgBetter = false; 6936 // First check if this is a system package that may involve an update 6937 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6938 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6939 // it needs to drop FLAG_PRIVILEGED. 6940 if (locationIsPrivileged(scanFile)) { 6941 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6942 } else { 6943 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6944 } 6945 6946 if (ps != null && !ps.codePath.equals(scanFile)) { 6947 // The path has changed from what was last scanned... check the 6948 // version of the new path against what we have stored to determine 6949 // what to do. 6950 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6951 if (pkg.mVersionCode <= ps.versionCode) { 6952 // The system package has been updated and the code path does not match 6953 // Ignore entry. Skip it. 6954 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6955 + " ignored: updated version " + ps.versionCode 6956 + " better than this " + pkg.mVersionCode); 6957 if (!updatedPkg.codePath.equals(scanFile)) { 6958 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6959 + ps.name + " changing from " + updatedPkg.codePathString 6960 + " to " + scanFile); 6961 updatedPkg.codePath = scanFile; 6962 updatedPkg.codePathString = scanFile.toString(); 6963 updatedPkg.resourcePath = scanFile; 6964 updatedPkg.resourcePathString = scanFile.toString(); 6965 } 6966 updatedPkg.pkg = pkg; 6967 updatedPkg.versionCode = pkg.mVersionCode; 6968 6969 // Update the disabled system child packages to point to the package too. 6970 final int childCount = updatedPkg.childPackageNames != null 6971 ? updatedPkg.childPackageNames.size() : 0; 6972 for (int i = 0; i < childCount; i++) { 6973 String childPackageName = updatedPkg.childPackageNames.get(i); 6974 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6975 childPackageName); 6976 if (updatedChildPkg != null) { 6977 updatedChildPkg.pkg = pkg; 6978 updatedChildPkg.versionCode = pkg.mVersionCode; 6979 } 6980 } 6981 6982 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6983 + scanFile + " ignored: updated version " + ps.versionCode 6984 + " better than this " + pkg.mVersionCode); 6985 } else { 6986 // The current app on the system partition is better than 6987 // what we have updated to on the data partition; switch 6988 // back to the system partition version. 6989 // At this point, its safely assumed that package installation for 6990 // apps in system partition will go through. If not there won't be a working 6991 // version of the app 6992 // writer 6993 synchronized (mPackages) { 6994 // Just remove the loaded entries from package lists. 6995 mPackages.remove(ps.name); 6996 } 6997 6998 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6999 + " reverting from " + ps.codePathString 7000 + ": new version " + pkg.mVersionCode 7001 + " better than installed " + ps.versionCode); 7002 7003 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7004 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7005 synchronized (mInstallLock) { 7006 args.cleanUpResourcesLI(); 7007 } 7008 synchronized (mPackages) { 7009 mSettings.enableSystemPackageLPw(ps.name); 7010 } 7011 updatedPkgBetter = true; 7012 } 7013 } 7014 } 7015 7016 if (updatedPkg != null) { 7017 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7018 // initially 7019 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7020 7021 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7022 // flag set initially 7023 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7024 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7025 } 7026 } 7027 7028 // Verify certificates against what was last scanned 7029 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7030 7031 /* 7032 * A new system app appeared, but we already had a non-system one of the 7033 * same name installed earlier. 7034 */ 7035 boolean shouldHideSystemApp = false; 7036 if (updatedPkg == null && ps != null 7037 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7038 /* 7039 * Check to make sure the signatures match first. If they don't, 7040 * wipe the installed application and its data. 7041 */ 7042 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7043 != PackageManager.SIGNATURE_MATCH) { 7044 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7045 + " signatures don't match existing userdata copy; removing"); 7046 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7047 "scanPackageInternalLI")) { 7048 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7049 } 7050 ps = null; 7051 } else { 7052 /* 7053 * If the newly-added system app is an older version than the 7054 * already installed version, hide it. It will be scanned later 7055 * and re-added like an update. 7056 */ 7057 if (pkg.mVersionCode <= ps.versionCode) { 7058 shouldHideSystemApp = true; 7059 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7060 + " but new version " + pkg.mVersionCode + " better than installed " 7061 + ps.versionCode + "; hiding system"); 7062 } else { 7063 /* 7064 * The newly found system app is a newer version that the 7065 * one previously installed. Simply remove the 7066 * already-installed application and replace it with our own 7067 * while keeping the application data. 7068 */ 7069 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7070 + " reverting from " + ps.codePathString + ": new version " 7071 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7072 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7073 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7074 synchronized (mInstallLock) { 7075 args.cleanUpResourcesLI(); 7076 } 7077 } 7078 } 7079 } 7080 7081 // The apk is forward locked (not public) if its code and resources 7082 // are kept in different files. (except for app in either system or 7083 // vendor path). 7084 // TODO grab this value from PackageSettings 7085 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7086 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7087 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7088 } 7089 } 7090 7091 // TODO: extend to support forward-locked splits 7092 String resourcePath = null; 7093 String baseResourcePath = null; 7094 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7095 if (ps != null && ps.resourcePathString != null) { 7096 resourcePath = ps.resourcePathString; 7097 baseResourcePath = ps.resourcePathString; 7098 } else { 7099 // Should not happen at all. Just log an error. 7100 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7101 } 7102 } else { 7103 resourcePath = pkg.codePath; 7104 baseResourcePath = pkg.baseCodePath; 7105 } 7106 7107 // Set application objects path explicitly. 7108 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7109 pkg.setApplicationInfoCodePath(pkg.codePath); 7110 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7111 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7112 pkg.setApplicationInfoResourcePath(resourcePath); 7113 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7114 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7115 7116 // Note that we invoke the following method only if we are about to unpack an application 7117 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7118 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7119 7120 /* 7121 * If the system app should be overridden by a previously installed 7122 * data, hide the system app now and let the /data/app scan pick it up 7123 * again. 7124 */ 7125 if (shouldHideSystemApp) { 7126 synchronized (mPackages) { 7127 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7128 } 7129 } 7130 7131 return scannedPkg; 7132 } 7133 7134 private static String fixProcessName(String defProcessName, 7135 String processName, int uid) { 7136 if (processName == null) { 7137 return defProcessName; 7138 } 7139 return processName; 7140 } 7141 7142 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7143 throws PackageManagerException { 7144 if (pkgSetting.signatures.mSignatures != null) { 7145 // Already existing package. Make sure signatures match 7146 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7147 == PackageManager.SIGNATURE_MATCH; 7148 if (!match) { 7149 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7150 == PackageManager.SIGNATURE_MATCH; 7151 } 7152 if (!match) { 7153 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7154 == PackageManager.SIGNATURE_MATCH; 7155 } 7156 if (!match) { 7157 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7158 + pkg.packageName + " signatures do not match the " 7159 + "previously installed version; ignoring!"); 7160 } 7161 } 7162 7163 // Check for shared user signatures 7164 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7165 // Already existing package. Make sure signatures match 7166 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7167 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7168 if (!match) { 7169 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7170 == PackageManager.SIGNATURE_MATCH; 7171 } 7172 if (!match) { 7173 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7174 == PackageManager.SIGNATURE_MATCH; 7175 } 7176 if (!match) { 7177 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7178 "Package " + pkg.packageName 7179 + " has no signatures that match those in shared user " 7180 + pkgSetting.sharedUser.name + "; ignoring!"); 7181 } 7182 } 7183 } 7184 7185 /** 7186 * Enforces that only the system UID or root's UID can call a method exposed 7187 * via Binder. 7188 * 7189 * @param message used as message if SecurityException is thrown 7190 * @throws SecurityException if the caller is not system or root 7191 */ 7192 private static final void enforceSystemOrRoot(String message) { 7193 final int uid = Binder.getCallingUid(); 7194 if (uid != Process.SYSTEM_UID && uid != 0) { 7195 throw new SecurityException(message); 7196 } 7197 } 7198 7199 @Override 7200 public void performFstrimIfNeeded() { 7201 enforceSystemOrRoot("Only the system can request fstrim"); 7202 7203 // Before everything else, see whether we need to fstrim. 7204 try { 7205 IMountService ms = PackageHelper.getMountService(); 7206 if (ms != null) { 7207 final boolean isUpgrade = isUpgrade(); 7208 boolean doTrim = isUpgrade; 7209 if (doTrim) { 7210 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7211 } else { 7212 final long interval = android.provider.Settings.Global.getLong( 7213 mContext.getContentResolver(), 7214 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7215 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7216 if (interval > 0) { 7217 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7218 if (timeSinceLast > interval) { 7219 doTrim = true; 7220 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7221 + "; running immediately"); 7222 } 7223 } 7224 } 7225 if (doTrim) { 7226 if (!isFirstBoot()) { 7227 try { 7228 ActivityManagerNative.getDefault().showBootMessage( 7229 mContext.getResources().getString( 7230 R.string.android_upgrading_fstrim), true); 7231 } catch (RemoteException e) { 7232 } 7233 } 7234 ms.runMaintenance(); 7235 } 7236 } else { 7237 Slog.e(TAG, "Mount service unavailable!"); 7238 } 7239 } catch (RemoteException e) { 7240 // Can't happen; MountService is local 7241 } 7242 } 7243 7244 @Override 7245 public void updatePackagesIfNeeded() { 7246 enforceSystemOrRoot("Only the system can request package update"); 7247 7248 // We need to re-extract after an OTA. 7249 boolean causeUpgrade = isUpgrade(); 7250 7251 // First boot or factory reset. 7252 // Note: we also handle devices that are upgrading to N right now as if it is their 7253 // first boot, as they do not have profile data. 7254 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7255 7256 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7257 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7258 7259 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7260 return; 7261 } 7262 7263 List<PackageParser.Package> pkgs; 7264 synchronized (mPackages) { 7265 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7266 } 7267 7268 final long startTime = System.nanoTime(); 7269 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7270 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7271 7272 final int elapsedTimeSeconds = 7273 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7274 7275 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7276 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7277 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7278 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7279 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7280 } 7281 7282 /** 7283 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7284 * containing statistics about the invocation. The array consists of three elements, 7285 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7286 * and {@code numberOfPackagesFailed}. 7287 */ 7288 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7289 String compilerFilter) { 7290 7291 int numberOfPackagesVisited = 0; 7292 int numberOfPackagesOptimized = 0; 7293 int numberOfPackagesSkipped = 0; 7294 int numberOfPackagesFailed = 0; 7295 final int numberOfPackagesToDexopt = pkgs.size(); 7296 7297 for (PackageParser.Package pkg : pkgs) { 7298 numberOfPackagesVisited++; 7299 7300 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7301 if (DEBUG_DEXOPT) { 7302 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7303 } 7304 numberOfPackagesSkipped++; 7305 continue; 7306 } 7307 7308 if (DEBUG_DEXOPT) { 7309 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7310 numberOfPackagesToDexopt + ": " + pkg.packageName); 7311 } 7312 7313 if (showDialog) { 7314 try { 7315 ActivityManagerNative.getDefault().showBootMessage( 7316 mContext.getResources().getString(R.string.android_upgrading_apk, 7317 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7318 } catch (RemoteException e) { 7319 } 7320 } 7321 7322 // checkProfiles is false to avoid merging profiles during boot which 7323 // might interfere with background compilation (b/28612421). 7324 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7325 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7326 // trade-off worth doing to save boot time work. 7327 int dexOptStatus = performDexOptTraced(pkg.packageName, 7328 false /* checkProfiles */, 7329 compilerFilter, 7330 false /* force */); 7331 switch (dexOptStatus) { 7332 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7333 numberOfPackagesOptimized++; 7334 break; 7335 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7336 numberOfPackagesSkipped++; 7337 break; 7338 case PackageDexOptimizer.DEX_OPT_FAILED: 7339 numberOfPackagesFailed++; 7340 break; 7341 default: 7342 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7343 break; 7344 } 7345 } 7346 7347 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7348 numberOfPackagesFailed }; 7349 } 7350 7351 @Override 7352 public void notifyPackageUse(String packageName, int reason) { 7353 synchronized (mPackages) { 7354 PackageParser.Package p = mPackages.get(packageName); 7355 if (p == null) { 7356 return; 7357 } 7358 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7359 } 7360 } 7361 7362 // TODO: this is not used nor needed. Delete it. 7363 @Override 7364 public boolean performDexOptIfNeeded(String packageName) { 7365 int dexOptStatus = performDexOptTraced(packageName, 7366 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7367 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7368 } 7369 7370 @Override 7371 public boolean performDexOpt(String packageName, 7372 boolean checkProfiles, int compileReason, boolean force) { 7373 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7374 getCompilerFilterForReason(compileReason), force); 7375 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7376 } 7377 7378 @Override 7379 public boolean performDexOptMode(String packageName, 7380 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7381 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7382 targetCompilerFilter, force); 7383 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7384 } 7385 7386 private int performDexOptTraced(String packageName, 7387 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7388 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7389 try { 7390 return performDexOptInternal(packageName, checkProfiles, 7391 targetCompilerFilter, force); 7392 } finally { 7393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7394 } 7395 } 7396 7397 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7398 // if the package can now be considered up to date for the given filter. 7399 private int performDexOptInternal(String packageName, 7400 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7401 PackageParser.Package p; 7402 synchronized (mPackages) { 7403 p = mPackages.get(packageName); 7404 if (p == null) { 7405 // Package could not be found. Report failure. 7406 return PackageDexOptimizer.DEX_OPT_FAILED; 7407 } 7408 mPackageUsage.write(false); 7409 } 7410 long callingId = Binder.clearCallingIdentity(); 7411 try { 7412 synchronized (mInstallLock) { 7413 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7414 targetCompilerFilter, force); 7415 } 7416 } finally { 7417 Binder.restoreCallingIdentity(callingId); 7418 } 7419 } 7420 7421 public ArraySet<String> getOptimizablePackages() { 7422 ArraySet<String> pkgs = new ArraySet<String>(); 7423 synchronized (mPackages) { 7424 for (PackageParser.Package p : mPackages.values()) { 7425 if (PackageDexOptimizer.canOptimizePackage(p)) { 7426 pkgs.add(p.packageName); 7427 } 7428 } 7429 } 7430 return pkgs; 7431 } 7432 7433 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7434 boolean checkProfiles, String targetCompilerFilter, 7435 boolean force) { 7436 // Select the dex optimizer based on the force parameter. 7437 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7438 // allocate an object here. 7439 PackageDexOptimizer pdo = force 7440 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7441 : mPackageDexOptimizer; 7442 7443 // Optimize all dependencies first. Note: we ignore the return value and march on 7444 // on errors. 7445 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7446 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7447 if (!deps.isEmpty()) { 7448 for (PackageParser.Package depPackage : deps) { 7449 // TODO: Analyze and investigate if we (should) profile libraries. 7450 // Currently this will do a full compilation of the library by default. 7451 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7452 false /* checkProfiles */, 7453 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7454 } 7455 } 7456 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7457 targetCompilerFilter); 7458 } 7459 7460 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7461 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7462 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7463 Set<String> collectedNames = new HashSet<>(); 7464 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7465 7466 retValue.remove(p); 7467 7468 return retValue; 7469 } else { 7470 return Collections.emptyList(); 7471 } 7472 } 7473 7474 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7475 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7476 if (!collectedNames.contains(p.packageName)) { 7477 collectedNames.add(p.packageName); 7478 collected.add(p); 7479 7480 if (p.usesLibraries != null) { 7481 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7482 } 7483 if (p.usesOptionalLibraries != null) { 7484 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7485 collectedNames); 7486 } 7487 } 7488 } 7489 7490 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7491 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7492 for (String libName : libs) { 7493 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7494 if (libPkg != null) { 7495 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7496 } 7497 } 7498 } 7499 7500 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7501 synchronized (mPackages) { 7502 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7503 if (lib != null && lib.apk != null) { 7504 return mPackages.get(lib.apk); 7505 } 7506 } 7507 return null; 7508 } 7509 7510 public void shutdown() { 7511 mPackageUsage.write(true); 7512 } 7513 7514 @Override 7515 public void dumpProfiles(String packageName) { 7516 PackageParser.Package pkg; 7517 synchronized (mPackages) { 7518 pkg = mPackages.get(packageName); 7519 if (pkg == null) { 7520 throw new IllegalArgumentException("Unknown package: " + packageName); 7521 } 7522 } 7523 /* Only the shell, root, or the app user should be able to dump profiles. */ 7524 int callingUid = Binder.getCallingUid(); 7525 if (callingUid != Process.SHELL_UID && 7526 callingUid != Process.ROOT_UID && 7527 callingUid != pkg.applicationInfo.uid) { 7528 throw new SecurityException("dumpProfiles"); 7529 } 7530 7531 synchronized (mInstallLock) { 7532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7533 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7534 try { 7535 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7536 String gid = Integer.toString(sharedGid); 7537 String codePaths = TextUtils.join(";", allCodePaths); 7538 mInstaller.dumpProfiles(gid, packageName, codePaths); 7539 } catch (InstallerException e) { 7540 Slog.w(TAG, "Failed to dump profiles", e); 7541 } 7542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7543 } 7544 } 7545 7546 @Override 7547 public void forceDexOpt(String packageName) { 7548 enforceSystemOrRoot("forceDexOpt"); 7549 7550 PackageParser.Package pkg; 7551 synchronized (mPackages) { 7552 pkg = mPackages.get(packageName); 7553 if (pkg == null) { 7554 throw new IllegalArgumentException("Unknown package: " + packageName); 7555 } 7556 } 7557 7558 synchronized (mInstallLock) { 7559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7560 7561 // Whoever is calling forceDexOpt wants a fully compiled package. 7562 // Don't use profiles since that may cause compilation to be skipped. 7563 final int res = performDexOptInternalWithDependenciesLI(pkg, 7564 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7565 true /* force */); 7566 7567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7568 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7569 throw new IllegalStateException("Failed to dexopt: " + res); 7570 } 7571 } 7572 } 7573 7574 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7575 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7576 Slog.w(TAG, "Unable to update from " + oldPkg.name 7577 + " to " + newPkg.packageName 7578 + ": old package not in system partition"); 7579 return false; 7580 } else if (mPackages.get(oldPkg.name) != null) { 7581 Slog.w(TAG, "Unable to update from " + oldPkg.name 7582 + " to " + newPkg.packageName 7583 + ": old package still exists"); 7584 return false; 7585 } 7586 return true; 7587 } 7588 7589 void removeCodePathLI(File codePath) { 7590 if (codePath.isDirectory()) { 7591 try { 7592 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7593 } catch (InstallerException e) { 7594 Slog.w(TAG, "Failed to remove code path", e); 7595 } 7596 } else { 7597 codePath.delete(); 7598 } 7599 } 7600 7601 private int[] resolveUserIds(int userId) { 7602 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7603 } 7604 7605 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7606 if (pkg == null) { 7607 Slog.wtf(TAG, "Package was null!", new Throwable()); 7608 return; 7609 } 7610 clearAppDataLeafLIF(pkg, userId, flags); 7611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7612 for (int i = 0; i < childCount; i++) { 7613 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7614 } 7615 } 7616 7617 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7618 final PackageSetting ps; 7619 synchronized (mPackages) { 7620 ps = mSettings.mPackages.get(pkg.packageName); 7621 } 7622 for (int realUserId : resolveUserIds(userId)) { 7623 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7624 try { 7625 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7626 ceDataInode); 7627 } catch (InstallerException e) { 7628 Slog.w(TAG, String.valueOf(e)); 7629 } 7630 } 7631 } 7632 7633 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7634 if (pkg == null) { 7635 Slog.wtf(TAG, "Package was null!", new Throwable()); 7636 return; 7637 } 7638 destroyAppDataLeafLIF(pkg, userId, flags); 7639 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7640 for (int i = 0; i < childCount; i++) { 7641 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7642 } 7643 } 7644 7645 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7646 final PackageSetting ps; 7647 synchronized (mPackages) { 7648 ps = mSettings.mPackages.get(pkg.packageName); 7649 } 7650 for (int realUserId : resolveUserIds(userId)) { 7651 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7652 try { 7653 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7654 ceDataInode); 7655 } catch (InstallerException e) { 7656 Slog.w(TAG, String.valueOf(e)); 7657 } 7658 } 7659 } 7660 7661 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7662 if (pkg == null) { 7663 Slog.wtf(TAG, "Package was null!", new Throwable()); 7664 return; 7665 } 7666 destroyAppProfilesLeafLIF(pkg); 7667 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7668 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7669 for (int i = 0; i < childCount; i++) { 7670 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7671 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7672 true /* removeBaseMarker */); 7673 } 7674 } 7675 7676 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7677 boolean removeBaseMarker) { 7678 if (pkg.isForwardLocked()) { 7679 return; 7680 } 7681 7682 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7683 try { 7684 path = PackageManagerServiceUtils.realpath(new File(path)); 7685 } catch (IOException e) { 7686 // TODO: Should we return early here ? 7687 Slog.w(TAG, "Failed to get canonical path", e); 7688 continue; 7689 } 7690 7691 final String useMarker = path.replace('/', '@'); 7692 for (int realUserId : resolveUserIds(userId)) { 7693 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7694 if (removeBaseMarker) { 7695 File foreignUseMark = new File(profileDir, useMarker); 7696 if (foreignUseMark.exists()) { 7697 if (!foreignUseMark.delete()) { 7698 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7699 + pkg.packageName); 7700 } 7701 } 7702 } 7703 7704 File[] markers = profileDir.listFiles(); 7705 if (markers != null) { 7706 final String searchString = "@" + pkg.packageName + "@"; 7707 // We also delete all markers that contain the package name we're 7708 // uninstalling. These are associated with secondary dex-files belonging 7709 // to the package. Reconstructing the path of these dex files is messy 7710 // in general. 7711 for (File marker : markers) { 7712 if (marker.getName().indexOf(searchString) > 0) { 7713 if (!marker.delete()) { 7714 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7715 + pkg.packageName); 7716 } 7717 } 7718 } 7719 } 7720 } 7721 } 7722 } 7723 7724 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7725 try { 7726 mInstaller.destroyAppProfiles(pkg.packageName); 7727 } catch (InstallerException e) { 7728 Slog.w(TAG, String.valueOf(e)); 7729 } 7730 } 7731 7732 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7733 if (pkg == null) { 7734 Slog.wtf(TAG, "Package was null!", new Throwable()); 7735 return; 7736 } 7737 clearAppProfilesLeafLIF(pkg); 7738 // We don't remove the base foreign use marker when clearing profiles because 7739 // we will rename it when the app is updated. Unlike the actual profile contents, 7740 // the foreign use marker is good across installs. 7741 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7742 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7743 for (int i = 0; i < childCount; i++) { 7744 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7745 } 7746 } 7747 7748 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7749 try { 7750 mInstaller.clearAppProfiles(pkg.packageName); 7751 } catch (InstallerException e) { 7752 Slog.w(TAG, String.valueOf(e)); 7753 } 7754 } 7755 7756 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7757 long lastUpdateTime) { 7758 // Set parent install/update time 7759 PackageSetting ps = (PackageSetting) pkg.mExtras; 7760 if (ps != null) { 7761 ps.firstInstallTime = firstInstallTime; 7762 ps.lastUpdateTime = lastUpdateTime; 7763 } 7764 // Set children install/update time 7765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7766 for (int i = 0; i < childCount; i++) { 7767 PackageParser.Package childPkg = pkg.childPackages.get(i); 7768 ps = (PackageSetting) childPkg.mExtras; 7769 if (ps != null) { 7770 ps.firstInstallTime = firstInstallTime; 7771 ps.lastUpdateTime = lastUpdateTime; 7772 } 7773 } 7774 } 7775 7776 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7777 PackageParser.Package changingLib) { 7778 if (file.path != null) { 7779 usesLibraryFiles.add(file.path); 7780 return; 7781 } 7782 PackageParser.Package p = mPackages.get(file.apk); 7783 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7784 // If we are doing this while in the middle of updating a library apk, 7785 // then we need to make sure to use that new apk for determining the 7786 // dependencies here. (We haven't yet finished committing the new apk 7787 // to the package manager state.) 7788 if (p == null || p.packageName.equals(changingLib.packageName)) { 7789 p = changingLib; 7790 } 7791 } 7792 if (p != null) { 7793 usesLibraryFiles.addAll(p.getAllCodePaths()); 7794 } 7795 } 7796 7797 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7798 PackageParser.Package changingLib) throws PackageManagerException { 7799 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7800 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7801 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7802 for (int i=0; i<N; i++) { 7803 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7804 if (file == null) { 7805 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7806 "Package " + pkg.packageName + " requires unavailable shared library " 7807 + pkg.usesLibraries.get(i) + "; failing!"); 7808 } 7809 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7810 } 7811 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7812 for (int i=0; i<N; i++) { 7813 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7814 if (file == null) { 7815 Slog.w(TAG, "Package " + pkg.packageName 7816 + " desires unavailable shared library " 7817 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7818 } else { 7819 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7820 } 7821 } 7822 N = usesLibraryFiles.size(); 7823 if (N > 0) { 7824 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7825 } else { 7826 pkg.usesLibraryFiles = null; 7827 } 7828 } 7829 } 7830 7831 private static boolean hasString(List<String> list, List<String> which) { 7832 if (list == null) { 7833 return false; 7834 } 7835 for (int i=list.size()-1; i>=0; i--) { 7836 for (int j=which.size()-1; j>=0; j--) { 7837 if (which.get(j).equals(list.get(i))) { 7838 return true; 7839 } 7840 } 7841 } 7842 return false; 7843 } 7844 7845 private void updateAllSharedLibrariesLPw() { 7846 for (PackageParser.Package pkg : mPackages.values()) { 7847 try { 7848 updateSharedLibrariesLPw(pkg, null); 7849 } catch (PackageManagerException e) { 7850 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7851 } 7852 } 7853 } 7854 7855 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7856 PackageParser.Package changingPkg) { 7857 ArrayList<PackageParser.Package> res = null; 7858 for (PackageParser.Package pkg : mPackages.values()) { 7859 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7860 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7861 if (res == null) { 7862 res = new ArrayList<PackageParser.Package>(); 7863 } 7864 res.add(pkg); 7865 try { 7866 updateSharedLibrariesLPw(pkg, changingPkg); 7867 } catch (PackageManagerException e) { 7868 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7869 } 7870 } 7871 } 7872 return res; 7873 } 7874 7875 /** 7876 * Derive the value of the {@code cpuAbiOverride} based on the provided 7877 * value and an optional stored value from the package settings. 7878 */ 7879 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7880 String cpuAbiOverride = null; 7881 7882 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7883 cpuAbiOverride = null; 7884 } else if (abiOverride != null) { 7885 cpuAbiOverride = abiOverride; 7886 } else if (settings != null) { 7887 cpuAbiOverride = settings.cpuAbiOverrideString; 7888 } 7889 7890 return cpuAbiOverride; 7891 } 7892 7893 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7894 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7895 throws PackageManagerException { 7896 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7897 // If the package has children and this is the first dive in the function 7898 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7899 // whether all packages (parent and children) would be successfully scanned 7900 // before the actual scan since scanning mutates internal state and we want 7901 // to atomically install the package and its children. 7902 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7903 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7904 scanFlags |= SCAN_CHECK_ONLY; 7905 } 7906 } else { 7907 scanFlags &= ~SCAN_CHECK_ONLY; 7908 } 7909 7910 final PackageParser.Package scannedPkg; 7911 try { 7912 // Scan the parent 7913 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7914 // Scan the children 7915 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7916 for (int i = 0; i < childCount; i++) { 7917 PackageParser.Package childPkg = pkg.childPackages.get(i); 7918 scanPackageLI(childPkg, policyFlags, 7919 scanFlags, currentTime, user); 7920 } 7921 } finally { 7922 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7923 } 7924 7925 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7926 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7927 } 7928 7929 return scannedPkg; 7930 } 7931 7932 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7933 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7934 boolean success = false; 7935 try { 7936 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7937 currentTime, user); 7938 success = true; 7939 return res; 7940 } finally { 7941 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7942 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7943 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7944 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7945 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7946 } 7947 } 7948 } 7949 7950 /** 7951 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7952 */ 7953 private static boolean apkHasCode(String fileName) { 7954 StrictJarFile jarFile = null; 7955 try { 7956 jarFile = new StrictJarFile(fileName, 7957 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7958 return jarFile.findEntry("classes.dex") != null; 7959 } catch (IOException ignore) { 7960 } finally { 7961 try { 7962 jarFile.close(); 7963 } catch (IOException ignore) {} 7964 } 7965 return false; 7966 } 7967 7968 /** 7969 * Enforces code policy for the package. This ensures that if an APK has 7970 * declared hasCode="true" in its manifest that the APK actually contains 7971 * code. 7972 * 7973 * @throws PackageManagerException If bytecode could not be found when it should exist 7974 */ 7975 private static void enforceCodePolicy(PackageParser.Package pkg) 7976 throws PackageManagerException { 7977 final boolean shouldHaveCode = 7978 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7979 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7980 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7981 "Package " + pkg.baseCodePath + " code is missing"); 7982 } 7983 7984 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7985 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7986 final boolean splitShouldHaveCode = 7987 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7988 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7989 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7990 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7991 } 7992 } 7993 } 7994 } 7995 7996 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7997 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7998 throws PackageManagerException { 7999 final File scanFile = new File(pkg.codePath); 8000 if (pkg.applicationInfo.getCodePath() == null || 8001 pkg.applicationInfo.getResourcePath() == null) { 8002 // Bail out. The resource and code paths haven't been set. 8003 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8004 "Code and resource paths haven't been set correctly"); 8005 } 8006 8007 // Apply policy 8008 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8009 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8010 if (pkg.applicationInfo.isDirectBootAware()) { 8011 // we're direct boot aware; set for all components 8012 for (PackageParser.Service s : pkg.services) { 8013 s.info.encryptionAware = s.info.directBootAware = true; 8014 } 8015 for (PackageParser.Provider p : pkg.providers) { 8016 p.info.encryptionAware = p.info.directBootAware = true; 8017 } 8018 for (PackageParser.Activity a : pkg.activities) { 8019 a.info.encryptionAware = a.info.directBootAware = true; 8020 } 8021 for (PackageParser.Activity r : pkg.receivers) { 8022 r.info.encryptionAware = r.info.directBootAware = true; 8023 } 8024 } 8025 } else { 8026 // Only allow system apps to be flagged as core apps. 8027 pkg.coreApp = false; 8028 // clear flags not applicable to regular apps 8029 pkg.applicationInfo.privateFlags &= 8030 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8031 pkg.applicationInfo.privateFlags &= 8032 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8033 } 8034 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8035 8036 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8037 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8038 } 8039 8040 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8041 enforceCodePolicy(pkg); 8042 } 8043 8044 if (mCustomResolverComponentName != null && 8045 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8046 setUpCustomResolverActivity(pkg); 8047 } 8048 8049 if (pkg.packageName.equals("android")) { 8050 synchronized (mPackages) { 8051 if (mAndroidApplication != null) { 8052 Slog.w(TAG, "*************************************************"); 8053 Slog.w(TAG, "Core android package being redefined. Skipping."); 8054 Slog.w(TAG, " file=" + scanFile); 8055 Slog.w(TAG, "*************************************************"); 8056 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8057 "Core android package being redefined. Skipping."); 8058 } 8059 8060 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8061 // Set up information for our fall-back user intent resolution activity. 8062 mPlatformPackage = pkg; 8063 pkg.mVersionCode = mSdkVersion; 8064 mAndroidApplication = pkg.applicationInfo; 8065 8066 if (!mResolverReplaced) { 8067 mResolveActivity.applicationInfo = mAndroidApplication; 8068 mResolveActivity.name = ResolverActivity.class.getName(); 8069 mResolveActivity.packageName = mAndroidApplication.packageName; 8070 mResolveActivity.processName = "system:ui"; 8071 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8072 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8073 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8074 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8075 mResolveActivity.exported = true; 8076 mResolveActivity.enabled = true; 8077 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8078 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8079 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8080 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8081 | ActivityInfo.CONFIG_ORIENTATION 8082 | ActivityInfo.CONFIG_KEYBOARD 8083 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8084 mResolveInfo.activityInfo = mResolveActivity; 8085 mResolveInfo.priority = 0; 8086 mResolveInfo.preferredOrder = 0; 8087 mResolveInfo.match = 0; 8088 mResolveComponentName = new ComponentName( 8089 mAndroidApplication.packageName, mResolveActivity.name); 8090 } 8091 } 8092 } 8093 } 8094 8095 if (DEBUG_PACKAGE_SCANNING) { 8096 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8097 Log.d(TAG, "Scanning package " + pkg.packageName); 8098 } 8099 8100 synchronized (mPackages) { 8101 if (mPackages.containsKey(pkg.packageName) 8102 || mSharedLibraries.containsKey(pkg.packageName)) { 8103 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8104 "Application package " + pkg.packageName 8105 + " already installed. Skipping duplicate."); 8106 } 8107 8108 // If we're only installing presumed-existing packages, require that the 8109 // scanned APK is both already known and at the path previously established 8110 // for it. Previously unknown packages we pick up normally, but if we have an 8111 // a priori expectation about this package's install presence, enforce it. 8112 // With a singular exception for new system packages. When an OTA contains 8113 // a new system package, we allow the codepath to change from a system location 8114 // to the user-installed location. If we don't allow this change, any newer, 8115 // user-installed version of the application will be ignored. 8116 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8117 if (mExpectingBetter.containsKey(pkg.packageName)) { 8118 logCriticalInfo(Log.WARN, 8119 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8120 } else { 8121 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8122 if (known != null) { 8123 if (DEBUG_PACKAGE_SCANNING) { 8124 Log.d(TAG, "Examining " + pkg.codePath 8125 + " and requiring known paths " + known.codePathString 8126 + " & " + known.resourcePathString); 8127 } 8128 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8129 || !pkg.applicationInfo.getResourcePath().equals( 8130 known.resourcePathString)) { 8131 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8132 "Application package " + pkg.packageName 8133 + " found at " + pkg.applicationInfo.getCodePath() 8134 + " but expected at " + known.codePathString 8135 + "; ignoring."); 8136 } 8137 } 8138 } 8139 } 8140 } 8141 8142 // Initialize package source and resource directories 8143 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8144 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8145 8146 SharedUserSetting suid = null; 8147 PackageSetting pkgSetting = null; 8148 8149 if (!isSystemApp(pkg)) { 8150 // Only system apps can use these features. 8151 pkg.mOriginalPackages = null; 8152 pkg.mRealPackage = null; 8153 pkg.mAdoptPermissions = null; 8154 } 8155 8156 // Getting the package setting may have a side-effect, so if we 8157 // are only checking if scan would succeed, stash a copy of the 8158 // old setting to restore at the end. 8159 PackageSetting nonMutatedPs = null; 8160 8161 // writer 8162 synchronized (mPackages) { 8163 if (pkg.mSharedUserId != null) { 8164 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8165 if (suid == null) { 8166 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8167 "Creating application package " + pkg.packageName 8168 + " for shared user failed"); 8169 } 8170 if (DEBUG_PACKAGE_SCANNING) { 8171 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8172 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8173 + "): packages=" + suid.packages); 8174 } 8175 } 8176 8177 // Check if we are renaming from an original package name. 8178 PackageSetting origPackage = null; 8179 String realName = null; 8180 if (pkg.mOriginalPackages != null) { 8181 // This package may need to be renamed to a previously 8182 // installed name. Let's check on that... 8183 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8184 if (pkg.mOriginalPackages.contains(renamed)) { 8185 // This package had originally been installed as the 8186 // original name, and we have already taken care of 8187 // transitioning to the new one. Just update the new 8188 // one to continue using the old name. 8189 realName = pkg.mRealPackage; 8190 if (!pkg.packageName.equals(renamed)) { 8191 // Callers into this function may have already taken 8192 // care of renaming the package; only do it here if 8193 // it is not already done. 8194 pkg.setPackageName(renamed); 8195 } 8196 8197 } else { 8198 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8199 if ((origPackage = mSettings.peekPackageLPr( 8200 pkg.mOriginalPackages.get(i))) != null) { 8201 // We do have the package already installed under its 8202 // original name... should we use it? 8203 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8204 // New package is not compatible with original. 8205 origPackage = null; 8206 continue; 8207 } else if (origPackage.sharedUser != null) { 8208 // Make sure uid is compatible between packages. 8209 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8210 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8211 + " to " + pkg.packageName + ": old uid " 8212 + origPackage.sharedUser.name 8213 + " differs from " + pkg.mSharedUserId); 8214 origPackage = null; 8215 continue; 8216 } 8217 // TODO: Add case when shared user id is added [b/28144775] 8218 } else { 8219 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8220 + pkg.packageName + " to old name " + origPackage.name); 8221 } 8222 break; 8223 } 8224 } 8225 } 8226 } 8227 8228 if (mTransferedPackages.contains(pkg.packageName)) { 8229 Slog.w(TAG, "Package " + pkg.packageName 8230 + " was transferred to another, but its .apk remains"); 8231 } 8232 8233 // See comments in nonMutatedPs declaration 8234 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8235 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8236 if (foundPs != null) { 8237 nonMutatedPs = new PackageSetting(foundPs); 8238 } 8239 } 8240 8241 // Just create the setting, don't add it yet. For already existing packages 8242 // the PkgSetting exists already and doesn't have to be created. 8243 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8244 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8245 pkg.applicationInfo.primaryCpuAbi, 8246 pkg.applicationInfo.secondaryCpuAbi, 8247 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8248 user, false); 8249 if (pkgSetting == null) { 8250 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8251 "Creating application package " + pkg.packageName + " failed"); 8252 } 8253 8254 if (pkgSetting.origPackage != null) { 8255 // If we are first transitioning from an original package, 8256 // fix up the new package's name now. We need to do this after 8257 // looking up the package under its new name, so getPackageLP 8258 // can take care of fiddling things correctly. 8259 pkg.setPackageName(origPackage.name); 8260 8261 // File a report about this. 8262 String msg = "New package " + pkgSetting.realName 8263 + " renamed to replace old package " + pkgSetting.name; 8264 reportSettingsProblem(Log.WARN, msg); 8265 8266 // Make a note of it. 8267 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8268 mTransferedPackages.add(origPackage.name); 8269 } 8270 8271 // No longer need to retain this. 8272 pkgSetting.origPackage = null; 8273 } 8274 8275 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8276 // Make a note of it. 8277 mTransferedPackages.add(pkg.packageName); 8278 } 8279 8280 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8281 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8282 } 8283 8284 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8285 // Check all shared libraries and map to their actual file path. 8286 // We only do this here for apps not on a system dir, because those 8287 // are the only ones that can fail an install due to this. We 8288 // will take care of the system apps by updating all of their 8289 // library paths after the scan is done. 8290 updateSharedLibrariesLPw(pkg, null); 8291 } 8292 8293 if (mFoundPolicyFile) { 8294 SELinuxMMAC.assignSeinfoValue(pkg); 8295 } 8296 8297 pkg.applicationInfo.uid = pkgSetting.appId; 8298 pkg.mExtras = pkgSetting; 8299 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8300 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8301 // We just determined the app is signed correctly, so bring 8302 // over the latest parsed certs. 8303 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8304 } else { 8305 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8306 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8307 "Package " + pkg.packageName + " upgrade keys do not match the " 8308 + "previously installed version"); 8309 } else { 8310 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8311 String msg = "System package " + pkg.packageName 8312 + " signature changed; retaining data."; 8313 reportSettingsProblem(Log.WARN, msg); 8314 } 8315 } 8316 } else { 8317 try { 8318 verifySignaturesLP(pkgSetting, pkg); 8319 // We just determined the app is signed correctly, so bring 8320 // over the latest parsed certs. 8321 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8322 } catch (PackageManagerException e) { 8323 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8324 throw e; 8325 } 8326 // The signature has changed, but this package is in the system 8327 // image... let's recover! 8328 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8329 // However... if this package is part of a shared user, but it 8330 // doesn't match the signature of the shared user, let's fail. 8331 // What this means is that you can't change the signatures 8332 // associated with an overall shared user, which doesn't seem all 8333 // that unreasonable. 8334 if (pkgSetting.sharedUser != null) { 8335 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8336 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8337 throw new PackageManagerException( 8338 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8339 "Signature mismatch for shared user: " 8340 + pkgSetting.sharedUser); 8341 } 8342 } 8343 // File a report about this. 8344 String msg = "System package " + pkg.packageName 8345 + " signature changed; retaining data."; 8346 reportSettingsProblem(Log.WARN, msg); 8347 } 8348 } 8349 // Verify that this new package doesn't have any content providers 8350 // that conflict with existing packages. Only do this if the 8351 // package isn't already installed, since we don't want to break 8352 // things that are installed. 8353 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8354 final int N = pkg.providers.size(); 8355 int i; 8356 for (i=0; i<N; i++) { 8357 PackageParser.Provider p = pkg.providers.get(i); 8358 if (p.info.authority != null) { 8359 String names[] = p.info.authority.split(";"); 8360 for (int j = 0; j < names.length; j++) { 8361 if (mProvidersByAuthority.containsKey(names[j])) { 8362 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8363 final String otherPackageName = 8364 ((other != null && other.getComponentName() != null) ? 8365 other.getComponentName().getPackageName() : "?"); 8366 throw new PackageManagerException( 8367 INSTALL_FAILED_CONFLICTING_PROVIDER, 8368 "Can't install because provider name " + names[j] 8369 + " (in package " + pkg.applicationInfo.packageName 8370 + ") is already used by " + otherPackageName); 8371 } 8372 } 8373 } 8374 } 8375 } 8376 8377 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8378 // This package wants to adopt ownership of permissions from 8379 // another package. 8380 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8381 final String origName = pkg.mAdoptPermissions.get(i); 8382 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8383 if (orig != null) { 8384 if (verifyPackageUpdateLPr(orig, pkg)) { 8385 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8386 + pkg.packageName); 8387 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8388 } 8389 } 8390 } 8391 } 8392 } 8393 8394 final String pkgName = pkg.packageName; 8395 8396 final long scanFileTime = scanFile.lastModified(); 8397 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8398 pkg.applicationInfo.processName = fixProcessName( 8399 pkg.applicationInfo.packageName, 8400 pkg.applicationInfo.processName, 8401 pkg.applicationInfo.uid); 8402 8403 if (pkg != mPlatformPackage) { 8404 // Get all of our default paths setup 8405 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8406 } 8407 8408 final String path = scanFile.getPath(); 8409 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8410 8411 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8412 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8413 8414 // Some system apps still use directory structure for native libraries 8415 // in which case we might end up not detecting abi solely based on apk 8416 // structure. Try to detect abi based on directory structure. 8417 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8418 pkg.applicationInfo.primaryCpuAbi == null) { 8419 setBundledAppAbisAndRoots(pkg, pkgSetting); 8420 setNativeLibraryPaths(pkg); 8421 } 8422 8423 } else { 8424 if ((scanFlags & SCAN_MOVE) != 0) { 8425 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8426 // but we already have this packages package info in the PackageSetting. We just 8427 // use that and derive the native library path based on the new codepath. 8428 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8429 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8430 } 8431 8432 // Set native library paths again. For moves, the path will be updated based on the 8433 // ABIs we've determined above. For non-moves, the path will be updated based on the 8434 // ABIs we determined during compilation, but the path will depend on the final 8435 // package path (after the rename away from the stage path). 8436 setNativeLibraryPaths(pkg); 8437 } 8438 8439 // This is a special case for the "system" package, where the ABI is 8440 // dictated by the zygote configuration (and init.rc). We should keep track 8441 // of this ABI so that we can deal with "normal" applications that run under 8442 // the same UID correctly. 8443 if (mPlatformPackage == pkg) { 8444 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8445 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8446 } 8447 8448 // If there's a mismatch between the abi-override in the package setting 8449 // and the abiOverride specified for the install. Warn about this because we 8450 // would've already compiled the app without taking the package setting into 8451 // account. 8452 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8453 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8454 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8455 " for package " + pkg.packageName); 8456 } 8457 } 8458 8459 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8460 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8461 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8462 8463 // Copy the derived override back to the parsed package, so that we can 8464 // update the package settings accordingly. 8465 pkg.cpuAbiOverride = cpuAbiOverride; 8466 8467 if (DEBUG_ABI_SELECTION) { 8468 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8469 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8470 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8471 } 8472 8473 // Push the derived path down into PackageSettings so we know what to 8474 // clean up at uninstall time. 8475 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8476 8477 if (DEBUG_ABI_SELECTION) { 8478 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8479 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8480 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8481 } 8482 8483 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8484 // We don't do this here during boot because we can do it all 8485 // at once after scanning all existing packages. 8486 // 8487 // We also do this *before* we perform dexopt on this package, so that 8488 // we can avoid redundant dexopts, and also to make sure we've got the 8489 // code and package path correct. 8490 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8491 pkg, true /* boot complete */); 8492 } 8493 8494 if (mFactoryTest && pkg.requestedPermissions.contains( 8495 android.Manifest.permission.FACTORY_TEST)) { 8496 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8497 } 8498 8499 ArrayList<PackageParser.Package> clientLibPkgs = null; 8500 8501 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8502 if (nonMutatedPs != null) { 8503 synchronized (mPackages) { 8504 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8505 } 8506 } 8507 return pkg; 8508 } 8509 8510 // Only privileged apps and updated privileged apps can add child packages. 8511 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8512 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8513 throw new PackageManagerException("Only privileged apps and updated " 8514 + "privileged apps can add child packages. Ignoring package " 8515 + pkg.packageName); 8516 } 8517 final int childCount = pkg.childPackages.size(); 8518 for (int i = 0; i < childCount; i++) { 8519 PackageParser.Package childPkg = pkg.childPackages.get(i); 8520 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8521 childPkg.packageName)) { 8522 throw new PackageManagerException("Cannot override a child package of " 8523 + "another disabled system app. Ignoring package " + pkg.packageName); 8524 } 8525 } 8526 } 8527 8528 // writer 8529 synchronized (mPackages) { 8530 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8531 // Only system apps can add new shared libraries. 8532 if (pkg.libraryNames != null) { 8533 for (int i=0; i<pkg.libraryNames.size(); i++) { 8534 String name = pkg.libraryNames.get(i); 8535 boolean allowed = false; 8536 if (pkg.isUpdatedSystemApp()) { 8537 // New library entries can only be added through the 8538 // system image. This is important to get rid of a lot 8539 // of nasty edge cases: for example if we allowed a non- 8540 // system update of the app to add a library, then uninstalling 8541 // the update would make the library go away, and assumptions 8542 // we made such as through app install filtering would now 8543 // have allowed apps on the device which aren't compatible 8544 // with it. Better to just have the restriction here, be 8545 // conservative, and create many fewer cases that can negatively 8546 // impact the user experience. 8547 final PackageSetting sysPs = mSettings 8548 .getDisabledSystemPkgLPr(pkg.packageName); 8549 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8550 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8551 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8552 allowed = true; 8553 break; 8554 } 8555 } 8556 } 8557 } else { 8558 allowed = true; 8559 } 8560 if (allowed) { 8561 if (!mSharedLibraries.containsKey(name)) { 8562 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8563 } else if (!name.equals(pkg.packageName)) { 8564 Slog.w(TAG, "Package " + pkg.packageName + " library " 8565 + name + " already exists; skipping"); 8566 } 8567 } else { 8568 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8569 + name + " that is not declared on system image; skipping"); 8570 } 8571 } 8572 if ((scanFlags & SCAN_BOOTING) == 0) { 8573 // If we are not booting, we need to update any applications 8574 // that are clients of our shared library. If we are booting, 8575 // this will all be done once the scan is complete. 8576 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8577 } 8578 } 8579 } 8580 } 8581 8582 if ((scanFlags & SCAN_BOOTING) != 0) { 8583 // No apps can run during boot scan, so they don't need to be frozen 8584 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8585 // Caller asked to not kill app, so it's probably not frozen 8586 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8587 // Caller asked us to ignore frozen check for some reason; they 8588 // probably didn't know the package name 8589 } else { 8590 // We're doing major surgery on this package, so it better be frozen 8591 // right now to keep it from launching 8592 checkPackageFrozen(pkgName); 8593 } 8594 8595 // Also need to kill any apps that are dependent on the library. 8596 if (clientLibPkgs != null) { 8597 for (int i=0; i<clientLibPkgs.size(); i++) { 8598 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8599 killApplication(clientPkg.applicationInfo.packageName, 8600 clientPkg.applicationInfo.uid, "update lib"); 8601 } 8602 } 8603 8604 // Make sure we're not adding any bogus keyset info 8605 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8606 ksms.assertScannedPackageValid(pkg); 8607 8608 // writer 8609 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8610 8611 boolean createIdmapFailed = false; 8612 synchronized (mPackages) { 8613 // We don't expect installation to fail beyond this point 8614 8615 if (pkgSetting.pkg != null) { 8616 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, user); 8617 } 8618 8619 // Add the new setting to mSettings 8620 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8621 // Add the new setting to mPackages 8622 mPackages.put(pkg.applicationInfo.packageName, pkg); 8623 // Make sure we don't accidentally delete its data. 8624 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8625 while (iter.hasNext()) { 8626 PackageCleanItem item = iter.next(); 8627 if (pkgName.equals(item.packageName)) { 8628 iter.remove(); 8629 } 8630 } 8631 8632 // Take care of first install / last update times. 8633 if (currentTime != 0) { 8634 if (pkgSetting.firstInstallTime == 0) { 8635 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8636 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8637 pkgSetting.lastUpdateTime = currentTime; 8638 } 8639 } else if (pkgSetting.firstInstallTime == 0) { 8640 // We need *something*. Take time time stamp of the file. 8641 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8642 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8643 if (scanFileTime != pkgSetting.timeStamp) { 8644 // A package on the system image has changed; consider this 8645 // to be an update. 8646 pkgSetting.lastUpdateTime = scanFileTime; 8647 } 8648 } 8649 8650 // Add the package's KeySets to the global KeySetManagerService 8651 ksms.addScannedPackageLPw(pkg); 8652 8653 int N = pkg.providers.size(); 8654 StringBuilder r = null; 8655 int i; 8656 for (i=0; i<N; i++) { 8657 PackageParser.Provider p = pkg.providers.get(i); 8658 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8659 p.info.processName, pkg.applicationInfo.uid); 8660 mProviders.addProvider(p); 8661 p.syncable = p.info.isSyncable; 8662 if (p.info.authority != null) { 8663 String names[] = p.info.authority.split(";"); 8664 p.info.authority = null; 8665 for (int j = 0; j < names.length; j++) { 8666 if (j == 1 && p.syncable) { 8667 // We only want the first authority for a provider to possibly be 8668 // syncable, so if we already added this provider using a different 8669 // authority clear the syncable flag. We copy the provider before 8670 // changing it because the mProviders object contains a reference 8671 // to a provider that we don't want to change. 8672 // Only do this for the second authority since the resulting provider 8673 // object can be the same for all future authorities for this provider. 8674 p = new PackageParser.Provider(p); 8675 p.syncable = false; 8676 } 8677 if (!mProvidersByAuthority.containsKey(names[j])) { 8678 mProvidersByAuthority.put(names[j], p); 8679 if (p.info.authority == null) { 8680 p.info.authority = names[j]; 8681 } else { 8682 p.info.authority = p.info.authority + ";" + names[j]; 8683 } 8684 if (DEBUG_PACKAGE_SCANNING) { 8685 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8686 Log.d(TAG, "Registered content provider: " + names[j] 8687 + ", className = " + p.info.name + ", isSyncable = " 8688 + p.info.isSyncable); 8689 } 8690 } else { 8691 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8692 Slog.w(TAG, "Skipping provider name " + names[j] + 8693 " (in package " + pkg.applicationInfo.packageName + 8694 "): name already used by " 8695 + ((other != null && other.getComponentName() != null) 8696 ? other.getComponentName().getPackageName() : "?")); 8697 } 8698 } 8699 } 8700 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8701 if (r == null) { 8702 r = new StringBuilder(256); 8703 } else { 8704 r.append(' '); 8705 } 8706 r.append(p.info.name); 8707 } 8708 } 8709 if (r != null) { 8710 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8711 } 8712 8713 N = pkg.services.size(); 8714 r = null; 8715 for (i=0; i<N; i++) { 8716 PackageParser.Service s = pkg.services.get(i); 8717 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8718 s.info.processName, pkg.applicationInfo.uid); 8719 mServices.addService(s); 8720 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8721 if (r == null) { 8722 r = new StringBuilder(256); 8723 } else { 8724 r.append(' '); 8725 } 8726 r.append(s.info.name); 8727 } 8728 } 8729 if (r != null) { 8730 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8731 } 8732 8733 N = pkg.receivers.size(); 8734 r = null; 8735 for (i=0; i<N; i++) { 8736 PackageParser.Activity a = pkg.receivers.get(i); 8737 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8738 a.info.processName, pkg.applicationInfo.uid); 8739 mReceivers.addActivity(a, "receiver"); 8740 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8741 if (r == null) { 8742 r = new StringBuilder(256); 8743 } else { 8744 r.append(' '); 8745 } 8746 r.append(a.info.name); 8747 } 8748 } 8749 if (r != null) { 8750 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8751 } 8752 8753 N = pkg.activities.size(); 8754 r = null; 8755 for (i=0; i<N; i++) { 8756 PackageParser.Activity a = pkg.activities.get(i); 8757 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8758 a.info.processName, pkg.applicationInfo.uid); 8759 mActivities.addActivity(a, "activity"); 8760 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8761 if (r == null) { 8762 r = new StringBuilder(256); 8763 } else { 8764 r.append(' '); 8765 } 8766 r.append(a.info.name); 8767 } 8768 } 8769 if (r != null) { 8770 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8771 } 8772 8773 N = pkg.permissionGroups.size(); 8774 r = null; 8775 for (i=0; i<N; i++) { 8776 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8777 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8778 if (cur == null) { 8779 mPermissionGroups.put(pg.info.name, pg); 8780 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8781 if (r == null) { 8782 r = new StringBuilder(256); 8783 } else { 8784 r.append(' '); 8785 } 8786 r.append(pg.info.name); 8787 } 8788 } else { 8789 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8790 + pg.info.packageName + " ignored: original from " 8791 + cur.info.packageName); 8792 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8793 if (r == null) { 8794 r = new StringBuilder(256); 8795 } else { 8796 r.append(' '); 8797 } 8798 r.append("DUP:"); 8799 r.append(pg.info.name); 8800 } 8801 } 8802 } 8803 if (r != null) { 8804 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8805 } 8806 8807 N = pkg.permissions.size(); 8808 r = null; 8809 for (i=0; i<N; i++) { 8810 PackageParser.Permission p = pkg.permissions.get(i); 8811 8812 // Assume by default that we did not install this permission into the system. 8813 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8814 8815 // Now that permission groups have a special meaning, we ignore permission 8816 // groups for legacy apps to prevent unexpected behavior. In particular, 8817 // permissions for one app being granted to someone just becase they happen 8818 // to be in a group defined by another app (before this had no implications). 8819 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8820 p.group = mPermissionGroups.get(p.info.group); 8821 // Warn for a permission in an unknown group. 8822 if (p.info.group != null && p.group == null) { 8823 Slog.w(TAG, "Permission " + p.info.name + " from package " 8824 + p.info.packageName + " in an unknown group " + p.info.group); 8825 } 8826 } 8827 8828 ArrayMap<String, BasePermission> permissionMap = 8829 p.tree ? mSettings.mPermissionTrees 8830 : mSettings.mPermissions; 8831 BasePermission bp = permissionMap.get(p.info.name); 8832 8833 // Allow system apps to redefine non-system permissions 8834 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8835 final boolean currentOwnerIsSystem = (bp.perm != null 8836 && isSystemApp(bp.perm.owner)); 8837 if (isSystemApp(p.owner)) { 8838 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8839 // It's a built-in permission and no owner, take ownership now 8840 bp.packageSetting = pkgSetting; 8841 bp.perm = p; 8842 bp.uid = pkg.applicationInfo.uid; 8843 bp.sourcePackage = p.info.packageName; 8844 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8845 } else if (!currentOwnerIsSystem) { 8846 String msg = "New decl " + p.owner + " of permission " 8847 + p.info.name + " is system; overriding " + bp.sourcePackage; 8848 reportSettingsProblem(Log.WARN, msg); 8849 bp = null; 8850 } 8851 } 8852 } 8853 8854 if (bp == null) { 8855 bp = new BasePermission(p.info.name, p.info.packageName, 8856 BasePermission.TYPE_NORMAL); 8857 permissionMap.put(p.info.name, bp); 8858 } 8859 8860 if (bp.perm == null) { 8861 if (bp.sourcePackage == null 8862 || bp.sourcePackage.equals(p.info.packageName)) { 8863 BasePermission tree = findPermissionTreeLP(p.info.name); 8864 if (tree == null 8865 || tree.sourcePackage.equals(p.info.packageName)) { 8866 bp.packageSetting = pkgSetting; 8867 bp.perm = p; 8868 bp.uid = pkg.applicationInfo.uid; 8869 bp.sourcePackage = p.info.packageName; 8870 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8871 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8872 if (r == null) { 8873 r = new StringBuilder(256); 8874 } else { 8875 r.append(' '); 8876 } 8877 r.append(p.info.name); 8878 } 8879 } else { 8880 Slog.w(TAG, "Permission " + p.info.name + " from package " 8881 + p.info.packageName + " ignored: base tree " 8882 + tree.name + " is from package " 8883 + tree.sourcePackage); 8884 } 8885 } else { 8886 Slog.w(TAG, "Permission " + p.info.name + " from package " 8887 + p.info.packageName + " ignored: original from " 8888 + bp.sourcePackage); 8889 } 8890 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8891 if (r == null) { 8892 r = new StringBuilder(256); 8893 } else { 8894 r.append(' '); 8895 } 8896 r.append("DUP:"); 8897 r.append(p.info.name); 8898 } 8899 if (bp.perm == p) { 8900 bp.protectionLevel = p.info.protectionLevel; 8901 } 8902 } 8903 8904 if (r != null) { 8905 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8906 } 8907 8908 N = pkg.instrumentation.size(); 8909 r = null; 8910 for (i=0; i<N; i++) { 8911 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8912 a.info.packageName = pkg.applicationInfo.packageName; 8913 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8914 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8915 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8916 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8917 a.info.dataDir = pkg.applicationInfo.dataDir; 8918 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8919 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8920 8921 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8922 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8923 mInstrumentation.put(a.getComponentName(), a); 8924 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8925 if (r == null) { 8926 r = new StringBuilder(256); 8927 } else { 8928 r.append(' '); 8929 } 8930 r.append(a.info.name); 8931 } 8932 } 8933 if (r != null) { 8934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8935 } 8936 8937 if (pkg.protectedBroadcasts != null) { 8938 N = pkg.protectedBroadcasts.size(); 8939 for (i=0; i<N; i++) { 8940 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8941 } 8942 } 8943 8944 pkgSetting.setTimeStamp(scanFileTime); 8945 8946 // Create idmap files for pairs of (packages, overlay packages). 8947 // Note: "android", ie framework-res.apk, is handled by native layers. 8948 if (pkg.mOverlayTarget != null) { 8949 // This is an overlay package. 8950 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8951 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8952 mOverlays.put(pkg.mOverlayTarget, 8953 new ArrayMap<String, PackageParser.Package>()); 8954 } 8955 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8956 map.put(pkg.packageName, pkg); 8957 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8958 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8959 createIdmapFailed = true; 8960 } 8961 } 8962 } else if (mOverlays.containsKey(pkg.packageName) && 8963 !pkg.packageName.equals("android")) { 8964 // This is a regular package, with one or more known overlay packages. 8965 createIdmapsForPackageLI(pkg); 8966 } 8967 } 8968 8969 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8970 8971 if (createIdmapFailed) { 8972 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8973 "scanPackageLI failed to createIdmap"); 8974 } 8975 return pkg; 8976 } 8977 8978 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8979 PackageParser.Package update, UserHandle user) { 8980 if (existing.applicationInfo == null || update.applicationInfo == null) { 8981 // This isn't due to an app installation. 8982 return; 8983 } 8984 8985 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8986 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8987 8988 // The codePath hasn't changed, so there's nothing for us to do. 8989 if (Objects.equals(oldCodePath, newCodePath)) { 8990 return; 8991 } 8992 8993 File canonicalNewCodePath; 8994 try { 8995 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8996 } catch (IOException e) { 8997 Slog.w(TAG, "Failed to get canonical path.", e); 8998 return; 8999 } 9000 9001 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9002 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9003 // that the last component of the path (i.e, the name) doesn't need canonicalization 9004 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9005 // but may change in the future. Hopefully this function won't exist at that point. 9006 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9007 oldCodePath.getName()); 9008 9009 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9010 // with "@". 9011 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9012 if (!oldMarkerPrefix.endsWith("@")) { 9013 oldMarkerPrefix += "@"; 9014 } 9015 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9016 if (!newMarkerPrefix.endsWith("@")) { 9017 newMarkerPrefix += "@"; 9018 } 9019 9020 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9021 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9022 for (String updatedPath : updatedPaths) { 9023 String updatedPathName = new File(updatedPath).getName(); 9024 markerSuffixes.add(updatedPathName.replace('/', '@')); 9025 } 9026 9027 for (int userId : resolveUserIds(user.getIdentifier())) { 9028 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9029 9030 for (String markerSuffix : markerSuffixes) { 9031 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9032 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9033 if (oldForeignUseMark.exists()) { 9034 try { 9035 Os.rename(oldForeignUseMark.getAbsolutePath(), 9036 newForeignUseMark.getAbsolutePath()); 9037 } catch (ErrnoException e) { 9038 Slog.w(TAG, "Failed to rename foreign use marker", e); 9039 oldForeignUseMark.delete(); 9040 } 9041 } 9042 } 9043 } 9044 } 9045 9046 /** 9047 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9048 * is derived purely on the basis of the contents of {@code scanFile} and 9049 * {@code cpuAbiOverride}. 9050 * 9051 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9052 */ 9053 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9054 String cpuAbiOverride, boolean extractLibs) 9055 throws PackageManagerException { 9056 // TODO: We can probably be smarter about this stuff. For installed apps, 9057 // we can calculate this information at install time once and for all. For 9058 // system apps, we can probably assume that this information doesn't change 9059 // after the first boot scan. As things stand, we do lots of unnecessary work. 9060 9061 // Give ourselves some initial paths; we'll come back for another 9062 // pass once we've determined ABI below. 9063 setNativeLibraryPaths(pkg); 9064 9065 // We would never need to extract libs for forward-locked and external packages, 9066 // since the container service will do it for us. We shouldn't attempt to 9067 // extract libs from system app when it was not updated. 9068 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9069 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9070 extractLibs = false; 9071 } 9072 9073 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9074 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9075 9076 NativeLibraryHelper.Handle handle = null; 9077 try { 9078 handle = NativeLibraryHelper.Handle.create(pkg); 9079 // TODO(multiArch): This can be null for apps that didn't go through the 9080 // usual installation process. We can calculate it again, like we 9081 // do during install time. 9082 // 9083 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9084 // unnecessary. 9085 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9086 9087 // Null out the abis so that they can be recalculated. 9088 pkg.applicationInfo.primaryCpuAbi = null; 9089 pkg.applicationInfo.secondaryCpuAbi = null; 9090 if (isMultiArch(pkg.applicationInfo)) { 9091 // Warn if we've set an abiOverride for multi-lib packages.. 9092 // By definition, we need to copy both 32 and 64 bit libraries for 9093 // such packages. 9094 if (pkg.cpuAbiOverride != null 9095 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9096 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9097 } 9098 9099 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9100 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9101 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9102 if (extractLibs) { 9103 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9104 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9105 useIsaSpecificSubdirs); 9106 } else { 9107 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9108 } 9109 } 9110 9111 maybeThrowExceptionForMultiArchCopy( 9112 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9113 9114 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9115 if (extractLibs) { 9116 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9117 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9118 useIsaSpecificSubdirs); 9119 } else { 9120 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9121 } 9122 } 9123 9124 maybeThrowExceptionForMultiArchCopy( 9125 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9126 9127 if (abi64 >= 0) { 9128 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9129 } 9130 9131 if (abi32 >= 0) { 9132 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9133 if (abi64 >= 0) { 9134 if (pkg.use32bitAbi) { 9135 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9136 pkg.applicationInfo.primaryCpuAbi = abi; 9137 } else { 9138 pkg.applicationInfo.secondaryCpuAbi = abi; 9139 } 9140 } else { 9141 pkg.applicationInfo.primaryCpuAbi = abi; 9142 } 9143 } 9144 9145 } else { 9146 String[] abiList = (cpuAbiOverride != null) ? 9147 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9148 9149 // Enable gross and lame hacks for apps that are built with old 9150 // SDK tools. We must scan their APKs for renderscript bitcode and 9151 // not launch them if it's present. Don't bother checking on devices 9152 // that don't have 64 bit support. 9153 boolean needsRenderScriptOverride = false; 9154 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9155 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9156 abiList = Build.SUPPORTED_32_BIT_ABIS; 9157 needsRenderScriptOverride = true; 9158 } 9159 9160 final int copyRet; 9161 if (extractLibs) { 9162 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9163 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9164 } else { 9165 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9166 } 9167 9168 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9169 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9170 "Error unpackaging native libs for app, errorCode=" + copyRet); 9171 } 9172 9173 if (copyRet >= 0) { 9174 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9175 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9176 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9177 } else if (needsRenderScriptOverride) { 9178 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9179 } 9180 } 9181 } catch (IOException ioe) { 9182 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9183 } finally { 9184 IoUtils.closeQuietly(handle); 9185 } 9186 9187 // Now that we've calculated the ABIs and determined if it's an internal app, 9188 // we will go ahead and populate the nativeLibraryPath. 9189 setNativeLibraryPaths(pkg); 9190 } 9191 9192 /** 9193 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9194 * i.e, so that all packages can be run inside a single process if required. 9195 * 9196 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9197 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9198 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9199 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9200 * updating a package that belongs to a shared user. 9201 * 9202 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9203 * adds unnecessary complexity. 9204 */ 9205 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9206 PackageParser.Package scannedPackage, boolean bootComplete) { 9207 String requiredInstructionSet = null; 9208 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9209 requiredInstructionSet = VMRuntime.getInstructionSet( 9210 scannedPackage.applicationInfo.primaryCpuAbi); 9211 } 9212 9213 PackageSetting requirer = null; 9214 for (PackageSetting ps : packagesForUser) { 9215 // If packagesForUser contains scannedPackage, we skip it. This will happen 9216 // when scannedPackage is an update of an existing package. Without this check, 9217 // we will never be able to change the ABI of any package belonging to a shared 9218 // user, even if it's compatible with other packages. 9219 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9220 if (ps.primaryCpuAbiString == null) { 9221 continue; 9222 } 9223 9224 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9225 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9226 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9227 // this but there's not much we can do. 9228 String errorMessage = "Instruction set mismatch, " 9229 + ((requirer == null) ? "[caller]" : requirer) 9230 + " requires " + requiredInstructionSet + " whereas " + ps 9231 + " requires " + instructionSet; 9232 Slog.w(TAG, errorMessage); 9233 } 9234 9235 if (requiredInstructionSet == null) { 9236 requiredInstructionSet = instructionSet; 9237 requirer = ps; 9238 } 9239 } 9240 } 9241 9242 if (requiredInstructionSet != null) { 9243 String adjustedAbi; 9244 if (requirer != null) { 9245 // requirer != null implies that either scannedPackage was null or that scannedPackage 9246 // did not require an ABI, in which case we have to adjust scannedPackage to match 9247 // the ABI of the set (which is the same as requirer's ABI) 9248 adjustedAbi = requirer.primaryCpuAbiString; 9249 if (scannedPackage != null) { 9250 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9251 } 9252 } else { 9253 // requirer == null implies that we're updating all ABIs in the set to 9254 // match scannedPackage. 9255 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9256 } 9257 9258 for (PackageSetting ps : packagesForUser) { 9259 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9260 if (ps.primaryCpuAbiString != null) { 9261 continue; 9262 } 9263 9264 ps.primaryCpuAbiString = adjustedAbi; 9265 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9266 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9267 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9268 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9269 + " (requirer=" 9270 + (requirer == null ? "null" : requirer.pkg.packageName) 9271 + ", scannedPackage=" 9272 + (scannedPackage != null ? scannedPackage.packageName : "null") 9273 + ")"); 9274 try { 9275 mInstaller.rmdex(ps.codePathString, 9276 getDexCodeInstructionSet(getPreferredInstructionSet())); 9277 } catch (InstallerException ignored) { 9278 } 9279 } 9280 } 9281 } 9282 } 9283 } 9284 9285 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9286 synchronized (mPackages) { 9287 mResolverReplaced = true; 9288 // Set up information for custom user intent resolution activity. 9289 mResolveActivity.applicationInfo = pkg.applicationInfo; 9290 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9291 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9292 mResolveActivity.processName = pkg.applicationInfo.packageName; 9293 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9294 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9295 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9296 mResolveActivity.theme = 0; 9297 mResolveActivity.exported = true; 9298 mResolveActivity.enabled = true; 9299 mResolveInfo.activityInfo = mResolveActivity; 9300 mResolveInfo.priority = 0; 9301 mResolveInfo.preferredOrder = 0; 9302 mResolveInfo.match = 0; 9303 mResolveComponentName = mCustomResolverComponentName; 9304 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9305 mResolveComponentName); 9306 } 9307 } 9308 9309 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9310 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9311 9312 // Set up information for ephemeral installer activity 9313 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9314 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9315 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9316 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9317 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9318 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9319 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9320 mEphemeralInstallerActivity.theme = 0; 9321 mEphemeralInstallerActivity.exported = true; 9322 mEphemeralInstallerActivity.enabled = true; 9323 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9324 mEphemeralInstallerInfo.priority = 0; 9325 mEphemeralInstallerInfo.preferredOrder = 0; 9326 mEphemeralInstallerInfo.match = 0; 9327 9328 if (DEBUG_EPHEMERAL) { 9329 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9330 } 9331 } 9332 9333 private static String calculateBundledApkRoot(final String codePathString) { 9334 final File codePath = new File(codePathString); 9335 final File codeRoot; 9336 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9337 codeRoot = Environment.getRootDirectory(); 9338 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9339 codeRoot = Environment.getOemDirectory(); 9340 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9341 codeRoot = Environment.getVendorDirectory(); 9342 } else { 9343 // Unrecognized code path; take its top real segment as the apk root: 9344 // e.g. /something/app/blah.apk => /something 9345 try { 9346 File f = codePath.getCanonicalFile(); 9347 File parent = f.getParentFile(); // non-null because codePath is a file 9348 File tmp; 9349 while ((tmp = parent.getParentFile()) != null) { 9350 f = parent; 9351 parent = tmp; 9352 } 9353 codeRoot = f; 9354 Slog.w(TAG, "Unrecognized code path " 9355 + codePath + " - using " + codeRoot); 9356 } catch (IOException e) { 9357 // Can't canonicalize the code path -- shenanigans? 9358 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9359 return Environment.getRootDirectory().getPath(); 9360 } 9361 } 9362 return codeRoot.getPath(); 9363 } 9364 9365 /** 9366 * Derive and set the location of native libraries for the given package, 9367 * which varies depending on where and how the package was installed. 9368 */ 9369 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9370 final ApplicationInfo info = pkg.applicationInfo; 9371 final String codePath = pkg.codePath; 9372 final File codeFile = new File(codePath); 9373 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9374 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9375 9376 info.nativeLibraryRootDir = null; 9377 info.nativeLibraryRootRequiresIsa = false; 9378 info.nativeLibraryDir = null; 9379 info.secondaryNativeLibraryDir = null; 9380 9381 if (isApkFile(codeFile)) { 9382 // Monolithic install 9383 if (bundledApp) { 9384 // If "/system/lib64/apkname" exists, assume that is the per-package 9385 // native library directory to use; otherwise use "/system/lib/apkname". 9386 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9387 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9388 getPrimaryInstructionSet(info)); 9389 9390 // This is a bundled system app so choose the path based on the ABI. 9391 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9392 // is just the default path. 9393 final String apkName = deriveCodePathName(codePath); 9394 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9395 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9396 apkName).getAbsolutePath(); 9397 9398 if (info.secondaryCpuAbi != null) { 9399 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9400 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9401 secondaryLibDir, apkName).getAbsolutePath(); 9402 } 9403 } else if (asecApp) { 9404 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9405 .getAbsolutePath(); 9406 } else { 9407 final String apkName = deriveCodePathName(codePath); 9408 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9409 .getAbsolutePath(); 9410 } 9411 9412 info.nativeLibraryRootRequiresIsa = false; 9413 info.nativeLibraryDir = info.nativeLibraryRootDir; 9414 } else { 9415 // Cluster install 9416 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9417 info.nativeLibraryRootRequiresIsa = true; 9418 9419 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9420 getPrimaryInstructionSet(info)).getAbsolutePath(); 9421 9422 if (info.secondaryCpuAbi != null) { 9423 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9424 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9425 } 9426 } 9427 } 9428 9429 /** 9430 * Calculate the abis and roots for a bundled app. These can uniquely 9431 * be determined from the contents of the system partition, i.e whether 9432 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9433 * of this information, and instead assume that the system was built 9434 * sensibly. 9435 */ 9436 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9437 PackageSetting pkgSetting) { 9438 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9439 9440 // If "/system/lib64/apkname" exists, assume that is the per-package 9441 // native library directory to use; otherwise use "/system/lib/apkname". 9442 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9443 setBundledAppAbi(pkg, apkRoot, apkName); 9444 // pkgSetting might be null during rescan following uninstall of updates 9445 // to a bundled app, so accommodate that possibility. The settings in 9446 // that case will be established later from the parsed package. 9447 // 9448 // If the settings aren't null, sync them up with what we've just derived. 9449 // note that apkRoot isn't stored in the package settings. 9450 if (pkgSetting != null) { 9451 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9452 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9453 } 9454 } 9455 9456 /** 9457 * Deduces the ABI of a bundled app and sets the relevant fields on the 9458 * parsed pkg object. 9459 * 9460 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9461 * under which system libraries are installed. 9462 * @param apkName the name of the installed package. 9463 */ 9464 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9465 final File codeFile = new File(pkg.codePath); 9466 9467 final boolean has64BitLibs; 9468 final boolean has32BitLibs; 9469 if (isApkFile(codeFile)) { 9470 // Monolithic install 9471 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9472 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9473 } else { 9474 // Cluster install 9475 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9476 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9477 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9478 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9479 has64BitLibs = (new File(rootDir, isa)).exists(); 9480 } else { 9481 has64BitLibs = false; 9482 } 9483 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9484 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9485 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9486 has32BitLibs = (new File(rootDir, isa)).exists(); 9487 } else { 9488 has32BitLibs = false; 9489 } 9490 } 9491 9492 if (has64BitLibs && !has32BitLibs) { 9493 // The package has 64 bit libs, but not 32 bit libs. Its primary 9494 // ABI should be 64 bit. We can safely assume here that the bundled 9495 // native libraries correspond to the most preferred ABI in the list. 9496 9497 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9498 pkg.applicationInfo.secondaryCpuAbi = null; 9499 } else if (has32BitLibs && !has64BitLibs) { 9500 // The package has 32 bit libs but not 64 bit libs. Its primary 9501 // ABI should be 32 bit. 9502 9503 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9504 pkg.applicationInfo.secondaryCpuAbi = null; 9505 } else if (has32BitLibs && has64BitLibs) { 9506 // The application has both 64 and 32 bit bundled libraries. We check 9507 // here that the app declares multiArch support, and warn if it doesn't. 9508 // 9509 // We will be lenient here and record both ABIs. The primary will be the 9510 // ABI that's higher on the list, i.e, a device that's configured to prefer 9511 // 64 bit apps will see a 64 bit primary ABI, 9512 9513 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9514 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9515 } 9516 9517 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9518 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9519 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9520 } else { 9521 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9522 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9523 } 9524 } else { 9525 pkg.applicationInfo.primaryCpuAbi = null; 9526 pkg.applicationInfo.secondaryCpuAbi = null; 9527 } 9528 } 9529 9530 private void killApplication(String pkgName, int appId, String reason) { 9531 // Request the ActivityManager to kill the process(only for existing packages) 9532 // so that we do not end up in a confused state while the user is still using the older 9533 // version of the application while the new one gets installed. 9534 final long token = Binder.clearCallingIdentity(); 9535 try { 9536 IActivityManager am = ActivityManagerNative.getDefault(); 9537 if (am != null) { 9538 try { 9539 am.killApplicationWithAppId(pkgName, appId, reason); 9540 } catch (RemoteException e) { 9541 } 9542 } 9543 } finally { 9544 Binder.restoreCallingIdentity(token); 9545 } 9546 } 9547 9548 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9549 // Remove the parent package setting 9550 PackageSetting ps = (PackageSetting) pkg.mExtras; 9551 if (ps != null) { 9552 removePackageLI(ps, chatty); 9553 } 9554 // Remove the child package setting 9555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9556 for (int i = 0; i < childCount; i++) { 9557 PackageParser.Package childPkg = pkg.childPackages.get(i); 9558 ps = (PackageSetting) childPkg.mExtras; 9559 if (ps != null) { 9560 removePackageLI(ps, chatty); 9561 } 9562 } 9563 } 9564 9565 void removePackageLI(PackageSetting ps, boolean chatty) { 9566 if (DEBUG_INSTALL) { 9567 if (chatty) 9568 Log.d(TAG, "Removing package " + ps.name); 9569 } 9570 9571 // writer 9572 synchronized (mPackages) { 9573 mPackages.remove(ps.name); 9574 final PackageParser.Package pkg = ps.pkg; 9575 if (pkg != null) { 9576 cleanPackageDataStructuresLILPw(pkg, chatty); 9577 } 9578 } 9579 } 9580 9581 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9582 if (DEBUG_INSTALL) { 9583 if (chatty) 9584 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9585 } 9586 9587 // writer 9588 synchronized (mPackages) { 9589 // Remove the parent package 9590 mPackages.remove(pkg.applicationInfo.packageName); 9591 cleanPackageDataStructuresLILPw(pkg, chatty); 9592 9593 // Remove the child packages 9594 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9595 for (int i = 0; i < childCount; i++) { 9596 PackageParser.Package childPkg = pkg.childPackages.get(i); 9597 mPackages.remove(childPkg.applicationInfo.packageName); 9598 cleanPackageDataStructuresLILPw(childPkg, chatty); 9599 } 9600 } 9601 } 9602 9603 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9604 int N = pkg.providers.size(); 9605 StringBuilder r = null; 9606 int i; 9607 for (i=0; i<N; i++) { 9608 PackageParser.Provider p = pkg.providers.get(i); 9609 mProviders.removeProvider(p); 9610 if (p.info.authority == null) { 9611 9612 /* There was another ContentProvider with this authority when 9613 * this app was installed so this authority is null, 9614 * Ignore it as we don't have to unregister the provider. 9615 */ 9616 continue; 9617 } 9618 String names[] = p.info.authority.split(";"); 9619 for (int j = 0; j < names.length; j++) { 9620 if (mProvidersByAuthority.get(names[j]) == p) { 9621 mProvidersByAuthority.remove(names[j]); 9622 if (DEBUG_REMOVE) { 9623 if (chatty) 9624 Log.d(TAG, "Unregistered content provider: " + names[j] 9625 + ", className = " + p.info.name + ", isSyncable = " 9626 + p.info.isSyncable); 9627 } 9628 } 9629 } 9630 if (DEBUG_REMOVE && chatty) { 9631 if (r == null) { 9632 r = new StringBuilder(256); 9633 } else { 9634 r.append(' '); 9635 } 9636 r.append(p.info.name); 9637 } 9638 } 9639 if (r != null) { 9640 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9641 } 9642 9643 N = pkg.services.size(); 9644 r = null; 9645 for (i=0; i<N; i++) { 9646 PackageParser.Service s = pkg.services.get(i); 9647 mServices.removeService(s); 9648 if (chatty) { 9649 if (r == null) { 9650 r = new StringBuilder(256); 9651 } else { 9652 r.append(' '); 9653 } 9654 r.append(s.info.name); 9655 } 9656 } 9657 if (r != null) { 9658 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9659 } 9660 9661 N = pkg.receivers.size(); 9662 r = null; 9663 for (i=0; i<N; i++) { 9664 PackageParser.Activity a = pkg.receivers.get(i); 9665 mReceivers.removeActivity(a, "receiver"); 9666 if (DEBUG_REMOVE && chatty) { 9667 if (r == null) { 9668 r = new StringBuilder(256); 9669 } else { 9670 r.append(' '); 9671 } 9672 r.append(a.info.name); 9673 } 9674 } 9675 if (r != null) { 9676 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9677 } 9678 9679 N = pkg.activities.size(); 9680 r = null; 9681 for (i=0; i<N; i++) { 9682 PackageParser.Activity a = pkg.activities.get(i); 9683 mActivities.removeActivity(a, "activity"); 9684 if (DEBUG_REMOVE && chatty) { 9685 if (r == null) { 9686 r = new StringBuilder(256); 9687 } else { 9688 r.append(' '); 9689 } 9690 r.append(a.info.name); 9691 } 9692 } 9693 if (r != null) { 9694 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9695 } 9696 9697 N = pkg.permissions.size(); 9698 r = null; 9699 for (i=0; i<N; i++) { 9700 PackageParser.Permission p = pkg.permissions.get(i); 9701 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9702 if (bp == null) { 9703 bp = mSettings.mPermissionTrees.get(p.info.name); 9704 } 9705 if (bp != null && bp.perm == p) { 9706 bp.perm = null; 9707 if (DEBUG_REMOVE && chatty) { 9708 if (r == null) { 9709 r = new StringBuilder(256); 9710 } else { 9711 r.append(' '); 9712 } 9713 r.append(p.info.name); 9714 } 9715 } 9716 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9717 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9718 if (appOpPkgs != null) { 9719 appOpPkgs.remove(pkg.packageName); 9720 } 9721 } 9722 } 9723 if (r != null) { 9724 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9725 } 9726 9727 N = pkg.requestedPermissions.size(); 9728 r = null; 9729 for (i=0; i<N; i++) { 9730 String perm = pkg.requestedPermissions.get(i); 9731 BasePermission bp = mSettings.mPermissions.get(perm); 9732 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9733 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9734 if (appOpPkgs != null) { 9735 appOpPkgs.remove(pkg.packageName); 9736 if (appOpPkgs.isEmpty()) { 9737 mAppOpPermissionPackages.remove(perm); 9738 } 9739 } 9740 } 9741 } 9742 if (r != null) { 9743 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9744 } 9745 9746 N = pkg.instrumentation.size(); 9747 r = null; 9748 for (i=0; i<N; i++) { 9749 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9750 mInstrumentation.remove(a.getComponentName()); 9751 if (DEBUG_REMOVE && chatty) { 9752 if (r == null) { 9753 r = new StringBuilder(256); 9754 } else { 9755 r.append(' '); 9756 } 9757 r.append(a.info.name); 9758 } 9759 } 9760 if (r != null) { 9761 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9762 } 9763 9764 r = null; 9765 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9766 // Only system apps can hold shared libraries. 9767 if (pkg.libraryNames != null) { 9768 for (i=0; i<pkg.libraryNames.size(); i++) { 9769 String name = pkg.libraryNames.get(i); 9770 SharedLibraryEntry cur = mSharedLibraries.get(name); 9771 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9772 mSharedLibraries.remove(name); 9773 if (DEBUG_REMOVE && chatty) { 9774 if (r == null) { 9775 r = new StringBuilder(256); 9776 } else { 9777 r.append(' '); 9778 } 9779 r.append(name); 9780 } 9781 } 9782 } 9783 } 9784 } 9785 if (r != null) { 9786 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9787 } 9788 } 9789 9790 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9791 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9792 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9793 return true; 9794 } 9795 } 9796 return false; 9797 } 9798 9799 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9800 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9801 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9802 9803 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9804 // Update the parent permissions 9805 updatePermissionsLPw(pkg.packageName, pkg, flags); 9806 // Update the child permissions 9807 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9808 for (int i = 0; i < childCount; i++) { 9809 PackageParser.Package childPkg = pkg.childPackages.get(i); 9810 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9811 } 9812 } 9813 9814 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9815 int flags) { 9816 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9817 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9818 } 9819 9820 private void updatePermissionsLPw(String changingPkg, 9821 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9822 // Make sure there are no dangling permission trees. 9823 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9824 while (it.hasNext()) { 9825 final BasePermission bp = it.next(); 9826 if (bp.packageSetting == null) { 9827 // We may not yet have parsed the package, so just see if 9828 // we still know about its settings. 9829 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9830 } 9831 if (bp.packageSetting == null) { 9832 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9833 + " from package " + bp.sourcePackage); 9834 it.remove(); 9835 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9836 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9837 Slog.i(TAG, "Removing old permission tree: " + bp.name 9838 + " from package " + bp.sourcePackage); 9839 flags |= UPDATE_PERMISSIONS_ALL; 9840 it.remove(); 9841 } 9842 } 9843 } 9844 9845 // Make sure all dynamic permissions have been assigned to a package, 9846 // and make sure there are no dangling permissions. 9847 it = mSettings.mPermissions.values().iterator(); 9848 while (it.hasNext()) { 9849 final BasePermission bp = it.next(); 9850 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9851 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9852 + bp.name + " pkg=" + bp.sourcePackage 9853 + " info=" + bp.pendingInfo); 9854 if (bp.packageSetting == null && bp.pendingInfo != null) { 9855 final BasePermission tree = findPermissionTreeLP(bp.name); 9856 if (tree != null && tree.perm != null) { 9857 bp.packageSetting = tree.packageSetting; 9858 bp.perm = new PackageParser.Permission(tree.perm.owner, 9859 new PermissionInfo(bp.pendingInfo)); 9860 bp.perm.info.packageName = tree.perm.info.packageName; 9861 bp.perm.info.name = bp.name; 9862 bp.uid = tree.uid; 9863 } 9864 } 9865 } 9866 if (bp.packageSetting == null) { 9867 // We may not yet have parsed the package, so just see if 9868 // we still know about its settings. 9869 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9870 } 9871 if (bp.packageSetting == null) { 9872 Slog.w(TAG, "Removing dangling permission: " + bp.name 9873 + " from package " + bp.sourcePackage); 9874 it.remove(); 9875 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9876 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9877 Slog.i(TAG, "Removing old permission: " + bp.name 9878 + " from package " + bp.sourcePackage); 9879 flags |= UPDATE_PERMISSIONS_ALL; 9880 it.remove(); 9881 } 9882 } 9883 } 9884 9885 // Now update the permissions for all packages, in particular 9886 // replace the granted permissions of the system packages. 9887 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9888 for (PackageParser.Package pkg : mPackages.values()) { 9889 if (pkg != pkgInfo) { 9890 // Only replace for packages on requested volume 9891 final String volumeUuid = getVolumeUuidForPackage(pkg); 9892 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9893 && Objects.equals(replaceVolumeUuid, volumeUuid); 9894 grantPermissionsLPw(pkg, replace, changingPkg); 9895 } 9896 } 9897 } 9898 9899 if (pkgInfo != null) { 9900 // Only replace for packages on requested volume 9901 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9902 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9903 && Objects.equals(replaceVolumeUuid, volumeUuid); 9904 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9905 } 9906 } 9907 9908 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9909 String packageOfInterest) { 9910 // IMPORTANT: There are two types of permissions: install and runtime. 9911 // Install time permissions are granted when the app is installed to 9912 // all device users and users added in the future. Runtime permissions 9913 // are granted at runtime explicitly to specific users. Normal and signature 9914 // protected permissions are install time permissions. Dangerous permissions 9915 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9916 // otherwise they are runtime permissions. This function does not manage 9917 // runtime permissions except for the case an app targeting Lollipop MR1 9918 // being upgraded to target a newer SDK, in which case dangerous permissions 9919 // are transformed from install time to runtime ones. 9920 9921 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9922 if (ps == null) { 9923 return; 9924 } 9925 9926 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9927 9928 PermissionsState permissionsState = ps.getPermissionsState(); 9929 PermissionsState origPermissions = permissionsState; 9930 9931 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9932 9933 boolean runtimePermissionsRevoked = false; 9934 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9935 9936 boolean changedInstallPermission = false; 9937 9938 if (replace) { 9939 ps.installPermissionsFixed = false; 9940 if (!ps.isSharedUser()) { 9941 origPermissions = new PermissionsState(permissionsState); 9942 permissionsState.reset(); 9943 } else { 9944 // We need to know only about runtime permission changes since the 9945 // calling code always writes the install permissions state but 9946 // the runtime ones are written only if changed. The only cases of 9947 // changed runtime permissions here are promotion of an install to 9948 // runtime and revocation of a runtime from a shared user. 9949 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9950 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9951 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9952 runtimePermissionsRevoked = true; 9953 } 9954 } 9955 } 9956 9957 permissionsState.setGlobalGids(mGlobalGids); 9958 9959 final int N = pkg.requestedPermissions.size(); 9960 for (int i=0; i<N; i++) { 9961 final String name = pkg.requestedPermissions.get(i); 9962 final BasePermission bp = mSettings.mPermissions.get(name); 9963 9964 if (DEBUG_INSTALL) { 9965 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9966 } 9967 9968 if (bp == null || bp.packageSetting == null) { 9969 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9970 Slog.w(TAG, "Unknown permission " + name 9971 + " in package " + pkg.packageName); 9972 } 9973 continue; 9974 } 9975 9976 final String perm = bp.name; 9977 boolean allowedSig = false; 9978 int grant = GRANT_DENIED; 9979 9980 // Keep track of app op permissions. 9981 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9982 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9983 if (pkgs == null) { 9984 pkgs = new ArraySet<>(); 9985 mAppOpPermissionPackages.put(bp.name, pkgs); 9986 } 9987 pkgs.add(pkg.packageName); 9988 } 9989 9990 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9991 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9992 >= Build.VERSION_CODES.M; 9993 switch (level) { 9994 case PermissionInfo.PROTECTION_NORMAL: { 9995 // For all apps normal permissions are install time ones. 9996 grant = GRANT_INSTALL; 9997 } break; 9998 9999 case PermissionInfo.PROTECTION_DANGEROUS: { 10000 // If a permission review is required for legacy apps we represent 10001 // their permissions as always granted runtime ones since we need 10002 // to keep the review required permission flag per user while an 10003 // install permission's state is shared across all users. 10004 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10005 // For legacy apps dangerous permissions are install time ones. 10006 grant = GRANT_INSTALL; 10007 } else if (origPermissions.hasInstallPermission(bp.name)) { 10008 // For legacy apps that became modern, install becomes runtime. 10009 grant = GRANT_UPGRADE; 10010 } else if (mPromoteSystemApps 10011 && isSystemApp(ps) 10012 && mExistingSystemPackages.contains(ps.name)) { 10013 // For legacy system apps, install becomes runtime. 10014 // We cannot check hasInstallPermission() for system apps since those 10015 // permissions were granted implicitly and not persisted pre-M. 10016 grant = GRANT_UPGRADE; 10017 } else { 10018 // For modern apps keep runtime permissions unchanged. 10019 grant = GRANT_RUNTIME; 10020 } 10021 } break; 10022 10023 case PermissionInfo.PROTECTION_SIGNATURE: { 10024 // For all apps signature permissions are install time ones. 10025 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10026 if (allowedSig) { 10027 grant = GRANT_INSTALL; 10028 } 10029 } break; 10030 } 10031 10032 if (DEBUG_INSTALL) { 10033 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10034 } 10035 10036 if (grant != GRANT_DENIED) { 10037 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10038 // If this is an existing, non-system package, then 10039 // we can't add any new permissions to it. 10040 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10041 // Except... if this is a permission that was added 10042 // to the platform (note: need to only do this when 10043 // updating the platform). 10044 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10045 grant = GRANT_DENIED; 10046 } 10047 } 10048 } 10049 10050 switch (grant) { 10051 case GRANT_INSTALL: { 10052 // Revoke this as runtime permission to handle the case of 10053 // a runtime permission being downgraded to an install one. 10054 // Also in permission review mode we keep dangerous permissions 10055 // for legacy apps 10056 for (int userId : UserManagerService.getInstance().getUserIds()) { 10057 if (origPermissions.getRuntimePermissionState( 10058 bp.name, userId) != null) { 10059 // Revoke the runtime permission and clear the flags. 10060 origPermissions.revokeRuntimePermission(bp, userId); 10061 origPermissions.updatePermissionFlags(bp, userId, 10062 PackageManager.MASK_PERMISSION_FLAGS, 0); 10063 // If we revoked a permission permission, we have to write. 10064 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10065 changedRuntimePermissionUserIds, userId); 10066 } 10067 } 10068 // Grant an install permission. 10069 if (permissionsState.grantInstallPermission(bp) != 10070 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10071 changedInstallPermission = true; 10072 } 10073 } break; 10074 10075 case GRANT_RUNTIME: { 10076 // Grant previously granted runtime permissions. 10077 for (int userId : UserManagerService.getInstance().getUserIds()) { 10078 PermissionState permissionState = origPermissions 10079 .getRuntimePermissionState(bp.name, userId); 10080 int flags = permissionState != null 10081 ? permissionState.getFlags() : 0; 10082 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10083 if (permissionsState.grantRuntimePermission(bp, userId) == 10084 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10085 // If we cannot put the permission as it was, we have to write. 10086 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10087 changedRuntimePermissionUserIds, userId); 10088 } 10089 // If the app supports runtime permissions no need for a review. 10090 if (Build.PERMISSIONS_REVIEW_REQUIRED 10091 && appSupportsRuntimePermissions 10092 && (flags & PackageManager 10093 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10094 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10095 // Since we changed the flags, we have to write. 10096 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10097 changedRuntimePermissionUserIds, userId); 10098 } 10099 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10100 && !appSupportsRuntimePermissions) { 10101 // For legacy apps that need a permission review, every new 10102 // runtime permission is granted but it is pending a review. 10103 // We also need to review only platform defined runtime 10104 // permissions as these are the only ones the platform knows 10105 // how to disable the API to simulate revocation as legacy 10106 // apps don't expect to run with revoked permissions. 10107 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10108 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10109 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10110 // We changed the flags, hence have to write. 10111 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10112 changedRuntimePermissionUserIds, userId); 10113 } 10114 } 10115 if (permissionsState.grantRuntimePermission(bp, userId) 10116 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10117 // We changed the permission, hence have to write. 10118 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10119 changedRuntimePermissionUserIds, userId); 10120 } 10121 } 10122 // Propagate the permission flags. 10123 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10124 } 10125 } break; 10126 10127 case GRANT_UPGRADE: { 10128 // Grant runtime permissions for a previously held install permission. 10129 PermissionState permissionState = origPermissions 10130 .getInstallPermissionState(bp.name); 10131 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10132 10133 if (origPermissions.revokeInstallPermission(bp) 10134 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10135 // We will be transferring the permission flags, so clear them. 10136 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10137 PackageManager.MASK_PERMISSION_FLAGS, 0); 10138 changedInstallPermission = true; 10139 } 10140 10141 // If the permission is not to be promoted to runtime we ignore it and 10142 // also its other flags as they are not applicable to install permissions. 10143 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10144 for (int userId : currentUserIds) { 10145 if (permissionsState.grantRuntimePermission(bp, userId) != 10146 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10147 // Transfer the permission flags. 10148 permissionsState.updatePermissionFlags(bp, userId, 10149 flags, flags); 10150 // If we granted the permission, we have to write. 10151 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10152 changedRuntimePermissionUserIds, userId); 10153 } 10154 } 10155 } 10156 } break; 10157 10158 default: { 10159 if (packageOfInterest == null 10160 || packageOfInterest.equals(pkg.packageName)) { 10161 Slog.w(TAG, "Not granting permission " + perm 10162 + " to package " + pkg.packageName 10163 + " because it was previously installed without"); 10164 } 10165 } break; 10166 } 10167 } else { 10168 if (permissionsState.revokeInstallPermission(bp) != 10169 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10170 // Also drop the permission flags. 10171 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10172 PackageManager.MASK_PERMISSION_FLAGS, 0); 10173 changedInstallPermission = true; 10174 Slog.i(TAG, "Un-granting permission " + perm 10175 + " from package " + pkg.packageName 10176 + " (protectionLevel=" + bp.protectionLevel 10177 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10178 + ")"); 10179 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10180 // Don't print warning for app op permissions, since it is fine for them 10181 // not to be granted, there is a UI for the user to decide. 10182 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10183 Slog.w(TAG, "Not granting permission " + perm 10184 + " to package " + pkg.packageName 10185 + " (protectionLevel=" + bp.protectionLevel 10186 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10187 + ")"); 10188 } 10189 } 10190 } 10191 } 10192 10193 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10194 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10195 // This is the first that we have heard about this package, so the 10196 // permissions we have now selected are fixed until explicitly 10197 // changed. 10198 ps.installPermissionsFixed = true; 10199 } 10200 10201 // Persist the runtime permissions state for users with changes. If permissions 10202 // were revoked because no app in the shared user declares them we have to 10203 // write synchronously to avoid losing runtime permissions state. 10204 for (int userId : changedRuntimePermissionUserIds) { 10205 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10206 } 10207 10208 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10209 } 10210 10211 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10212 boolean allowed = false; 10213 final int NP = PackageParser.NEW_PERMISSIONS.length; 10214 for (int ip=0; ip<NP; ip++) { 10215 final PackageParser.NewPermissionInfo npi 10216 = PackageParser.NEW_PERMISSIONS[ip]; 10217 if (npi.name.equals(perm) 10218 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10219 allowed = true; 10220 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10221 + pkg.packageName); 10222 break; 10223 } 10224 } 10225 return allowed; 10226 } 10227 10228 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10229 BasePermission bp, PermissionsState origPermissions) { 10230 boolean allowed; 10231 allowed = (compareSignatures( 10232 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10233 == PackageManager.SIGNATURE_MATCH) 10234 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10235 == PackageManager.SIGNATURE_MATCH); 10236 if (!allowed && (bp.protectionLevel 10237 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10238 if (isSystemApp(pkg)) { 10239 // For updated system applications, a system permission 10240 // is granted only if it had been defined by the original application. 10241 if (pkg.isUpdatedSystemApp()) { 10242 final PackageSetting sysPs = mSettings 10243 .getDisabledSystemPkgLPr(pkg.packageName); 10244 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10245 // If the original was granted this permission, we take 10246 // that grant decision as read and propagate it to the 10247 // update. 10248 if (sysPs.isPrivileged()) { 10249 allowed = true; 10250 } 10251 } else { 10252 // The system apk may have been updated with an older 10253 // version of the one on the data partition, but which 10254 // granted a new system permission that it didn't have 10255 // before. In this case we do want to allow the app to 10256 // now get the new permission if the ancestral apk is 10257 // privileged to get it. 10258 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10259 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10260 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10261 allowed = true; 10262 break; 10263 } 10264 } 10265 } 10266 // Also if a privileged parent package on the system image or any of 10267 // its children requested a privileged permission, the updated child 10268 // packages can also get the permission. 10269 if (pkg.parentPackage != null) { 10270 final PackageSetting disabledSysParentPs = mSettings 10271 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10272 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10273 && disabledSysParentPs.isPrivileged()) { 10274 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10275 allowed = true; 10276 } else if (disabledSysParentPs.pkg.childPackages != null) { 10277 final int count = disabledSysParentPs.pkg.childPackages.size(); 10278 for (int i = 0; i < count; i++) { 10279 PackageParser.Package disabledSysChildPkg = 10280 disabledSysParentPs.pkg.childPackages.get(i); 10281 if (isPackageRequestingPermission(disabledSysChildPkg, 10282 perm)) { 10283 allowed = true; 10284 break; 10285 } 10286 } 10287 } 10288 } 10289 } 10290 } 10291 } else { 10292 allowed = isPrivilegedApp(pkg); 10293 } 10294 } 10295 } 10296 if (!allowed) { 10297 if (!allowed && (bp.protectionLevel 10298 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10299 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10300 // If this was a previously normal/dangerous permission that got moved 10301 // to a system permission as part of the runtime permission redesign, then 10302 // we still want to blindly grant it to old apps. 10303 allowed = true; 10304 } 10305 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10306 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10307 // If this permission is to be granted to the system installer and 10308 // this app is an installer, then it gets the permission. 10309 allowed = true; 10310 } 10311 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10312 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10313 // If this permission is to be granted to the system verifier and 10314 // this app is a verifier, then it gets the permission. 10315 allowed = true; 10316 } 10317 if (!allowed && (bp.protectionLevel 10318 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10319 && isSystemApp(pkg)) { 10320 // Any pre-installed system app is allowed to get this permission. 10321 allowed = true; 10322 } 10323 if (!allowed && (bp.protectionLevel 10324 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10325 // For development permissions, a development permission 10326 // is granted only if it was already granted. 10327 allowed = origPermissions.hasInstallPermission(perm); 10328 } 10329 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10330 && pkg.packageName.equals(mSetupWizardPackage)) { 10331 // If this permission is to be granted to the system setup wizard and 10332 // this app is a setup wizard, then it gets the permission. 10333 allowed = true; 10334 } 10335 } 10336 return allowed; 10337 } 10338 10339 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10340 final int permCount = pkg.requestedPermissions.size(); 10341 for (int j = 0; j < permCount; j++) { 10342 String requestedPermission = pkg.requestedPermissions.get(j); 10343 if (permission.equals(requestedPermission)) { 10344 return true; 10345 } 10346 } 10347 return false; 10348 } 10349 10350 final class ActivityIntentResolver 10351 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10352 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10353 boolean defaultOnly, int userId) { 10354 if (!sUserManager.exists(userId)) return null; 10355 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10356 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10357 } 10358 10359 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10360 int userId) { 10361 if (!sUserManager.exists(userId)) return null; 10362 mFlags = flags; 10363 return super.queryIntent(intent, resolvedType, 10364 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10365 } 10366 10367 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10368 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10369 if (!sUserManager.exists(userId)) return null; 10370 if (packageActivities == null) { 10371 return null; 10372 } 10373 mFlags = flags; 10374 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10375 final int N = packageActivities.size(); 10376 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10377 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10378 10379 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10380 for (int i = 0; i < N; ++i) { 10381 intentFilters = packageActivities.get(i).intents; 10382 if (intentFilters != null && intentFilters.size() > 0) { 10383 PackageParser.ActivityIntentInfo[] array = 10384 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10385 intentFilters.toArray(array); 10386 listCut.add(array); 10387 } 10388 } 10389 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10390 } 10391 10392 /** 10393 * Finds a privileged activity that matches the specified activity names. 10394 */ 10395 private PackageParser.Activity findMatchingActivity( 10396 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10397 for (PackageParser.Activity sysActivity : activityList) { 10398 if (sysActivity.info.name.equals(activityInfo.name)) { 10399 return sysActivity; 10400 } 10401 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10402 return sysActivity; 10403 } 10404 if (sysActivity.info.targetActivity != null) { 10405 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10406 return sysActivity; 10407 } 10408 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10409 return sysActivity; 10410 } 10411 } 10412 } 10413 return null; 10414 } 10415 10416 public class IterGenerator<E> { 10417 public Iterator<E> generate(ActivityIntentInfo info) { 10418 return null; 10419 } 10420 } 10421 10422 public class ActionIterGenerator extends IterGenerator<String> { 10423 @Override 10424 public Iterator<String> generate(ActivityIntentInfo info) { 10425 return info.actionsIterator(); 10426 } 10427 } 10428 10429 public class CategoriesIterGenerator extends IterGenerator<String> { 10430 @Override 10431 public Iterator<String> generate(ActivityIntentInfo info) { 10432 return info.categoriesIterator(); 10433 } 10434 } 10435 10436 public class SchemesIterGenerator extends IterGenerator<String> { 10437 @Override 10438 public Iterator<String> generate(ActivityIntentInfo info) { 10439 return info.schemesIterator(); 10440 } 10441 } 10442 10443 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10444 @Override 10445 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10446 return info.authoritiesIterator(); 10447 } 10448 } 10449 10450 /** 10451 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10452 * MODIFIED. Do not pass in a list that should not be changed. 10453 */ 10454 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10455 IterGenerator<T> generator, Iterator<T> searchIterator) { 10456 // loop through the set of actions; every one must be found in the intent filter 10457 while (searchIterator.hasNext()) { 10458 // we must have at least one filter in the list to consider a match 10459 if (intentList.size() == 0) { 10460 break; 10461 } 10462 10463 final T searchAction = searchIterator.next(); 10464 10465 // loop through the set of intent filters 10466 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10467 while (intentIter.hasNext()) { 10468 final ActivityIntentInfo intentInfo = intentIter.next(); 10469 boolean selectionFound = false; 10470 10471 // loop through the intent filter's selection criteria; at least one 10472 // of them must match the searched criteria 10473 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10474 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10475 final T intentSelection = intentSelectionIter.next(); 10476 if (intentSelection != null && intentSelection.equals(searchAction)) { 10477 selectionFound = true; 10478 break; 10479 } 10480 } 10481 10482 // the selection criteria wasn't found in this filter's set; this filter 10483 // is not a potential match 10484 if (!selectionFound) { 10485 intentIter.remove(); 10486 } 10487 } 10488 } 10489 } 10490 10491 private boolean isProtectedAction(ActivityIntentInfo filter) { 10492 final Iterator<String> actionsIter = filter.actionsIterator(); 10493 while (actionsIter != null && actionsIter.hasNext()) { 10494 final String filterAction = actionsIter.next(); 10495 if (PROTECTED_ACTIONS.contains(filterAction)) { 10496 return true; 10497 } 10498 } 10499 return false; 10500 } 10501 10502 /** 10503 * Adjusts the priority of the given intent filter according to policy. 10504 * <p> 10505 * <ul> 10506 * <li>The priority for non privileged applications is capped to '0'</li> 10507 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10508 * <li>The priority for unbundled updates to privileged applications is capped to the 10509 * priority defined on the system partition</li> 10510 * </ul> 10511 * <p> 10512 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10513 * allowed to obtain any priority on any action. 10514 */ 10515 private void adjustPriority( 10516 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10517 // nothing to do; priority is fine as-is 10518 if (intent.getPriority() <= 0) { 10519 return; 10520 } 10521 10522 final ActivityInfo activityInfo = intent.activity.info; 10523 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10524 10525 final boolean privilegedApp = 10526 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10527 if (!privilegedApp) { 10528 // non-privileged applications can never define a priority >0 10529 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10530 + " package: " + applicationInfo.packageName 10531 + " activity: " + intent.activity.className 10532 + " origPrio: " + intent.getPriority()); 10533 intent.setPriority(0); 10534 return; 10535 } 10536 10537 if (systemActivities == null) { 10538 // the system package is not disabled; we're parsing the system partition 10539 if (isProtectedAction(intent)) { 10540 if (mDeferProtectedFilters) { 10541 // We can't deal with these just yet. No component should ever obtain a 10542 // >0 priority for a protected actions, with ONE exception -- the setup 10543 // wizard. The setup wizard, however, cannot be known until we're able to 10544 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10545 // until all intent filters have been processed. Chicken, meet egg. 10546 // Let the filter temporarily have a high priority and rectify the 10547 // priorities after all system packages have been scanned. 10548 mProtectedFilters.add(intent); 10549 if (DEBUG_FILTERS) { 10550 Slog.i(TAG, "Protected action; save for later;" 10551 + " package: " + applicationInfo.packageName 10552 + " activity: " + intent.activity.className 10553 + " origPrio: " + intent.getPriority()); 10554 } 10555 return; 10556 } else { 10557 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10558 Slog.i(TAG, "No setup wizard;" 10559 + " All protected intents capped to priority 0"); 10560 } 10561 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10562 if (DEBUG_FILTERS) { 10563 Slog.i(TAG, "Found setup wizard;" 10564 + " allow priority " + intent.getPriority() + ";" 10565 + " package: " + intent.activity.info.packageName 10566 + " activity: " + intent.activity.className 10567 + " priority: " + intent.getPriority()); 10568 } 10569 // setup wizard gets whatever it wants 10570 return; 10571 } 10572 Slog.w(TAG, "Protected action; cap priority to 0;" 10573 + " package: " + intent.activity.info.packageName 10574 + " activity: " + intent.activity.className 10575 + " origPrio: " + intent.getPriority()); 10576 intent.setPriority(0); 10577 return; 10578 } 10579 } 10580 // privileged apps on the system image get whatever priority they request 10581 return; 10582 } 10583 10584 // privileged app unbundled update ... try to find the same activity 10585 final PackageParser.Activity foundActivity = 10586 findMatchingActivity(systemActivities, activityInfo); 10587 if (foundActivity == null) { 10588 // this is a new activity; it cannot obtain >0 priority 10589 if (DEBUG_FILTERS) { 10590 Slog.i(TAG, "New activity; cap priority to 0;" 10591 + " package: " + applicationInfo.packageName 10592 + " activity: " + intent.activity.className 10593 + " origPrio: " + intent.getPriority()); 10594 } 10595 intent.setPriority(0); 10596 return; 10597 } 10598 10599 // found activity, now check for filter equivalence 10600 10601 // a shallow copy is enough; we modify the list, not its contents 10602 final List<ActivityIntentInfo> intentListCopy = 10603 new ArrayList<>(foundActivity.intents); 10604 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10605 10606 // find matching action subsets 10607 final Iterator<String> actionsIterator = intent.actionsIterator(); 10608 if (actionsIterator != null) { 10609 getIntentListSubset( 10610 intentListCopy, new ActionIterGenerator(), actionsIterator); 10611 if (intentListCopy.size() == 0) { 10612 // no more intents to match; we're not equivalent 10613 if (DEBUG_FILTERS) { 10614 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10615 + " package: " + applicationInfo.packageName 10616 + " activity: " + intent.activity.className 10617 + " origPrio: " + intent.getPriority()); 10618 } 10619 intent.setPriority(0); 10620 return; 10621 } 10622 } 10623 10624 // find matching category subsets 10625 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10626 if (categoriesIterator != null) { 10627 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10628 categoriesIterator); 10629 if (intentListCopy.size() == 0) { 10630 // no more intents to match; we're not equivalent 10631 if (DEBUG_FILTERS) { 10632 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10633 + " package: " + applicationInfo.packageName 10634 + " activity: " + intent.activity.className 10635 + " origPrio: " + intent.getPriority()); 10636 } 10637 intent.setPriority(0); 10638 return; 10639 } 10640 } 10641 10642 // find matching schemes subsets 10643 final Iterator<String> schemesIterator = intent.schemesIterator(); 10644 if (schemesIterator != null) { 10645 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10646 schemesIterator); 10647 if (intentListCopy.size() == 0) { 10648 // no more intents to match; we're not equivalent 10649 if (DEBUG_FILTERS) { 10650 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10651 + " package: " + applicationInfo.packageName 10652 + " activity: " + intent.activity.className 10653 + " origPrio: " + intent.getPriority()); 10654 } 10655 intent.setPriority(0); 10656 return; 10657 } 10658 } 10659 10660 // find matching authorities subsets 10661 final Iterator<IntentFilter.AuthorityEntry> 10662 authoritiesIterator = intent.authoritiesIterator(); 10663 if (authoritiesIterator != null) { 10664 getIntentListSubset(intentListCopy, 10665 new AuthoritiesIterGenerator(), 10666 authoritiesIterator); 10667 if (intentListCopy.size() == 0) { 10668 // no more intents to match; we're not equivalent 10669 if (DEBUG_FILTERS) { 10670 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10671 + " package: " + applicationInfo.packageName 10672 + " activity: " + intent.activity.className 10673 + " origPrio: " + intent.getPriority()); 10674 } 10675 intent.setPriority(0); 10676 return; 10677 } 10678 } 10679 10680 // we found matching filter(s); app gets the max priority of all intents 10681 int cappedPriority = 0; 10682 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10683 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10684 } 10685 if (intent.getPriority() > cappedPriority) { 10686 if (DEBUG_FILTERS) { 10687 Slog.i(TAG, "Found matching filter(s);" 10688 + " cap priority to " + cappedPriority + ";" 10689 + " package: " + applicationInfo.packageName 10690 + " activity: " + intent.activity.className 10691 + " origPrio: " + intent.getPriority()); 10692 } 10693 intent.setPriority(cappedPriority); 10694 return; 10695 } 10696 // all this for nothing; the requested priority was <= what was on the system 10697 } 10698 10699 public final void addActivity(PackageParser.Activity a, String type) { 10700 mActivities.put(a.getComponentName(), a); 10701 if (DEBUG_SHOW_INFO) 10702 Log.v( 10703 TAG, " " + type + " " + 10704 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10705 if (DEBUG_SHOW_INFO) 10706 Log.v(TAG, " Class=" + a.info.name); 10707 final int NI = a.intents.size(); 10708 for (int j=0; j<NI; j++) { 10709 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10710 if ("activity".equals(type)) { 10711 final PackageSetting ps = 10712 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10713 final List<PackageParser.Activity> systemActivities = 10714 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10715 adjustPriority(systemActivities, intent); 10716 } 10717 if (DEBUG_SHOW_INFO) { 10718 Log.v(TAG, " IntentFilter:"); 10719 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10720 } 10721 if (!intent.debugCheck()) { 10722 Log.w(TAG, "==> For Activity " + a.info.name); 10723 } 10724 addFilter(intent); 10725 } 10726 } 10727 10728 public final void removeActivity(PackageParser.Activity a, String type) { 10729 mActivities.remove(a.getComponentName()); 10730 if (DEBUG_SHOW_INFO) { 10731 Log.v(TAG, " " + type + " " 10732 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10733 : a.info.name) + ":"); 10734 Log.v(TAG, " Class=" + a.info.name); 10735 } 10736 final int NI = a.intents.size(); 10737 for (int j=0; j<NI; j++) { 10738 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10739 if (DEBUG_SHOW_INFO) { 10740 Log.v(TAG, " IntentFilter:"); 10741 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10742 } 10743 removeFilter(intent); 10744 } 10745 } 10746 10747 @Override 10748 protected boolean allowFilterResult( 10749 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10750 ActivityInfo filterAi = filter.activity.info; 10751 for (int i=dest.size()-1; i>=0; i--) { 10752 ActivityInfo destAi = dest.get(i).activityInfo; 10753 if (destAi.name == filterAi.name 10754 && destAi.packageName == filterAi.packageName) { 10755 return false; 10756 } 10757 } 10758 return true; 10759 } 10760 10761 @Override 10762 protected ActivityIntentInfo[] newArray(int size) { 10763 return new ActivityIntentInfo[size]; 10764 } 10765 10766 @Override 10767 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10768 if (!sUserManager.exists(userId)) return true; 10769 PackageParser.Package p = filter.activity.owner; 10770 if (p != null) { 10771 PackageSetting ps = (PackageSetting)p.mExtras; 10772 if (ps != null) { 10773 // System apps are never considered stopped for purposes of 10774 // filtering, because there may be no way for the user to 10775 // actually re-launch them. 10776 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10777 && ps.getStopped(userId); 10778 } 10779 } 10780 return false; 10781 } 10782 10783 @Override 10784 protected boolean isPackageForFilter(String packageName, 10785 PackageParser.ActivityIntentInfo info) { 10786 return packageName.equals(info.activity.owner.packageName); 10787 } 10788 10789 @Override 10790 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10791 int match, int userId) { 10792 if (!sUserManager.exists(userId)) return null; 10793 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10794 return null; 10795 } 10796 final PackageParser.Activity activity = info.activity; 10797 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10798 if (ps == null) { 10799 return null; 10800 } 10801 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10802 ps.readUserState(userId), userId); 10803 if (ai == null) { 10804 return null; 10805 } 10806 final ResolveInfo res = new ResolveInfo(); 10807 res.activityInfo = ai; 10808 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10809 res.filter = info; 10810 } 10811 if (info != null) { 10812 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10813 } 10814 res.priority = info.getPriority(); 10815 res.preferredOrder = activity.owner.mPreferredOrder; 10816 //System.out.println("Result: " + res.activityInfo.className + 10817 // " = " + res.priority); 10818 res.match = match; 10819 res.isDefault = info.hasDefault; 10820 res.labelRes = info.labelRes; 10821 res.nonLocalizedLabel = info.nonLocalizedLabel; 10822 if (userNeedsBadging(userId)) { 10823 res.noResourceId = true; 10824 } else { 10825 res.icon = info.icon; 10826 } 10827 res.iconResourceId = info.icon; 10828 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10829 return res; 10830 } 10831 10832 @Override 10833 protected void sortResults(List<ResolveInfo> results) { 10834 Collections.sort(results, mResolvePrioritySorter); 10835 } 10836 10837 @Override 10838 protected void dumpFilter(PrintWriter out, String prefix, 10839 PackageParser.ActivityIntentInfo filter) { 10840 out.print(prefix); out.print( 10841 Integer.toHexString(System.identityHashCode(filter.activity))); 10842 out.print(' '); 10843 filter.activity.printComponentShortName(out); 10844 out.print(" filter "); 10845 out.println(Integer.toHexString(System.identityHashCode(filter))); 10846 } 10847 10848 @Override 10849 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10850 return filter.activity; 10851 } 10852 10853 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10854 PackageParser.Activity activity = (PackageParser.Activity)label; 10855 out.print(prefix); out.print( 10856 Integer.toHexString(System.identityHashCode(activity))); 10857 out.print(' '); 10858 activity.printComponentShortName(out); 10859 if (count > 1) { 10860 out.print(" ("); out.print(count); out.print(" filters)"); 10861 } 10862 out.println(); 10863 } 10864 10865 // Keys are String (activity class name), values are Activity. 10866 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10867 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10868 private int mFlags; 10869 } 10870 10871 private final class ServiceIntentResolver 10872 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10873 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10874 boolean defaultOnly, int userId) { 10875 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10876 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10877 } 10878 10879 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10880 int userId) { 10881 if (!sUserManager.exists(userId)) return null; 10882 mFlags = flags; 10883 return super.queryIntent(intent, resolvedType, 10884 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10885 } 10886 10887 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10888 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10889 if (!sUserManager.exists(userId)) return null; 10890 if (packageServices == null) { 10891 return null; 10892 } 10893 mFlags = flags; 10894 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10895 final int N = packageServices.size(); 10896 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10897 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10898 10899 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10900 for (int i = 0; i < N; ++i) { 10901 intentFilters = packageServices.get(i).intents; 10902 if (intentFilters != null && intentFilters.size() > 0) { 10903 PackageParser.ServiceIntentInfo[] array = 10904 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10905 intentFilters.toArray(array); 10906 listCut.add(array); 10907 } 10908 } 10909 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10910 } 10911 10912 public final void addService(PackageParser.Service s) { 10913 mServices.put(s.getComponentName(), s); 10914 if (DEBUG_SHOW_INFO) { 10915 Log.v(TAG, " " 10916 + (s.info.nonLocalizedLabel != null 10917 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10918 Log.v(TAG, " Class=" + s.info.name); 10919 } 10920 final int NI = s.intents.size(); 10921 int j; 10922 for (j=0; j<NI; j++) { 10923 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10924 if (DEBUG_SHOW_INFO) { 10925 Log.v(TAG, " IntentFilter:"); 10926 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10927 } 10928 if (!intent.debugCheck()) { 10929 Log.w(TAG, "==> For Service " + s.info.name); 10930 } 10931 addFilter(intent); 10932 } 10933 } 10934 10935 public final void removeService(PackageParser.Service s) { 10936 mServices.remove(s.getComponentName()); 10937 if (DEBUG_SHOW_INFO) { 10938 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10939 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10940 Log.v(TAG, " Class=" + s.info.name); 10941 } 10942 final int NI = s.intents.size(); 10943 int j; 10944 for (j=0; j<NI; j++) { 10945 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10946 if (DEBUG_SHOW_INFO) { 10947 Log.v(TAG, " IntentFilter:"); 10948 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10949 } 10950 removeFilter(intent); 10951 } 10952 } 10953 10954 @Override 10955 protected boolean allowFilterResult( 10956 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10957 ServiceInfo filterSi = filter.service.info; 10958 for (int i=dest.size()-1; i>=0; i--) { 10959 ServiceInfo destAi = dest.get(i).serviceInfo; 10960 if (destAi.name == filterSi.name 10961 && destAi.packageName == filterSi.packageName) { 10962 return false; 10963 } 10964 } 10965 return true; 10966 } 10967 10968 @Override 10969 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10970 return new PackageParser.ServiceIntentInfo[size]; 10971 } 10972 10973 @Override 10974 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10975 if (!sUserManager.exists(userId)) return true; 10976 PackageParser.Package p = filter.service.owner; 10977 if (p != null) { 10978 PackageSetting ps = (PackageSetting)p.mExtras; 10979 if (ps != null) { 10980 // System apps are never considered stopped for purposes of 10981 // filtering, because there may be no way for the user to 10982 // actually re-launch them. 10983 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10984 && ps.getStopped(userId); 10985 } 10986 } 10987 return false; 10988 } 10989 10990 @Override 10991 protected boolean isPackageForFilter(String packageName, 10992 PackageParser.ServiceIntentInfo info) { 10993 return packageName.equals(info.service.owner.packageName); 10994 } 10995 10996 @Override 10997 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10998 int match, int userId) { 10999 if (!sUserManager.exists(userId)) return null; 11000 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11001 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11002 return null; 11003 } 11004 final PackageParser.Service service = info.service; 11005 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11006 if (ps == null) { 11007 return null; 11008 } 11009 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11010 ps.readUserState(userId), userId); 11011 if (si == null) { 11012 return null; 11013 } 11014 final ResolveInfo res = new ResolveInfo(); 11015 res.serviceInfo = si; 11016 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11017 res.filter = filter; 11018 } 11019 res.priority = info.getPriority(); 11020 res.preferredOrder = service.owner.mPreferredOrder; 11021 res.match = match; 11022 res.isDefault = info.hasDefault; 11023 res.labelRes = info.labelRes; 11024 res.nonLocalizedLabel = info.nonLocalizedLabel; 11025 res.icon = info.icon; 11026 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11027 return res; 11028 } 11029 11030 @Override 11031 protected void sortResults(List<ResolveInfo> results) { 11032 Collections.sort(results, mResolvePrioritySorter); 11033 } 11034 11035 @Override 11036 protected void dumpFilter(PrintWriter out, String prefix, 11037 PackageParser.ServiceIntentInfo filter) { 11038 out.print(prefix); out.print( 11039 Integer.toHexString(System.identityHashCode(filter.service))); 11040 out.print(' '); 11041 filter.service.printComponentShortName(out); 11042 out.print(" filter "); 11043 out.println(Integer.toHexString(System.identityHashCode(filter))); 11044 } 11045 11046 @Override 11047 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11048 return filter.service; 11049 } 11050 11051 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11052 PackageParser.Service service = (PackageParser.Service)label; 11053 out.print(prefix); out.print( 11054 Integer.toHexString(System.identityHashCode(service))); 11055 out.print(' '); 11056 service.printComponentShortName(out); 11057 if (count > 1) { 11058 out.print(" ("); out.print(count); out.print(" filters)"); 11059 } 11060 out.println(); 11061 } 11062 11063// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11064// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11065// final List<ResolveInfo> retList = Lists.newArrayList(); 11066// while (i.hasNext()) { 11067// final ResolveInfo resolveInfo = (ResolveInfo) i; 11068// if (isEnabledLP(resolveInfo.serviceInfo)) { 11069// retList.add(resolveInfo); 11070// } 11071// } 11072// return retList; 11073// } 11074 11075 // Keys are String (activity class name), values are Activity. 11076 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11077 = new ArrayMap<ComponentName, PackageParser.Service>(); 11078 private int mFlags; 11079 }; 11080 11081 private final class ProviderIntentResolver 11082 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11083 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11084 boolean defaultOnly, int userId) { 11085 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11086 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11087 } 11088 11089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11090 int userId) { 11091 if (!sUserManager.exists(userId)) 11092 return null; 11093 mFlags = flags; 11094 return super.queryIntent(intent, resolvedType, 11095 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11096 } 11097 11098 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11099 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11100 if (!sUserManager.exists(userId)) 11101 return null; 11102 if (packageProviders == null) { 11103 return null; 11104 } 11105 mFlags = flags; 11106 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11107 final int N = packageProviders.size(); 11108 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11109 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11110 11111 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11112 for (int i = 0; i < N; ++i) { 11113 intentFilters = packageProviders.get(i).intents; 11114 if (intentFilters != null && intentFilters.size() > 0) { 11115 PackageParser.ProviderIntentInfo[] array = 11116 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11117 intentFilters.toArray(array); 11118 listCut.add(array); 11119 } 11120 } 11121 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11122 } 11123 11124 public final void addProvider(PackageParser.Provider p) { 11125 if (mProviders.containsKey(p.getComponentName())) { 11126 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11127 return; 11128 } 11129 11130 mProviders.put(p.getComponentName(), p); 11131 if (DEBUG_SHOW_INFO) { 11132 Log.v(TAG, " " 11133 + (p.info.nonLocalizedLabel != null 11134 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11135 Log.v(TAG, " Class=" + p.info.name); 11136 } 11137 final int NI = p.intents.size(); 11138 int j; 11139 for (j = 0; j < NI; j++) { 11140 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11141 if (DEBUG_SHOW_INFO) { 11142 Log.v(TAG, " IntentFilter:"); 11143 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11144 } 11145 if (!intent.debugCheck()) { 11146 Log.w(TAG, "==> For Provider " + p.info.name); 11147 } 11148 addFilter(intent); 11149 } 11150 } 11151 11152 public final void removeProvider(PackageParser.Provider p) { 11153 mProviders.remove(p.getComponentName()); 11154 if (DEBUG_SHOW_INFO) { 11155 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11156 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11157 Log.v(TAG, " Class=" + p.info.name); 11158 } 11159 final int NI = p.intents.size(); 11160 int j; 11161 for (j = 0; j < NI; j++) { 11162 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11163 if (DEBUG_SHOW_INFO) { 11164 Log.v(TAG, " IntentFilter:"); 11165 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11166 } 11167 removeFilter(intent); 11168 } 11169 } 11170 11171 @Override 11172 protected boolean allowFilterResult( 11173 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11174 ProviderInfo filterPi = filter.provider.info; 11175 for (int i = dest.size() - 1; i >= 0; i--) { 11176 ProviderInfo destPi = dest.get(i).providerInfo; 11177 if (destPi.name == filterPi.name 11178 && destPi.packageName == filterPi.packageName) { 11179 return false; 11180 } 11181 } 11182 return true; 11183 } 11184 11185 @Override 11186 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11187 return new PackageParser.ProviderIntentInfo[size]; 11188 } 11189 11190 @Override 11191 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11192 if (!sUserManager.exists(userId)) 11193 return true; 11194 PackageParser.Package p = filter.provider.owner; 11195 if (p != null) { 11196 PackageSetting ps = (PackageSetting) p.mExtras; 11197 if (ps != null) { 11198 // System apps are never considered stopped for purposes of 11199 // filtering, because there may be no way for the user to 11200 // actually re-launch them. 11201 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11202 && ps.getStopped(userId); 11203 } 11204 } 11205 return false; 11206 } 11207 11208 @Override 11209 protected boolean isPackageForFilter(String packageName, 11210 PackageParser.ProviderIntentInfo info) { 11211 return packageName.equals(info.provider.owner.packageName); 11212 } 11213 11214 @Override 11215 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11216 int match, int userId) { 11217 if (!sUserManager.exists(userId)) 11218 return null; 11219 final PackageParser.ProviderIntentInfo info = filter; 11220 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11221 return null; 11222 } 11223 final PackageParser.Provider provider = info.provider; 11224 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11225 if (ps == null) { 11226 return null; 11227 } 11228 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11229 ps.readUserState(userId), userId); 11230 if (pi == null) { 11231 return null; 11232 } 11233 final ResolveInfo res = new ResolveInfo(); 11234 res.providerInfo = pi; 11235 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11236 res.filter = filter; 11237 } 11238 res.priority = info.getPriority(); 11239 res.preferredOrder = provider.owner.mPreferredOrder; 11240 res.match = match; 11241 res.isDefault = info.hasDefault; 11242 res.labelRes = info.labelRes; 11243 res.nonLocalizedLabel = info.nonLocalizedLabel; 11244 res.icon = info.icon; 11245 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11246 return res; 11247 } 11248 11249 @Override 11250 protected void sortResults(List<ResolveInfo> results) { 11251 Collections.sort(results, mResolvePrioritySorter); 11252 } 11253 11254 @Override 11255 protected void dumpFilter(PrintWriter out, String prefix, 11256 PackageParser.ProviderIntentInfo filter) { 11257 out.print(prefix); 11258 out.print( 11259 Integer.toHexString(System.identityHashCode(filter.provider))); 11260 out.print(' '); 11261 filter.provider.printComponentShortName(out); 11262 out.print(" filter "); 11263 out.println(Integer.toHexString(System.identityHashCode(filter))); 11264 } 11265 11266 @Override 11267 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11268 return filter.provider; 11269 } 11270 11271 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11272 PackageParser.Provider provider = (PackageParser.Provider)label; 11273 out.print(prefix); out.print( 11274 Integer.toHexString(System.identityHashCode(provider))); 11275 out.print(' '); 11276 provider.printComponentShortName(out); 11277 if (count > 1) { 11278 out.print(" ("); out.print(count); out.print(" filters)"); 11279 } 11280 out.println(); 11281 } 11282 11283 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11284 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11285 private int mFlags; 11286 } 11287 11288 private static final class EphemeralIntentResolver 11289 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11290 @Override 11291 protected EphemeralResolveIntentInfo[] newArray(int size) { 11292 return new EphemeralResolveIntentInfo[size]; 11293 } 11294 11295 @Override 11296 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11297 return true; 11298 } 11299 11300 @Override 11301 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11302 int userId) { 11303 if (!sUserManager.exists(userId)) { 11304 return null; 11305 } 11306 return info.getEphemeralResolveInfo(); 11307 } 11308 } 11309 11310 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11311 new Comparator<ResolveInfo>() { 11312 public int compare(ResolveInfo r1, ResolveInfo r2) { 11313 int v1 = r1.priority; 11314 int v2 = r2.priority; 11315 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11316 if (v1 != v2) { 11317 return (v1 > v2) ? -1 : 1; 11318 } 11319 v1 = r1.preferredOrder; 11320 v2 = r2.preferredOrder; 11321 if (v1 != v2) { 11322 return (v1 > v2) ? -1 : 1; 11323 } 11324 if (r1.isDefault != r2.isDefault) { 11325 return r1.isDefault ? -1 : 1; 11326 } 11327 v1 = r1.match; 11328 v2 = r2.match; 11329 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11330 if (v1 != v2) { 11331 return (v1 > v2) ? -1 : 1; 11332 } 11333 if (r1.system != r2.system) { 11334 return r1.system ? -1 : 1; 11335 } 11336 if (r1.activityInfo != null) { 11337 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11338 } 11339 if (r1.serviceInfo != null) { 11340 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11341 } 11342 if (r1.providerInfo != null) { 11343 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11344 } 11345 return 0; 11346 } 11347 }; 11348 11349 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11350 new Comparator<ProviderInfo>() { 11351 public int compare(ProviderInfo p1, ProviderInfo p2) { 11352 final int v1 = p1.initOrder; 11353 final int v2 = p2.initOrder; 11354 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11355 } 11356 }; 11357 11358 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11359 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11360 final int[] userIds) { 11361 mHandler.post(new Runnable() { 11362 @Override 11363 public void run() { 11364 try { 11365 final IActivityManager am = ActivityManagerNative.getDefault(); 11366 if (am == null) return; 11367 final int[] resolvedUserIds; 11368 if (userIds == null) { 11369 resolvedUserIds = am.getRunningUserIds(); 11370 } else { 11371 resolvedUserIds = userIds; 11372 } 11373 for (int id : resolvedUserIds) { 11374 final Intent intent = new Intent(action, 11375 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11376 if (extras != null) { 11377 intent.putExtras(extras); 11378 } 11379 if (targetPkg != null) { 11380 intent.setPackage(targetPkg); 11381 } 11382 // Modify the UID when posting to other users 11383 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11384 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11385 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11386 intent.putExtra(Intent.EXTRA_UID, uid); 11387 } 11388 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11389 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11390 if (DEBUG_BROADCASTS) { 11391 RuntimeException here = new RuntimeException("here"); 11392 here.fillInStackTrace(); 11393 Slog.d(TAG, "Sending to user " + id + ": " 11394 + intent.toShortString(false, true, false, false) 11395 + " " + intent.getExtras(), here); 11396 } 11397 am.broadcastIntent(null, intent, null, finishedReceiver, 11398 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11399 null, finishedReceiver != null, false, id); 11400 } 11401 } catch (RemoteException ex) { 11402 } 11403 } 11404 }); 11405 } 11406 11407 /** 11408 * Check if the external storage media is available. This is true if there 11409 * is a mounted external storage medium or if the external storage is 11410 * emulated. 11411 */ 11412 private boolean isExternalMediaAvailable() { 11413 return mMediaMounted || Environment.isExternalStorageEmulated(); 11414 } 11415 11416 @Override 11417 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11418 // writer 11419 synchronized (mPackages) { 11420 if (!isExternalMediaAvailable()) { 11421 // If the external storage is no longer mounted at this point, 11422 // the caller may not have been able to delete all of this 11423 // packages files and can not delete any more. Bail. 11424 return null; 11425 } 11426 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11427 if (lastPackage != null) { 11428 pkgs.remove(lastPackage); 11429 } 11430 if (pkgs.size() > 0) { 11431 return pkgs.get(0); 11432 } 11433 } 11434 return null; 11435 } 11436 11437 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11438 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11439 userId, andCode ? 1 : 0, packageName); 11440 if (mSystemReady) { 11441 msg.sendToTarget(); 11442 } else { 11443 if (mPostSystemReadyMessages == null) { 11444 mPostSystemReadyMessages = new ArrayList<>(); 11445 } 11446 mPostSystemReadyMessages.add(msg); 11447 } 11448 } 11449 11450 void startCleaningPackages() { 11451 // reader 11452 if (!isExternalMediaAvailable()) { 11453 return; 11454 } 11455 synchronized (mPackages) { 11456 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11457 return; 11458 } 11459 } 11460 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11461 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11462 IActivityManager am = ActivityManagerNative.getDefault(); 11463 if (am != null) { 11464 try { 11465 am.startService(null, intent, null, mContext.getOpPackageName(), 11466 UserHandle.USER_SYSTEM); 11467 } catch (RemoteException e) { 11468 } 11469 } 11470 } 11471 11472 @Override 11473 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11474 int installFlags, String installerPackageName, int userId) { 11475 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11476 11477 final int callingUid = Binder.getCallingUid(); 11478 enforceCrossUserPermission(callingUid, userId, 11479 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11480 11481 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11482 try { 11483 if (observer != null) { 11484 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11485 } 11486 } catch (RemoteException re) { 11487 } 11488 return; 11489 } 11490 11491 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11492 installFlags |= PackageManager.INSTALL_FROM_ADB; 11493 11494 } else { 11495 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11496 // about installerPackageName. 11497 11498 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11499 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11500 } 11501 11502 UserHandle user; 11503 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11504 user = UserHandle.ALL; 11505 } else { 11506 user = new UserHandle(userId); 11507 } 11508 11509 // Only system components can circumvent runtime permissions when installing. 11510 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11511 && mContext.checkCallingOrSelfPermission(Manifest.permission 11512 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11513 throw new SecurityException("You need the " 11514 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11515 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11516 } 11517 11518 final File originFile = new File(originPath); 11519 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11520 11521 final Message msg = mHandler.obtainMessage(INIT_COPY); 11522 final VerificationInfo verificationInfo = new VerificationInfo( 11523 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11524 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11525 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11526 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11527 null /*certificates*/); 11528 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11529 msg.obj = params; 11530 11531 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11532 System.identityHashCode(msg.obj)); 11533 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11534 System.identityHashCode(msg.obj)); 11535 11536 mHandler.sendMessage(msg); 11537 } 11538 11539 void installStage(String packageName, File stagedDir, String stagedCid, 11540 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11541 String installerPackageName, int installerUid, UserHandle user, 11542 Certificate[][] certificates) { 11543 if (DEBUG_EPHEMERAL) { 11544 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11545 Slog.d(TAG, "Ephemeral install of " + packageName); 11546 } 11547 } 11548 final VerificationInfo verificationInfo = new VerificationInfo( 11549 sessionParams.originatingUri, sessionParams.referrerUri, 11550 sessionParams.originatingUid, installerUid); 11551 11552 final OriginInfo origin; 11553 if (stagedDir != null) { 11554 origin = OriginInfo.fromStagedFile(stagedDir); 11555 } else { 11556 origin = OriginInfo.fromStagedContainer(stagedCid); 11557 } 11558 11559 final Message msg = mHandler.obtainMessage(INIT_COPY); 11560 final InstallParams params = new InstallParams(origin, null, observer, 11561 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11562 verificationInfo, user, sessionParams.abiOverride, 11563 sessionParams.grantedRuntimePermissions, certificates); 11564 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11565 msg.obj = params; 11566 11567 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11568 System.identityHashCode(msg.obj)); 11569 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11570 System.identityHashCode(msg.obj)); 11571 11572 mHandler.sendMessage(msg); 11573 } 11574 11575 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11576 int userId) { 11577 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11578 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11579 } 11580 11581 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11582 int appId, int userId) { 11583 Bundle extras = new Bundle(1); 11584 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11585 11586 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11587 packageName, extras, 0, null, null, new int[] {userId}); 11588 try { 11589 IActivityManager am = ActivityManagerNative.getDefault(); 11590 if (isSystem && am.isUserRunning(userId, 0)) { 11591 // The just-installed/enabled app is bundled on the system, so presumed 11592 // to be able to run automatically without needing an explicit launch. 11593 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11594 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11595 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11596 .setPackage(packageName); 11597 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11598 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11599 } 11600 } catch (RemoteException e) { 11601 // shouldn't happen 11602 Slog.w(TAG, "Unable to bootstrap installed package", e); 11603 } 11604 } 11605 11606 @Override 11607 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11608 int userId) { 11609 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11610 PackageSetting pkgSetting; 11611 final int uid = Binder.getCallingUid(); 11612 enforceCrossUserPermission(uid, userId, 11613 true /* requireFullPermission */, true /* checkShell */, 11614 "setApplicationHiddenSetting for user " + userId); 11615 11616 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11617 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11618 return false; 11619 } 11620 11621 long callingId = Binder.clearCallingIdentity(); 11622 try { 11623 boolean sendAdded = false; 11624 boolean sendRemoved = false; 11625 // writer 11626 synchronized (mPackages) { 11627 pkgSetting = mSettings.mPackages.get(packageName); 11628 if (pkgSetting == null) { 11629 return false; 11630 } 11631 if (pkgSetting.getHidden(userId) != hidden) { 11632 pkgSetting.setHidden(hidden, userId); 11633 mSettings.writePackageRestrictionsLPr(userId); 11634 if (hidden) { 11635 sendRemoved = true; 11636 } else { 11637 sendAdded = true; 11638 } 11639 } 11640 } 11641 if (sendAdded) { 11642 sendPackageAddedForUser(packageName, pkgSetting, userId); 11643 return true; 11644 } 11645 if (sendRemoved) { 11646 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11647 "hiding pkg"); 11648 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11649 return true; 11650 } 11651 } finally { 11652 Binder.restoreCallingIdentity(callingId); 11653 } 11654 return false; 11655 } 11656 11657 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11658 int userId) { 11659 final PackageRemovedInfo info = new PackageRemovedInfo(); 11660 info.removedPackage = packageName; 11661 info.removedUsers = new int[] {userId}; 11662 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11663 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11664 } 11665 11666 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11667 if (pkgList.length > 0) { 11668 Bundle extras = new Bundle(1); 11669 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11670 11671 sendPackageBroadcast( 11672 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11673 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11674 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11675 new int[] {userId}); 11676 } 11677 } 11678 11679 /** 11680 * Returns true if application is not found or there was an error. Otherwise it returns 11681 * the hidden state of the package for the given user. 11682 */ 11683 @Override 11684 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11685 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11686 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11687 true /* requireFullPermission */, false /* checkShell */, 11688 "getApplicationHidden for user " + userId); 11689 PackageSetting pkgSetting; 11690 long callingId = Binder.clearCallingIdentity(); 11691 try { 11692 // writer 11693 synchronized (mPackages) { 11694 pkgSetting = mSettings.mPackages.get(packageName); 11695 if (pkgSetting == null) { 11696 return true; 11697 } 11698 return pkgSetting.getHidden(userId); 11699 } 11700 } finally { 11701 Binder.restoreCallingIdentity(callingId); 11702 } 11703 } 11704 11705 /** 11706 * @hide 11707 */ 11708 @Override 11709 public int installExistingPackageAsUser(String packageName, int userId) { 11710 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11711 null); 11712 PackageSetting pkgSetting; 11713 final int uid = Binder.getCallingUid(); 11714 enforceCrossUserPermission(uid, userId, 11715 true /* requireFullPermission */, true /* checkShell */, 11716 "installExistingPackage for user " + userId); 11717 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11718 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11719 } 11720 11721 long callingId = Binder.clearCallingIdentity(); 11722 try { 11723 boolean installed = false; 11724 11725 // writer 11726 synchronized (mPackages) { 11727 pkgSetting = mSettings.mPackages.get(packageName); 11728 if (pkgSetting == null) { 11729 return PackageManager.INSTALL_FAILED_INVALID_URI; 11730 } 11731 if (!pkgSetting.getInstalled(userId)) { 11732 pkgSetting.setInstalled(true, userId); 11733 pkgSetting.setHidden(false, userId); 11734 mSettings.writePackageRestrictionsLPr(userId); 11735 installed = true; 11736 } 11737 } 11738 11739 if (installed) { 11740 if (pkgSetting.pkg != null) { 11741 synchronized (mInstallLock) { 11742 // We don't need to freeze for a brand new install 11743 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11744 } 11745 } 11746 sendPackageAddedForUser(packageName, pkgSetting, userId); 11747 } 11748 } finally { 11749 Binder.restoreCallingIdentity(callingId); 11750 } 11751 11752 return PackageManager.INSTALL_SUCCEEDED; 11753 } 11754 11755 boolean isUserRestricted(int userId, String restrictionKey) { 11756 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11757 if (restrictions.getBoolean(restrictionKey, false)) { 11758 Log.w(TAG, "User is restricted: " + restrictionKey); 11759 return true; 11760 } 11761 return false; 11762 } 11763 11764 @Override 11765 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11766 int userId) { 11767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11768 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11769 true /* requireFullPermission */, true /* checkShell */, 11770 "setPackagesSuspended for user " + userId); 11771 11772 if (ArrayUtils.isEmpty(packageNames)) { 11773 return packageNames; 11774 } 11775 11776 // List of package names for whom the suspended state has changed. 11777 List<String> changedPackages = new ArrayList<>(packageNames.length); 11778 // List of package names for whom the suspended state is not set as requested in this 11779 // method. 11780 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11781 long callingId = Binder.clearCallingIdentity(); 11782 try { 11783 for (int i = 0; i < packageNames.length; i++) { 11784 String packageName = packageNames[i]; 11785 boolean changed = false; 11786 final int appId; 11787 synchronized (mPackages) { 11788 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11789 if (pkgSetting == null) { 11790 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11791 + "\". Skipping suspending/un-suspending."); 11792 unactionedPackages.add(packageName); 11793 continue; 11794 } 11795 appId = pkgSetting.appId; 11796 if (pkgSetting.getSuspended(userId) != suspended) { 11797 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11798 unactionedPackages.add(packageName); 11799 continue; 11800 } 11801 pkgSetting.setSuspended(suspended, userId); 11802 mSettings.writePackageRestrictionsLPr(userId); 11803 changed = true; 11804 changedPackages.add(packageName); 11805 } 11806 } 11807 11808 if (changed && suspended) { 11809 killApplication(packageName, UserHandle.getUid(userId, appId), 11810 "suspending package"); 11811 } 11812 } 11813 } finally { 11814 Binder.restoreCallingIdentity(callingId); 11815 } 11816 11817 if (!changedPackages.isEmpty()) { 11818 sendPackagesSuspendedForUser(changedPackages.toArray( 11819 new String[changedPackages.size()]), userId, suspended); 11820 } 11821 11822 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11823 } 11824 11825 @Override 11826 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11827 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11828 true /* requireFullPermission */, false /* checkShell */, 11829 "isPackageSuspendedForUser for user " + userId); 11830 synchronized (mPackages) { 11831 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11832 if (pkgSetting == null) { 11833 throw new IllegalArgumentException("Unknown target package: " + packageName); 11834 } 11835 return pkgSetting.getSuspended(userId); 11836 } 11837 } 11838 11839 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11840 if (isPackageDeviceAdmin(packageName, userId)) { 11841 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11842 + "\": has an active device admin"); 11843 return false; 11844 } 11845 11846 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11847 if (packageName.equals(activeLauncherPackageName)) { 11848 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11849 + "\": contains the active launcher"); 11850 return false; 11851 } 11852 11853 if (packageName.equals(mRequiredInstallerPackage)) { 11854 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11855 + "\": required for package installation"); 11856 return false; 11857 } 11858 11859 if (packageName.equals(mRequiredVerifierPackage)) { 11860 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11861 + "\": required for package verification"); 11862 return false; 11863 } 11864 11865 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11866 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11867 + "\": is the default dialer"); 11868 return false; 11869 } 11870 11871 return true; 11872 } 11873 11874 private String getActiveLauncherPackageName(int userId) { 11875 Intent intent = new Intent(Intent.ACTION_MAIN); 11876 intent.addCategory(Intent.CATEGORY_HOME); 11877 ResolveInfo resolveInfo = resolveIntent( 11878 intent, 11879 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11880 PackageManager.MATCH_DEFAULT_ONLY, 11881 userId); 11882 11883 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11884 } 11885 11886 private String getDefaultDialerPackageName(int userId) { 11887 synchronized (mPackages) { 11888 return mSettings.getDefaultDialerPackageNameLPw(userId); 11889 } 11890 } 11891 11892 @Override 11893 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11894 mContext.enforceCallingOrSelfPermission( 11895 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11896 "Only package verification agents can verify applications"); 11897 11898 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11899 final PackageVerificationResponse response = new PackageVerificationResponse( 11900 verificationCode, Binder.getCallingUid()); 11901 msg.arg1 = id; 11902 msg.obj = response; 11903 mHandler.sendMessage(msg); 11904 } 11905 11906 @Override 11907 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11908 long millisecondsToDelay) { 11909 mContext.enforceCallingOrSelfPermission( 11910 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11911 "Only package verification agents can extend verification timeouts"); 11912 11913 final PackageVerificationState state = mPendingVerification.get(id); 11914 final PackageVerificationResponse response = new PackageVerificationResponse( 11915 verificationCodeAtTimeout, Binder.getCallingUid()); 11916 11917 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11918 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11919 } 11920 if (millisecondsToDelay < 0) { 11921 millisecondsToDelay = 0; 11922 } 11923 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11924 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11925 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11926 } 11927 11928 if ((state != null) && !state.timeoutExtended()) { 11929 state.extendTimeout(); 11930 11931 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11932 msg.arg1 = id; 11933 msg.obj = response; 11934 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11935 } 11936 } 11937 11938 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11939 int verificationCode, UserHandle user) { 11940 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11941 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11942 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11943 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11944 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11945 11946 mContext.sendBroadcastAsUser(intent, user, 11947 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11948 } 11949 11950 private ComponentName matchComponentForVerifier(String packageName, 11951 List<ResolveInfo> receivers) { 11952 ActivityInfo targetReceiver = null; 11953 11954 final int NR = receivers.size(); 11955 for (int i = 0; i < NR; i++) { 11956 final ResolveInfo info = receivers.get(i); 11957 if (info.activityInfo == null) { 11958 continue; 11959 } 11960 11961 if (packageName.equals(info.activityInfo.packageName)) { 11962 targetReceiver = info.activityInfo; 11963 break; 11964 } 11965 } 11966 11967 if (targetReceiver == null) { 11968 return null; 11969 } 11970 11971 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11972 } 11973 11974 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11975 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11976 if (pkgInfo.verifiers.length == 0) { 11977 return null; 11978 } 11979 11980 final int N = pkgInfo.verifiers.length; 11981 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11982 for (int i = 0; i < N; i++) { 11983 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11984 11985 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11986 receivers); 11987 if (comp == null) { 11988 continue; 11989 } 11990 11991 final int verifierUid = getUidForVerifier(verifierInfo); 11992 if (verifierUid == -1) { 11993 continue; 11994 } 11995 11996 if (DEBUG_VERIFY) { 11997 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11998 + " with the correct signature"); 11999 } 12000 sufficientVerifiers.add(comp); 12001 verificationState.addSufficientVerifier(verifierUid); 12002 } 12003 12004 return sufficientVerifiers; 12005 } 12006 12007 private int getUidForVerifier(VerifierInfo verifierInfo) { 12008 synchronized (mPackages) { 12009 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12010 if (pkg == null) { 12011 return -1; 12012 } else if (pkg.mSignatures.length != 1) { 12013 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12014 + " has more than one signature; ignoring"); 12015 return -1; 12016 } 12017 12018 /* 12019 * If the public key of the package's signature does not match 12020 * our expected public key, then this is a different package and 12021 * we should skip. 12022 */ 12023 12024 final byte[] expectedPublicKey; 12025 try { 12026 final Signature verifierSig = pkg.mSignatures[0]; 12027 final PublicKey publicKey = verifierSig.getPublicKey(); 12028 expectedPublicKey = publicKey.getEncoded(); 12029 } catch (CertificateException e) { 12030 return -1; 12031 } 12032 12033 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12034 12035 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12036 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12037 + " does not have the expected public key; ignoring"); 12038 return -1; 12039 } 12040 12041 return pkg.applicationInfo.uid; 12042 } 12043 } 12044 12045 @Override 12046 public void finishPackageInstall(int token, boolean didLaunch) { 12047 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12048 12049 if (DEBUG_INSTALL) { 12050 Slog.v(TAG, "BM finishing package install for " + token); 12051 } 12052 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12053 12054 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12055 mHandler.sendMessage(msg); 12056 } 12057 12058 /** 12059 * Get the verification agent timeout. 12060 * 12061 * @return verification timeout in milliseconds 12062 */ 12063 private long getVerificationTimeout() { 12064 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12065 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12066 DEFAULT_VERIFICATION_TIMEOUT); 12067 } 12068 12069 /** 12070 * Get the default verification agent response code. 12071 * 12072 * @return default verification response code 12073 */ 12074 private int getDefaultVerificationResponse() { 12075 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12076 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12077 DEFAULT_VERIFICATION_RESPONSE); 12078 } 12079 12080 /** 12081 * Check whether or not package verification has been enabled. 12082 * 12083 * @return true if verification should be performed 12084 */ 12085 private boolean isVerificationEnabled(int userId, int installFlags) { 12086 if (!DEFAULT_VERIFY_ENABLE) { 12087 return false; 12088 } 12089 // Ephemeral apps don't get the full verification treatment 12090 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12091 if (DEBUG_EPHEMERAL) { 12092 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12093 } 12094 return false; 12095 } 12096 12097 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12098 12099 // Check if installing from ADB 12100 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12101 // Do not run verification in a test harness environment 12102 if (ActivityManager.isRunningInTestHarness()) { 12103 return false; 12104 } 12105 if (ensureVerifyAppsEnabled) { 12106 return true; 12107 } 12108 // Check if the developer does not want package verification for ADB installs 12109 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12110 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12111 return false; 12112 } 12113 } 12114 12115 if (ensureVerifyAppsEnabled) { 12116 return true; 12117 } 12118 12119 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12120 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12121 } 12122 12123 @Override 12124 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12125 throws RemoteException { 12126 mContext.enforceCallingOrSelfPermission( 12127 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12128 "Only intentfilter verification agents can verify applications"); 12129 12130 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12131 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12132 Binder.getCallingUid(), verificationCode, failedDomains); 12133 msg.arg1 = id; 12134 msg.obj = response; 12135 mHandler.sendMessage(msg); 12136 } 12137 12138 @Override 12139 public int getIntentVerificationStatus(String packageName, int userId) { 12140 synchronized (mPackages) { 12141 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12142 } 12143 } 12144 12145 @Override 12146 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12147 mContext.enforceCallingOrSelfPermission( 12148 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12149 12150 boolean result = false; 12151 synchronized (mPackages) { 12152 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12153 } 12154 if (result) { 12155 scheduleWritePackageRestrictionsLocked(userId); 12156 } 12157 return result; 12158 } 12159 12160 @Override 12161 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12162 String packageName) { 12163 synchronized (mPackages) { 12164 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12165 } 12166 } 12167 12168 @Override 12169 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12170 if (TextUtils.isEmpty(packageName)) { 12171 return ParceledListSlice.emptyList(); 12172 } 12173 synchronized (mPackages) { 12174 PackageParser.Package pkg = mPackages.get(packageName); 12175 if (pkg == null || pkg.activities == null) { 12176 return ParceledListSlice.emptyList(); 12177 } 12178 final int count = pkg.activities.size(); 12179 ArrayList<IntentFilter> result = new ArrayList<>(); 12180 for (int n=0; n<count; n++) { 12181 PackageParser.Activity activity = pkg.activities.get(n); 12182 if (activity.intents != null && activity.intents.size() > 0) { 12183 result.addAll(activity.intents); 12184 } 12185 } 12186 return new ParceledListSlice<>(result); 12187 } 12188 } 12189 12190 @Override 12191 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12192 mContext.enforceCallingOrSelfPermission( 12193 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12194 12195 synchronized (mPackages) { 12196 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12197 if (packageName != null) { 12198 result |= updateIntentVerificationStatus(packageName, 12199 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12200 userId); 12201 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12202 packageName, userId); 12203 } 12204 return result; 12205 } 12206 } 12207 12208 @Override 12209 public String getDefaultBrowserPackageName(int userId) { 12210 synchronized (mPackages) { 12211 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12212 } 12213 } 12214 12215 /** 12216 * Get the "allow unknown sources" setting. 12217 * 12218 * @return the current "allow unknown sources" setting 12219 */ 12220 private int getUnknownSourcesSettings() { 12221 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12222 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12223 -1); 12224 } 12225 12226 @Override 12227 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12228 final int uid = Binder.getCallingUid(); 12229 // writer 12230 synchronized (mPackages) { 12231 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12232 if (targetPackageSetting == null) { 12233 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12234 } 12235 12236 PackageSetting installerPackageSetting; 12237 if (installerPackageName != null) { 12238 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12239 if (installerPackageSetting == null) { 12240 throw new IllegalArgumentException("Unknown installer package: " 12241 + installerPackageName); 12242 } 12243 } else { 12244 installerPackageSetting = null; 12245 } 12246 12247 Signature[] callerSignature; 12248 Object obj = mSettings.getUserIdLPr(uid); 12249 if (obj != null) { 12250 if (obj instanceof SharedUserSetting) { 12251 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12252 } else if (obj instanceof PackageSetting) { 12253 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12254 } else { 12255 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12256 } 12257 } else { 12258 throw new SecurityException("Unknown calling UID: " + uid); 12259 } 12260 12261 // Verify: can't set installerPackageName to a package that is 12262 // not signed with the same cert as the caller. 12263 if (installerPackageSetting != null) { 12264 if (compareSignatures(callerSignature, 12265 installerPackageSetting.signatures.mSignatures) 12266 != PackageManager.SIGNATURE_MATCH) { 12267 throw new SecurityException( 12268 "Caller does not have same cert as new installer package " 12269 + installerPackageName); 12270 } 12271 } 12272 12273 // Verify: if target already has an installer package, it must 12274 // be signed with the same cert as the caller. 12275 if (targetPackageSetting.installerPackageName != null) { 12276 PackageSetting setting = mSettings.mPackages.get( 12277 targetPackageSetting.installerPackageName); 12278 // If the currently set package isn't valid, then it's always 12279 // okay to change it. 12280 if (setting != null) { 12281 if (compareSignatures(callerSignature, 12282 setting.signatures.mSignatures) 12283 != PackageManager.SIGNATURE_MATCH) { 12284 throw new SecurityException( 12285 "Caller does not have same cert as old installer package " 12286 + targetPackageSetting.installerPackageName); 12287 } 12288 } 12289 } 12290 12291 // Okay! 12292 targetPackageSetting.installerPackageName = installerPackageName; 12293 if (installerPackageName != null) { 12294 mSettings.mInstallerPackages.add(installerPackageName); 12295 } 12296 scheduleWriteSettingsLocked(); 12297 } 12298 } 12299 12300 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12301 // Queue up an async operation since the package installation may take a little while. 12302 mHandler.post(new Runnable() { 12303 public void run() { 12304 mHandler.removeCallbacks(this); 12305 // Result object to be returned 12306 PackageInstalledInfo res = new PackageInstalledInfo(); 12307 res.setReturnCode(currentStatus); 12308 res.uid = -1; 12309 res.pkg = null; 12310 res.removedInfo = null; 12311 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12312 args.doPreInstall(res.returnCode); 12313 synchronized (mInstallLock) { 12314 installPackageTracedLI(args, res); 12315 } 12316 args.doPostInstall(res.returnCode, res.uid); 12317 } 12318 12319 // A restore should be performed at this point if (a) the install 12320 // succeeded, (b) the operation is not an update, and (c) the new 12321 // package has not opted out of backup participation. 12322 final boolean update = res.removedInfo != null 12323 && res.removedInfo.removedPackage != null; 12324 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12325 boolean doRestore = !update 12326 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12327 12328 // Set up the post-install work request bookkeeping. This will be used 12329 // and cleaned up by the post-install event handling regardless of whether 12330 // there's a restore pass performed. Token values are >= 1. 12331 int token; 12332 if (mNextInstallToken < 0) mNextInstallToken = 1; 12333 token = mNextInstallToken++; 12334 12335 PostInstallData data = new PostInstallData(args, res); 12336 mRunningInstalls.put(token, data); 12337 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12338 12339 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12340 // Pass responsibility to the Backup Manager. It will perform a 12341 // restore if appropriate, then pass responsibility back to the 12342 // Package Manager to run the post-install observer callbacks 12343 // and broadcasts. 12344 IBackupManager bm = IBackupManager.Stub.asInterface( 12345 ServiceManager.getService(Context.BACKUP_SERVICE)); 12346 if (bm != null) { 12347 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12348 + " to BM for possible restore"); 12349 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12350 try { 12351 // TODO: http://b/22388012 12352 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12353 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12354 } else { 12355 doRestore = false; 12356 } 12357 } catch (RemoteException e) { 12358 // can't happen; the backup manager is local 12359 } catch (Exception e) { 12360 Slog.e(TAG, "Exception trying to enqueue restore", e); 12361 doRestore = false; 12362 } 12363 } else { 12364 Slog.e(TAG, "Backup Manager not found!"); 12365 doRestore = false; 12366 } 12367 } 12368 12369 if (!doRestore) { 12370 // No restore possible, or the Backup Manager was mysteriously not 12371 // available -- just fire the post-install work request directly. 12372 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12373 12374 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12375 12376 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12377 mHandler.sendMessage(msg); 12378 } 12379 } 12380 }); 12381 } 12382 12383 /** 12384 * Callback from PackageSettings whenever an app is first transitioned out of the 12385 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12386 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12387 * here whether the app is the target of an ongoing install, and only send the 12388 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12389 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12390 * handling. 12391 */ 12392 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12393 // Serialize this with the rest of the install-process message chain. In the 12394 // restore-at-install case, this Runnable will necessarily run before the 12395 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12396 // are coherent. In the non-restore case, the app has already completed install 12397 // and been launched through some other means, so it is not in a problematic 12398 // state for observers to see the FIRST_LAUNCH signal. 12399 mHandler.post(new Runnable() { 12400 @Override 12401 public void run() { 12402 for (int i = 0; i < mRunningInstalls.size(); i++) { 12403 final PostInstallData data = mRunningInstalls.valueAt(i); 12404 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12405 // right package; but is it for the right user? 12406 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12407 if (userId == data.res.newUsers[uIndex]) { 12408 if (DEBUG_BACKUP) { 12409 Slog.i(TAG, "Package " + pkgName 12410 + " being restored so deferring FIRST_LAUNCH"); 12411 } 12412 return; 12413 } 12414 } 12415 } 12416 } 12417 // didn't find it, so not being restored 12418 if (DEBUG_BACKUP) { 12419 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12420 } 12421 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12422 } 12423 }); 12424 } 12425 12426 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12427 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12428 installerPkg, null, userIds); 12429 } 12430 12431 private abstract class HandlerParams { 12432 private static final int MAX_RETRIES = 4; 12433 12434 /** 12435 * Number of times startCopy() has been attempted and had a non-fatal 12436 * error. 12437 */ 12438 private int mRetries = 0; 12439 12440 /** User handle for the user requesting the information or installation. */ 12441 private final UserHandle mUser; 12442 String traceMethod; 12443 int traceCookie; 12444 12445 HandlerParams(UserHandle user) { 12446 mUser = user; 12447 } 12448 12449 UserHandle getUser() { 12450 return mUser; 12451 } 12452 12453 HandlerParams setTraceMethod(String traceMethod) { 12454 this.traceMethod = traceMethod; 12455 return this; 12456 } 12457 12458 HandlerParams setTraceCookie(int traceCookie) { 12459 this.traceCookie = traceCookie; 12460 return this; 12461 } 12462 12463 final boolean startCopy() { 12464 boolean res; 12465 try { 12466 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12467 12468 if (++mRetries > MAX_RETRIES) { 12469 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12470 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12471 handleServiceError(); 12472 return false; 12473 } else { 12474 handleStartCopy(); 12475 res = true; 12476 } 12477 } catch (RemoteException e) { 12478 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12479 mHandler.sendEmptyMessage(MCS_RECONNECT); 12480 res = false; 12481 } 12482 handleReturnCode(); 12483 return res; 12484 } 12485 12486 final void serviceError() { 12487 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12488 handleServiceError(); 12489 handleReturnCode(); 12490 } 12491 12492 abstract void handleStartCopy() throws RemoteException; 12493 abstract void handleServiceError(); 12494 abstract void handleReturnCode(); 12495 } 12496 12497 class MeasureParams extends HandlerParams { 12498 private final PackageStats mStats; 12499 private boolean mSuccess; 12500 12501 private final IPackageStatsObserver mObserver; 12502 12503 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12504 super(new UserHandle(stats.userHandle)); 12505 mObserver = observer; 12506 mStats = stats; 12507 } 12508 12509 @Override 12510 public String toString() { 12511 return "MeasureParams{" 12512 + Integer.toHexString(System.identityHashCode(this)) 12513 + " " + mStats.packageName + "}"; 12514 } 12515 12516 @Override 12517 void handleStartCopy() throws RemoteException { 12518 synchronized (mInstallLock) { 12519 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12520 } 12521 12522 if (mSuccess) { 12523 final boolean mounted; 12524 if (Environment.isExternalStorageEmulated()) { 12525 mounted = true; 12526 } else { 12527 final String status = Environment.getExternalStorageState(); 12528 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12529 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12530 } 12531 12532 if (mounted) { 12533 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12534 12535 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12536 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12537 12538 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12539 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12540 12541 // Always subtract cache size, since it's a subdirectory 12542 mStats.externalDataSize -= mStats.externalCacheSize; 12543 12544 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12545 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12546 12547 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12548 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12549 } 12550 } 12551 } 12552 12553 @Override 12554 void handleReturnCode() { 12555 if (mObserver != null) { 12556 try { 12557 mObserver.onGetStatsCompleted(mStats, mSuccess); 12558 } catch (RemoteException e) { 12559 Slog.i(TAG, "Observer no longer exists."); 12560 } 12561 } 12562 } 12563 12564 @Override 12565 void handleServiceError() { 12566 Slog.e(TAG, "Could not measure application " + mStats.packageName 12567 + " external storage"); 12568 } 12569 } 12570 12571 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12572 throws RemoteException { 12573 long result = 0; 12574 for (File path : paths) { 12575 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12576 } 12577 return result; 12578 } 12579 12580 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12581 for (File path : paths) { 12582 try { 12583 mcs.clearDirectory(path.getAbsolutePath()); 12584 } catch (RemoteException e) { 12585 } 12586 } 12587 } 12588 12589 static class OriginInfo { 12590 /** 12591 * Location where install is coming from, before it has been 12592 * copied/renamed into place. This could be a single monolithic APK 12593 * file, or a cluster directory. This location may be untrusted. 12594 */ 12595 final File file; 12596 final String cid; 12597 12598 /** 12599 * Flag indicating that {@link #file} or {@link #cid} has already been 12600 * staged, meaning downstream users don't need to defensively copy the 12601 * contents. 12602 */ 12603 final boolean staged; 12604 12605 /** 12606 * Flag indicating that {@link #file} or {@link #cid} is an already 12607 * installed app that is being moved. 12608 */ 12609 final boolean existing; 12610 12611 final String resolvedPath; 12612 final File resolvedFile; 12613 12614 static OriginInfo fromNothing() { 12615 return new OriginInfo(null, null, false, false); 12616 } 12617 12618 static OriginInfo fromUntrustedFile(File file) { 12619 return new OriginInfo(file, null, false, false); 12620 } 12621 12622 static OriginInfo fromExistingFile(File file) { 12623 return new OriginInfo(file, null, false, true); 12624 } 12625 12626 static OriginInfo fromStagedFile(File file) { 12627 return new OriginInfo(file, null, true, false); 12628 } 12629 12630 static OriginInfo fromStagedContainer(String cid) { 12631 return new OriginInfo(null, cid, true, false); 12632 } 12633 12634 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12635 this.file = file; 12636 this.cid = cid; 12637 this.staged = staged; 12638 this.existing = existing; 12639 12640 if (cid != null) { 12641 resolvedPath = PackageHelper.getSdDir(cid); 12642 resolvedFile = new File(resolvedPath); 12643 } else if (file != null) { 12644 resolvedPath = file.getAbsolutePath(); 12645 resolvedFile = file; 12646 } else { 12647 resolvedPath = null; 12648 resolvedFile = null; 12649 } 12650 } 12651 } 12652 12653 static class MoveInfo { 12654 final int moveId; 12655 final String fromUuid; 12656 final String toUuid; 12657 final String packageName; 12658 final String dataAppName; 12659 final int appId; 12660 final String seinfo; 12661 final int targetSdkVersion; 12662 12663 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12664 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12665 this.moveId = moveId; 12666 this.fromUuid = fromUuid; 12667 this.toUuid = toUuid; 12668 this.packageName = packageName; 12669 this.dataAppName = dataAppName; 12670 this.appId = appId; 12671 this.seinfo = seinfo; 12672 this.targetSdkVersion = targetSdkVersion; 12673 } 12674 } 12675 12676 static class VerificationInfo { 12677 /** A constant used to indicate that a uid value is not present. */ 12678 public static final int NO_UID = -1; 12679 12680 /** URI referencing where the package was downloaded from. */ 12681 final Uri originatingUri; 12682 12683 /** HTTP referrer URI associated with the originatingURI. */ 12684 final Uri referrer; 12685 12686 /** UID of the application that the install request originated from. */ 12687 final int originatingUid; 12688 12689 /** UID of application requesting the install */ 12690 final int installerUid; 12691 12692 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12693 this.originatingUri = originatingUri; 12694 this.referrer = referrer; 12695 this.originatingUid = originatingUid; 12696 this.installerUid = installerUid; 12697 } 12698 } 12699 12700 class InstallParams extends HandlerParams { 12701 final OriginInfo origin; 12702 final MoveInfo move; 12703 final IPackageInstallObserver2 observer; 12704 int installFlags; 12705 final String installerPackageName; 12706 final String volumeUuid; 12707 private InstallArgs mArgs; 12708 private int mRet; 12709 final String packageAbiOverride; 12710 final String[] grantedRuntimePermissions; 12711 final VerificationInfo verificationInfo; 12712 final Certificate[][] certificates; 12713 12714 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12715 int installFlags, String installerPackageName, String volumeUuid, 12716 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12717 String[] grantedPermissions, Certificate[][] certificates) { 12718 super(user); 12719 this.origin = origin; 12720 this.move = move; 12721 this.observer = observer; 12722 this.installFlags = installFlags; 12723 this.installerPackageName = installerPackageName; 12724 this.volumeUuid = volumeUuid; 12725 this.verificationInfo = verificationInfo; 12726 this.packageAbiOverride = packageAbiOverride; 12727 this.grantedRuntimePermissions = grantedPermissions; 12728 this.certificates = certificates; 12729 } 12730 12731 @Override 12732 public String toString() { 12733 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12734 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12735 } 12736 12737 private int installLocationPolicy(PackageInfoLite pkgLite) { 12738 String packageName = pkgLite.packageName; 12739 int installLocation = pkgLite.installLocation; 12740 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12741 // reader 12742 synchronized (mPackages) { 12743 // Currently installed package which the new package is attempting to replace or 12744 // null if no such package is installed. 12745 PackageParser.Package installedPkg = mPackages.get(packageName); 12746 // Package which currently owns the data which the new package will own if installed. 12747 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12748 // will be null whereas dataOwnerPkg will contain information about the package 12749 // which was uninstalled while keeping its data. 12750 PackageParser.Package dataOwnerPkg = installedPkg; 12751 if (dataOwnerPkg == null) { 12752 PackageSetting ps = mSettings.mPackages.get(packageName); 12753 if (ps != null) { 12754 dataOwnerPkg = ps.pkg; 12755 } 12756 } 12757 12758 if (dataOwnerPkg != null) { 12759 // If installed, the package will get access to data left on the device by its 12760 // predecessor. As a security measure, this is permited only if this is not a 12761 // version downgrade or if the predecessor package is marked as debuggable and 12762 // a downgrade is explicitly requested. 12763 // 12764 // On debuggable platform builds, downgrades are permitted even for 12765 // non-debuggable packages to make testing easier. Debuggable platform builds do 12766 // not offer security guarantees and thus it's OK to disable some security 12767 // mechanisms to make debugging/testing easier on those builds. However, even on 12768 // debuggable builds downgrades of packages are permitted only if requested via 12769 // installFlags. This is because we aim to keep the behavior of debuggable 12770 // platform builds as close as possible to the behavior of non-debuggable 12771 // platform builds. 12772 final boolean downgradeRequested = 12773 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12774 final boolean packageDebuggable = 12775 (dataOwnerPkg.applicationInfo.flags 12776 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12777 final boolean downgradePermitted = 12778 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12779 if (!downgradePermitted) { 12780 try { 12781 checkDowngrade(dataOwnerPkg, pkgLite); 12782 } catch (PackageManagerException e) { 12783 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12784 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12785 } 12786 } 12787 } 12788 12789 if (installedPkg != null) { 12790 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12791 // Check for updated system application. 12792 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12793 if (onSd) { 12794 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12795 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12796 } 12797 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12798 } else { 12799 if (onSd) { 12800 // Install flag overrides everything. 12801 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12802 } 12803 // If current upgrade specifies particular preference 12804 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12805 // Application explicitly specified internal. 12806 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12807 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12808 // App explictly prefers external. Let policy decide 12809 } else { 12810 // Prefer previous location 12811 if (isExternal(installedPkg)) { 12812 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12813 } 12814 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12815 } 12816 } 12817 } else { 12818 // Invalid install. Return error code 12819 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12820 } 12821 } 12822 } 12823 // All the special cases have been taken care of. 12824 // Return result based on recommended install location. 12825 if (onSd) { 12826 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12827 } 12828 return pkgLite.recommendedInstallLocation; 12829 } 12830 12831 /* 12832 * Invoke remote method to get package information and install 12833 * location values. Override install location based on default 12834 * policy if needed and then create install arguments based 12835 * on the install location. 12836 */ 12837 public void handleStartCopy() throws RemoteException { 12838 int ret = PackageManager.INSTALL_SUCCEEDED; 12839 12840 // If we're already staged, we've firmly committed to an install location 12841 if (origin.staged) { 12842 if (origin.file != null) { 12843 installFlags |= PackageManager.INSTALL_INTERNAL; 12844 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12845 } else if (origin.cid != null) { 12846 installFlags |= PackageManager.INSTALL_EXTERNAL; 12847 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12848 } else { 12849 throw new IllegalStateException("Invalid stage location"); 12850 } 12851 } 12852 12853 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12854 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12855 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12856 PackageInfoLite pkgLite = null; 12857 12858 if (onInt && onSd) { 12859 // Check if both bits are set. 12860 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12861 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12862 } else if (onSd && ephemeral) { 12863 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12864 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12865 } else { 12866 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12867 packageAbiOverride); 12868 12869 if (DEBUG_EPHEMERAL && ephemeral) { 12870 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12871 } 12872 12873 /* 12874 * If we have too little free space, try to free cache 12875 * before giving up. 12876 */ 12877 if (!origin.staged && pkgLite.recommendedInstallLocation 12878 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12879 // TODO: focus freeing disk space on the target device 12880 final StorageManager storage = StorageManager.from(mContext); 12881 final long lowThreshold = storage.getStorageLowBytes( 12882 Environment.getDataDirectory()); 12883 12884 final long sizeBytes = mContainerService.calculateInstalledSize( 12885 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12886 12887 try { 12888 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12889 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12890 installFlags, packageAbiOverride); 12891 } catch (InstallerException e) { 12892 Slog.w(TAG, "Failed to free cache", e); 12893 } 12894 12895 /* 12896 * The cache free must have deleted the file we 12897 * downloaded to install. 12898 * 12899 * TODO: fix the "freeCache" call to not delete 12900 * the file we care about. 12901 */ 12902 if (pkgLite.recommendedInstallLocation 12903 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12904 pkgLite.recommendedInstallLocation 12905 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12906 } 12907 } 12908 } 12909 12910 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12911 int loc = pkgLite.recommendedInstallLocation; 12912 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12913 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12914 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12915 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12916 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12917 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12918 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12919 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12920 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12921 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12922 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12923 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12924 } else { 12925 // Override with defaults if needed. 12926 loc = installLocationPolicy(pkgLite); 12927 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12928 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12929 } else if (!onSd && !onInt) { 12930 // Override install location with flags 12931 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12932 // Set the flag to install on external media. 12933 installFlags |= PackageManager.INSTALL_EXTERNAL; 12934 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12935 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12936 if (DEBUG_EPHEMERAL) { 12937 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12938 } 12939 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12940 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12941 |PackageManager.INSTALL_INTERNAL); 12942 } else { 12943 // Make sure the flag for installing on external 12944 // media is unset 12945 installFlags |= PackageManager.INSTALL_INTERNAL; 12946 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12947 } 12948 } 12949 } 12950 } 12951 12952 final InstallArgs args = createInstallArgs(this); 12953 mArgs = args; 12954 12955 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12956 // TODO: http://b/22976637 12957 // Apps installed for "all" users use the device owner to verify the app 12958 UserHandle verifierUser = getUser(); 12959 if (verifierUser == UserHandle.ALL) { 12960 verifierUser = UserHandle.SYSTEM; 12961 } 12962 12963 /* 12964 * Determine if we have any installed package verifiers. If we 12965 * do, then we'll defer to them to verify the packages. 12966 */ 12967 final int requiredUid = mRequiredVerifierPackage == null ? -1 12968 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12969 verifierUser.getIdentifier()); 12970 if (!origin.existing && requiredUid != -1 12971 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12972 final Intent verification = new Intent( 12973 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12974 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12975 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12976 PACKAGE_MIME_TYPE); 12977 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12978 12979 // Query all live verifiers based on current user state 12980 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12981 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12982 12983 if (DEBUG_VERIFY) { 12984 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12985 + verification.toString() + " with " + pkgLite.verifiers.length 12986 + " optional verifiers"); 12987 } 12988 12989 final int verificationId = mPendingVerificationToken++; 12990 12991 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12992 12993 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12994 installerPackageName); 12995 12996 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12997 installFlags); 12998 12999 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13000 pkgLite.packageName); 13001 13002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13003 pkgLite.versionCode); 13004 13005 if (verificationInfo != null) { 13006 if (verificationInfo.originatingUri != null) { 13007 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13008 verificationInfo.originatingUri); 13009 } 13010 if (verificationInfo.referrer != null) { 13011 verification.putExtra(Intent.EXTRA_REFERRER, 13012 verificationInfo.referrer); 13013 } 13014 if (verificationInfo.originatingUid >= 0) { 13015 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13016 verificationInfo.originatingUid); 13017 } 13018 if (verificationInfo.installerUid >= 0) { 13019 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13020 verificationInfo.installerUid); 13021 } 13022 } 13023 13024 final PackageVerificationState verificationState = new PackageVerificationState( 13025 requiredUid, args); 13026 13027 mPendingVerification.append(verificationId, verificationState); 13028 13029 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13030 receivers, verificationState); 13031 13032 /* 13033 * If any sufficient verifiers were listed in the package 13034 * manifest, attempt to ask them. 13035 */ 13036 if (sufficientVerifiers != null) { 13037 final int N = sufficientVerifiers.size(); 13038 if (N == 0) { 13039 Slog.i(TAG, "Additional verifiers required, but none installed."); 13040 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13041 } else { 13042 for (int i = 0; i < N; i++) { 13043 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13044 13045 final Intent sufficientIntent = new Intent(verification); 13046 sufficientIntent.setComponent(verifierComponent); 13047 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13048 } 13049 } 13050 } 13051 13052 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13053 mRequiredVerifierPackage, receivers); 13054 if (ret == PackageManager.INSTALL_SUCCEEDED 13055 && mRequiredVerifierPackage != null) { 13056 Trace.asyncTraceBegin( 13057 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13058 /* 13059 * Send the intent to the required verification agent, 13060 * but only start the verification timeout after the 13061 * target BroadcastReceivers have run. 13062 */ 13063 verification.setComponent(requiredVerifierComponent); 13064 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13065 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13066 new BroadcastReceiver() { 13067 @Override 13068 public void onReceive(Context context, Intent intent) { 13069 final Message msg = mHandler 13070 .obtainMessage(CHECK_PENDING_VERIFICATION); 13071 msg.arg1 = verificationId; 13072 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13073 } 13074 }, null, 0, null, null); 13075 13076 /* 13077 * We don't want the copy to proceed until verification 13078 * succeeds, so null out this field. 13079 */ 13080 mArgs = null; 13081 } 13082 } else { 13083 /* 13084 * No package verification is enabled, so immediately start 13085 * the remote call to initiate copy using temporary file. 13086 */ 13087 ret = args.copyApk(mContainerService, true); 13088 } 13089 } 13090 13091 mRet = ret; 13092 } 13093 13094 @Override 13095 void handleReturnCode() { 13096 // If mArgs is null, then MCS couldn't be reached. When it 13097 // reconnects, it will try again to install. At that point, this 13098 // will succeed. 13099 if (mArgs != null) { 13100 processPendingInstall(mArgs, mRet); 13101 } 13102 } 13103 13104 @Override 13105 void handleServiceError() { 13106 mArgs = createInstallArgs(this); 13107 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13108 } 13109 13110 public boolean isForwardLocked() { 13111 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13112 } 13113 } 13114 13115 /** 13116 * Used during creation of InstallArgs 13117 * 13118 * @param installFlags package installation flags 13119 * @return true if should be installed on external storage 13120 */ 13121 private static boolean installOnExternalAsec(int installFlags) { 13122 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13123 return false; 13124 } 13125 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13126 return true; 13127 } 13128 return false; 13129 } 13130 13131 /** 13132 * Used during creation of InstallArgs 13133 * 13134 * @param installFlags package installation flags 13135 * @return true if should be installed as forward locked 13136 */ 13137 private static boolean installForwardLocked(int installFlags) { 13138 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13139 } 13140 13141 private InstallArgs createInstallArgs(InstallParams params) { 13142 if (params.move != null) { 13143 return new MoveInstallArgs(params); 13144 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13145 return new AsecInstallArgs(params); 13146 } else { 13147 return new FileInstallArgs(params); 13148 } 13149 } 13150 13151 /** 13152 * Create args that describe an existing installed package. Typically used 13153 * when cleaning up old installs, or used as a move source. 13154 */ 13155 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13156 String resourcePath, String[] instructionSets) { 13157 final boolean isInAsec; 13158 if (installOnExternalAsec(installFlags)) { 13159 /* Apps on SD card are always in ASEC containers. */ 13160 isInAsec = true; 13161 } else if (installForwardLocked(installFlags) 13162 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13163 /* 13164 * Forward-locked apps are only in ASEC containers if they're the 13165 * new style 13166 */ 13167 isInAsec = true; 13168 } else { 13169 isInAsec = false; 13170 } 13171 13172 if (isInAsec) { 13173 return new AsecInstallArgs(codePath, instructionSets, 13174 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13175 } else { 13176 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13177 } 13178 } 13179 13180 static abstract class InstallArgs { 13181 /** @see InstallParams#origin */ 13182 final OriginInfo origin; 13183 /** @see InstallParams#move */ 13184 final MoveInfo move; 13185 13186 final IPackageInstallObserver2 observer; 13187 // Always refers to PackageManager flags only 13188 final int installFlags; 13189 final String installerPackageName; 13190 final String volumeUuid; 13191 final UserHandle user; 13192 final String abiOverride; 13193 final String[] installGrantPermissions; 13194 /** If non-null, drop an async trace when the install completes */ 13195 final String traceMethod; 13196 final int traceCookie; 13197 final Certificate[][] certificates; 13198 13199 // The list of instruction sets supported by this app. This is currently 13200 // only used during the rmdex() phase to clean up resources. We can get rid of this 13201 // if we move dex files under the common app path. 13202 /* nullable */ String[] instructionSets; 13203 13204 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13205 int installFlags, String installerPackageName, String volumeUuid, 13206 UserHandle user, String[] instructionSets, 13207 String abiOverride, String[] installGrantPermissions, 13208 String traceMethod, int traceCookie, Certificate[][] certificates) { 13209 this.origin = origin; 13210 this.move = move; 13211 this.installFlags = installFlags; 13212 this.observer = observer; 13213 this.installerPackageName = installerPackageName; 13214 this.volumeUuid = volumeUuid; 13215 this.user = user; 13216 this.instructionSets = instructionSets; 13217 this.abiOverride = abiOverride; 13218 this.installGrantPermissions = installGrantPermissions; 13219 this.traceMethod = traceMethod; 13220 this.traceCookie = traceCookie; 13221 this.certificates = certificates; 13222 } 13223 13224 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13225 abstract int doPreInstall(int status); 13226 13227 /** 13228 * Rename package into final resting place. All paths on the given 13229 * scanned package should be updated to reflect the rename. 13230 */ 13231 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13232 abstract int doPostInstall(int status, int uid); 13233 13234 /** @see PackageSettingBase#codePathString */ 13235 abstract String getCodePath(); 13236 /** @see PackageSettingBase#resourcePathString */ 13237 abstract String getResourcePath(); 13238 13239 // Need installer lock especially for dex file removal. 13240 abstract void cleanUpResourcesLI(); 13241 abstract boolean doPostDeleteLI(boolean delete); 13242 13243 /** 13244 * Called before the source arguments are copied. This is used mostly 13245 * for MoveParams when it needs to read the source file to put it in the 13246 * destination. 13247 */ 13248 int doPreCopy() { 13249 return PackageManager.INSTALL_SUCCEEDED; 13250 } 13251 13252 /** 13253 * Called after the source arguments are copied. This is used mostly for 13254 * MoveParams when it needs to read the source file to put it in the 13255 * destination. 13256 */ 13257 int doPostCopy(int uid) { 13258 return PackageManager.INSTALL_SUCCEEDED; 13259 } 13260 13261 protected boolean isFwdLocked() { 13262 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13263 } 13264 13265 protected boolean isExternalAsec() { 13266 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13267 } 13268 13269 protected boolean isEphemeral() { 13270 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13271 } 13272 13273 UserHandle getUser() { 13274 return user; 13275 } 13276 } 13277 13278 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13279 if (!allCodePaths.isEmpty()) { 13280 if (instructionSets == null) { 13281 throw new IllegalStateException("instructionSet == null"); 13282 } 13283 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13284 for (String codePath : allCodePaths) { 13285 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13286 try { 13287 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13288 } catch (InstallerException ignored) { 13289 } 13290 } 13291 } 13292 } 13293 } 13294 13295 /** 13296 * Logic to handle installation of non-ASEC applications, including copying 13297 * and renaming logic. 13298 */ 13299 class FileInstallArgs extends InstallArgs { 13300 private File codeFile; 13301 private File resourceFile; 13302 13303 // Example topology: 13304 // /data/app/com.example/base.apk 13305 // /data/app/com.example/split_foo.apk 13306 // /data/app/com.example/lib/arm/libfoo.so 13307 // /data/app/com.example/lib/arm64/libfoo.so 13308 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13309 13310 /** New install */ 13311 FileInstallArgs(InstallParams params) { 13312 super(params.origin, params.move, params.observer, params.installFlags, 13313 params.installerPackageName, params.volumeUuid, 13314 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13315 params.grantedRuntimePermissions, 13316 params.traceMethod, params.traceCookie, params.certificates); 13317 if (isFwdLocked()) { 13318 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13319 } 13320 } 13321 13322 /** Existing install */ 13323 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13324 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13325 null, null, null, 0, null /*certificates*/); 13326 this.codeFile = (codePath != null) ? new File(codePath) : null; 13327 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13328 } 13329 13330 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13331 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13332 try { 13333 return doCopyApk(imcs, temp); 13334 } finally { 13335 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13336 } 13337 } 13338 13339 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13340 if (origin.staged) { 13341 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13342 codeFile = origin.file; 13343 resourceFile = origin.file; 13344 return PackageManager.INSTALL_SUCCEEDED; 13345 } 13346 13347 try { 13348 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13349 final File tempDir = 13350 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13351 codeFile = tempDir; 13352 resourceFile = tempDir; 13353 } catch (IOException e) { 13354 Slog.w(TAG, "Failed to create copy file: " + e); 13355 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13356 } 13357 13358 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13359 @Override 13360 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13361 if (!FileUtils.isValidExtFilename(name)) { 13362 throw new IllegalArgumentException("Invalid filename: " + name); 13363 } 13364 try { 13365 final File file = new File(codeFile, name); 13366 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13367 O_RDWR | O_CREAT, 0644); 13368 Os.chmod(file.getAbsolutePath(), 0644); 13369 return new ParcelFileDescriptor(fd); 13370 } catch (ErrnoException e) { 13371 throw new RemoteException("Failed to open: " + e.getMessage()); 13372 } 13373 } 13374 }; 13375 13376 int ret = PackageManager.INSTALL_SUCCEEDED; 13377 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13378 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13379 Slog.e(TAG, "Failed to copy package"); 13380 return ret; 13381 } 13382 13383 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13384 NativeLibraryHelper.Handle handle = null; 13385 try { 13386 handle = NativeLibraryHelper.Handle.create(codeFile); 13387 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13388 abiOverride); 13389 } catch (IOException e) { 13390 Slog.e(TAG, "Copying native libraries failed", e); 13391 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13392 } finally { 13393 IoUtils.closeQuietly(handle); 13394 } 13395 13396 return ret; 13397 } 13398 13399 int doPreInstall(int status) { 13400 if (status != PackageManager.INSTALL_SUCCEEDED) { 13401 cleanUp(); 13402 } 13403 return status; 13404 } 13405 13406 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13407 if (status != PackageManager.INSTALL_SUCCEEDED) { 13408 cleanUp(); 13409 return false; 13410 } 13411 13412 final File targetDir = codeFile.getParentFile(); 13413 final File beforeCodeFile = codeFile; 13414 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13415 13416 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13417 try { 13418 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13419 } catch (ErrnoException e) { 13420 Slog.w(TAG, "Failed to rename", e); 13421 return false; 13422 } 13423 13424 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13425 Slog.w(TAG, "Failed to restorecon"); 13426 return false; 13427 } 13428 13429 // Reflect the rename internally 13430 codeFile = afterCodeFile; 13431 resourceFile = afterCodeFile; 13432 13433 // Reflect the rename in scanned details 13434 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13435 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13436 afterCodeFile, pkg.baseCodePath)); 13437 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13438 afterCodeFile, pkg.splitCodePaths)); 13439 13440 // Reflect the rename in app info 13441 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13442 pkg.setApplicationInfoCodePath(pkg.codePath); 13443 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13444 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13445 pkg.setApplicationInfoResourcePath(pkg.codePath); 13446 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13447 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13448 13449 return true; 13450 } 13451 13452 int doPostInstall(int status, int uid) { 13453 if (status != PackageManager.INSTALL_SUCCEEDED) { 13454 cleanUp(); 13455 } 13456 return status; 13457 } 13458 13459 @Override 13460 String getCodePath() { 13461 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13462 } 13463 13464 @Override 13465 String getResourcePath() { 13466 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13467 } 13468 13469 private boolean cleanUp() { 13470 if (codeFile == null || !codeFile.exists()) { 13471 return false; 13472 } 13473 13474 removeCodePathLI(codeFile); 13475 13476 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13477 resourceFile.delete(); 13478 } 13479 13480 return true; 13481 } 13482 13483 void cleanUpResourcesLI() { 13484 // Try enumerating all code paths before deleting 13485 List<String> allCodePaths = Collections.EMPTY_LIST; 13486 if (codeFile != null && codeFile.exists()) { 13487 try { 13488 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13489 allCodePaths = pkg.getAllCodePaths(); 13490 } catch (PackageParserException e) { 13491 // Ignored; we tried our best 13492 } 13493 } 13494 13495 cleanUp(); 13496 removeDexFiles(allCodePaths, instructionSets); 13497 } 13498 13499 boolean doPostDeleteLI(boolean delete) { 13500 // XXX err, shouldn't we respect the delete flag? 13501 cleanUpResourcesLI(); 13502 return true; 13503 } 13504 } 13505 13506 private boolean isAsecExternal(String cid) { 13507 final String asecPath = PackageHelper.getSdFilesystem(cid); 13508 return !asecPath.startsWith(mAsecInternalPath); 13509 } 13510 13511 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13512 PackageManagerException { 13513 if (copyRet < 0) { 13514 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13515 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13516 throw new PackageManagerException(copyRet, message); 13517 } 13518 } 13519 } 13520 13521 /** 13522 * Extract the MountService "container ID" from the full code path of an 13523 * .apk. 13524 */ 13525 static String cidFromCodePath(String fullCodePath) { 13526 int eidx = fullCodePath.lastIndexOf("/"); 13527 String subStr1 = fullCodePath.substring(0, eidx); 13528 int sidx = subStr1.lastIndexOf("/"); 13529 return subStr1.substring(sidx+1, eidx); 13530 } 13531 13532 /** 13533 * Logic to handle installation of ASEC applications, including copying and 13534 * renaming logic. 13535 */ 13536 class AsecInstallArgs extends InstallArgs { 13537 static final String RES_FILE_NAME = "pkg.apk"; 13538 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13539 13540 String cid; 13541 String packagePath; 13542 String resourcePath; 13543 13544 /** New install */ 13545 AsecInstallArgs(InstallParams params) { 13546 super(params.origin, params.move, params.observer, params.installFlags, 13547 params.installerPackageName, params.volumeUuid, 13548 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13549 params.grantedRuntimePermissions, 13550 params.traceMethod, params.traceCookie, params.certificates); 13551 } 13552 13553 /** Existing install */ 13554 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13555 boolean isExternal, boolean isForwardLocked) { 13556 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13557 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13558 instructionSets, null, null, null, 0, null /*certificates*/); 13559 // Hackily pretend we're still looking at a full code path 13560 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13561 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13562 } 13563 13564 // Extract cid from fullCodePath 13565 int eidx = fullCodePath.lastIndexOf("/"); 13566 String subStr1 = fullCodePath.substring(0, eidx); 13567 int sidx = subStr1.lastIndexOf("/"); 13568 cid = subStr1.substring(sidx+1, eidx); 13569 setMountPath(subStr1); 13570 } 13571 13572 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13573 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13574 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13575 instructionSets, null, null, null, 0, null /*certificates*/); 13576 this.cid = cid; 13577 setMountPath(PackageHelper.getSdDir(cid)); 13578 } 13579 13580 void createCopyFile() { 13581 cid = mInstallerService.allocateExternalStageCidLegacy(); 13582 } 13583 13584 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13585 if (origin.staged && origin.cid != null) { 13586 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13587 cid = origin.cid; 13588 setMountPath(PackageHelper.getSdDir(cid)); 13589 return PackageManager.INSTALL_SUCCEEDED; 13590 } 13591 13592 if (temp) { 13593 createCopyFile(); 13594 } else { 13595 /* 13596 * Pre-emptively destroy the container since it's destroyed if 13597 * copying fails due to it existing anyway. 13598 */ 13599 PackageHelper.destroySdDir(cid); 13600 } 13601 13602 final String newMountPath = imcs.copyPackageToContainer( 13603 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13604 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13605 13606 if (newMountPath != null) { 13607 setMountPath(newMountPath); 13608 return PackageManager.INSTALL_SUCCEEDED; 13609 } else { 13610 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13611 } 13612 } 13613 13614 @Override 13615 String getCodePath() { 13616 return packagePath; 13617 } 13618 13619 @Override 13620 String getResourcePath() { 13621 return resourcePath; 13622 } 13623 13624 int doPreInstall(int status) { 13625 if (status != PackageManager.INSTALL_SUCCEEDED) { 13626 // Destroy container 13627 PackageHelper.destroySdDir(cid); 13628 } else { 13629 boolean mounted = PackageHelper.isContainerMounted(cid); 13630 if (!mounted) { 13631 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13632 Process.SYSTEM_UID); 13633 if (newMountPath != null) { 13634 setMountPath(newMountPath); 13635 } else { 13636 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13637 } 13638 } 13639 } 13640 return status; 13641 } 13642 13643 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13644 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13645 String newMountPath = null; 13646 if (PackageHelper.isContainerMounted(cid)) { 13647 // Unmount the container 13648 if (!PackageHelper.unMountSdDir(cid)) { 13649 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13650 return false; 13651 } 13652 } 13653 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13654 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13655 " which might be stale. Will try to clean up."); 13656 // Clean up the stale container and proceed to recreate. 13657 if (!PackageHelper.destroySdDir(newCacheId)) { 13658 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13659 return false; 13660 } 13661 // Successfully cleaned up stale container. Try to rename again. 13662 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13663 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13664 + " inspite of cleaning it up."); 13665 return false; 13666 } 13667 } 13668 if (!PackageHelper.isContainerMounted(newCacheId)) { 13669 Slog.w(TAG, "Mounting container " + newCacheId); 13670 newMountPath = PackageHelper.mountSdDir(newCacheId, 13671 getEncryptKey(), Process.SYSTEM_UID); 13672 } else { 13673 newMountPath = PackageHelper.getSdDir(newCacheId); 13674 } 13675 if (newMountPath == null) { 13676 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13677 return false; 13678 } 13679 Log.i(TAG, "Succesfully renamed " + cid + 13680 " to " + newCacheId + 13681 " at new path: " + newMountPath); 13682 cid = newCacheId; 13683 13684 final File beforeCodeFile = new File(packagePath); 13685 setMountPath(newMountPath); 13686 final File afterCodeFile = new File(packagePath); 13687 13688 // Reflect the rename in scanned details 13689 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13690 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13691 afterCodeFile, pkg.baseCodePath)); 13692 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13693 afterCodeFile, pkg.splitCodePaths)); 13694 13695 // Reflect the rename in app info 13696 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13697 pkg.setApplicationInfoCodePath(pkg.codePath); 13698 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13699 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13700 pkg.setApplicationInfoResourcePath(pkg.codePath); 13701 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13702 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13703 13704 return true; 13705 } 13706 13707 private void setMountPath(String mountPath) { 13708 final File mountFile = new File(mountPath); 13709 13710 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13711 if (monolithicFile.exists()) { 13712 packagePath = monolithicFile.getAbsolutePath(); 13713 if (isFwdLocked()) { 13714 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13715 } else { 13716 resourcePath = packagePath; 13717 } 13718 } else { 13719 packagePath = mountFile.getAbsolutePath(); 13720 resourcePath = packagePath; 13721 } 13722 } 13723 13724 int doPostInstall(int status, int uid) { 13725 if (status != PackageManager.INSTALL_SUCCEEDED) { 13726 cleanUp(); 13727 } else { 13728 final int groupOwner; 13729 final String protectedFile; 13730 if (isFwdLocked()) { 13731 groupOwner = UserHandle.getSharedAppGid(uid); 13732 protectedFile = RES_FILE_NAME; 13733 } else { 13734 groupOwner = -1; 13735 protectedFile = null; 13736 } 13737 13738 if (uid < Process.FIRST_APPLICATION_UID 13739 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13740 Slog.e(TAG, "Failed to finalize " + cid); 13741 PackageHelper.destroySdDir(cid); 13742 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13743 } 13744 13745 boolean mounted = PackageHelper.isContainerMounted(cid); 13746 if (!mounted) { 13747 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13748 } 13749 } 13750 return status; 13751 } 13752 13753 private void cleanUp() { 13754 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13755 13756 // Destroy secure container 13757 PackageHelper.destroySdDir(cid); 13758 } 13759 13760 private List<String> getAllCodePaths() { 13761 final File codeFile = new File(getCodePath()); 13762 if (codeFile != null && codeFile.exists()) { 13763 try { 13764 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13765 return pkg.getAllCodePaths(); 13766 } catch (PackageParserException e) { 13767 // Ignored; we tried our best 13768 } 13769 } 13770 return Collections.EMPTY_LIST; 13771 } 13772 13773 void cleanUpResourcesLI() { 13774 // Enumerate all code paths before deleting 13775 cleanUpResourcesLI(getAllCodePaths()); 13776 } 13777 13778 private void cleanUpResourcesLI(List<String> allCodePaths) { 13779 cleanUp(); 13780 removeDexFiles(allCodePaths, instructionSets); 13781 } 13782 13783 String getPackageName() { 13784 return getAsecPackageName(cid); 13785 } 13786 13787 boolean doPostDeleteLI(boolean delete) { 13788 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13789 final List<String> allCodePaths = getAllCodePaths(); 13790 boolean mounted = PackageHelper.isContainerMounted(cid); 13791 if (mounted) { 13792 // Unmount first 13793 if (PackageHelper.unMountSdDir(cid)) { 13794 mounted = false; 13795 } 13796 } 13797 if (!mounted && delete) { 13798 cleanUpResourcesLI(allCodePaths); 13799 } 13800 return !mounted; 13801 } 13802 13803 @Override 13804 int doPreCopy() { 13805 if (isFwdLocked()) { 13806 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13807 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13808 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13809 } 13810 } 13811 13812 return PackageManager.INSTALL_SUCCEEDED; 13813 } 13814 13815 @Override 13816 int doPostCopy(int uid) { 13817 if (isFwdLocked()) { 13818 if (uid < Process.FIRST_APPLICATION_UID 13819 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13820 RES_FILE_NAME)) { 13821 Slog.e(TAG, "Failed to finalize " + cid); 13822 PackageHelper.destroySdDir(cid); 13823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13824 } 13825 } 13826 13827 return PackageManager.INSTALL_SUCCEEDED; 13828 } 13829 } 13830 13831 /** 13832 * Logic to handle movement of existing installed applications. 13833 */ 13834 class MoveInstallArgs extends InstallArgs { 13835 private File codeFile; 13836 private File resourceFile; 13837 13838 /** New install */ 13839 MoveInstallArgs(InstallParams params) { 13840 super(params.origin, params.move, params.observer, params.installFlags, 13841 params.installerPackageName, params.volumeUuid, 13842 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13843 params.grantedRuntimePermissions, 13844 params.traceMethod, params.traceCookie, params.certificates); 13845 } 13846 13847 int copyApk(IMediaContainerService imcs, boolean temp) { 13848 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13849 + move.fromUuid + " to " + move.toUuid); 13850 synchronized (mInstaller) { 13851 try { 13852 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13853 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13854 } catch (InstallerException e) { 13855 Slog.w(TAG, "Failed to move app", e); 13856 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13857 } 13858 } 13859 13860 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13861 resourceFile = codeFile; 13862 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13863 13864 return PackageManager.INSTALL_SUCCEEDED; 13865 } 13866 13867 int doPreInstall(int status) { 13868 if (status != PackageManager.INSTALL_SUCCEEDED) { 13869 cleanUp(move.toUuid); 13870 } 13871 return status; 13872 } 13873 13874 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13875 if (status != PackageManager.INSTALL_SUCCEEDED) { 13876 cleanUp(move.toUuid); 13877 return false; 13878 } 13879 13880 // Reflect the move in app info 13881 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13882 pkg.setApplicationInfoCodePath(pkg.codePath); 13883 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13884 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13885 pkg.setApplicationInfoResourcePath(pkg.codePath); 13886 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13887 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13888 13889 return true; 13890 } 13891 13892 int doPostInstall(int status, int uid) { 13893 if (status == PackageManager.INSTALL_SUCCEEDED) { 13894 cleanUp(move.fromUuid); 13895 } else { 13896 cleanUp(move.toUuid); 13897 } 13898 return status; 13899 } 13900 13901 @Override 13902 String getCodePath() { 13903 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13904 } 13905 13906 @Override 13907 String getResourcePath() { 13908 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13909 } 13910 13911 private boolean cleanUp(String volumeUuid) { 13912 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13913 move.dataAppName); 13914 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13915 final int[] userIds = sUserManager.getUserIds(); 13916 synchronized (mInstallLock) { 13917 // Clean up both app data and code 13918 // All package moves are frozen until finished 13919 for (int userId : userIds) { 13920 try { 13921 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13922 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13923 } catch (InstallerException e) { 13924 Slog.w(TAG, String.valueOf(e)); 13925 } 13926 } 13927 removeCodePathLI(codeFile); 13928 } 13929 return true; 13930 } 13931 13932 void cleanUpResourcesLI() { 13933 throw new UnsupportedOperationException(); 13934 } 13935 13936 boolean doPostDeleteLI(boolean delete) { 13937 throw new UnsupportedOperationException(); 13938 } 13939 } 13940 13941 static String getAsecPackageName(String packageCid) { 13942 int idx = packageCid.lastIndexOf("-"); 13943 if (idx == -1) { 13944 return packageCid; 13945 } 13946 return packageCid.substring(0, idx); 13947 } 13948 13949 // Utility method used to create code paths based on package name and available index. 13950 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13951 String idxStr = ""; 13952 int idx = 1; 13953 // Fall back to default value of idx=1 if prefix is not 13954 // part of oldCodePath 13955 if (oldCodePath != null) { 13956 String subStr = oldCodePath; 13957 // Drop the suffix right away 13958 if (suffix != null && subStr.endsWith(suffix)) { 13959 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13960 } 13961 // If oldCodePath already contains prefix find out the 13962 // ending index to either increment or decrement. 13963 int sidx = subStr.lastIndexOf(prefix); 13964 if (sidx != -1) { 13965 subStr = subStr.substring(sidx + prefix.length()); 13966 if (subStr != null) { 13967 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13968 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13969 } 13970 try { 13971 idx = Integer.parseInt(subStr); 13972 if (idx <= 1) { 13973 idx++; 13974 } else { 13975 idx--; 13976 } 13977 } catch(NumberFormatException e) { 13978 } 13979 } 13980 } 13981 } 13982 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13983 return prefix + idxStr; 13984 } 13985 13986 private File getNextCodePath(File targetDir, String packageName) { 13987 int suffix = 1; 13988 File result; 13989 do { 13990 result = new File(targetDir, packageName + "-" + suffix); 13991 suffix++; 13992 } while (result.exists()); 13993 return result; 13994 } 13995 13996 // Utility method that returns the relative package path with respect 13997 // to the installation directory. Like say for /data/data/com.test-1.apk 13998 // string com.test-1 is returned. 13999 static String deriveCodePathName(String codePath) { 14000 if (codePath == null) { 14001 return null; 14002 } 14003 final File codeFile = new File(codePath); 14004 final String name = codeFile.getName(); 14005 if (codeFile.isDirectory()) { 14006 return name; 14007 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14008 final int lastDot = name.lastIndexOf('.'); 14009 return name.substring(0, lastDot); 14010 } else { 14011 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14012 return null; 14013 } 14014 } 14015 14016 static class PackageInstalledInfo { 14017 String name; 14018 int uid; 14019 // The set of users that originally had this package installed. 14020 int[] origUsers; 14021 // The set of users that now have this package installed. 14022 int[] newUsers; 14023 PackageParser.Package pkg; 14024 int returnCode; 14025 String returnMsg; 14026 PackageRemovedInfo removedInfo; 14027 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14028 14029 public void setError(int code, String msg) { 14030 setReturnCode(code); 14031 setReturnMessage(msg); 14032 Slog.w(TAG, msg); 14033 } 14034 14035 public void setError(String msg, PackageParserException e) { 14036 setReturnCode(e.error); 14037 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14038 Slog.w(TAG, msg, e); 14039 } 14040 14041 public void setError(String msg, PackageManagerException e) { 14042 returnCode = e.error; 14043 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14044 Slog.w(TAG, msg, e); 14045 } 14046 14047 public void setReturnCode(int returnCode) { 14048 this.returnCode = returnCode; 14049 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14050 for (int i = 0; i < childCount; i++) { 14051 addedChildPackages.valueAt(i).returnCode = returnCode; 14052 } 14053 } 14054 14055 private void setReturnMessage(String returnMsg) { 14056 this.returnMsg = returnMsg; 14057 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14058 for (int i = 0; i < childCount; i++) { 14059 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14060 } 14061 } 14062 14063 // In some error cases we want to convey more info back to the observer 14064 String origPackage; 14065 String origPermission; 14066 } 14067 14068 /* 14069 * Install a non-existing package. 14070 */ 14071 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14072 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14073 PackageInstalledInfo res) { 14074 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14075 14076 // Remember this for later, in case we need to rollback this install 14077 String pkgName = pkg.packageName; 14078 14079 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14080 14081 synchronized(mPackages) { 14082 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14083 // A package with the same name is already installed, though 14084 // it has been renamed to an older name. The package we 14085 // are trying to install should be installed as an update to 14086 // the existing one, but that has not been requested, so bail. 14087 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14088 + " without first uninstalling package running as " 14089 + mSettings.mRenamedPackages.get(pkgName)); 14090 return; 14091 } 14092 if (mPackages.containsKey(pkgName)) { 14093 // Don't allow installation over an existing package with the same name. 14094 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14095 + " without first uninstalling."); 14096 return; 14097 } 14098 } 14099 14100 try { 14101 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14102 System.currentTimeMillis(), user); 14103 14104 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14105 14106 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14107 prepareAppDataAfterInstallLIF(newPackage); 14108 14109 } else { 14110 // Remove package from internal structures, but keep around any 14111 // data that might have already existed 14112 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14113 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14114 } 14115 } catch (PackageManagerException e) { 14116 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14117 } 14118 14119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14120 } 14121 14122 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14123 // Can't rotate keys during boot or if sharedUser. 14124 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14125 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14126 return false; 14127 } 14128 // app is using upgradeKeySets; make sure all are valid 14129 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14130 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14131 for (int i = 0; i < upgradeKeySets.length; i++) { 14132 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14133 Slog.wtf(TAG, "Package " 14134 + (oldPs.name != null ? oldPs.name : "<null>") 14135 + " contains upgrade-key-set reference to unknown key-set: " 14136 + upgradeKeySets[i] 14137 + " reverting to signatures check."); 14138 return false; 14139 } 14140 } 14141 return true; 14142 } 14143 14144 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14145 // Upgrade keysets are being used. Determine if new package has a superset of the 14146 // required keys. 14147 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14148 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14149 for (int i = 0; i < upgradeKeySets.length; i++) { 14150 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14151 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14152 return true; 14153 } 14154 } 14155 return false; 14156 } 14157 14158 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14159 try (DigestInputStream digestStream = 14160 new DigestInputStream(new FileInputStream(file), digest)) { 14161 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14162 } 14163 } 14164 14165 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14166 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14167 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14168 14169 final PackageParser.Package oldPackage; 14170 final String pkgName = pkg.packageName; 14171 final int[] allUsers; 14172 final int[] installedUsers; 14173 14174 synchronized(mPackages) { 14175 oldPackage = mPackages.get(pkgName); 14176 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14177 14178 // don't allow upgrade to target a release SDK from a pre-release SDK 14179 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14180 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14181 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14182 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14183 if (oldTargetsPreRelease 14184 && !newTargetsPreRelease 14185 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14186 Slog.w(TAG, "Can't install package targeting released sdk"); 14187 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14188 return; 14189 } 14190 14191 // don't allow an upgrade from full to ephemeral 14192 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14193 if (isEphemeral && !oldIsEphemeral) { 14194 // can't downgrade from full to ephemeral 14195 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14196 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14197 return; 14198 } 14199 14200 // verify signatures are valid 14201 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14202 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14203 if (!checkUpgradeKeySetLP(ps, pkg)) { 14204 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14205 "New package not signed by keys specified by upgrade-keysets: " 14206 + pkgName); 14207 return; 14208 } 14209 } else { 14210 // default to original signature matching 14211 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14212 != PackageManager.SIGNATURE_MATCH) { 14213 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14214 "New package has a different signature: " + pkgName); 14215 return; 14216 } 14217 } 14218 14219 // don't allow a system upgrade unless the upgrade hash matches 14220 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14221 byte[] digestBytes = null; 14222 try { 14223 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14224 updateDigest(digest, new File(pkg.baseCodePath)); 14225 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14226 for (String path : pkg.splitCodePaths) { 14227 updateDigest(digest, new File(path)); 14228 } 14229 } 14230 digestBytes = digest.digest(); 14231 } catch (NoSuchAlgorithmException | IOException e) { 14232 res.setError(INSTALL_FAILED_INVALID_APK, 14233 "Could not compute hash: " + pkgName); 14234 return; 14235 } 14236 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14237 res.setError(INSTALL_FAILED_INVALID_APK, 14238 "New package fails restrict-update check: " + pkgName); 14239 return; 14240 } 14241 // retain upgrade restriction 14242 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14243 } 14244 14245 // Check for shared user id changes 14246 String invalidPackageName = 14247 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14248 if (invalidPackageName != null) { 14249 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14250 "Package " + invalidPackageName + " tried to change user " 14251 + oldPackage.mSharedUserId); 14252 return; 14253 } 14254 14255 // In case of rollback, remember per-user/profile install state 14256 allUsers = sUserManager.getUserIds(); 14257 installedUsers = ps.queryInstalledUsers(allUsers, true); 14258 } 14259 14260 // Update what is removed 14261 res.removedInfo = new PackageRemovedInfo(); 14262 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14263 res.removedInfo.removedPackage = oldPackage.packageName; 14264 res.removedInfo.isUpdate = true; 14265 res.removedInfo.origUsers = installedUsers; 14266 final int childCount = (oldPackage.childPackages != null) 14267 ? oldPackage.childPackages.size() : 0; 14268 for (int i = 0; i < childCount; i++) { 14269 boolean childPackageUpdated = false; 14270 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14271 if (res.addedChildPackages != null) { 14272 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14273 if (childRes != null) { 14274 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14275 childRes.removedInfo.removedPackage = childPkg.packageName; 14276 childRes.removedInfo.isUpdate = true; 14277 childPackageUpdated = true; 14278 } 14279 } 14280 if (!childPackageUpdated) { 14281 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14282 childRemovedRes.removedPackage = childPkg.packageName; 14283 childRemovedRes.isUpdate = false; 14284 childRemovedRes.dataRemoved = true; 14285 synchronized (mPackages) { 14286 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14287 if (childPs != null) { 14288 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14289 } 14290 } 14291 if (res.removedInfo.removedChildPackages == null) { 14292 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14293 } 14294 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14295 } 14296 } 14297 14298 boolean sysPkg = (isSystemApp(oldPackage)); 14299 if (sysPkg) { 14300 // Set the system/privileged flags as needed 14301 final boolean privileged = 14302 (oldPackage.applicationInfo.privateFlags 14303 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14304 final int systemPolicyFlags = policyFlags 14305 | PackageParser.PARSE_IS_SYSTEM 14306 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14307 14308 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14309 user, allUsers, installerPackageName, res); 14310 } else { 14311 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14312 user, allUsers, installerPackageName, res); 14313 } 14314 } 14315 14316 public List<String> getPreviousCodePaths(String packageName) { 14317 final PackageSetting ps = mSettings.mPackages.get(packageName); 14318 final List<String> result = new ArrayList<String>(); 14319 if (ps != null && ps.oldCodePaths != null) { 14320 result.addAll(ps.oldCodePaths); 14321 } 14322 return result; 14323 } 14324 14325 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14326 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14327 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14328 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14329 + deletedPackage); 14330 14331 String pkgName = deletedPackage.packageName; 14332 boolean deletedPkg = true; 14333 boolean addedPkg = false; 14334 boolean updatedSettings = false; 14335 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14336 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14337 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14338 14339 final long origUpdateTime = (pkg.mExtras != null) 14340 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14341 14342 // First delete the existing package while retaining the data directory 14343 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14344 res.removedInfo, true, pkg)) { 14345 // If the existing package wasn't successfully deleted 14346 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14347 deletedPkg = false; 14348 } else { 14349 // Successfully deleted the old package; proceed with replace. 14350 14351 // If deleted package lived in a container, give users a chance to 14352 // relinquish resources before killing. 14353 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14354 if (DEBUG_INSTALL) { 14355 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14356 } 14357 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14358 final ArrayList<String> pkgList = new ArrayList<String>(1); 14359 pkgList.add(deletedPackage.applicationInfo.packageName); 14360 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14361 } 14362 14363 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14364 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14365 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14366 14367 try { 14368 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14369 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14370 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14371 14372 // Update the in-memory copy of the previous code paths. 14373 PackageSetting ps = mSettings.mPackages.get(pkgName); 14374 if (!killApp) { 14375 if (ps.oldCodePaths == null) { 14376 ps.oldCodePaths = new ArraySet<>(); 14377 } 14378 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14379 if (deletedPackage.splitCodePaths != null) { 14380 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14381 } 14382 } else { 14383 ps.oldCodePaths = null; 14384 } 14385 if (ps.childPackageNames != null) { 14386 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14387 final String childPkgName = ps.childPackageNames.get(i); 14388 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14389 childPs.oldCodePaths = ps.oldCodePaths; 14390 } 14391 } 14392 prepareAppDataAfterInstallLIF(newPackage); 14393 addedPkg = true; 14394 } catch (PackageManagerException e) { 14395 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14396 } 14397 } 14398 14399 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14400 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14401 14402 // Revert all internal state mutations and added folders for the failed install 14403 if (addedPkg) { 14404 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14405 res.removedInfo, true, null); 14406 } 14407 14408 // Restore the old package 14409 if (deletedPkg) { 14410 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14411 File restoreFile = new File(deletedPackage.codePath); 14412 // Parse old package 14413 boolean oldExternal = isExternal(deletedPackage); 14414 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14415 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14416 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14417 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14418 try { 14419 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14420 null); 14421 } catch (PackageManagerException e) { 14422 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14423 + e.getMessage()); 14424 return; 14425 } 14426 14427 synchronized (mPackages) { 14428 // Ensure the installer package name up to date 14429 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14430 14431 // Update permissions for restored package 14432 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14433 14434 mSettings.writeLPr(); 14435 } 14436 14437 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14438 } 14439 } else { 14440 synchronized (mPackages) { 14441 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14442 if (ps != null) { 14443 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14444 if (res.removedInfo.removedChildPackages != null) { 14445 final int childCount = res.removedInfo.removedChildPackages.size(); 14446 // Iterate in reverse as we may modify the collection 14447 for (int i = childCount - 1; i >= 0; i--) { 14448 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14449 if (res.addedChildPackages.containsKey(childPackageName)) { 14450 res.removedInfo.removedChildPackages.removeAt(i); 14451 } else { 14452 PackageRemovedInfo childInfo = res.removedInfo 14453 .removedChildPackages.valueAt(i); 14454 childInfo.removedForAllUsers = mPackages.get( 14455 childInfo.removedPackage) == null; 14456 } 14457 } 14458 } 14459 } 14460 } 14461 } 14462 } 14463 14464 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14465 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14466 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14467 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14468 + ", old=" + deletedPackage); 14469 14470 final boolean disabledSystem; 14471 14472 // Remove existing system package 14473 removePackageLI(deletedPackage, true); 14474 14475 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14476 if (!disabledSystem) { 14477 // We didn't need to disable the .apk as a current system package, 14478 // which means we are replacing another update that is already 14479 // installed. We need to make sure to delete the older one's .apk. 14480 res.removedInfo.args = createInstallArgsForExisting(0, 14481 deletedPackage.applicationInfo.getCodePath(), 14482 deletedPackage.applicationInfo.getResourcePath(), 14483 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14484 } else { 14485 res.removedInfo.args = null; 14486 } 14487 14488 // Successfully disabled the old package. Now proceed with re-installation 14489 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14490 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14491 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14492 14493 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14494 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14495 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14496 14497 PackageParser.Package newPackage = null; 14498 try { 14499 // Add the package to the internal data structures 14500 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14501 14502 // Set the update and install times 14503 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14504 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14505 System.currentTimeMillis()); 14506 14507 // Update the package dynamic state if succeeded 14508 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14509 // Now that the install succeeded make sure we remove data 14510 // directories for any child package the update removed. 14511 final int deletedChildCount = (deletedPackage.childPackages != null) 14512 ? deletedPackage.childPackages.size() : 0; 14513 final int newChildCount = (newPackage.childPackages != null) 14514 ? newPackage.childPackages.size() : 0; 14515 for (int i = 0; i < deletedChildCount; i++) { 14516 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14517 boolean childPackageDeleted = true; 14518 for (int j = 0; j < newChildCount; j++) { 14519 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14520 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14521 childPackageDeleted = false; 14522 break; 14523 } 14524 } 14525 if (childPackageDeleted) { 14526 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14527 deletedChildPkg.packageName); 14528 if (ps != null && res.removedInfo.removedChildPackages != null) { 14529 PackageRemovedInfo removedChildRes = res.removedInfo 14530 .removedChildPackages.get(deletedChildPkg.packageName); 14531 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14532 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14533 } 14534 } 14535 } 14536 14537 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14538 prepareAppDataAfterInstallLIF(newPackage); 14539 } 14540 } catch (PackageManagerException e) { 14541 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14542 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14543 } 14544 14545 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14546 // Re installation failed. Restore old information 14547 // Remove new pkg information 14548 if (newPackage != null) { 14549 removeInstalledPackageLI(newPackage, true); 14550 } 14551 // Add back the old system package 14552 try { 14553 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14554 } catch (PackageManagerException e) { 14555 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14556 } 14557 14558 synchronized (mPackages) { 14559 if (disabledSystem) { 14560 enableSystemPackageLPw(deletedPackage); 14561 } 14562 14563 // Ensure the installer package name up to date 14564 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14565 14566 // Update permissions for restored package 14567 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14568 14569 mSettings.writeLPr(); 14570 } 14571 14572 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14573 + " after failed upgrade"); 14574 } 14575 } 14576 14577 /** 14578 * Checks whether the parent or any of the child packages have a change shared 14579 * user. For a package to be a valid update the shred users of the parent and 14580 * the children should match. We may later support changing child shared users. 14581 * @param oldPkg The updated package. 14582 * @param newPkg The update package. 14583 * @return The shared user that change between the versions. 14584 */ 14585 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14586 PackageParser.Package newPkg) { 14587 // Check parent shared user 14588 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14589 return newPkg.packageName; 14590 } 14591 // Check child shared users 14592 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14593 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14594 for (int i = 0; i < newChildCount; i++) { 14595 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14596 // If this child was present, did it have the same shared user? 14597 for (int j = 0; j < oldChildCount; j++) { 14598 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14599 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14600 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14601 return newChildPkg.packageName; 14602 } 14603 } 14604 } 14605 return null; 14606 } 14607 14608 private void removeNativeBinariesLI(PackageSetting ps) { 14609 // Remove the lib path for the parent package 14610 if (ps != null) { 14611 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14612 // Remove the lib path for the child packages 14613 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14614 for (int i = 0; i < childCount; i++) { 14615 PackageSetting childPs = null; 14616 synchronized (mPackages) { 14617 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14618 } 14619 if (childPs != null) { 14620 NativeLibraryHelper.removeNativeBinariesLI(childPs 14621 .legacyNativeLibraryPathString); 14622 } 14623 } 14624 } 14625 } 14626 14627 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14628 // Enable the parent package 14629 mSettings.enableSystemPackageLPw(pkg.packageName); 14630 // Enable the child packages 14631 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14632 for (int i = 0; i < childCount; i++) { 14633 PackageParser.Package childPkg = pkg.childPackages.get(i); 14634 mSettings.enableSystemPackageLPw(childPkg.packageName); 14635 } 14636 } 14637 14638 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14639 PackageParser.Package newPkg) { 14640 // Disable the parent package (parent always replaced) 14641 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14642 // Disable the child packages 14643 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14644 for (int i = 0; i < childCount; i++) { 14645 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14646 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14647 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14648 } 14649 return disabled; 14650 } 14651 14652 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14653 String installerPackageName) { 14654 // Enable the parent package 14655 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14656 // Enable the child packages 14657 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14658 for (int i = 0; i < childCount; i++) { 14659 PackageParser.Package childPkg = pkg.childPackages.get(i); 14660 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14661 } 14662 } 14663 14664 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14665 // Collect all used permissions in the UID 14666 ArraySet<String> usedPermissions = new ArraySet<>(); 14667 final int packageCount = su.packages.size(); 14668 for (int i = 0; i < packageCount; i++) { 14669 PackageSetting ps = su.packages.valueAt(i); 14670 if (ps.pkg == null) { 14671 continue; 14672 } 14673 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14674 for (int j = 0; j < requestedPermCount; j++) { 14675 String permission = ps.pkg.requestedPermissions.get(j); 14676 BasePermission bp = mSettings.mPermissions.get(permission); 14677 if (bp != null) { 14678 usedPermissions.add(permission); 14679 } 14680 } 14681 } 14682 14683 PermissionsState permissionsState = su.getPermissionsState(); 14684 // Prune install permissions 14685 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14686 final int installPermCount = installPermStates.size(); 14687 for (int i = installPermCount - 1; i >= 0; i--) { 14688 PermissionState permissionState = installPermStates.get(i); 14689 if (!usedPermissions.contains(permissionState.getName())) { 14690 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14691 if (bp != null) { 14692 permissionsState.revokeInstallPermission(bp); 14693 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14694 PackageManager.MASK_PERMISSION_FLAGS, 0); 14695 } 14696 } 14697 } 14698 14699 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14700 14701 // Prune runtime permissions 14702 for (int userId : allUserIds) { 14703 List<PermissionState> runtimePermStates = permissionsState 14704 .getRuntimePermissionStates(userId); 14705 final int runtimePermCount = runtimePermStates.size(); 14706 for (int i = runtimePermCount - 1; i >= 0; i--) { 14707 PermissionState permissionState = runtimePermStates.get(i); 14708 if (!usedPermissions.contains(permissionState.getName())) { 14709 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14710 if (bp != null) { 14711 permissionsState.revokeRuntimePermission(bp, userId); 14712 permissionsState.updatePermissionFlags(bp, userId, 14713 PackageManager.MASK_PERMISSION_FLAGS, 0); 14714 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14715 runtimePermissionChangedUserIds, userId); 14716 } 14717 } 14718 } 14719 } 14720 14721 return runtimePermissionChangedUserIds; 14722 } 14723 14724 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14725 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14726 // Update the parent package setting 14727 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14728 res, user); 14729 // Update the child packages setting 14730 final int childCount = (newPackage.childPackages != null) 14731 ? newPackage.childPackages.size() : 0; 14732 for (int i = 0; i < childCount; i++) { 14733 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14734 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14735 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14736 childRes.origUsers, childRes, user); 14737 } 14738 } 14739 14740 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14741 String installerPackageName, int[] allUsers, int[] installedForUsers, 14742 PackageInstalledInfo res, UserHandle user) { 14743 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14744 14745 String pkgName = newPackage.packageName; 14746 synchronized (mPackages) { 14747 //write settings. the installStatus will be incomplete at this stage. 14748 //note that the new package setting would have already been 14749 //added to mPackages. It hasn't been persisted yet. 14750 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14751 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14752 mSettings.writeLPr(); 14753 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14754 } 14755 14756 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14757 synchronized (mPackages) { 14758 updatePermissionsLPw(newPackage.packageName, newPackage, 14759 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14760 ? UPDATE_PERMISSIONS_ALL : 0)); 14761 // For system-bundled packages, we assume that installing an upgraded version 14762 // of the package implies that the user actually wants to run that new code, 14763 // so we enable the package. 14764 PackageSetting ps = mSettings.mPackages.get(pkgName); 14765 final int userId = user.getIdentifier(); 14766 if (ps != null) { 14767 if (isSystemApp(newPackage)) { 14768 if (DEBUG_INSTALL) { 14769 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14770 } 14771 // Enable system package for requested users 14772 if (res.origUsers != null) { 14773 for (int origUserId : res.origUsers) { 14774 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14775 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14776 origUserId, installerPackageName); 14777 } 14778 } 14779 } 14780 // Also convey the prior install/uninstall state 14781 if (allUsers != null && installedForUsers != null) { 14782 for (int currentUserId : allUsers) { 14783 final boolean installed = ArrayUtils.contains( 14784 installedForUsers, currentUserId); 14785 if (DEBUG_INSTALL) { 14786 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14787 } 14788 ps.setInstalled(installed, currentUserId); 14789 } 14790 // these install state changes will be persisted in the 14791 // upcoming call to mSettings.writeLPr(). 14792 } 14793 } 14794 // It's implied that when a user requests installation, they want the app to be 14795 // installed and enabled. 14796 if (userId != UserHandle.USER_ALL) { 14797 ps.setInstalled(true, userId); 14798 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14799 } 14800 } 14801 res.name = pkgName; 14802 res.uid = newPackage.applicationInfo.uid; 14803 res.pkg = newPackage; 14804 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14805 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14806 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14807 //to update install status 14808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14809 mSettings.writeLPr(); 14810 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14811 } 14812 14813 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14814 } 14815 14816 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14817 try { 14818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14819 installPackageLI(args, res); 14820 } finally { 14821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14822 } 14823 } 14824 14825 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14826 final int installFlags = args.installFlags; 14827 final String installerPackageName = args.installerPackageName; 14828 final String volumeUuid = args.volumeUuid; 14829 final File tmpPackageFile = new File(args.getCodePath()); 14830 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14831 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14832 || (args.volumeUuid != null)); 14833 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14834 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14835 boolean replace = false; 14836 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14837 if (args.move != null) { 14838 // moving a complete application; perform an initial scan on the new install location 14839 scanFlags |= SCAN_INITIAL; 14840 } 14841 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14842 scanFlags |= SCAN_DONT_KILL_APP; 14843 } 14844 14845 // Result object to be returned 14846 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14847 14848 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14849 14850 // Sanity check 14851 if (ephemeral && (forwardLocked || onExternal)) { 14852 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14853 + " external=" + onExternal); 14854 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14855 return; 14856 } 14857 14858 // Retrieve PackageSettings and parse package 14859 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14860 | PackageParser.PARSE_ENFORCE_CODE 14861 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14862 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14863 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14864 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14865 PackageParser pp = new PackageParser(); 14866 pp.setSeparateProcesses(mSeparateProcesses); 14867 pp.setDisplayMetrics(mMetrics); 14868 14869 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14870 final PackageParser.Package pkg; 14871 try { 14872 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14873 } catch (PackageParserException e) { 14874 res.setError("Failed parse during installPackageLI", e); 14875 return; 14876 } finally { 14877 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14878 } 14879 14880 // If we are installing a clustered package add results for the children 14881 if (pkg.childPackages != null) { 14882 synchronized (mPackages) { 14883 final int childCount = pkg.childPackages.size(); 14884 for (int i = 0; i < childCount; i++) { 14885 PackageParser.Package childPkg = pkg.childPackages.get(i); 14886 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14887 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14888 childRes.pkg = childPkg; 14889 childRes.name = childPkg.packageName; 14890 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14891 if (childPs != null) { 14892 childRes.origUsers = childPs.queryInstalledUsers( 14893 sUserManager.getUserIds(), true); 14894 } 14895 if ((mPackages.containsKey(childPkg.packageName))) { 14896 childRes.removedInfo = new PackageRemovedInfo(); 14897 childRes.removedInfo.removedPackage = childPkg.packageName; 14898 } 14899 if (res.addedChildPackages == null) { 14900 res.addedChildPackages = new ArrayMap<>(); 14901 } 14902 res.addedChildPackages.put(childPkg.packageName, childRes); 14903 } 14904 } 14905 } 14906 14907 // If package doesn't declare API override, mark that we have an install 14908 // time CPU ABI override. 14909 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14910 pkg.cpuAbiOverride = args.abiOverride; 14911 } 14912 14913 String pkgName = res.name = pkg.packageName; 14914 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14915 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14916 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14917 return; 14918 } 14919 } 14920 14921 try { 14922 // either use what we've been given or parse directly from the APK 14923 if (args.certificates != null) { 14924 try { 14925 PackageParser.populateCertificates(pkg, args.certificates); 14926 } catch (PackageParserException e) { 14927 // there was something wrong with the certificates we were given; 14928 // try to pull them from the APK 14929 PackageParser.collectCertificates(pkg, parseFlags); 14930 } 14931 } else { 14932 PackageParser.collectCertificates(pkg, parseFlags); 14933 } 14934 } catch (PackageParserException e) { 14935 res.setError("Failed collect during installPackageLI", e); 14936 return; 14937 } 14938 14939 // Get rid of all references to package scan path via parser. 14940 pp = null; 14941 String oldCodePath = null; 14942 boolean systemApp = false; 14943 synchronized (mPackages) { 14944 // Check if installing already existing package 14945 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14946 String oldName = mSettings.mRenamedPackages.get(pkgName); 14947 if (pkg.mOriginalPackages != null 14948 && pkg.mOriginalPackages.contains(oldName) 14949 && mPackages.containsKey(oldName)) { 14950 // This package is derived from an original package, 14951 // and this device has been updating from that original 14952 // name. We must continue using the original name, so 14953 // rename the new package here. 14954 pkg.setPackageName(oldName); 14955 pkgName = pkg.packageName; 14956 replace = true; 14957 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14958 + oldName + " pkgName=" + pkgName); 14959 } else if (mPackages.containsKey(pkgName)) { 14960 // This package, under its official name, already exists 14961 // on the device; we should replace it. 14962 replace = true; 14963 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14964 } 14965 14966 // Child packages are installed through the parent package 14967 if (pkg.parentPackage != null) { 14968 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14969 "Package " + pkg.packageName + " is child of package " 14970 + pkg.parentPackage.parentPackage + ". Child packages " 14971 + "can be updated only through the parent package."); 14972 return; 14973 } 14974 14975 if (replace) { 14976 // Prevent apps opting out from runtime permissions 14977 PackageParser.Package oldPackage = mPackages.get(pkgName); 14978 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14979 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14980 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14981 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14982 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14983 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14984 + " doesn't support runtime permissions but the old" 14985 + " target SDK " + oldTargetSdk + " does."); 14986 return; 14987 } 14988 14989 // Prevent installing of child packages 14990 if (oldPackage.parentPackage != null) { 14991 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14992 "Package " + pkg.packageName + " is child of package " 14993 + oldPackage.parentPackage + ". Child packages " 14994 + "can be updated only through the parent package."); 14995 return; 14996 } 14997 } 14998 } 14999 15000 PackageSetting ps = mSettings.mPackages.get(pkgName); 15001 if (ps != null) { 15002 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15003 15004 // Quick sanity check that we're signed correctly if updating; 15005 // we'll check this again later when scanning, but we want to 15006 // bail early here before tripping over redefined permissions. 15007 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15008 if (!checkUpgradeKeySetLP(ps, pkg)) { 15009 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15010 + pkg.packageName + " upgrade keys do not match the " 15011 + "previously installed version"); 15012 return; 15013 } 15014 } else { 15015 try { 15016 verifySignaturesLP(ps, pkg); 15017 } catch (PackageManagerException e) { 15018 res.setError(e.error, e.getMessage()); 15019 return; 15020 } 15021 } 15022 15023 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15024 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15025 systemApp = (ps.pkg.applicationInfo.flags & 15026 ApplicationInfo.FLAG_SYSTEM) != 0; 15027 } 15028 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15029 } 15030 15031 // Check whether the newly-scanned package wants to define an already-defined perm 15032 int N = pkg.permissions.size(); 15033 for (int i = N-1; i >= 0; i--) { 15034 PackageParser.Permission perm = pkg.permissions.get(i); 15035 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15036 if (bp != null) { 15037 // If the defining package is signed with our cert, it's okay. This 15038 // also includes the "updating the same package" case, of course. 15039 // "updating same package" could also involve key-rotation. 15040 final boolean sigsOk; 15041 if (bp.sourcePackage.equals(pkg.packageName) 15042 && (bp.packageSetting instanceof PackageSetting) 15043 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15044 scanFlags))) { 15045 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15046 } else { 15047 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15048 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15049 } 15050 if (!sigsOk) { 15051 // If the owning package is the system itself, we log but allow 15052 // install to proceed; we fail the install on all other permission 15053 // redefinitions. 15054 if (!bp.sourcePackage.equals("android")) { 15055 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15056 + pkg.packageName + " attempting to redeclare permission " 15057 + perm.info.name + " already owned by " + bp.sourcePackage); 15058 res.origPermission = perm.info.name; 15059 res.origPackage = bp.sourcePackage; 15060 return; 15061 } else { 15062 Slog.w(TAG, "Package " + pkg.packageName 15063 + " attempting to redeclare system permission " 15064 + perm.info.name + "; ignoring new declaration"); 15065 pkg.permissions.remove(i); 15066 } 15067 } 15068 } 15069 } 15070 } 15071 15072 if (systemApp) { 15073 if (onExternal) { 15074 // Abort update; system app can't be replaced with app on sdcard 15075 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15076 "Cannot install updates to system apps on sdcard"); 15077 return; 15078 } else if (ephemeral) { 15079 // Abort update; system app can't be replaced with an ephemeral app 15080 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15081 "Cannot update a system app with an ephemeral app"); 15082 return; 15083 } 15084 } 15085 15086 if (args.move != null) { 15087 // We did an in-place move, so dex is ready to roll 15088 scanFlags |= SCAN_NO_DEX; 15089 scanFlags |= SCAN_MOVE; 15090 15091 synchronized (mPackages) { 15092 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15093 if (ps == null) { 15094 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15095 "Missing settings for moved package " + pkgName); 15096 } 15097 15098 // We moved the entire application as-is, so bring over the 15099 // previously derived ABI information. 15100 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15101 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15102 } 15103 15104 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15105 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15106 scanFlags |= SCAN_NO_DEX; 15107 15108 try { 15109 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15110 args.abiOverride : pkg.cpuAbiOverride); 15111 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15112 true /* extract libs */); 15113 } catch (PackageManagerException pme) { 15114 Slog.e(TAG, "Error deriving application ABI", pme); 15115 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15116 return; 15117 } 15118 15119 // Shared libraries for the package need to be updated. 15120 synchronized (mPackages) { 15121 try { 15122 updateSharedLibrariesLPw(pkg, null); 15123 } catch (PackageManagerException e) { 15124 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15125 } 15126 } 15127 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15128 // Do not run PackageDexOptimizer through the local performDexOpt 15129 // method because `pkg` is not in `mPackages` yet. 15130 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15131 null /* instructionSets */, false /* checkProfiles */, 15132 getCompilerFilterForReason(REASON_INSTALL)); 15133 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15134 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15135 String msg = "Extracting package failed for " + pkgName; 15136 res.setError(INSTALL_FAILED_DEXOPT, msg); 15137 return; 15138 } 15139 15140 // Notify BackgroundDexOptService that the package has been changed. 15141 // If this is an update of a package which used to fail to compile, 15142 // BDOS will remove it from its blacklist. 15143 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15144 } 15145 15146 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15147 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15148 return; 15149 } 15150 15151 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15152 15153 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15154 "installPackageLI")) { 15155 if (replace) { 15156 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15157 installerPackageName, res); 15158 } else { 15159 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15160 args.user, installerPackageName, volumeUuid, res); 15161 } 15162 } 15163 synchronized (mPackages) { 15164 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15165 if (ps != null) { 15166 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15167 } 15168 15169 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15170 for (int i = 0; i < childCount; i++) { 15171 PackageParser.Package childPkg = pkg.childPackages.get(i); 15172 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15173 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15174 if (childPs != null) { 15175 childRes.newUsers = childPs.queryInstalledUsers( 15176 sUserManager.getUserIds(), true); 15177 } 15178 } 15179 } 15180 } 15181 15182 private void startIntentFilterVerifications(int userId, boolean replacing, 15183 PackageParser.Package pkg) { 15184 if (mIntentFilterVerifierComponent == null) { 15185 Slog.w(TAG, "No IntentFilter verification will not be done as " 15186 + "there is no IntentFilterVerifier available!"); 15187 return; 15188 } 15189 15190 final int verifierUid = getPackageUid( 15191 mIntentFilterVerifierComponent.getPackageName(), 15192 MATCH_DEBUG_TRIAGED_MISSING, 15193 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15194 15195 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15196 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15197 mHandler.sendMessage(msg); 15198 15199 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15200 for (int i = 0; i < childCount; i++) { 15201 PackageParser.Package childPkg = pkg.childPackages.get(i); 15202 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15203 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15204 mHandler.sendMessage(msg); 15205 } 15206 } 15207 15208 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15209 PackageParser.Package pkg) { 15210 int size = pkg.activities.size(); 15211 if (size == 0) { 15212 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15213 "No activity, so no need to verify any IntentFilter!"); 15214 return; 15215 } 15216 15217 final boolean hasDomainURLs = hasDomainURLs(pkg); 15218 if (!hasDomainURLs) { 15219 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15220 "No domain URLs, so no need to verify any IntentFilter!"); 15221 return; 15222 } 15223 15224 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15225 + " if any IntentFilter from the " + size 15226 + " Activities needs verification ..."); 15227 15228 int count = 0; 15229 final String packageName = pkg.packageName; 15230 15231 synchronized (mPackages) { 15232 // If this is a new install and we see that we've already run verification for this 15233 // package, we have nothing to do: it means the state was restored from backup. 15234 if (!replacing) { 15235 IntentFilterVerificationInfo ivi = 15236 mSettings.getIntentFilterVerificationLPr(packageName); 15237 if (ivi != null) { 15238 if (DEBUG_DOMAIN_VERIFICATION) { 15239 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15240 + ivi.getStatusString()); 15241 } 15242 return; 15243 } 15244 } 15245 15246 // If any filters need to be verified, then all need to be. 15247 boolean needToVerify = false; 15248 for (PackageParser.Activity a : pkg.activities) { 15249 for (ActivityIntentInfo filter : a.intents) { 15250 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15251 if (DEBUG_DOMAIN_VERIFICATION) { 15252 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15253 } 15254 needToVerify = true; 15255 break; 15256 } 15257 } 15258 } 15259 15260 if (needToVerify) { 15261 final int verificationId = mIntentFilterVerificationToken++; 15262 for (PackageParser.Activity a : pkg.activities) { 15263 for (ActivityIntentInfo filter : a.intents) { 15264 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15265 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15266 "Verification needed for IntentFilter:" + filter.toString()); 15267 mIntentFilterVerifier.addOneIntentFilterVerification( 15268 verifierUid, userId, verificationId, filter, packageName); 15269 count++; 15270 } 15271 } 15272 } 15273 } 15274 } 15275 15276 if (count > 0) { 15277 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15278 + " IntentFilter verification" + (count > 1 ? "s" : "") 15279 + " for userId:" + userId); 15280 mIntentFilterVerifier.startVerifications(userId); 15281 } else { 15282 if (DEBUG_DOMAIN_VERIFICATION) { 15283 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15284 } 15285 } 15286 } 15287 15288 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15289 final ComponentName cn = filter.activity.getComponentName(); 15290 final String packageName = cn.getPackageName(); 15291 15292 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15293 packageName); 15294 if (ivi == null) { 15295 return true; 15296 } 15297 int status = ivi.getStatus(); 15298 switch (status) { 15299 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15300 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15301 return true; 15302 15303 default: 15304 // Nothing to do 15305 return false; 15306 } 15307 } 15308 15309 private static boolean isMultiArch(ApplicationInfo info) { 15310 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15311 } 15312 15313 private static boolean isExternal(PackageParser.Package pkg) { 15314 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15315 } 15316 15317 private static boolean isExternal(PackageSetting ps) { 15318 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15319 } 15320 15321 private static boolean isEphemeral(PackageParser.Package pkg) { 15322 return pkg.applicationInfo.isEphemeralApp(); 15323 } 15324 15325 private static boolean isEphemeral(PackageSetting ps) { 15326 return ps.pkg != null && isEphemeral(ps.pkg); 15327 } 15328 15329 private static boolean isSystemApp(PackageParser.Package pkg) { 15330 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15331 } 15332 15333 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15334 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15335 } 15336 15337 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15338 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15339 } 15340 15341 private static boolean isSystemApp(PackageSetting ps) { 15342 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15343 } 15344 15345 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15346 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15347 } 15348 15349 private int packageFlagsToInstallFlags(PackageSetting ps) { 15350 int installFlags = 0; 15351 if (isEphemeral(ps)) { 15352 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15353 } 15354 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15355 // This existing package was an external ASEC install when we have 15356 // the external flag without a UUID 15357 installFlags |= PackageManager.INSTALL_EXTERNAL; 15358 } 15359 if (ps.isForwardLocked()) { 15360 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15361 } 15362 return installFlags; 15363 } 15364 15365 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15366 if (isExternal(pkg)) { 15367 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15368 return StorageManager.UUID_PRIMARY_PHYSICAL; 15369 } else { 15370 return pkg.volumeUuid; 15371 } 15372 } else { 15373 return StorageManager.UUID_PRIVATE_INTERNAL; 15374 } 15375 } 15376 15377 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15378 if (isExternal(pkg)) { 15379 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15380 return mSettings.getExternalVersion(); 15381 } else { 15382 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15383 } 15384 } else { 15385 return mSettings.getInternalVersion(); 15386 } 15387 } 15388 15389 private void deleteTempPackageFiles() { 15390 final FilenameFilter filter = new FilenameFilter() { 15391 public boolean accept(File dir, String name) { 15392 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15393 } 15394 }; 15395 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15396 file.delete(); 15397 } 15398 } 15399 15400 @Override 15401 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15402 int flags) { 15403 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15404 flags); 15405 } 15406 15407 @Override 15408 public void deletePackage(final String packageName, 15409 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15410 mContext.enforceCallingOrSelfPermission( 15411 android.Manifest.permission.DELETE_PACKAGES, null); 15412 Preconditions.checkNotNull(packageName); 15413 Preconditions.checkNotNull(observer); 15414 final int uid = Binder.getCallingUid(); 15415 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15416 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15417 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15418 mContext.enforceCallingOrSelfPermission( 15419 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15420 "deletePackage for user " + userId); 15421 } 15422 15423 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15424 try { 15425 observer.onPackageDeleted(packageName, 15426 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15427 } catch (RemoteException re) { 15428 } 15429 return; 15430 } 15431 15432 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15433 try { 15434 observer.onPackageDeleted(packageName, 15435 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15436 } catch (RemoteException re) { 15437 } 15438 return; 15439 } 15440 15441 if (DEBUG_REMOVE) { 15442 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15443 + " deleteAllUsers: " + deleteAllUsers ); 15444 } 15445 // Queue up an async operation since the package deletion may take a little while. 15446 mHandler.post(new Runnable() { 15447 public void run() { 15448 mHandler.removeCallbacks(this); 15449 int returnCode; 15450 if (!deleteAllUsers) { 15451 returnCode = deletePackageX(packageName, userId, deleteFlags); 15452 } else { 15453 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15454 // If nobody is blocking uninstall, proceed with delete for all users 15455 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15456 returnCode = deletePackageX(packageName, userId, deleteFlags); 15457 } else { 15458 // Otherwise uninstall individually for users with blockUninstalls=false 15459 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15460 for (int userId : users) { 15461 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15462 returnCode = deletePackageX(packageName, userId, userFlags); 15463 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15464 Slog.w(TAG, "Package delete failed for user " + userId 15465 + ", returnCode " + returnCode); 15466 } 15467 } 15468 } 15469 // The app has only been marked uninstalled for certain users. 15470 // We still need to report that delete was blocked 15471 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15472 } 15473 } 15474 try { 15475 observer.onPackageDeleted(packageName, returnCode, null); 15476 } catch (RemoteException e) { 15477 Log.i(TAG, "Observer no longer exists."); 15478 } //end catch 15479 } //end run 15480 }); 15481 } 15482 15483 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15484 int[] result = EMPTY_INT_ARRAY; 15485 for (int userId : userIds) { 15486 if (getBlockUninstallForUser(packageName, userId)) { 15487 result = ArrayUtils.appendInt(result, userId); 15488 } 15489 } 15490 return result; 15491 } 15492 15493 @Override 15494 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15495 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15496 } 15497 15498 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15499 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15500 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15501 try { 15502 if (dpm != null) { 15503 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15504 /* callingUserOnly =*/ false); 15505 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15506 : deviceOwnerComponentName.getPackageName(); 15507 // Does the package contains the device owner? 15508 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15509 // this check is probably not needed, since DO should be registered as a device 15510 // admin on some user too. (Original bug for this: b/17657954) 15511 if (packageName.equals(deviceOwnerPackageName)) { 15512 return true; 15513 } 15514 // Does it contain a device admin for any user? 15515 int[] users; 15516 if (userId == UserHandle.USER_ALL) { 15517 users = sUserManager.getUserIds(); 15518 } else { 15519 users = new int[]{userId}; 15520 } 15521 for (int i = 0; i < users.length; ++i) { 15522 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15523 return true; 15524 } 15525 } 15526 } 15527 } catch (RemoteException e) { 15528 } 15529 return false; 15530 } 15531 15532 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15533 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15534 } 15535 15536 /** 15537 * This method is an internal method that could be get invoked either 15538 * to delete an installed package or to clean up a failed installation. 15539 * After deleting an installed package, a broadcast is sent to notify any 15540 * listeners that the package has been removed. For cleaning up a failed 15541 * installation, the broadcast is not necessary since the package's 15542 * installation wouldn't have sent the initial broadcast either 15543 * The key steps in deleting a package are 15544 * deleting the package information in internal structures like mPackages, 15545 * deleting the packages base directories through installd 15546 * updating mSettings to reflect current status 15547 * persisting settings for later use 15548 * sending a broadcast if necessary 15549 */ 15550 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15551 final PackageRemovedInfo info = new PackageRemovedInfo(); 15552 final boolean res; 15553 15554 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15555 ? UserHandle.ALL : new UserHandle(userId); 15556 15557 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15558 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15559 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15560 } 15561 15562 PackageSetting uninstalledPs = null; 15563 15564 // for the uninstall-updates case and restricted profiles, remember the per- 15565 // user handle installed state 15566 int[] allUsers; 15567 synchronized (mPackages) { 15568 uninstalledPs = mSettings.mPackages.get(packageName); 15569 if (uninstalledPs == null) { 15570 Slog.w(TAG, "Not removing non-existent package " + packageName); 15571 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15572 } 15573 allUsers = sUserManager.getUserIds(); 15574 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15575 } 15576 15577 synchronized (mInstallLock) { 15578 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15579 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15580 "deletePackageX")) { 15581 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15582 deleteFlags | REMOVE_CHATTY, info, true, null); 15583 } 15584 synchronized (mPackages) { 15585 if (res) { 15586 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15587 } 15588 } 15589 } 15590 15591 if (res) { 15592 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15593 info.sendPackageRemovedBroadcasts(killApp); 15594 info.sendSystemPackageUpdatedBroadcasts(); 15595 info.sendSystemPackageAppearedBroadcasts(); 15596 } 15597 // Force a gc here. 15598 Runtime.getRuntime().gc(); 15599 // Delete the resources here after sending the broadcast to let 15600 // other processes clean up before deleting resources. 15601 if (info.args != null) { 15602 synchronized (mInstallLock) { 15603 info.args.doPostDeleteLI(true); 15604 } 15605 } 15606 15607 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15608 } 15609 15610 class PackageRemovedInfo { 15611 String removedPackage; 15612 int uid = -1; 15613 int removedAppId = -1; 15614 int[] origUsers; 15615 int[] removedUsers = null; 15616 boolean isRemovedPackageSystemUpdate = false; 15617 boolean isUpdate; 15618 boolean dataRemoved; 15619 boolean removedForAllUsers; 15620 // Clean up resources deleted packages. 15621 InstallArgs args = null; 15622 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15623 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15624 15625 void sendPackageRemovedBroadcasts(boolean killApp) { 15626 sendPackageRemovedBroadcastInternal(killApp); 15627 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15628 for (int i = 0; i < childCount; i++) { 15629 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15630 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15631 } 15632 } 15633 15634 void sendSystemPackageUpdatedBroadcasts() { 15635 if (isRemovedPackageSystemUpdate) { 15636 sendSystemPackageUpdatedBroadcastsInternal(); 15637 final int childCount = (removedChildPackages != null) 15638 ? removedChildPackages.size() : 0; 15639 for (int i = 0; i < childCount; i++) { 15640 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15641 if (childInfo.isRemovedPackageSystemUpdate) { 15642 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15643 } 15644 } 15645 } 15646 } 15647 15648 void sendSystemPackageAppearedBroadcasts() { 15649 final int packageCount = (appearedChildPackages != null) 15650 ? appearedChildPackages.size() : 0; 15651 for (int i = 0; i < packageCount; i++) { 15652 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15653 for (int userId : installedInfo.newUsers) { 15654 sendPackageAddedForUser(installedInfo.name, true, 15655 UserHandle.getAppId(installedInfo.uid), userId); 15656 } 15657 } 15658 } 15659 15660 private void sendSystemPackageUpdatedBroadcastsInternal() { 15661 Bundle extras = new Bundle(2); 15662 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15663 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15664 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15665 extras, 0, null, null, null); 15666 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15667 extras, 0, null, null, null); 15668 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15669 null, 0, removedPackage, null, null); 15670 } 15671 15672 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15673 Bundle extras = new Bundle(2); 15674 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15675 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15676 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15677 if (isUpdate || isRemovedPackageSystemUpdate) { 15678 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15679 } 15680 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15681 if (removedPackage != null) { 15682 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15683 extras, 0, null, null, removedUsers); 15684 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15685 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15686 removedPackage, extras, 0, null, null, removedUsers); 15687 } 15688 } 15689 if (removedAppId >= 0) { 15690 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15691 removedUsers); 15692 } 15693 } 15694 } 15695 15696 /* 15697 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15698 * flag is not set, the data directory is removed as well. 15699 * make sure this flag is set for partially installed apps. If not its meaningless to 15700 * delete a partially installed application. 15701 */ 15702 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15703 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15704 String packageName = ps.name; 15705 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15706 // Retrieve object to delete permissions for shared user later on 15707 final PackageParser.Package deletedPkg; 15708 final PackageSetting deletedPs; 15709 // reader 15710 synchronized (mPackages) { 15711 deletedPkg = mPackages.get(packageName); 15712 deletedPs = mSettings.mPackages.get(packageName); 15713 if (outInfo != null) { 15714 outInfo.removedPackage = packageName; 15715 outInfo.removedUsers = deletedPs != null 15716 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15717 : null; 15718 } 15719 } 15720 15721 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15722 15723 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15724 final PackageParser.Package resolvedPkg; 15725 if (deletedPkg != null) { 15726 resolvedPkg = deletedPkg; 15727 } else { 15728 // We don't have a parsed package when it lives on an ejected 15729 // adopted storage device, so fake something together 15730 resolvedPkg = new PackageParser.Package(ps.name); 15731 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15732 } 15733 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15734 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15735 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15736 if (outInfo != null) { 15737 outInfo.dataRemoved = true; 15738 } 15739 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15740 } 15741 15742 // writer 15743 synchronized (mPackages) { 15744 if (deletedPs != null) { 15745 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15746 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15747 clearDefaultBrowserIfNeeded(packageName); 15748 if (outInfo != null) { 15749 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15750 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15751 } 15752 updatePermissionsLPw(deletedPs.name, null, 0); 15753 if (deletedPs.sharedUser != null) { 15754 // Remove permissions associated with package. Since runtime 15755 // permissions are per user we have to kill the removed package 15756 // or packages running under the shared user of the removed 15757 // package if revoking the permissions requested only by the removed 15758 // package is successful and this causes a change in gids. 15759 for (int userId : UserManagerService.getInstance().getUserIds()) { 15760 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15761 userId); 15762 if (userIdToKill == UserHandle.USER_ALL 15763 || userIdToKill >= UserHandle.USER_SYSTEM) { 15764 // If gids changed for this user, kill all affected packages. 15765 mHandler.post(new Runnable() { 15766 @Override 15767 public void run() { 15768 // This has to happen with no lock held. 15769 killApplication(deletedPs.name, deletedPs.appId, 15770 KILL_APP_REASON_GIDS_CHANGED); 15771 } 15772 }); 15773 break; 15774 } 15775 } 15776 } 15777 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15778 } 15779 // make sure to preserve per-user disabled state if this removal was just 15780 // a downgrade of a system app to the factory package 15781 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15782 if (DEBUG_REMOVE) { 15783 Slog.d(TAG, "Propagating install state across downgrade"); 15784 } 15785 for (int userId : allUserHandles) { 15786 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15787 if (DEBUG_REMOVE) { 15788 Slog.d(TAG, " user " + userId + " => " + installed); 15789 } 15790 ps.setInstalled(installed, userId); 15791 } 15792 } 15793 } 15794 // can downgrade to reader 15795 if (writeSettings) { 15796 // Save settings now 15797 mSettings.writeLPr(); 15798 } 15799 } 15800 if (outInfo != null) { 15801 // A user ID was deleted here. Go through all users and remove it 15802 // from KeyStore. 15803 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15804 } 15805 } 15806 15807 static boolean locationIsPrivileged(File path) { 15808 try { 15809 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15810 .getCanonicalPath(); 15811 return path.getCanonicalPath().startsWith(privilegedAppDir); 15812 } catch (IOException e) { 15813 Slog.e(TAG, "Unable to access code path " + path); 15814 } 15815 return false; 15816 } 15817 15818 /* 15819 * Tries to delete system package. 15820 */ 15821 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15822 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15823 boolean writeSettings) { 15824 if (deletedPs.parentPackageName != null) { 15825 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15826 return false; 15827 } 15828 15829 final boolean applyUserRestrictions 15830 = (allUserHandles != null) && (outInfo.origUsers != null); 15831 final PackageSetting disabledPs; 15832 // Confirm if the system package has been updated 15833 // An updated system app can be deleted. This will also have to restore 15834 // the system pkg from system partition 15835 // reader 15836 synchronized (mPackages) { 15837 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15838 } 15839 15840 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15841 + " disabledPs=" + disabledPs); 15842 15843 if (disabledPs == null) { 15844 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15845 return false; 15846 } else if (DEBUG_REMOVE) { 15847 Slog.d(TAG, "Deleting system pkg from data partition"); 15848 } 15849 15850 if (DEBUG_REMOVE) { 15851 if (applyUserRestrictions) { 15852 Slog.d(TAG, "Remembering install states:"); 15853 for (int userId : allUserHandles) { 15854 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15855 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15856 } 15857 } 15858 } 15859 15860 // Delete the updated package 15861 outInfo.isRemovedPackageSystemUpdate = true; 15862 if (outInfo.removedChildPackages != null) { 15863 final int childCount = (deletedPs.childPackageNames != null) 15864 ? deletedPs.childPackageNames.size() : 0; 15865 for (int i = 0; i < childCount; i++) { 15866 String childPackageName = deletedPs.childPackageNames.get(i); 15867 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15868 .contains(childPackageName)) { 15869 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15870 childPackageName); 15871 if (childInfo != null) { 15872 childInfo.isRemovedPackageSystemUpdate = true; 15873 } 15874 } 15875 } 15876 } 15877 15878 if (disabledPs.versionCode < deletedPs.versionCode) { 15879 // Delete data for downgrades 15880 flags &= ~PackageManager.DELETE_KEEP_DATA; 15881 } else { 15882 // Preserve data by setting flag 15883 flags |= PackageManager.DELETE_KEEP_DATA; 15884 } 15885 15886 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15887 outInfo, writeSettings, disabledPs.pkg); 15888 if (!ret) { 15889 return false; 15890 } 15891 15892 // writer 15893 synchronized (mPackages) { 15894 // Reinstate the old system package 15895 enableSystemPackageLPw(disabledPs.pkg); 15896 // Remove any native libraries from the upgraded package. 15897 removeNativeBinariesLI(deletedPs); 15898 } 15899 15900 // Install the system package 15901 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15902 int parseFlags = mDefParseFlags 15903 | PackageParser.PARSE_MUST_BE_APK 15904 | PackageParser.PARSE_IS_SYSTEM 15905 | PackageParser.PARSE_IS_SYSTEM_DIR; 15906 if (locationIsPrivileged(disabledPs.codePath)) { 15907 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15908 } 15909 15910 final PackageParser.Package newPkg; 15911 try { 15912 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15913 } catch (PackageManagerException e) { 15914 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15915 + e.getMessage()); 15916 return false; 15917 } 15918 15919 prepareAppDataAfterInstallLIF(newPkg); 15920 15921 // writer 15922 synchronized (mPackages) { 15923 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15924 15925 // Propagate the permissions state as we do not want to drop on the floor 15926 // runtime permissions. The update permissions method below will take 15927 // care of removing obsolete permissions and grant install permissions. 15928 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15929 updatePermissionsLPw(newPkg.packageName, newPkg, 15930 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15931 15932 if (applyUserRestrictions) { 15933 if (DEBUG_REMOVE) { 15934 Slog.d(TAG, "Propagating install state across reinstall"); 15935 } 15936 for (int userId : allUserHandles) { 15937 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15938 if (DEBUG_REMOVE) { 15939 Slog.d(TAG, " user " + userId + " => " + installed); 15940 } 15941 ps.setInstalled(installed, userId); 15942 15943 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15944 } 15945 // Regardless of writeSettings we need to ensure that this restriction 15946 // state propagation is persisted 15947 mSettings.writeAllUsersPackageRestrictionsLPr(); 15948 } 15949 // can downgrade to reader here 15950 if (writeSettings) { 15951 mSettings.writeLPr(); 15952 } 15953 } 15954 return true; 15955 } 15956 15957 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15958 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15959 PackageRemovedInfo outInfo, boolean writeSettings, 15960 PackageParser.Package replacingPackage) { 15961 synchronized (mPackages) { 15962 if (outInfo != null) { 15963 outInfo.uid = ps.appId; 15964 } 15965 15966 if (outInfo != null && outInfo.removedChildPackages != null) { 15967 final int childCount = (ps.childPackageNames != null) 15968 ? ps.childPackageNames.size() : 0; 15969 for (int i = 0; i < childCount; i++) { 15970 String childPackageName = ps.childPackageNames.get(i); 15971 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15972 if (childPs == null) { 15973 return false; 15974 } 15975 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15976 childPackageName); 15977 if (childInfo != null) { 15978 childInfo.uid = childPs.appId; 15979 } 15980 } 15981 } 15982 } 15983 15984 // Delete package data from internal structures and also remove data if flag is set 15985 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15986 15987 // Delete the child packages data 15988 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15989 for (int i = 0; i < childCount; i++) { 15990 PackageSetting childPs; 15991 synchronized (mPackages) { 15992 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15993 } 15994 if (childPs != null) { 15995 PackageRemovedInfo childOutInfo = (outInfo != null 15996 && outInfo.removedChildPackages != null) 15997 ? outInfo.removedChildPackages.get(childPs.name) : null; 15998 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15999 && (replacingPackage != null 16000 && !replacingPackage.hasChildPackage(childPs.name)) 16001 ? flags & ~DELETE_KEEP_DATA : flags; 16002 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16003 deleteFlags, writeSettings); 16004 } 16005 } 16006 16007 // Delete application code and resources only for parent packages 16008 if (ps.parentPackageName == null) { 16009 if (deleteCodeAndResources && (outInfo != null)) { 16010 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16011 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16012 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16013 } 16014 } 16015 16016 return true; 16017 } 16018 16019 @Override 16020 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16021 int userId) { 16022 mContext.enforceCallingOrSelfPermission( 16023 android.Manifest.permission.DELETE_PACKAGES, null); 16024 synchronized (mPackages) { 16025 PackageSetting ps = mSettings.mPackages.get(packageName); 16026 if (ps == null) { 16027 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16028 return false; 16029 } 16030 if (!ps.getInstalled(userId)) { 16031 // Can't block uninstall for an app that is not installed or enabled. 16032 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16033 return false; 16034 } 16035 ps.setBlockUninstall(blockUninstall, userId); 16036 mSettings.writePackageRestrictionsLPr(userId); 16037 } 16038 return true; 16039 } 16040 16041 @Override 16042 public boolean getBlockUninstallForUser(String packageName, int userId) { 16043 synchronized (mPackages) { 16044 PackageSetting ps = mSettings.mPackages.get(packageName); 16045 if (ps == null) { 16046 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16047 return false; 16048 } 16049 return ps.getBlockUninstall(userId); 16050 } 16051 } 16052 16053 @Override 16054 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16055 int callingUid = Binder.getCallingUid(); 16056 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16057 throw new SecurityException( 16058 "setRequiredForSystemUser can only be run by the system or root"); 16059 } 16060 synchronized (mPackages) { 16061 PackageSetting ps = mSettings.mPackages.get(packageName); 16062 if (ps == null) { 16063 Log.w(TAG, "Package doesn't exist: " + packageName); 16064 return false; 16065 } 16066 if (systemUserApp) { 16067 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16068 } else { 16069 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16070 } 16071 mSettings.writeLPr(); 16072 } 16073 return true; 16074 } 16075 16076 /* 16077 * This method handles package deletion in general 16078 */ 16079 private boolean deletePackageLIF(String packageName, UserHandle user, 16080 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16081 PackageRemovedInfo outInfo, boolean writeSettings, 16082 PackageParser.Package replacingPackage) { 16083 if (packageName == null) { 16084 Slog.w(TAG, "Attempt to delete null packageName."); 16085 return false; 16086 } 16087 16088 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16089 16090 PackageSetting ps; 16091 16092 synchronized (mPackages) { 16093 ps = mSettings.mPackages.get(packageName); 16094 if (ps == null) { 16095 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16096 return false; 16097 } 16098 16099 if (ps.parentPackageName != null && (!isSystemApp(ps) 16100 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16101 if (DEBUG_REMOVE) { 16102 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16103 + ((user == null) ? UserHandle.USER_ALL : user)); 16104 } 16105 final int removedUserId = (user != null) ? user.getIdentifier() 16106 : UserHandle.USER_ALL; 16107 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16108 return false; 16109 } 16110 markPackageUninstalledForUserLPw(ps, user); 16111 scheduleWritePackageRestrictionsLocked(user); 16112 return true; 16113 } 16114 } 16115 16116 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16117 && user.getIdentifier() != UserHandle.USER_ALL)) { 16118 // The caller is asking that the package only be deleted for a single 16119 // user. To do this, we just mark its uninstalled state and delete 16120 // its data. If this is a system app, we only allow this to happen if 16121 // they have set the special DELETE_SYSTEM_APP which requests different 16122 // semantics than normal for uninstalling system apps. 16123 markPackageUninstalledForUserLPw(ps, user); 16124 16125 if (!isSystemApp(ps)) { 16126 // Do not uninstall the APK if an app should be cached 16127 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16128 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16129 // Other user still have this package installed, so all 16130 // we need to do is clear this user's data and save that 16131 // it is uninstalled. 16132 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16133 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16134 return false; 16135 } 16136 scheduleWritePackageRestrictionsLocked(user); 16137 return true; 16138 } else { 16139 // We need to set it back to 'installed' so the uninstall 16140 // broadcasts will be sent correctly. 16141 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16142 ps.setInstalled(true, user.getIdentifier()); 16143 } 16144 } else { 16145 // This is a system app, so we assume that the 16146 // other users still have this package installed, so all 16147 // we need to do is clear this user's data and save that 16148 // it is uninstalled. 16149 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16150 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16151 return false; 16152 } 16153 scheduleWritePackageRestrictionsLocked(user); 16154 return true; 16155 } 16156 } 16157 16158 // If we are deleting a composite package for all users, keep track 16159 // of result for each child. 16160 if (ps.childPackageNames != null && outInfo != null) { 16161 synchronized (mPackages) { 16162 final int childCount = ps.childPackageNames.size(); 16163 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16164 for (int i = 0; i < childCount; i++) { 16165 String childPackageName = ps.childPackageNames.get(i); 16166 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16167 childInfo.removedPackage = childPackageName; 16168 outInfo.removedChildPackages.put(childPackageName, childInfo); 16169 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16170 if (childPs != null) { 16171 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16172 } 16173 } 16174 } 16175 } 16176 16177 boolean ret = false; 16178 if (isSystemApp(ps)) { 16179 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16180 // When an updated system application is deleted we delete the existing resources 16181 // as well and fall back to existing code in system partition 16182 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16183 } else { 16184 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16185 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16186 outInfo, writeSettings, replacingPackage); 16187 } 16188 16189 // Take a note whether we deleted the package for all users 16190 if (outInfo != null) { 16191 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16192 if (outInfo.removedChildPackages != null) { 16193 synchronized (mPackages) { 16194 final int childCount = outInfo.removedChildPackages.size(); 16195 for (int i = 0; i < childCount; i++) { 16196 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16197 if (childInfo != null) { 16198 childInfo.removedForAllUsers = mPackages.get( 16199 childInfo.removedPackage) == null; 16200 } 16201 } 16202 } 16203 } 16204 // If we uninstalled an update to a system app there may be some 16205 // child packages that appeared as they are declared in the system 16206 // app but were not declared in the update. 16207 if (isSystemApp(ps)) { 16208 synchronized (mPackages) { 16209 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16210 final int childCount = (updatedPs.childPackageNames != null) 16211 ? updatedPs.childPackageNames.size() : 0; 16212 for (int i = 0; i < childCount; i++) { 16213 String childPackageName = updatedPs.childPackageNames.get(i); 16214 if (outInfo.removedChildPackages == null 16215 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16216 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16217 if (childPs == null) { 16218 continue; 16219 } 16220 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16221 installRes.name = childPackageName; 16222 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16223 installRes.pkg = mPackages.get(childPackageName); 16224 installRes.uid = childPs.pkg.applicationInfo.uid; 16225 if (outInfo.appearedChildPackages == null) { 16226 outInfo.appearedChildPackages = new ArrayMap<>(); 16227 } 16228 outInfo.appearedChildPackages.put(childPackageName, installRes); 16229 } 16230 } 16231 } 16232 } 16233 } 16234 16235 return ret; 16236 } 16237 16238 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16239 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16240 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16241 for (int nextUserId : userIds) { 16242 if (DEBUG_REMOVE) { 16243 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16244 } 16245 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16246 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16247 false /*hidden*/, false /*suspended*/, null, null, null, 16248 false /*blockUninstall*/, 16249 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16250 } 16251 } 16252 16253 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16254 PackageRemovedInfo outInfo) { 16255 final PackageParser.Package pkg; 16256 synchronized (mPackages) { 16257 pkg = mPackages.get(ps.name); 16258 } 16259 16260 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16261 : new int[] {userId}; 16262 for (int nextUserId : userIds) { 16263 if (DEBUG_REMOVE) { 16264 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16265 + nextUserId); 16266 } 16267 16268 destroyAppDataLIF(pkg, userId, 16269 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16270 destroyAppProfilesLIF(pkg, userId); 16271 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16272 schedulePackageCleaning(ps.name, nextUserId, false); 16273 synchronized (mPackages) { 16274 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16275 scheduleWritePackageRestrictionsLocked(nextUserId); 16276 } 16277 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16278 } 16279 } 16280 16281 if (outInfo != null) { 16282 outInfo.removedPackage = ps.name; 16283 outInfo.removedAppId = ps.appId; 16284 outInfo.removedUsers = userIds; 16285 } 16286 16287 return true; 16288 } 16289 16290 private final class ClearStorageConnection implements ServiceConnection { 16291 IMediaContainerService mContainerService; 16292 16293 @Override 16294 public void onServiceConnected(ComponentName name, IBinder service) { 16295 synchronized (this) { 16296 mContainerService = IMediaContainerService.Stub.asInterface(service); 16297 notifyAll(); 16298 } 16299 } 16300 16301 @Override 16302 public void onServiceDisconnected(ComponentName name) { 16303 } 16304 } 16305 16306 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16307 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16308 16309 final boolean mounted; 16310 if (Environment.isExternalStorageEmulated()) { 16311 mounted = true; 16312 } else { 16313 final String status = Environment.getExternalStorageState(); 16314 16315 mounted = status.equals(Environment.MEDIA_MOUNTED) 16316 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16317 } 16318 16319 if (!mounted) { 16320 return; 16321 } 16322 16323 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16324 int[] users; 16325 if (userId == UserHandle.USER_ALL) { 16326 users = sUserManager.getUserIds(); 16327 } else { 16328 users = new int[] { userId }; 16329 } 16330 final ClearStorageConnection conn = new ClearStorageConnection(); 16331 if (mContext.bindServiceAsUser( 16332 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16333 try { 16334 for (int curUser : users) { 16335 long timeout = SystemClock.uptimeMillis() + 5000; 16336 synchronized (conn) { 16337 long now = SystemClock.uptimeMillis(); 16338 while (conn.mContainerService == null && now < timeout) { 16339 try { 16340 conn.wait(timeout - now); 16341 } catch (InterruptedException e) { 16342 } 16343 } 16344 } 16345 if (conn.mContainerService == null) { 16346 return; 16347 } 16348 16349 final UserEnvironment userEnv = new UserEnvironment(curUser); 16350 clearDirectory(conn.mContainerService, 16351 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16352 if (allData) { 16353 clearDirectory(conn.mContainerService, 16354 userEnv.buildExternalStorageAppDataDirs(packageName)); 16355 clearDirectory(conn.mContainerService, 16356 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16357 } 16358 } 16359 } finally { 16360 mContext.unbindService(conn); 16361 } 16362 } 16363 } 16364 16365 @Override 16366 public void clearApplicationProfileData(String packageName) { 16367 enforceSystemOrRoot("Only the system can clear all profile data"); 16368 16369 final PackageParser.Package pkg; 16370 synchronized (mPackages) { 16371 pkg = mPackages.get(packageName); 16372 } 16373 16374 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16375 synchronized (mInstallLock) { 16376 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16377 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16378 true /* removeBaseMarker */); 16379 } 16380 } 16381 } 16382 16383 @Override 16384 public void clearApplicationUserData(final String packageName, 16385 final IPackageDataObserver observer, final int userId) { 16386 mContext.enforceCallingOrSelfPermission( 16387 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16388 16389 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16390 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16391 16392 final DevicePolicyManagerInternal dpmi = LocalServices 16393 .getService(DevicePolicyManagerInternal.class); 16394 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16395 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16396 } 16397 // Queue up an async operation since the package deletion may take a little while. 16398 mHandler.post(new Runnable() { 16399 public void run() { 16400 mHandler.removeCallbacks(this); 16401 final boolean succeeded; 16402 try (PackageFreezer freezer = freezePackage(packageName, 16403 "clearApplicationUserData")) { 16404 synchronized (mInstallLock) { 16405 succeeded = clearApplicationUserDataLIF(packageName, userId); 16406 } 16407 clearExternalStorageDataSync(packageName, userId, true); 16408 } 16409 if (succeeded) { 16410 // invoke DeviceStorageMonitor's update method to clear any notifications 16411 DeviceStorageMonitorInternal dsm = LocalServices 16412 .getService(DeviceStorageMonitorInternal.class); 16413 if (dsm != null) { 16414 dsm.checkMemory(); 16415 } 16416 } 16417 if(observer != null) { 16418 try { 16419 observer.onRemoveCompleted(packageName, succeeded); 16420 } catch (RemoteException e) { 16421 Log.i(TAG, "Observer no longer exists."); 16422 } 16423 } //end if observer 16424 } //end run 16425 }); 16426 } 16427 16428 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16429 if (packageName == null) { 16430 Slog.w(TAG, "Attempt to delete null packageName."); 16431 return false; 16432 } 16433 16434 // Try finding details about the requested package 16435 PackageParser.Package pkg; 16436 synchronized (mPackages) { 16437 pkg = mPackages.get(packageName); 16438 if (pkg == null) { 16439 final PackageSetting ps = mSettings.mPackages.get(packageName); 16440 if (ps != null) { 16441 pkg = ps.pkg; 16442 } 16443 } 16444 16445 if (pkg == null) { 16446 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16447 return false; 16448 } 16449 16450 PackageSetting ps = (PackageSetting) pkg.mExtras; 16451 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16452 } 16453 16454 clearAppDataLIF(pkg, userId, 16455 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16456 16457 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16458 removeKeystoreDataIfNeeded(userId, appId); 16459 16460 UserManagerInternal umInternal = getUserManagerInternal(); 16461 final int flags; 16462 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16463 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16464 } else if (umInternal.isUserRunning(userId)) { 16465 flags = StorageManager.FLAG_STORAGE_DE; 16466 } else { 16467 flags = 0; 16468 } 16469 prepareAppDataContentsLIF(pkg, userId, flags); 16470 16471 return true; 16472 } 16473 16474 /** 16475 * Reverts user permission state changes (permissions and flags) in 16476 * all packages for a given user. 16477 * 16478 * @param userId The device user for which to do a reset. 16479 */ 16480 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16481 final int packageCount = mPackages.size(); 16482 for (int i = 0; i < packageCount; i++) { 16483 PackageParser.Package pkg = mPackages.valueAt(i); 16484 PackageSetting ps = (PackageSetting) pkg.mExtras; 16485 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16486 } 16487 } 16488 16489 private void resetNetworkPolicies(int userId) { 16490 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16491 } 16492 16493 /** 16494 * Reverts user permission state changes (permissions and flags). 16495 * 16496 * @param ps The package for which to reset. 16497 * @param userId The device user for which to do a reset. 16498 */ 16499 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16500 final PackageSetting ps, final int userId) { 16501 if (ps.pkg == null) { 16502 return; 16503 } 16504 16505 // These are flags that can change base on user actions. 16506 final int userSettableMask = FLAG_PERMISSION_USER_SET 16507 | FLAG_PERMISSION_USER_FIXED 16508 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16509 | FLAG_PERMISSION_REVIEW_REQUIRED; 16510 16511 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16512 | FLAG_PERMISSION_POLICY_FIXED; 16513 16514 boolean writeInstallPermissions = false; 16515 boolean writeRuntimePermissions = false; 16516 16517 final int permissionCount = ps.pkg.requestedPermissions.size(); 16518 for (int i = 0; i < permissionCount; i++) { 16519 String permission = ps.pkg.requestedPermissions.get(i); 16520 16521 BasePermission bp = mSettings.mPermissions.get(permission); 16522 if (bp == null) { 16523 continue; 16524 } 16525 16526 // If shared user we just reset the state to which only this app contributed. 16527 if (ps.sharedUser != null) { 16528 boolean used = false; 16529 final int packageCount = ps.sharedUser.packages.size(); 16530 for (int j = 0; j < packageCount; j++) { 16531 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16532 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16533 && pkg.pkg.requestedPermissions.contains(permission)) { 16534 used = true; 16535 break; 16536 } 16537 } 16538 if (used) { 16539 continue; 16540 } 16541 } 16542 16543 PermissionsState permissionsState = ps.getPermissionsState(); 16544 16545 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16546 16547 // Always clear the user settable flags. 16548 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16549 bp.name) != null; 16550 // If permission review is enabled and this is a legacy app, mark the 16551 // permission as requiring a review as this is the initial state. 16552 int flags = 0; 16553 if (Build.PERMISSIONS_REVIEW_REQUIRED 16554 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16555 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16556 } 16557 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16558 if (hasInstallState) { 16559 writeInstallPermissions = true; 16560 } else { 16561 writeRuntimePermissions = true; 16562 } 16563 } 16564 16565 // Below is only runtime permission handling. 16566 if (!bp.isRuntime()) { 16567 continue; 16568 } 16569 16570 // Never clobber system or policy. 16571 if ((oldFlags & policyOrSystemFlags) != 0) { 16572 continue; 16573 } 16574 16575 // If this permission was granted by default, make sure it is. 16576 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16577 if (permissionsState.grantRuntimePermission(bp, userId) 16578 != PERMISSION_OPERATION_FAILURE) { 16579 writeRuntimePermissions = true; 16580 } 16581 // If permission review is enabled the permissions for a legacy apps 16582 // are represented as constantly granted runtime ones, so don't revoke. 16583 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16584 // Otherwise, reset the permission. 16585 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16586 switch (revokeResult) { 16587 case PERMISSION_OPERATION_SUCCESS: 16588 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16589 writeRuntimePermissions = true; 16590 final int appId = ps.appId; 16591 mHandler.post(new Runnable() { 16592 @Override 16593 public void run() { 16594 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16595 } 16596 }); 16597 } break; 16598 } 16599 } 16600 } 16601 16602 // Synchronously write as we are taking permissions away. 16603 if (writeRuntimePermissions) { 16604 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16605 } 16606 16607 // Synchronously write as we are taking permissions away. 16608 if (writeInstallPermissions) { 16609 mSettings.writeLPr(); 16610 } 16611 } 16612 16613 /** 16614 * Remove entries from the keystore daemon. Will only remove it if the 16615 * {@code appId} is valid. 16616 */ 16617 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16618 if (appId < 0) { 16619 return; 16620 } 16621 16622 final KeyStore keyStore = KeyStore.getInstance(); 16623 if (keyStore != null) { 16624 if (userId == UserHandle.USER_ALL) { 16625 for (final int individual : sUserManager.getUserIds()) { 16626 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16627 } 16628 } else { 16629 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16630 } 16631 } else { 16632 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16633 } 16634 } 16635 16636 @Override 16637 public void deleteApplicationCacheFiles(final String packageName, 16638 final IPackageDataObserver observer) { 16639 final int userId = UserHandle.getCallingUserId(); 16640 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16641 } 16642 16643 @Override 16644 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16645 final IPackageDataObserver observer) { 16646 mContext.enforceCallingOrSelfPermission( 16647 android.Manifest.permission.DELETE_CACHE_FILES, null); 16648 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16649 /* requireFullPermission= */ true, /* checkShell= */ false, 16650 "delete application cache files"); 16651 16652 final PackageParser.Package pkg; 16653 synchronized (mPackages) { 16654 pkg = mPackages.get(packageName); 16655 } 16656 16657 // Queue up an async operation since the package deletion may take a little while. 16658 mHandler.post(new Runnable() { 16659 public void run() { 16660 synchronized (mInstallLock) { 16661 final int flags = StorageManager.FLAG_STORAGE_DE 16662 | StorageManager.FLAG_STORAGE_CE; 16663 // We're only clearing cache files, so we don't care if the 16664 // app is unfrozen and still able to run 16665 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16666 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16667 } 16668 clearExternalStorageDataSync(packageName, userId, false); 16669 if (observer != null) { 16670 try { 16671 observer.onRemoveCompleted(packageName, true); 16672 } catch (RemoteException e) { 16673 Log.i(TAG, "Observer no longer exists."); 16674 } 16675 } 16676 } 16677 }); 16678 } 16679 16680 @Override 16681 public void getPackageSizeInfo(final String packageName, int userHandle, 16682 final IPackageStatsObserver observer) { 16683 mContext.enforceCallingOrSelfPermission( 16684 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16685 if (packageName == null) { 16686 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16687 } 16688 16689 PackageStats stats = new PackageStats(packageName, userHandle); 16690 16691 /* 16692 * Queue up an async operation since the package measurement may take a 16693 * little while. 16694 */ 16695 Message msg = mHandler.obtainMessage(INIT_COPY); 16696 msg.obj = new MeasureParams(stats, observer); 16697 mHandler.sendMessage(msg); 16698 } 16699 16700 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16701 final PackageSetting ps; 16702 synchronized (mPackages) { 16703 ps = mSettings.mPackages.get(packageName); 16704 if (ps == null) { 16705 Slog.w(TAG, "Failed to find settings for " + packageName); 16706 return false; 16707 } 16708 } 16709 try { 16710 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16711 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16712 ps.getCeDataInode(userId), ps.codePathString, stats); 16713 } catch (InstallerException e) { 16714 Slog.w(TAG, String.valueOf(e)); 16715 return false; 16716 } 16717 16718 // For now, ignore code size of packages on system partition 16719 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16720 stats.codeSize = 0; 16721 } 16722 16723 return true; 16724 } 16725 16726 private int getUidTargetSdkVersionLockedLPr(int uid) { 16727 Object obj = mSettings.getUserIdLPr(uid); 16728 if (obj instanceof SharedUserSetting) { 16729 final SharedUserSetting sus = (SharedUserSetting) obj; 16730 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16731 final Iterator<PackageSetting> it = sus.packages.iterator(); 16732 while (it.hasNext()) { 16733 final PackageSetting ps = it.next(); 16734 if (ps.pkg != null) { 16735 int v = ps.pkg.applicationInfo.targetSdkVersion; 16736 if (v < vers) vers = v; 16737 } 16738 } 16739 return vers; 16740 } else if (obj instanceof PackageSetting) { 16741 final PackageSetting ps = (PackageSetting) obj; 16742 if (ps.pkg != null) { 16743 return ps.pkg.applicationInfo.targetSdkVersion; 16744 } 16745 } 16746 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16747 } 16748 16749 @Override 16750 public void addPreferredActivity(IntentFilter filter, int match, 16751 ComponentName[] set, ComponentName activity, int userId) { 16752 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16753 "Adding preferred"); 16754 } 16755 16756 private void addPreferredActivityInternal(IntentFilter filter, int match, 16757 ComponentName[] set, ComponentName activity, boolean always, int userId, 16758 String opname) { 16759 // writer 16760 int callingUid = Binder.getCallingUid(); 16761 enforceCrossUserPermission(callingUid, userId, 16762 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16763 if (filter.countActions() == 0) { 16764 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16765 return; 16766 } 16767 synchronized (mPackages) { 16768 if (mContext.checkCallingOrSelfPermission( 16769 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16770 != PackageManager.PERMISSION_GRANTED) { 16771 if (getUidTargetSdkVersionLockedLPr(callingUid) 16772 < Build.VERSION_CODES.FROYO) { 16773 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16774 + callingUid); 16775 return; 16776 } 16777 mContext.enforceCallingOrSelfPermission( 16778 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16779 } 16780 16781 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16782 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16783 + userId + ":"); 16784 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16785 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16786 scheduleWritePackageRestrictionsLocked(userId); 16787 } 16788 } 16789 16790 @Override 16791 public void replacePreferredActivity(IntentFilter filter, int match, 16792 ComponentName[] set, ComponentName activity, int userId) { 16793 if (filter.countActions() != 1) { 16794 throw new IllegalArgumentException( 16795 "replacePreferredActivity expects filter to have only 1 action."); 16796 } 16797 if (filter.countDataAuthorities() != 0 16798 || filter.countDataPaths() != 0 16799 || filter.countDataSchemes() > 1 16800 || filter.countDataTypes() != 0) { 16801 throw new IllegalArgumentException( 16802 "replacePreferredActivity expects filter to have no data authorities, " + 16803 "paths, or types; and at most one scheme."); 16804 } 16805 16806 final int callingUid = Binder.getCallingUid(); 16807 enforceCrossUserPermission(callingUid, userId, 16808 true /* requireFullPermission */, false /* checkShell */, 16809 "replace preferred activity"); 16810 synchronized (mPackages) { 16811 if (mContext.checkCallingOrSelfPermission( 16812 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16813 != PackageManager.PERMISSION_GRANTED) { 16814 if (getUidTargetSdkVersionLockedLPr(callingUid) 16815 < Build.VERSION_CODES.FROYO) { 16816 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16817 + Binder.getCallingUid()); 16818 return; 16819 } 16820 mContext.enforceCallingOrSelfPermission( 16821 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16822 } 16823 16824 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16825 if (pir != null) { 16826 // Get all of the existing entries that exactly match this filter. 16827 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16828 if (existing != null && existing.size() == 1) { 16829 PreferredActivity cur = existing.get(0); 16830 if (DEBUG_PREFERRED) { 16831 Slog.i(TAG, "Checking replace of preferred:"); 16832 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16833 if (!cur.mPref.mAlways) { 16834 Slog.i(TAG, " -- CUR; not mAlways!"); 16835 } else { 16836 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16837 Slog.i(TAG, " -- CUR: mSet=" 16838 + Arrays.toString(cur.mPref.mSetComponents)); 16839 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16840 Slog.i(TAG, " -- NEW: mMatch=" 16841 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16842 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16843 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16844 } 16845 } 16846 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16847 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16848 && cur.mPref.sameSet(set)) { 16849 // Setting the preferred activity to what it happens to be already 16850 if (DEBUG_PREFERRED) { 16851 Slog.i(TAG, "Replacing with same preferred activity " 16852 + cur.mPref.mShortComponent + " for user " 16853 + userId + ":"); 16854 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16855 } 16856 return; 16857 } 16858 } 16859 16860 if (existing != null) { 16861 if (DEBUG_PREFERRED) { 16862 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16863 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16864 } 16865 for (int i = 0; i < existing.size(); i++) { 16866 PreferredActivity pa = existing.get(i); 16867 if (DEBUG_PREFERRED) { 16868 Slog.i(TAG, "Removing existing preferred activity " 16869 + pa.mPref.mComponent + ":"); 16870 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16871 } 16872 pir.removeFilter(pa); 16873 } 16874 } 16875 } 16876 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16877 "Replacing preferred"); 16878 } 16879 } 16880 16881 @Override 16882 public void clearPackagePreferredActivities(String packageName) { 16883 final int uid = Binder.getCallingUid(); 16884 // writer 16885 synchronized (mPackages) { 16886 PackageParser.Package pkg = mPackages.get(packageName); 16887 if (pkg == null || pkg.applicationInfo.uid != uid) { 16888 if (mContext.checkCallingOrSelfPermission( 16889 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16890 != PackageManager.PERMISSION_GRANTED) { 16891 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16892 < Build.VERSION_CODES.FROYO) { 16893 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16894 + Binder.getCallingUid()); 16895 return; 16896 } 16897 mContext.enforceCallingOrSelfPermission( 16898 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16899 } 16900 } 16901 16902 int user = UserHandle.getCallingUserId(); 16903 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16904 scheduleWritePackageRestrictionsLocked(user); 16905 } 16906 } 16907 } 16908 16909 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16910 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16911 ArrayList<PreferredActivity> removed = null; 16912 boolean changed = false; 16913 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16914 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16915 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16916 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16917 continue; 16918 } 16919 Iterator<PreferredActivity> it = pir.filterIterator(); 16920 while (it.hasNext()) { 16921 PreferredActivity pa = it.next(); 16922 // Mark entry for removal only if it matches the package name 16923 // and the entry is of type "always". 16924 if (packageName == null || 16925 (pa.mPref.mComponent.getPackageName().equals(packageName) 16926 && pa.mPref.mAlways)) { 16927 if (removed == null) { 16928 removed = new ArrayList<PreferredActivity>(); 16929 } 16930 removed.add(pa); 16931 } 16932 } 16933 if (removed != null) { 16934 for (int j=0; j<removed.size(); j++) { 16935 PreferredActivity pa = removed.get(j); 16936 pir.removeFilter(pa); 16937 } 16938 changed = true; 16939 } 16940 } 16941 return changed; 16942 } 16943 16944 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16945 private void clearIntentFilterVerificationsLPw(int userId) { 16946 final int packageCount = mPackages.size(); 16947 for (int i = 0; i < packageCount; i++) { 16948 PackageParser.Package pkg = mPackages.valueAt(i); 16949 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16950 } 16951 } 16952 16953 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16954 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16955 if (userId == UserHandle.USER_ALL) { 16956 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16957 sUserManager.getUserIds())) { 16958 for (int oneUserId : sUserManager.getUserIds()) { 16959 scheduleWritePackageRestrictionsLocked(oneUserId); 16960 } 16961 } 16962 } else { 16963 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16964 scheduleWritePackageRestrictionsLocked(userId); 16965 } 16966 } 16967 } 16968 16969 void clearDefaultBrowserIfNeeded(String packageName) { 16970 for (int oneUserId : sUserManager.getUserIds()) { 16971 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16972 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16973 if (packageName.equals(defaultBrowserPackageName)) { 16974 setDefaultBrowserPackageName(null, oneUserId); 16975 } 16976 } 16977 } 16978 16979 @Override 16980 public void resetApplicationPreferences(int userId) { 16981 mContext.enforceCallingOrSelfPermission( 16982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16983 final long identity = Binder.clearCallingIdentity(); 16984 // writer 16985 try { 16986 synchronized (mPackages) { 16987 clearPackagePreferredActivitiesLPw(null, userId); 16988 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16989 // TODO: We have to reset the default SMS and Phone. This requires 16990 // significant refactoring to keep all default apps in the package 16991 // manager (cleaner but more work) or have the services provide 16992 // callbacks to the package manager to request a default app reset. 16993 applyFactoryDefaultBrowserLPw(userId); 16994 clearIntentFilterVerificationsLPw(userId); 16995 primeDomainVerificationsLPw(userId); 16996 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16997 scheduleWritePackageRestrictionsLocked(userId); 16998 } 16999 resetNetworkPolicies(userId); 17000 } finally { 17001 Binder.restoreCallingIdentity(identity); 17002 } 17003 } 17004 17005 @Override 17006 public int getPreferredActivities(List<IntentFilter> outFilters, 17007 List<ComponentName> outActivities, String packageName) { 17008 17009 int num = 0; 17010 final int userId = UserHandle.getCallingUserId(); 17011 // reader 17012 synchronized (mPackages) { 17013 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17014 if (pir != null) { 17015 final Iterator<PreferredActivity> it = pir.filterIterator(); 17016 while (it.hasNext()) { 17017 final PreferredActivity pa = it.next(); 17018 if (packageName == null 17019 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17020 && pa.mPref.mAlways)) { 17021 if (outFilters != null) { 17022 outFilters.add(new IntentFilter(pa)); 17023 } 17024 if (outActivities != null) { 17025 outActivities.add(pa.mPref.mComponent); 17026 } 17027 } 17028 } 17029 } 17030 } 17031 17032 return num; 17033 } 17034 17035 @Override 17036 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17037 int userId) { 17038 int callingUid = Binder.getCallingUid(); 17039 if (callingUid != Process.SYSTEM_UID) { 17040 throw new SecurityException( 17041 "addPersistentPreferredActivity can only be run by the system"); 17042 } 17043 if (filter.countActions() == 0) { 17044 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17045 return; 17046 } 17047 synchronized (mPackages) { 17048 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17049 ":"); 17050 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17051 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17052 new PersistentPreferredActivity(filter, activity)); 17053 scheduleWritePackageRestrictionsLocked(userId); 17054 } 17055 } 17056 17057 @Override 17058 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17059 int callingUid = Binder.getCallingUid(); 17060 if (callingUid != Process.SYSTEM_UID) { 17061 throw new SecurityException( 17062 "clearPackagePersistentPreferredActivities can only be run by the system"); 17063 } 17064 ArrayList<PersistentPreferredActivity> removed = null; 17065 boolean changed = false; 17066 synchronized (mPackages) { 17067 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17068 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17069 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17070 .valueAt(i); 17071 if (userId != thisUserId) { 17072 continue; 17073 } 17074 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17075 while (it.hasNext()) { 17076 PersistentPreferredActivity ppa = it.next(); 17077 // Mark entry for removal only if it matches the package name. 17078 if (ppa.mComponent.getPackageName().equals(packageName)) { 17079 if (removed == null) { 17080 removed = new ArrayList<PersistentPreferredActivity>(); 17081 } 17082 removed.add(ppa); 17083 } 17084 } 17085 if (removed != null) { 17086 for (int j=0; j<removed.size(); j++) { 17087 PersistentPreferredActivity ppa = removed.get(j); 17088 ppir.removeFilter(ppa); 17089 } 17090 changed = true; 17091 } 17092 } 17093 17094 if (changed) { 17095 scheduleWritePackageRestrictionsLocked(userId); 17096 } 17097 } 17098 } 17099 17100 /** 17101 * Common machinery for picking apart a restored XML blob and passing 17102 * it to a caller-supplied functor to be applied to the running system. 17103 */ 17104 private void restoreFromXml(XmlPullParser parser, int userId, 17105 String expectedStartTag, BlobXmlRestorer functor) 17106 throws IOException, XmlPullParserException { 17107 int type; 17108 while ((type = parser.next()) != XmlPullParser.START_TAG 17109 && type != XmlPullParser.END_DOCUMENT) { 17110 } 17111 if (type != XmlPullParser.START_TAG) { 17112 // oops didn't find a start tag?! 17113 if (DEBUG_BACKUP) { 17114 Slog.e(TAG, "Didn't find start tag during restore"); 17115 } 17116 return; 17117 } 17118Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17119 // this is supposed to be TAG_PREFERRED_BACKUP 17120 if (!expectedStartTag.equals(parser.getName())) { 17121 if (DEBUG_BACKUP) { 17122 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17123 } 17124 return; 17125 } 17126 17127 // skip interfering stuff, then we're aligned with the backing implementation 17128 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17129Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17130 functor.apply(parser, userId); 17131 } 17132 17133 private interface BlobXmlRestorer { 17134 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17135 } 17136 17137 /** 17138 * Non-Binder method, support for the backup/restore mechanism: write the 17139 * full set of preferred activities in its canonical XML format. Returns the 17140 * XML output as a byte array, or null if there is none. 17141 */ 17142 @Override 17143 public byte[] getPreferredActivityBackup(int userId) { 17144 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17145 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17146 } 17147 17148 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17149 try { 17150 final XmlSerializer serializer = new FastXmlSerializer(); 17151 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17152 serializer.startDocument(null, true); 17153 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17154 17155 synchronized (mPackages) { 17156 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17157 } 17158 17159 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17160 serializer.endDocument(); 17161 serializer.flush(); 17162 } catch (Exception e) { 17163 if (DEBUG_BACKUP) { 17164 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17165 } 17166 return null; 17167 } 17168 17169 return dataStream.toByteArray(); 17170 } 17171 17172 @Override 17173 public void restorePreferredActivities(byte[] backup, int userId) { 17174 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17175 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17176 } 17177 17178 try { 17179 final XmlPullParser parser = Xml.newPullParser(); 17180 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17181 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17182 new BlobXmlRestorer() { 17183 @Override 17184 public void apply(XmlPullParser parser, int userId) 17185 throws XmlPullParserException, IOException { 17186 synchronized (mPackages) { 17187 mSettings.readPreferredActivitiesLPw(parser, userId); 17188 } 17189 } 17190 } ); 17191 } catch (Exception e) { 17192 if (DEBUG_BACKUP) { 17193 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17194 } 17195 } 17196 } 17197 17198 /** 17199 * Non-Binder method, support for the backup/restore mechanism: write the 17200 * default browser (etc) settings in its canonical XML format. Returns the default 17201 * browser XML representation as a byte array, or null if there is none. 17202 */ 17203 @Override 17204 public byte[] getDefaultAppsBackup(int userId) { 17205 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17206 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17207 } 17208 17209 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17210 try { 17211 final XmlSerializer serializer = new FastXmlSerializer(); 17212 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17213 serializer.startDocument(null, true); 17214 serializer.startTag(null, TAG_DEFAULT_APPS); 17215 17216 synchronized (mPackages) { 17217 mSettings.writeDefaultAppsLPr(serializer, userId); 17218 } 17219 17220 serializer.endTag(null, TAG_DEFAULT_APPS); 17221 serializer.endDocument(); 17222 serializer.flush(); 17223 } catch (Exception e) { 17224 if (DEBUG_BACKUP) { 17225 Slog.e(TAG, "Unable to write default apps for backup", e); 17226 } 17227 return null; 17228 } 17229 17230 return dataStream.toByteArray(); 17231 } 17232 17233 @Override 17234 public void restoreDefaultApps(byte[] backup, int userId) { 17235 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17236 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17237 } 17238 17239 try { 17240 final XmlPullParser parser = Xml.newPullParser(); 17241 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17242 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17243 new BlobXmlRestorer() { 17244 @Override 17245 public void apply(XmlPullParser parser, int userId) 17246 throws XmlPullParserException, IOException { 17247 synchronized (mPackages) { 17248 mSettings.readDefaultAppsLPw(parser, userId); 17249 } 17250 } 17251 } ); 17252 } catch (Exception e) { 17253 if (DEBUG_BACKUP) { 17254 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17255 } 17256 } 17257 } 17258 17259 @Override 17260 public byte[] getIntentFilterVerificationBackup(int userId) { 17261 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17262 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17263 } 17264 17265 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17266 try { 17267 final XmlSerializer serializer = new FastXmlSerializer(); 17268 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17269 serializer.startDocument(null, true); 17270 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17271 17272 synchronized (mPackages) { 17273 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17274 } 17275 17276 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17277 serializer.endDocument(); 17278 serializer.flush(); 17279 } catch (Exception e) { 17280 if (DEBUG_BACKUP) { 17281 Slog.e(TAG, "Unable to write default apps for backup", e); 17282 } 17283 return null; 17284 } 17285 17286 return dataStream.toByteArray(); 17287 } 17288 17289 @Override 17290 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17291 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17292 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17293 } 17294 17295 try { 17296 final XmlPullParser parser = Xml.newPullParser(); 17297 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17298 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17299 new BlobXmlRestorer() { 17300 @Override 17301 public void apply(XmlPullParser parser, int userId) 17302 throws XmlPullParserException, IOException { 17303 synchronized (mPackages) { 17304 mSettings.readAllDomainVerificationsLPr(parser, userId); 17305 mSettings.writeLPr(); 17306 } 17307 } 17308 } ); 17309 } catch (Exception e) { 17310 if (DEBUG_BACKUP) { 17311 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17312 } 17313 } 17314 } 17315 17316 @Override 17317 public byte[] getPermissionGrantBackup(int userId) { 17318 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17319 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17320 } 17321 17322 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17323 try { 17324 final XmlSerializer serializer = new FastXmlSerializer(); 17325 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17326 serializer.startDocument(null, true); 17327 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17328 17329 synchronized (mPackages) { 17330 serializeRuntimePermissionGrantsLPr(serializer, userId); 17331 } 17332 17333 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17334 serializer.endDocument(); 17335 serializer.flush(); 17336 } catch (Exception e) { 17337 if (DEBUG_BACKUP) { 17338 Slog.e(TAG, "Unable to write default apps for backup", e); 17339 } 17340 return null; 17341 } 17342 17343 return dataStream.toByteArray(); 17344 } 17345 17346 @Override 17347 public void restorePermissionGrants(byte[] backup, int userId) { 17348 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17349 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17350 } 17351 17352 try { 17353 final XmlPullParser parser = Xml.newPullParser(); 17354 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17355 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17356 new BlobXmlRestorer() { 17357 @Override 17358 public void apply(XmlPullParser parser, int userId) 17359 throws XmlPullParserException, IOException { 17360 synchronized (mPackages) { 17361 processRestoredPermissionGrantsLPr(parser, userId); 17362 } 17363 } 17364 } ); 17365 } catch (Exception e) { 17366 if (DEBUG_BACKUP) { 17367 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17368 } 17369 } 17370 } 17371 17372 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17373 throws IOException { 17374 serializer.startTag(null, TAG_ALL_GRANTS); 17375 17376 final int N = mSettings.mPackages.size(); 17377 for (int i = 0; i < N; i++) { 17378 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17379 boolean pkgGrantsKnown = false; 17380 17381 PermissionsState packagePerms = ps.getPermissionsState(); 17382 17383 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17384 final int grantFlags = state.getFlags(); 17385 // only look at grants that are not system/policy fixed 17386 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17387 final boolean isGranted = state.isGranted(); 17388 // And only back up the user-twiddled state bits 17389 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17390 final String packageName = mSettings.mPackages.keyAt(i); 17391 if (!pkgGrantsKnown) { 17392 serializer.startTag(null, TAG_GRANT); 17393 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17394 pkgGrantsKnown = true; 17395 } 17396 17397 final boolean userSet = 17398 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17399 final boolean userFixed = 17400 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17401 final boolean revoke = 17402 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17403 17404 serializer.startTag(null, TAG_PERMISSION); 17405 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17406 if (isGranted) { 17407 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17408 } 17409 if (userSet) { 17410 serializer.attribute(null, ATTR_USER_SET, "true"); 17411 } 17412 if (userFixed) { 17413 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17414 } 17415 if (revoke) { 17416 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17417 } 17418 serializer.endTag(null, TAG_PERMISSION); 17419 } 17420 } 17421 } 17422 17423 if (pkgGrantsKnown) { 17424 serializer.endTag(null, TAG_GRANT); 17425 } 17426 } 17427 17428 serializer.endTag(null, TAG_ALL_GRANTS); 17429 } 17430 17431 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17432 throws XmlPullParserException, IOException { 17433 String pkgName = null; 17434 int outerDepth = parser.getDepth(); 17435 int type; 17436 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17437 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17438 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17439 continue; 17440 } 17441 17442 final String tagName = parser.getName(); 17443 if (tagName.equals(TAG_GRANT)) { 17444 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17445 if (DEBUG_BACKUP) { 17446 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17447 } 17448 } else if (tagName.equals(TAG_PERMISSION)) { 17449 17450 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17451 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17452 17453 int newFlagSet = 0; 17454 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17455 newFlagSet |= FLAG_PERMISSION_USER_SET; 17456 } 17457 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17458 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17459 } 17460 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17461 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17462 } 17463 if (DEBUG_BACKUP) { 17464 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17465 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17466 } 17467 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17468 if (ps != null) { 17469 // Already installed so we apply the grant immediately 17470 if (DEBUG_BACKUP) { 17471 Slog.v(TAG, " + already installed; applying"); 17472 } 17473 PermissionsState perms = ps.getPermissionsState(); 17474 BasePermission bp = mSettings.mPermissions.get(permName); 17475 if (bp != null) { 17476 if (isGranted) { 17477 perms.grantRuntimePermission(bp, userId); 17478 } 17479 if (newFlagSet != 0) { 17480 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17481 } 17482 } 17483 } else { 17484 // Need to wait for post-restore install to apply the grant 17485 if (DEBUG_BACKUP) { 17486 Slog.v(TAG, " - not yet installed; saving for later"); 17487 } 17488 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17489 isGranted, newFlagSet, userId); 17490 } 17491 } else { 17492 PackageManagerService.reportSettingsProblem(Log.WARN, 17493 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17494 XmlUtils.skipCurrentTag(parser); 17495 } 17496 } 17497 17498 scheduleWriteSettingsLocked(); 17499 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17500 } 17501 17502 @Override 17503 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17504 int sourceUserId, int targetUserId, int flags) { 17505 mContext.enforceCallingOrSelfPermission( 17506 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17507 int callingUid = Binder.getCallingUid(); 17508 enforceOwnerRights(ownerPackage, callingUid); 17509 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17510 if (intentFilter.countActions() == 0) { 17511 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17512 return; 17513 } 17514 synchronized (mPackages) { 17515 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17516 ownerPackage, targetUserId, flags); 17517 CrossProfileIntentResolver resolver = 17518 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17519 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17520 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17521 if (existing != null) { 17522 int size = existing.size(); 17523 for (int i = 0; i < size; i++) { 17524 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17525 return; 17526 } 17527 } 17528 } 17529 resolver.addFilter(newFilter); 17530 scheduleWritePackageRestrictionsLocked(sourceUserId); 17531 } 17532 } 17533 17534 @Override 17535 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17536 mContext.enforceCallingOrSelfPermission( 17537 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17538 int callingUid = Binder.getCallingUid(); 17539 enforceOwnerRights(ownerPackage, callingUid); 17540 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17541 synchronized (mPackages) { 17542 CrossProfileIntentResolver resolver = 17543 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17544 ArraySet<CrossProfileIntentFilter> set = 17545 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17546 for (CrossProfileIntentFilter filter : set) { 17547 if (filter.getOwnerPackage().equals(ownerPackage)) { 17548 resolver.removeFilter(filter); 17549 } 17550 } 17551 scheduleWritePackageRestrictionsLocked(sourceUserId); 17552 } 17553 } 17554 17555 // Enforcing that callingUid is owning pkg on userId 17556 private void enforceOwnerRights(String pkg, int callingUid) { 17557 // The system owns everything. 17558 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17559 return; 17560 } 17561 int callingUserId = UserHandle.getUserId(callingUid); 17562 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17563 if (pi == null) { 17564 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17565 + callingUserId); 17566 } 17567 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17568 throw new SecurityException("Calling uid " + callingUid 17569 + " does not own package " + pkg); 17570 } 17571 } 17572 17573 @Override 17574 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17575 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17576 } 17577 17578 private Intent getHomeIntent() { 17579 Intent intent = new Intent(Intent.ACTION_MAIN); 17580 intent.addCategory(Intent.CATEGORY_HOME); 17581 return intent; 17582 } 17583 17584 private IntentFilter getHomeFilter() { 17585 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17586 filter.addCategory(Intent.CATEGORY_HOME); 17587 filter.addCategory(Intent.CATEGORY_DEFAULT); 17588 return filter; 17589 } 17590 17591 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17592 int userId) { 17593 Intent intent = getHomeIntent(); 17594 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17595 PackageManager.GET_META_DATA, userId); 17596 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17597 true, false, false, userId); 17598 17599 allHomeCandidates.clear(); 17600 if (list != null) { 17601 for (ResolveInfo ri : list) { 17602 allHomeCandidates.add(ri); 17603 } 17604 } 17605 return (preferred == null || preferred.activityInfo == null) 17606 ? null 17607 : new ComponentName(preferred.activityInfo.packageName, 17608 preferred.activityInfo.name); 17609 } 17610 17611 @Override 17612 public void setHomeActivity(ComponentName comp, int userId) { 17613 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17614 getHomeActivitiesAsUser(homeActivities, userId); 17615 17616 boolean found = false; 17617 17618 final int size = homeActivities.size(); 17619 final ComponentName[] set = new ComponentName[size]; 17620 for (int i = 0; i < size; i++) { 17621 final ResolveInfo candidate = homeActivities.get(i); 17622 final ActivityInfo info = candidate.activityInfo; 17623 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17624 set[i] = activityName; 17625 if (!found && activityName.equals(comp)) { 17626 found = true; 17627 } 17628 } 17629 if (!found) { 17630 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17631 + userId); 17632 } 17633 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17634 set, comp, userId); 17635 } 17636 17637 private @Nullable String getSetupWizardPackageName() { 17638 final Intent intent = new Intent(Intent.ACTION_MAIN); 17639 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17640 17641 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17642 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17643 | MATCH_DISABLED_COMPONENTS, 17644 UserHandle.myUserId()); 17645 if (matches.size() == 1) { 17646 return matches.get(0).getComponentInfo().packageName; 17647 } else { 17648 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17649 + ": matches=" + matches); 17650 return null; 17651 } 17652 } 17653 17654 @Override 17655 public void setApplicationEnabledSetting(String appPackageName, 17656 int newState, int flags, int userId, String callingPackage) { 17657 if (!sUserManager.exists(userId)) return; 17658 if (callingPackage == null) { 17659 callingPackage = Integer.toString(Binder.getCallingUid()); 17660 } 17661 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17662 } 17663 17664 @Override 17665 public void setComponentEnabledSetting(ComponentName componentName, 17666 int newState, int flags, int userId) { 17667 if (!sUserManager.exists(userId)) return; 17668 setEnabledSetting(componentName.getPackageName(), 17669 componentName.getClassName(), newState, flags, userId, null); 17670 } 17671 17672 private void setEnabledSetting(final String packageName, String className, int newState, 17673 final int flags, int userId, String callingPackage) { 17674 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17675 || newState == COMPONENT_ENABLED_STATE_ENABLED 17676 || newState == COMPONENT_ENABLED_STATE_DISABLED 17677 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17678 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17679 throw new IllegalArgumentException("Invalid new component state: " 17680 + newState); 17681 } 17682 PackageSetting pkgSetting; 17683 final int uid = Binder.getCallingUid(); 17684 final int permission; 17685 if (uid == Process.SYSTEM_UID) { 17686 permission = PackageManager.PERMISSION_GRANTED; 17687 } else { 17688 permission = mContext.checkCallingOrSelfPermission( 17689 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17690 } 17691 enforceCrossUserPermission(uid, userId, 17692 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17693 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17694 boolean sendNow = false; 17695 boolean isApp = (className == null); 17696 String componentName = isApp ? packageName : className; 17697 int packageUid = -1; 17698 ArrayList<String> components; 17699 17700 // writer 17701 synchronized (mPackages) { 17702 pkgSetting = mSettings.mPackages.get(packageName); 17703 if (pkgSetting == null) { 17704 if (className == null) { 17705 throw new IllegalArgumentException("Unknown package: " + packageName); 17706 } 17707 throw new IllegalArgumentException( 17708 "Unknown component: " + packageName + "/" + className); 17709 } 17710 } 17711 17712 // Limit who can change which apps 17713 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17714 // Don't allow apps that don't have permission to modify other apps 17715 if (!allowedByPermission) { 17716 throw new SecurityException( 17717 "Permission Denial: attempt to change component state from pid=" 17718 + Binder.getCallingPid() 17719 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17720 } 17721 // Don't allow changing profile and device owners. Calling into DPMS, so no locking. 17722 final DevicePolicyManagerInternal dpmi = LocalServices 17723 .getService(DevicePolicyManagerInternal.class); 17724 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17725 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17726 } 17727 } 17728 17729 synchronized (mPackages) { 17730 if (uid == Process.SHELL_UID) { 17731 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17732 int oldState = pkgSetting.getEnabled(userId); 17733 if (className == null 17734 && 17735 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17736 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17737 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17738 && 17739 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17740 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17741 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17742 // ok 17743 } else { 17744 throw new SecurityException( 17745 "Shell cannot change component state for " + packageName + "/" 17746 + className + " to " + newState); 17747 } 17748 } 17749 if (className == null) { 17750 // We're dealing with an application/package level state change 17751 if (pkgSetting.getEnabled(userId) == newState) { 17752 // Nothing to do 17753 return; 17754 } 17755 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17756 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17757 // Don't care about who enables an app. 17758 callingPackage = null; 17759 } 17760 pkgSetting.setEnabled(newState, userId, callingPackage); 17761 // pkgSetting.pkg.mSetEnabled = newState; 17762 } else { 17763 // We're dealing with a component level state change 17764 // First, verify that this is a valid class name. 17765 PackageParser.Package pkg = pkgSetting.pkg; 17766 if (pkg == null || !pkg.hasComponentClassName(className)) { 17767 if (pkg != null && 17768 pkg.applicationInfo.targetSdkVersion >= 17769 Build.VERSION_CODES.JELLY_BEAN) { 17770 throw new IllegalArgumentException("Component class " + className 17771 + " does not exist in " + packageName); 17772 } else { 17773 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17774 + className + " does not exist in " + packageName); 17775 } 17776 } 17777 switch (newState) { 17778 case COMPONENT_ENABLED_STATE_ENABLED: 17779 if (!pkgSetting.enableComponentLPw(className, userId)) { 17780 return; 17781 } 17782 break; 17783 case COMPONENT_ENABLED_STATE_DISABLED: 17784 if (!pkgSetting.disableComponentLPw(className, userId)) { 17785 return; 17786 } 17787 break; 17788 case COMPONENT_ENABLED_STATE_DEFAULT: 17789 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17790 return; 17791 } 17792 break; 17793 default: 17794 Slog.e(TAG, "Invalid new component state: " + newState); 17795 return; 17796 } 17797 } 17798 scheduleWritePackageRestrictionsLocked(userId); 17799 components = mPendingBroadcasts.get(userId, packageName); 17800 final boolean newPackage = components == null; 17801 if (newPackage) { 17802 components = new ArrayList<String>(); 17803 } 17804 if (!components.contains(componentName)) { 17805 components.add(componentName); 17806 } 17807 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17808 sendNow = true; 17809 // Purge entry from pending broadcast list if another one exists already 17810 // since we are sending one right away. 17811 mPendingBroadcasts.remove(userId, packageName); 17812 } else { 17813 if (newPackage) { 17814 mPendingBroadcasts.put(userId, packageName, components); 17815 } 17816 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17817 // Schedule a message 17818 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17819 } 17820 } 17821 } 17822 17823 long callingId = Binder.clearCallingIdentity(); 17824 try { 17825 if (sendNow) { 17826 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17827 sendPackageChangedBroadcast(packageName, 17828 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17829 } 17830 } finally { 17831 Binder.restoreCallingIdentity(callingId); 17832 } 17833 } 17834 17835 @Override 17836 public void flushPackageRestrictionsAsUser(int userId) { 17837 if (!sUserManager.exists(userId)) { 17838 return; 17839 } 17840 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17841 false /* checkShell */, "flushPackageRestrictions"); 17842 synchronized (mPackages) { 17843 mSettings.writePackageRestrictionsLPr(userId); 17844 mDirtyUsers.remove(userId); 17845 if (mDirtyUsers.isEmpty()) { 17846 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17847 } 17848 } 17849 } 17850 17851 private void sendPackageChangedBroadcast(String packageName, 17852 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17853 if (DEBUG_INSTALL) 17854 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17855 + componentNames); 17856 Bundle extras = new Bundle(4); 17857 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17858 String nameList[] = new String[componentNames.size()]; 17859 componentNames.toArray(nameList); 17860 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17861 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17862 extras.putInt(Intent.EXTRA_UID, packageUid); 17863 // If this is not reporting a change of the overall package, then only send it 17864 // to registered receivers. We don't want to launch a swath of apps for every 17865 // little component state change. 17866 final int flags = !componentNames.contains(packageName) 17867 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17868 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17869 new int[] {UserHandle.getUserId(packageUid)}); 17870 } 17871 17872 @Override 17873 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17874 if (!sUserManager.exists(userId)) return; 17875 final int uid = Binder.getCallingUid(); 17876 final int permission = mContext.checkCallingOrSelfPermission( 17877 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17878 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17879 enforceCrossUserPermission(uid, userId, 17880 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17881 // writer 17882 synchronized (mPackages) { 17883 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17884 allowedByPermission, uid, userId)) { 17885 scheduleWritePackageRestrictionsLocked(userId); 17886 } 17887 } 17888 } 17889 17890 @Override 17891 public String getInstallerPackageName(String packageName) { 17892 // reader 17893 synchronized (mPackages) { 17894 return mSettings.getInstallerPackageNameLPr(packageName); 17895 } 17896 } 17897 17898 public boolean isOrphaned(String packageName) { 17899 // reader 17900 synchronized (mPackages) { 17901 return mSettings.isOrphaned(packageName); 17902 } 17903 } 17904 17905 @Override 17906 public int getApplicationEnabledSetting(String packageName, int userId) { 17907 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17908 int uid = Binder.getCallingUid(); 17909 enforceCrossUserPermission(uid, userId, 17910 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17911 // reader 17912 synchronized (mPackages) { 17913 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17914 } 17915 } 17916 17917 @Override 17918 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17919 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17920 int uid = Binder.getCallingUid(); 17921 enforceCrossUserPermission(uid, userId, 17922 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17923 // reader 17924 synchronized (mPackages) { 17925 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17926 } 17927 } 17928 17929 @Override 17930 public void enterSafeMode() { 17931 enforceSystemOrRoot("Only the system can request entering safe mode"); 17932 17933 if (!mSystemReady) { 17934 mSafeMode = true; 17935 } 17936 } 17937 17938 @Override 17939 public void systemReady() { 17940 mSystemReady = true; 17941 17942 // Read the compatibilty setting when the system is ready. 17943 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17944 mContext.getContentResolver(), 17945 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17946 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17947 if (DEBUG_SETTINGS) { 17948 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17949 } 17950 17951 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17952 17953 synchronized (mPackages) { 17954 // Verify that all of the preferred activity components actually 17955 // exist. It is possible for applications to be updated and at 17956 // that point remove a previously declared activity component that 17957 // had been set as a preferred activity. We try to clean this up 17958 // the next time we encounter that preferred activity, but it is 17959 // possible for the user flow to never be able to return to that 17960 // situation so here we do a sanity check to make sure we haven't 17961 // left any junk around. 17962 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17963 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17964 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17965 removed.clear(); 17966 for (PreferredActivity pa : pir.filterSet()) { 17967 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17968 removed.add(pa); 17969 } 17970 } 17971 if (removed.size() > 0) { 17972 for (int r=0; r<removed.size(); r++) { 17973 PreferredActivity pa = removed.get(r); 17974 Slog.w(TAG, "Removing dangling preferred activity: " 17975 + pa.mPref.mComponent); 17976 pir.removeFilter(pa); 17977 } 17978 mSettings.writePackageRestrictionsLPr( 17979 mSettings.mPreferredActivities.keyAt(i)); 17980 } 17981 } 17982 17983 for (int userId : UserManagerService.getInstance().getUserIds()) { 17984 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17985 grantPermissionsUserIds = ArrayUtils.appendInt( 17986 grantPermissionsUserIds, userId); 17987 } 17988 } 17989 } 17990 sUserManager.systemReady(); 17991 17992 // If we upgraded grant all default permissions before kicking off. 17993 for (int userId : grantPermissionsUserIds) { 17994 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17995 } 17996 17997 // Kick off any messages waiting for system ready 17998 if (mPostSystemReadyMessages != null) { 17999 for (Message msg : mPostSystemReadyMessages) { 18000 msg.sendToTarget(); 18001 } 18002 mPostSystemReadyMessages = null; 18003 } 18004 18005 // Watch for external volumes that come and go over time 18006 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18007 storage.registerListener(mStorageListener); 18008 18009 mInstallerService.systemReady(); 18010 mPackageDexOptimizer.systemReady(); 18011 18012 MountServiceInternal mountServiceInternal = LocalServices.getService( 18013 MountServiceInternal.class); 18014 mountServiceInternal.addExternalStoragePolicy( 18015 new MountServiceInternal.ExternalStorageMountPolicy() { 18016 @Override 18017 public int getMountMode(int uid, String packageName) { 18018 if (Process.isIsolated(uid)) { 18019 return Zygote.MOUNT_EXTERNAL_NONE; 18020 } 18021 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18022 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18023 } 18024 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18025 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18026 } 18027 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18028 return Zygote.MOUNT_EXTERNAL_READ; 18029 } 18030 return Zygote.MOUNT_EXTERNAL_WRITE; 18031 } 18032 18033 @Override 18034 public boolean hasExternalStorage(int uid, String packageName) { 18035 return true; 18036 } 18037 }); 18038 18039 // Now that we're mostly running, clean up stale users and apps 18040 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18041 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18042 } 18043 18044 @Override 18045 public boolean isSafeMode() { 18046 return mSafeMode; 18047 } 18048 18049 @Override 18050 public boolean hasSystemUidErrors() { 18051 return mHasSystemUidErrors; 18052 } 18053 18054 static String arrayToString(int[] array) { 18055 StringBuffer buf = new StringBuffer(128); 18056 buf.append('['); 18057 if (array != null) { 18058 for (int i=0; i<array.length; i++) { 18059 if (i > 0) buf.append(", "); 18060 buf.append(array[i]); 18061 } 18062 } 18063 buf.append(']'); 18064 return buf.toString(); 18065 } 18066 18067 static class DumpState { 18068 public static final int DUMP_LIBS = 1 << 0; 18069 public static final int DUMP_FEATURES = 1 << 1; 18070 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18071 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18072 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18073 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18074 public static final int DUMP_PERMISSIONS = 1 << 6; 18075 public static final int DUMP_PACKAGES = 1 << 7; 18076 public static final int DUMP_SHARED_USERS = 1 << 8; 18077 public static final int DUMP_MESSAGES = 1 << 9; 18078 public static final int DUMP_PROVIDERS = 1 << 10; 18079 public static final int DUMP_VERIFIERS = 1 << 11; 18080 public static final int DUMP_PREFERRED = 1 << 12; 18081 public static final int DUMP_PREFERRED_XML = 1 << 13; 18082 public static final int DUMP_KEYSETS = 1 << 14; 18083 public static final int DUMP_VERSION = 1 << 15; 18084 public static final int DUMP_INSTALLS = 1 << 16; 18085 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18086 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18087 public static final int DUMP_FROZEN = 1 << 19; 18088 public static final int DUMP_DEXOPT = 1 << 20; 18089 18090 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18091 18092 private int mTypes; 18093 18094 private int mOptions; 18095 18096 private boolean mTitlePrinted; 18097 18098 private SharedUserSetting mSharedUser; 18099 18100 public boolean isDumping(int type) { 18101 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18102 return true; 18103 } 18104 18105 return (mTypes & type) != 0; 18106 } 18107 18108 public void setDump(int type) { 18109 mTypes |= type; 18110 } 18111 18112 public boolean isOptionEnabled(int option) { 18113 return (mOptions & option) != 0; 18114 } 18115 18116 public void setOptionEnabled(int option) { 18117 mOptions |= option; 18118 } 18119 18120 public boolean onTitlePrinted() { 18121 final boolean printed = mTitlePrinted; 18122 mTitlePrinted = true; 18123 return printed; 18124 } 18125 18126 public boolean getTitlePrinted() { 18127 return mTitlePrinted; 18128 } 18129 18130 public void setTitlePrinted(boolean enabled) { 18131 mTitlePrinted = enabled; 18132 } 18133 18134 public SharedUserSetting getSharedUser() { 18135 return mSharedUser; 18136 } 18137 18138 public void setSharedUser(SharedUserSetting user) { 18139 mSharedUser = user; 18140 } 18141 } 18142 18143 @Override 18144 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18145 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18146 (new PackageManagerShellCommand(this)).exec( 18147 this, in, out, err, args, resultReceiver); 18148 } 18149 18150 @Override 18151 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18152 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18153 != PackageManager.PERMISSION_GRANTED) { 18154 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18155 + Binder.getCallingPid() 18156 + ", uid=" + Binder.getCallingUid() 18157 + " without permission " 18158 + android.Manifest.permission.DUMP); 18159 return; 18160 } 18161 18162 DumpState dumpState = new DumpState(); 18163 boolean fullPreferred = false; 18164 boolean checkin = false; 18165 18166 String packageName = null; 18167 ArraySet<String> permissionNames = null; 18168 18169 int opti = 0; 18170 while (opti < args.length) { 18171 String opt = args[opti]; 18172 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18173 break; 18174 } 18175 opti++; 18176 18177 if ("-a".equals(opt)) { 18178 // Right now we only know how to print all. 18179 } else if ("-h".equals(opt)) { 18180 pw.println("Package manager dump options:"); 18181 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18182 pw.println(" --checkin: dump for a checkin"); 18183 pw.println(" -f: print details of intent filters"); 18184 pw.println(" -h: print this help"); 18185 pw.println(" cmd may be one of:"); 18186 pw.println(" l[ibraries]: list known shared libraries"); 18187 pw.println(" f[eatures]: list device features"); 18188 pw.println(" k[eysets]: print known keysets"); 18189 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18190 pw.println(" perm[issions]: dump permissions"); 18191 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18192 pw.println(" pref[erred]: print preferred package settings"); 18193 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18194 pw.println(" prov[iders]: dump content providers"); 18195 pw.println(" p[ackages]: dump installed packages"); 18196 pw.println(" s[hared-users]: dump shared user IDs"); 18197 pw.println(" m[essages]: print collected runtime messages"); 18198 pw.println(" v[erifiers]: print package verifier info"); 18199 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18200 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18201 pw.println(" version: print database version info"); 18202 pw.println(" write: write current settings now"); 18203 pw.println(" installs: details about install sessions"); 18204 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18205 pw.println(" dexopt: dump dexopt state"); 18206 pw.println(" <package.name>: info about given package"); 18207 return; 18208 } else if ("--checkin".equals(opt)) { 18209 checkin = true; 18210 } else if ("-f".equals(opt)) { 18211 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18212 } else { 18213 pw.println("Unknown argument: " + opt + "; use -h for help"); 18214 } 18215 } 18216 18217 // Is the caller requesting to dump a particular piece of data? 18218 if (opti < args.length) { 18219 String cmd = args[opti]; 18220 opti++; 18221 // Is this a package name? 18222 if ("android".equals(cmd) || cmd.contains(".")) { 18223 packageName = cmd; 18224 // When dumping a single package, we always dump all of its 18225 // filter information since the amount of data will be reasonable. 18226 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18227 } else if ("check-permission".equals(cmd)) { 18228 if (opti >= args.length) { 18229 pw.println("Error: check-permission missing permission argument"); 18230 return; 18231 } 18232 String perm = args[opti]; 18233 opti++; 18234 if (opti >= args.length) { 18235 pw.println("Error: check-permission missing package argument"); 18236 return; 18237 } 18238 String pkg = args[opti]; 18239 opti++; 18240 int user = UserHandle.getUserId(Binder.getCallingUid()); 18241 if (opti < args.length) { 18242 try { 18243 user = Integer.parseInt(args[opti]); 18244 } catch (NumberFormatException e) { 18245 pw.println("Error: check-permission user argument is not a number: " 18246 + args[opti]); 18247 return; 18248 } 18249 } 18250 pw.println(checkPermission(perm, pkg, user)); 18251 return; 18252 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18253 dumpState.setDump(DumpState.DUMP_LIBS); 18254 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18255 dumpState.setDump(DumpState.DUMP_FEATURES); 18256 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18257 if (opti >= args.length) { 18258 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18259 | DumpState.DUMP_SERVICE_RESOLVERS 18260 | DumpState.DUMP_RECEIVER_RESOLVERS 18261 | DumpState.DUMP_CONTENT_RESOLVERS); 18262 } else { 18263 while (opti < args.length) { 18264 String name = args[opti]; 18265 if ("a".equals(name) || "activity".equals(name)) { 18266 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18267 } else if ("s".equals(name) || "service".equals(name)) { 18268 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18269 } else if ("r".equals(name) || "receiver".equals(name)) { 18270 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18271 } else if ("c".equals(name) || "content".equals(name)) { 18272 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18273 } else { 18274 pw.println("Error: unknown resolver table type: " + name); 18275 return; 18276 } 18277 opti++; 18278 } 18279 } 18280 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18281 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18282 } else if ("permission".equals(cmd)) { 18283 if (opti >= args.length) { 18284 pw.println("Error: permission requires permission name"); 18285 return; 18286 } 18287 permissionNames = new ArraySet<>(); 18288 while (opti < args.length) { 18289 permissionNames.add(args[opti]); 18290 opti++; 18291 } 18292 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18293 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18294 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18295 dumpState.setDump(DumpState.DUMP_PREFERRED); 18296 } else if ("preferred-xml".equals(cmd)) { 18297 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18298 if (opti < args.length && "--full".equals(args[opti])) { 18299 fullPreferred = true; 18300 opti++; 18301 } 18302 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18303 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18304 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18305 dumpState.setDump(DumpState.DUMP_PACKAGES); 18306 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18307 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18308 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18309 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18310 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18311 dumpState.setDump(DumpState.DUMP_MESSAGES); 18312 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18313 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18314 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18315 || "intent-filter-verifiers".equals(cmd)) { 18316 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18317 } else if ("version".equals(cmd)) { 18318 dumpState.setDump(DumpState.DUMP_VERSION); 18319 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18320 dumpState.setDump(DumpState.DUMP_KEYSETS); 18321 } else if ("installs".equals(cmd)) { 18322 dumpState.setDump(DumpState.DUMP_INSTALLS); 18323 } else if ("frozen".equals(cmd)) { 18324 dumpState.setDump(DumpState.DUMP_FROZEN); 18325 } else if ("dexopt".equals(cmd)) { 18326 dumpState.setDump(DumpState.DUMP_DEXOPT); 18327 } else if ("write".equals(cmd)) { 18328 synchronized (mPackages) { 18329 mSettings.writeLPr(); 18330 pw.println("Settings written."); 18331 return; 18332 } 18333 } 18334 } 18335 18336 if (checkin) { 18337 pw.println("vers,1"); 18338 } 18339 18340 // reader 18341 synchronized (mPackages) { 18342 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18343 if (!checkin) { 18344 if (dumpState.onTitlePrinted()) 18345 pw.println(); 18346 pw.println("Database versions:"); 18347 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18348 } 18349 } 18350 18351 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18352 if (!checkin) { 18353 if (dumpState.onTitlePrinted()) 18354 pw.println(); 18355 pw.println("Verifiers:"); 18356 pw.print(" Required: "); 18357 pw.print(mRequiredVerifierPackage); 18358 pw.print(" (uid="); 18359 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18360 UserHandle.USER_SYSTEM)); 18361 pw.println(")"); 18362 } else if (mRequiredVerifierPackage != null) { 18363 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18364 pw.print(","); 18365 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18366 UserHandle.USER_SYSTEM)); 18367 } 18368 } 18369 18370 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18371 packageName == null) { 18372 if (mIntentFilterVerifierComponent != null) { 18373 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18374 if (!checkin) { 18375 if (dumpState.onTitlePrinted()) 18376 pw.println(); 18377 pw.println("Intent Filter Verifier:"); 18378 pw.print(" Using: "); 18379 pw.print(verifierPackageName); 18380 pw.print(" (uid="); 18381 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18382 UserHandle.USER_SYSTEM)); 18383 pw.println(")"); 18384 } else if (verifierPackageName != null) { 18385 pw.print("ifv,"); pw.print(verifierPackageName); 18386 pw.print(","); 18387 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18388 UserHandle.USER_SYSTEM)); 18389 } 18390 } else { 18391 pw.println(); 18392 pw.println("No Intent Filter Verifier available!"); 18393 } 18394 } 18395 18396 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18397 boolean printedHeader = false; 18398 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18399 while (it.hasNext()) { 18400 String name = it.next(); 18401 SharedLibraryEntry ent = mSharedLibraries.get(name); 18402 if (!checkin) { 18403 if (!printedHeader) { 18404 if (dumpState.onTitlePrinted()) 18405 pw.println(); 18406 pw.println("Libraries:"); 18407 printedHeader = true; 18408 } 18409 pw.print(" "); 18410 } else { 18411 pw.print("lib,"); 18412 } 18413 pw.print(name); 18414 if (!checkin) { 18415 pw.print(" -> "); 18416 } 18417 if (ent.path != null) { 18418 if (!checkin) { 18419 pw.print("(jar) "); 18420 pw.print(ent.path); 18421 } else { 18422 pw.print(",jar,"); 18423 pw.print(ent.path); 18424 } 18425 } else { 18426 if (!checkin) { 18427 pw.print("(apk) "); 18428 pw.print(ent.apk); 18429 } else { 18430 pw.print(",apk,"); 18431 pw.print(ent.apk); 18432 } 18433 } 18434 pw.println(); 18435 } 18436 } 18437 18438 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18439 if (dumpState.onTitlePrinted()) 18440 pw.println(); 18441 if (!checkin) { 18442 pw.println("Features:"); 18443 } 18444 18445 for (FeatureInfo feat : mAvailableFeatures.values()) { 18446 if (checkin) { 18447 pw.print("feat,"); 18448 pw.print(feat.name); 18449 pw.print(","); 18450 pw.println(feat.version); 18451 } else { 18452 pw.print(" "); 18453 pw.print(feat.name); 18454 if (feat.version > 0) { 18455 pw.print(" version="); 18456 pw.print(feat.version); 18457 } 18458 pw.println(); 18459 } 18460 } 18461 } 18462 18463 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18464 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18465 : "Activity Resolver Table:", " ", packageName, 18466 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18467 dumpState.setTitlePrinted(true); 18468 } 18469 } 18470 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18471 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18472 : "Receiver Resolver Table:", " ", packageName, 18473 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18474 dumpState.setTitlePrinted(true); 18475 } 18476 } 18477 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18478 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18479 : "Service Resolver Table:", " ", packageName, 18480 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18481 dumpState.setTitlePrinted(true); 18482 } 18483 } 18484 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18485 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18486 : "Provider Resolver Table:", " ", packageName, 18487 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18488 dumpState.setTitlePrinted(true); 18489 } 18490 } 18491 18492 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18493 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18494 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18495 int user = mSettings.mPreferredActivities.keyAt(i); 18496 if (pir.dump(pw, 18497 dumpState.getTitlePrinted() 18498 ? "\nPreferred Activities User " + user + ":" 18499 : "Preferred Activities User " + user + ":", " ", 18500 packageName, true, false)) { 18501 dumpState.setTitlePrinted(true); 18502 } 18503 } 18504 } 18505 18506 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18507 pw.flush(); 18508 FileOutputStream fout = new FileOutputStream(fd); 18509 BufferedOutputStream str = new BufferedOutputStream(fout); 18510 XmlSerializer serializer = new FastXmlSerializer(); 18511 try { 18512 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18513 serializer.startDocument(null, true); 18514 serializer.setFeature( 18515 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18516 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18517 serializer.endDocument(); 18518 serializer.flush(); 18519 } catch (IllegalArgumentException e) { 18520 pw.println("Failed writing: " + e); 18521 } catch (IllegalStateException e) { 18522 pw.println("Failed writing: " + e); 18523 } catch (IOException e) { 18524 pw.println("Failed writing: " + e); 18525 } 18526 } 18527 18528 if (!checkin 18529 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18530 && packageName == null) { 18531 pw.println(); 18532 int count = mSettings.mPackages.size(); 18533 if (count == 0) { 18534 pw.println("No applications!"); 18535 pw.println(); 18536 } else { 18537 final String prefix = " "; 18538 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18539 if (allPackageSettings.size() == 0) { 18540 pw.println("No domain preferred apps!"); 18541 pw.println(); 18542 } else { 18543 pw.println("App verification status:"); 18544 pw.println(); 18545 count = 0; 18546 for (PackageSetting ps : allPackageSettings) { 18547 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18548 if (ivi == null || ivi.getPackageName() == null) continue; 18549 pw.println(prefix + "Package: " + ivi.getPackageName()); 18550 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18551 pw.println(prefix + "Status: " + ivi.getStatusString()); 18552 pw.println(); 18553 count++; 18554 } 18555 if (count == 0) { 18556 pw.println(prefix + "No app verification established."); 18557 pw.println(); 18558 } 18559 for (int userId : sUserManager.getUserIds()) { 18560 pw.println("App linkages for user " + userId + ":"); 18561 pw.println(); 18562 count = 0; 18563 for (PackageSetting ps : allPackageSettings) { 18564 final long status = ps.getDomainVerificationStatusForUser(userId); 18565 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18566 continue; 18567 } 18568 pw.println(prefix + "Package: " + ps.name); 18569 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18570 String statusStr = IntentFilterVerificationInfo. 18571 getStatusStringFromValue(status); 18572 pw.println(prefix + "Status: " + statusStr); 18573 pw.println(); 18574 count++; 18575 } 18576 if (count == 0) { 18577 pw.println(prefix + "No configured app linkages."); 18578 pw.println(); 18579 } 18580 } 18581 } 18582 } 18583 } 18584 18585 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18586 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18587 if (packageName == null && permissionNames == null) { 18588 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18589 if (iperm == 0) { 18590 if (dumpState.onTitlePrinted()) 18591 pw.println(); 18592 pw.println("AppOp Permissions:"); 18593 } 18594 pw.print(" AppOp Permission "); 18595 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18596 pw.println(":"); 18597 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18598 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18599 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18600 } 18601 } 18602 } 18603 } 18604 18605 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18606 boolean printedSomething = false; 18607 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18608 if (packageName != null && !packageName.equals(p.info.packageName)) { 18609 continue; 18610 } 18611 if (!printedSomething) { 18612 if (dumpState.onTitlePrinted()) 18613 pw.println(); 18614 pw.println("Registered ContentProviders:"); 18615 printedSomething = true; 18616 } 18617 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18618 pw.print(" "); pw.println(p.toString()); 18619 } 18620 printedSomething = false; 18621 for (Map.Entry<String, PackageParser.Provider> entry : 18622 mProvidersByAuthority.entrySet()) { 18623 PackageParser.Provider p = entry.getValue(); 18624 if (packageName != null && !packageName.equals(p.info.packageName)) { 18625 continue; 18626 } 18627 if (!printedSomething) { 18628 if (dumpState.onTitlePrinted()) 18629 pw.println(); 18630 pw.println("ContentProvider Authorities:"); 18631 printedSomething = true; 18632 } 18633 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18634 pw.print(" "); pw.println(p.toString()); 18635 if (p.info != null && p.info.applicationInfo != null) { 18636 final String appInfo = p.info.applicationInfo.toString(); 18637 pw.print(" applicationInfo="); pw.println(appInfo); 18638 } 18639 } 18640 } 18641 18642 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18643 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18644 } 18645 18646 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18647 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18648 } 18649 18650 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18651 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18652 } 18653 18654 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18655 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18656 } 18657 18658 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18659 // XXX should handle packageName != null by dumping only install data that 18660 // the given package is involved with. 18661 if (dumpState.onTitlePrinted()) pw.println(); 18662 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18663 } 18664 18665 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18666 // XXX should handle packageName != null by dumping only install data that 18667 // the given package is involved with. 18668 if (dumpState.onTitlePrinted()) pw.println(); 18669 18670 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18671 ipw.println(); 18672 ipw.println("Frozen packages:"); 18673 ipw.increaseIndent(); 18674 if (mFrozenPackages.size() == 0) { 18675 ipw.println("(none)"); 18676 } else { 18677 for (int i = 0; i < mFrozenPackages.size(); i++) { 18678 ipw.println(mFrozenPackages.valueAt(i)); 18679 } 18680 } 18681 ipw.decreaseIndent(); 18682 } 18683 18684 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18685 if (dumpState.onTitlePrinted()) pw.println(); 18686 dumpDexoptStateLPr(pw, packageName); 18687 } 18688 18689 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18690 if (dumpState.onTitlePrinted()) pw.println(); 18691 mSettings.dumpReadMessagesLPr(pw, dumpState); 18692 18693 pw.println(); 18694 pw.println("Package warning messages:"); 18695 BufferedReader in = null; 18696 String line = null; 18697 try { 18698 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18699 while ((line = in.readLine()) != null) { 18700 if (line.contains("ignored: updated version")) continue; 18701 pw.println(line); 18702 } 18703 } catch (IOException ignored) { 18704 } finally { 18705 IoUtils.closeQuietly(in); 18706 } 18707 } 18708 18709 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18710 BufferedReader in = null; 18711 String line = null; 18712 try { 18713 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18714 while ((line = in.readLine()) != null) { 18715 if (line.contains("ignored: updated version")) continue; 18716 pw.print("msg,"); 18717 pw.println(line); 18718 } 18719 } catch (IOException ignored) { 18720 } finally { 18721 IoUtils.closeQuietly(in); 18722 } 18723 } 18724 } 18725 } 18726 18727 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18728 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18729 ipw.println(); 18730 ipw.println("Dexopt state:"); 18731 ipw.increaseIndent(); 18732 Collection<PackageParser.Package> packages = null; 18733 if (packageName != null) { 18734 PackageParser.Package targetPackage = mPackages.get(packageName); 18735 if (targetPackage != null) { 18736 packages = Collections.singletonList(targetPackage); 18737 } else { 18738 ipw.println("Unable to find package: " + packageName); 18739 return; 18740 } 18741 } else { 18742 packages = mPackages.values(); 18743 } 18744 18745 for (PackageParser.Package pkg : packages) { 18746 ipw.println("[" + pkg.packageName + "]"); 18747 ipw.increaseIndent(); 18748 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18749 ipw.decreaseIndent(); 18750 } 18751 } 18752 18753 private String dumpDomainString(String packageName) { 18754 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18755 .getList(); 18756 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18757 18758 ArraySet<String> result = new ArraySet<>(); 18759 if (iviList.size() > 0) { 18760 for (IntentFilterVerificationInfo ivi : iviList) { 18761 for (String host : ivi.getDomains()) { 18762 result.add(host); 18763 } 18764 } 18765 } 18766 if (filters != null && filters.size() > 0) { 18767 for (IntentFilter filter : filters) { 18768 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18769 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18770 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18771 result.addAll(filter.getHostsList()); 18772 } 18773 } 18774 } 18775 18776 StringBuilder sb = new StringBuilder(result.size() * 16); 18777 for (String domain : result) { 18778 if (sb.length() > 0) sb.append(" "); 18779 sb.append(domain); 18780 } 18781 return sb.toString(); 18782 } 18783 18784 // ------- apps on sdcard specific code ------- 18785 static final boolean DEBUG_SD_INSTALL = false; 18786 18787 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18788 18789 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18790 18791 private boolean mMediaMounted = false; 18792 18793 static String getEncryptKey() { 18794 try { 18795 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18796 SD_ENCRYPTION_KEYSTORE_NAME); 18797 if (sdEncKey == null) { 18798 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18799 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18800 if (sdEncKey == null) { 18801 Slog.e(TAG, "Failed to create encryption keys"); 18802 return null; 18803 } 18804 } 18805 return sdEncKey; 18806 } catch (NoSuchAlgorithmException nsae) { 18807 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18808 return null; 18809 } catch (IOException ioe) { 18810 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18811 return null; 18812 } 18813 } 18814 18815 /* 18816 * Update media status on PackageManager. 18817 */ 18818 @Override 18819 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18820 int callingUid = Binder.getCallingUid(); 18821 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18822 throw new SecurityException("Media status can only be updated by the system"); 18823 } 18824 // reader; this apparently protects mMediaMounted, but should probably 18825 // be a different lock in that case. 18826 synchronized (mPackages) { 18827 Log.i(TAG, "Updating external media status from " 18828 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18829 + (mediaStatus ? "mounted" : "unmounted")); 18830 if (DEBUG_SD_INSTALL) 18831 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18832 + ", mMediaMounted=" + mMediaMounted); 18833 if (mediaStatus == mMediaMounted) { 18834 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18835 : 0, -1); 18836 mHandler.sendMessage(msg); 18837 return; 18838 } 18839 mMediaMounted = mediaStatus; 18840 } 18841 // Queue up an async operation since the package installation may take a 18842 // little while. 18843 mHandler.post(new Runnable() { 18844 public void run() { 18845 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18846 } 18847 }); 18848 } 18849 18850 /** 18851 * Called by MountService when the initial ASECs to scan are available. 18852 * Should block until all the ASEC containers are finished being scanned. 18853 */ 18854 public void scanAvailableAsecs() { 18855 updateExternalMediaStatusInner(true, false, false); 18856 } 18857 18858 /* 18859 * Collect information of applications on external media, map them against 18860 * existing containers and update information based on current mount status. 18861 * Please note that we always have to report status if reportStatus has been 18862 * set to true especially when unloading packages. 18863 */ 18864 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18865 boolean externalStorage) { 18866 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18867 int[] uidArr = EmptyArray.INT; 18868 18869 final String[] list = PackageHelper.getSecureContainerList(); 18870 if (ArrayUtils.isEmpty(list)) { 18871 Log.i(TAG, "No secure containers found"); 18872 } else { 18873 // Process list of secure containers and categorize them 18874 // as active or stale based on their package internal state. 18875 18876 // reader 18877 synchronized (mPackages) { 18878 for (String cid : list) { 18879 // Leave stages untouched for now; installer service owns them 18880 if (PackageInstallerService.isStageName(cid)) continue; 18881 18882 if (DEBUG_SD_INSTALL) 18883 Log.i(TAG, "Processing container " + cid); 18884 String pkgName = getAsecPackageName(cid); 18885 if (pkgName == null) { 18886 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18887 continue; 18888 } 18889 if (DEBUG_SD_INSTALL) 18890 Log.i(TAG, "Looking for pkg : " + pkgName); 18891 18892 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18893 if (ps == null) { 18894 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18895 continue; 18896 } 18897 18898 /* 18899 * Skip packages that are not external if we're unmounting 18900 * external storage. 18901 */ 18902 if (externalStorage && !isMounted && !isExternal(ps)) { 18903 continue; 18904 } 18905 18906 final AsecInstallArgs args = new AsecInstallArgs(cid, 18907 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18908 // The package status is changed only if the code path 18909 // matches between settings and the container id. 18910 if (ps.codePathString != null 18911 && ps.codePathString.startsWith(args.getCodePath())) { 18912 if (DEBUG_SD_INSTALL) { 18913 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18914 + " at code path: " + ps.codePathString); 18915 } 18916 18917 // We do have a valid package installed on sdcard 18918 processCids.put(args, ps.codePathString); 18919 final int uid = ps.appId; 18920 if (uid != -1) { 18921 uidArr = ArrayUtils.appendInt(uidArr, uid); 18922 } 18923 } else { 18924 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18925 + ps.codePathString); 18926 } 18927 } 18928 } 18929 18930 Arrays.sort(uidArr); 18931 } 18932 18933 // Process packages with valid entries. 18934 if (isMounted) { 18935 if (DEBUG_SD_INSTALL) 18936 Log.i(TAG, "Loading packages"); 18937 loadMediaPackages(processCids, uidArr, externalStorage); 18938 startCleaningPackages(); 18939 mInstallerService.onSecureContainersAvailable(); 18940 } else { 18941 if (DEBUG_SD_INSTALL) 18942 Log.i(TAG, "Unloading packages"); 18943 unloadMediaPackages(processCids, uidArr, reportStatus); 18944 } 18945 } 18946 18947 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18948 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18949 final int size = infos.size(); 18950 final String[] packageNames = new String[size]; 18951 final int[] packageUids = new int[size]; 18952 for (int i = 0; i < size; i++) { 18953 final ApplicationInfo info = infos.get(i); 18954 packageNames[i] = info.packageName; 18955 packageUids[i] = info.uid; 18956 } 18957 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18958 finishedReceiver); 18959 } 18960 18961 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18962 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18963 sendResourcesChangedBroadcast(mediaStatus, replacing, 18964 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18965 } 18966 18967 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18968 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18969 int size = pkgList.length; 18970 if (size > 0) { 18971 // Send broadcasts here 18972 Bundle extras = new Bundle(); 18973 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18974 if (uidArr != null) { 18975 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18976 } 18977 if (replacing) { 18978 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18979 } 18980 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18981 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18982 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18983 } 18984 } 18985 18986 /* 18987 * Look at potentially valid container ids from processCids If package 18988 * information doesn't match the one on record or package scanning fails, 18989 * the cid is added to list of removeCids. We currently don't delete stale 18990 * containers. 18991 */ 18992 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18993 boolean externalStorage) { 18994 ArrayList<String> pkgList = new ArrayList<String>(); 18995 Set<AsecInstallArgs> keys = processCids.keySet(); 18996 18997 for (AsecInstallArgs args : keys) { 18998 String codePath = processCids.get(args); 18999 if (DEBUG_SD_INSTALL) 19000 Log.i(TAG, "Loading container : " + args.cid); 19001 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19002 try { 19003 // Make sure there are no container errors first. 19004 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19005 Slog.e(TAG, "Failed to mount cid : " + args.cid 19006 + " when installing from sdcard"); 19007 continue; 19008 } 19009 // Check code path here. 19010 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19011 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19012 + " does not match one in settings " + codePath); 19013 continue; 19014 } 19015 // Parse package 19016 int parseFlags = mDefParseFlags; 19017 if (args.isExternalAsec()) { 19018 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19019 } 19020 if (args.isFwdLocked()) { 19021 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19022 } 19023 19024 synchronized (mInstallLock) { 19025 PackageParser.Package pkg = null; 19026 try { 19027 // Sadly we don't know the package name yet to freeze it 19028 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19029 SCAN_IGNORE_FROZEN, 0, null); 19030 } catch (PackageManagerException e) { 19031 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19032 } 19033 // Scan the package 19034 if (pkg != null) { 19035 /* 19036 * TODO why is the lock being held? doPostInstall is 19037 * called in other places without the lock. This needs 19038 * to be straightened out. 19039 */ 19040 // writer 19041 synchronized (mPackages) { 19042 retCode = PackageManager.INSTALL_SUCCEEDED; 19043 pkgList.add(pkg.packageName); 19044 // Post process args 19045 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19046 pkg.applicationInfo.uid); 19047 } 19048 } else { 19049 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19050 } 19051 } 19052 19053 } finally { 19054 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19055 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19056 } 19057 } 19058 } 19059 // writer 19060 synchronized (mPackages) { 19061 // If the platform SDK has changed since the last time we booted, 19062 // we need to re-grant app permission to catch any new ones that 19063 // appear. This is really a hack, and means that apps can in some 19064 // cases get permissions that the user didn't initially explicitly 19065 // allow... it would be nice to have some better way to handle 19066 // this situation. 19067 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19068 : mSettings.getInternalVersion(); 19069 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19070 : StorageManager.UUID_PRIVATE_INTERNAL; 19071 19072 int updateFlags = UPDATE_PERMISSIONS_ALL; 19073 if (ver.sdkVersion != mSdkVersion) { 19074 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19075 + mSdkVersion + "; regranting permissions for external"); 19076 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19077 } 19078 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19079 19080 // Yay, everything is now upgraded 19081 ver.forceCurrent(); 19082 19083 // can downgrade to reader 19084 // Persist settings 19085 mSettings.writeLPr(); 19086 } 19087 // Send a broadcast to let everyone know we are done processing 19088 if (pkgList.size() > 0) { 19089 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19090 } 19091 } 19092 19093 /* 19094 * Utility method to unload a list of specified containers 19095 */ 19096 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19097 // Just unmount all valid containers. 19098 for (AsecInstallArgs arg : cidArgs) { 19099 synchronized (mInstallLock) { 19100 arg.doPostDeleteLI(false); 19101 } 19102 } 19103 } 19104 19105 /* 19106 * Unload packages mounted on external media. This involves deleting package 19107 * data from internal structures, sending broadcasts about disabled packages, 19108 * gc'ing to free up references, unmounting all secure containers 19109 * corresponding to packages on external media, and posting a 19110 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19111 * that we always have to post this message if status has been requested no 19112 * matter what. 19113 */ 19114 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19115 final boolean reportStatus) { 19116 if (DEBUG_SD_INSTALL) 19117 Log.i(TAG, "unloading media packages"); 19118 ArrayList<String> pkgList = new ArrayList<String>(); 19119 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19120 final Set<AsecInstallArgs> keys = processCids.keySet(); 19121 for (AsecInstallArgs args : keys) { 19122 String pkgName = args.getPackageName(); 19123 if (DEBUG_SD_INSTALL) 19124 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19125 // Delete package internally 19126 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19127 synchronized (mInstallLock) { 19128 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19129 final boolean res; 19130 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19131 "unloadMediaPackages")) { 19132 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19133 null); 19134 } 19135 if (res) { 19136 pkgList.add(pkgName); 19137 } else { 19138 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19139 failedList.add(args); 19140 } 19141 } 19142 } 19143 19144 // reader 19145 synchronized (mPackages) { 19146 // We didn't update the settings after removing each package; 19147 // write them now for all packages. 19148 mSettings.writeLPr(); 19149 } 19150 19151 // We have to absolutely send UPDATED_MEDIA_STATUS only 19152 // after confirming that all the receivers processed the ordered 19153 // broadcast when packages get disabled, force a gc to clean things up. 19154 // and unload all the containers. 19155 if (pkgList.size() > 0) { 19156 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19157 new IIntentReceiver.Stub() { 19158 public void performReceive(Intent intent, int resultCode, String data, 19159 Bundle extras, boolean ordered, boolean sticky, 19160 int sendingUser) throws RemoteException { 19161 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19162 reportStatus ? 1 : 0, 1, keys); 19163 mHandler.sendMessage(msg); 19164 } 19165 }); 19166 } else { 19167 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19168 keys); 19169 mHandler.sendMessage(msg); 19170 } 19171 } 19172 19173 private void loadPrivatePackages(final VolumeInfo vol) { 19174 mHandler.post(new Runnable() { 19175 @Override 19176 public void run() { 19177 loadPrivatePackagesInner(vol); 19178 } 19179 }); 19180 } 19181 19182 private void loadPrivatePackagesInner(VolumeInfo vol) { 19183 final String volumeUuid = vol.fsUuid; 19184 if (TextUtils.isEmpty(volumeUuid)) { 19185 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19186 return; 19187 } 19188 19189 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19190 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19191 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19192 19193 final VersionInfo ver; 19194 final List<PackageSetting> packages; 19195 synchronized (mPackages) { 19196 ver = mSettings.findOrCreateVersion(volumeUuid); 19197 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19198 } 19199 19200 for (PackageSetting ps : packages) { 19201 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19202 synchronized (mInstallLock) { 19203 final PackageParser.Package pkg; 19204 try { 19205 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19206 loaded.add(pkg.applicationInfo); 19207 19208 } catch (PackageManagerException e) { 19209 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19210 } 19211 19212 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19213 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19214 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19215 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19216 } 19217 } 19218 } 19219 19220 // Reconcile app data for all started/unlocked users 19221 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19222 final UserManager um = mContext.getSystemService(UserManager.class); 19223 UserManagerInternal umInternal = getUserManagerInternal(); 19224 for (UserInfo user : um.getUsers()) { 19225 final int flags; 19226 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19227 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19228 } else if (umInternal.isUserRunning(user.id)) { 19229 flags = StorageManager.FLAG_STORAGE_DE; 19230 } else { 19231 continue; 19232 } 19233 19234 try { 19235 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19236 synchronized (mInstallLock) { 19237 reconcileAppsDataLI(volumeUuid, user.id, flags); 19238 } 19239 } catch (IllegalStateException e) { 19240 // Device was probably ejected, and we'll process that event momentarily 19241 Slog.w(TAG, "Failed to prepare storage: " + e); 19242 } 19243 } 19244 19245 synchronized (mPackages) { 19246 int updateFlags = UPDATE_PERMISSIONS_ALL; 19247 if (ver.sdkVersion != mSdkVersion) { 19248 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19249 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19250 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19251 } 19252 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19253 19254 // Yay, everything is now upgraded 19255 ver.forceCurrent(); 19256 19257 mSettings.writeLPr(); 19258 } 19259 19260 for (PackageFreezer freezer : freezers) { 19261 freezer.close(); 19262 } 19263 19264 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19265 sendResourcesChangedBroadcast(true, false, loaded, null); 19266 } 19267 19268 private void unloadPrivatePackages(final VolumeInfo vol) { 19269 mHandler.post(new Runnable() { 19270 @Override 19271 public void run() { 19272 unloadPrivatePackagesInner(vol); 19273 } 19274 }); 19275 } 19276 19277 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19278 final String volumeUuid = vol.fsUuid; 19279 if (TextUtils.isEmpty(volumeUuid)) { 19280 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19281 return; 19282 } 19283 19284 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19285 synchronized (mInstallLock) { 19286 synchronized (mPackages) { 19287 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19288 for (PackageSetting ps : packages) { 19289 if (ps.pkg == null) continue; 19290 19291 final ApplicationInfo info = ps.pkg.applicationInfo; 19292 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19293 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19294 19295 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19296 "unloadPrivatePackagesInner")) { 19297 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19298 false, null)) { 19299 unloaded.add(info); 19300 } else { 19301 Slog.w(TAG, "Failed to unload " + ps.codePath); 19302 } 19303 } 19304 19305 // Try very hard to release any references to this package 19306 // so we don't risk the system server being killed due to 19307 // open FDs 19308 AttributeCache.instance().removePackage(ps.name); 19309 } 19310 19311 mSettings.writeLPr(); 19312 } 19313 } 19314 19315 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19316 sendResourcesChangedBroadcast(false, false, unloaded, null); 19317 19318 // Try very hard to release any references to this path so we don't risk 19319 // the system server being killed due to open FDs 19320 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19321 19322 for (int i = 0; i < 3; i++) { 19323 System.gc(); 19324 System.runFinalization(); 19325 } 19326 } 19327 19328 /** 19329 * Prepare storage areas for given user on all mounted devices. 19330 */ 19331 void prepareUserData(int userId, int userSerial, int flags) { 19332 synchronized (mInstallLock) { 19333 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19334 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19335 final String volumeUuid = vol.getFsUuid(); 19336 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19337 } 19338 } 19339 } 19340 19341 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19342 boolean allowRecover) { 19343 // Prepare storage and verify that serial numbers are consistent; if 19344 // there's a mismatch we need to destroy to avoid leaking data 19345 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19346 try { 19347 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19348 19349 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19350 UserManagerService.enforceSerialNumber( 19351 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19352 } 19353 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19354 UserManagerService.enforceSerialNumber( 19355 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19356 } 19357 19358 synchronized (mInstallLock) { 19359 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19360 } 19361 } catch (Exception e) { 19362 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19363 + " because we failed to prepare: " + e); 19364 destroyUserDataLI(volumeUuid, userId, 19365 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19366 19367 if (allowRecover) { 19368 // Try one last time; if we fail again we're really in trouble 19369 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19370 } 19371 } 19372 } 19373 19374 /** 19375 * Destroy storage areas for given user on all mounted devices. 19376 */ 19377 void destroyUserData(int userId, int flags) { 19378 synchronized (mInstallLock) { 19379 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19380 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19381 final String volumeUuid = vol.getFsUuid(); 19382 destroyUserDataLI(volumeUuid, userId, flags); 19383 } 19384 } 19385 } 19386 19387 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19389 try { 19390 // Clean up app data, profile data, and media data 19391 mInstaller.destroyUserData(volumeUuid, userId, flags); 19392 19393 // Clean up system data 19394 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19395 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19396 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19397 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19398 } 19399 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19400 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19401 } 19402 } 19403 19404 // Data with special labels is now gone, so finish the job 19405 storage.destroyUserStorage(volumeUuid, userId, flags); 19406 19407 } catch (Exception e) { 19408 logCriticalInfo(Log.WARN, 19409 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19410 } 19411 } 19412 19413 /** 19414 * Examine all users present on given mounted volume, and destroy data 19415 * belonging to users that are no longer valid, or whose user ID has been 19416 * recycled. 19417 */ 19418 private void reconcileUsers(String volumeUuid) { 19419 final List<File> files = new ArrayList<>(); 19420 Collections.addAll(files, FileUtils 19421 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19422 Collections.addAll(files, FileUtils 19423 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19424 for (File file : files) { 19425 if (!file.isDirectory()) continue; 19426 19427 final int userId; 19428 final UserInfo info; 19429 try { 19430 userId = Integer.parseInt(file.getName()); 19431 info = sUserManager.getUserInfo(userId); 19432 } catch (NumberFormatException e) { 19433 Slog.w(TAG, "Invalid user directory " + file); 19434 continue; 19435 } 19436 19437 boolean destroyUser = false; 19438 if (info == null) { 19439 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19440 + " because no matching user was found"); 19441 destroyUser = true; 19442 } else if (!mOnlyCore) { 19443 try { 19444 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19445 } catch (IOException e) { 19446 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19447 + " because we failed to enforce serial number: " + e); 19448 destroyUser = true; 19449 } 19450 } 19451 19452 if (destroyUser) { 19453 synchronized (mInstallLock) { 19454 destroyUserDataLI(volumeUuid, userId, 19455 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19456 } 19457 } 19458 } 19459 } 19460 19461 private void assertPackageKnown(String volumeUuid, String packageName) 19462 throws PackageManagerException { 19463 synchronized (mPackages) { 19464 final PackageSetting ps = mSettings.mPackages.get(packageName); 19465 if (ps == null) { 19466 throw new PackageManagerException("Package " + packageName + " is unknown"); 19467 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19468 throw new PackageManagerException( 19469 "Package " + packageName + " found on unknown volume " + volumeUuid 19470 + "; expected volume " + ps.volumeUuid); 19471 } 19472 } 19473 } 19474 19475 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19476 throws PackageManagerException { 19477 synchronized (mPackages) { 19478 final PackageSetting ps = mSettings.mPackages.get(packageName); 19479 if (ps == null) { 19480 throw new PackageManagerException("Package " + packageName + " is unknown"); 19481 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19482 throw new PackageManagerException( 19483 "Package " + packageName + " found on unknown volume " + volumeUuid 19484 + "; expected volume " + ps.volumeUuid); 19485 } else if (!ps.getInstalled(userId)) { 19486 throw new PackageManagerException( 19487 "Package " + packageName + " not installed for user " + userId); 19488 } 19489 } 19490 } 19491 19492 /** 19493 * Examine all apps present on given mounted volume, and destroy apps that 19494 * aren't expected, either due to uninstallation or reinstallation on 19495 * another volume. 19496 */ 19497 private void reconcileApps(String volumeUuid) { 19498 final File[] files = FileUtils 19499 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19500 for (File file : files) { 19501 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19502 && !PackageInstallerService.isStageName(file.getName()); 19503 if (!isPackage) { 19504 // Ignore entries which are not packages 19505 continue; 19506 } 19507 19508 try { 19509 final PackageLite pkg = PackageParser.parsePackageLite(file, 19510 PackageParser.PARSE_MUST_BE_APK); 19511 assertPackageKnown(volumeUuid, pkg.packageName); 19512 19513 } catch (PackageParserException | PackageManagerException e) { 19514 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19515 synchronized (mInstallLock) { 19516 removeCodePathLI(file); 19517 } 19518 } 19519 } 19520 } 19521 19522 /** 19523 * Reconcile all app data for the given user. 19524 * <p> 19525 * Verifies that directories exist and that ownership and labeling is 19526 * correct for all installed apps on all mounted volumes. 19527 */ 19528 void reconcileAppsData(int userId, int flags) { 19529 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19530 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19531 final String volumeUuid = vol.getFsUuid(); 19532 synchronized (mInstallLock) { 19533 reconcileAppsDataLI(volumeUuid, userId, flags); 19534 } 19535 } 19536 } 19537 19538 /** 19539 * Reconcile all app data on given mounted volume. 19540 * <p> 19541 * Destroys app data that isn't expected, either due to uninstallation or 19542 * reinstallation on another volume. 19543 * <p> 19544 * Verifies that directories exist and that ownership and labeling is 19545 * correct for all installed apps. 19546 */ 19547 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19548 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19549 + Integer.toHexString(flags)); 19550 19551 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19552 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19553 19554 boolean restoreconNeeded = false; 19555 19556 // First look for stale data that doesn't belong, and check if things 19557 // have changed since we did our last restorecon 19558 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19559 if (StorageManager.isFileEncryptedNativeOrEmulated() 19560 && !StorageManager.isUserKeyUnlocked(userId)) { 19561 throw new RuntimeException( 19562 "Yikes, someone asked us to reconcile CE storage while " + userId 19563 + " was still locked; this would have caused massive data loss!"); 19564 } 19565 19566 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19567 19568 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19569 for (File file : files) { 19570 final String packageName = file.getName(); 19571 try { 19572 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19573 } catch (PackageManagerException e) { 19574 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19575 try { 19576 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19577 StorageManager.FLAG_STORAGE_CE, 0); 19578 } catch (InstallerException e2) { 19579 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19580 } 19581 } 19582 } 19583 } 19584 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19585 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19586 19587 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19588 for (File file : files) { 19589 final String packageName = file.getName(); 19590 try { 19591 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19592 } catch (PackageManagerException e) { 19593 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19594 try { 19595 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19596 StorageManager.FLAG_STORAGE_DE, 0); 19597 } catch (InstallerException e2) { 19598 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19599 } 19600 } 19601 } 19602 } 19603 19604 // Ensure that data directories are ready to roll for all packages 19605 // installed for this volume and user 19606 final List<PackageSetting> packages; 19607 synchronized (mPackages) { 19608 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19609 } 19610 int preparedCount = 0; 19611 for (PackageSetting ps : packages) { 19612 final String packageName = ps.name; 19613 if (ps.pkg == null) { 19614 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19615 // TODO: might be due to legacy ASEC apps; we should circle back 19616 // and reconcile again once they're scanned 19617 continue; 19618 } 19619 19620 if (ps.getInstalled(userId)) { 19621 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19622 19623 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19624 // We may have just shuffled around app data directories, so 19625 // prepare them one more time 19626 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19627 } 19628 19629 preparedCount++; 19630 } 19631 } 19632 19633 if (restoreconNeeded) { 19634 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19635 SELinuxMMAC.setRestoreconDone(ceDir); 19636 } 19637 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19638 SELinuxMMAC.setRestoreconDone(deDir); 19639 } 19640 } 19641 19642 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19643 + " packages; restoreconNeeded was " + restoreconNeeded); 19644 } 19645 19646 /** 19647 * Prepare app data for the given app just after it was installed or 19648 * upgraded. This method carefully only touches users that it's installed 19649 * for, and it forces a restorecon to handle any seinfo changes. 19650 * <p> 19651 * Verifies that directories exist and that ownership and labeling is 19652 * correct for all installed apps. If there is an ownership mismatch, it 19653 * will try recovering system apps by wiping data; third-party app data is 19654 * left intact. 19655 * <p> 19656 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19657 */ 19658 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19659 final PackageSetting ps; 19660 synchronized (mPackages) { 19661 ps = mSettings.mPackages.get(pkg.packageName); 19662 mSettings.writeKernelMappingLPr(ps); 19663 } 19664 19665 final UserManager um = mContext.getSystemService(UserManager.class); 19666 UserManagerInternal umInternal = getUserManagerInternal(); 19667 for (UserInfo user : um.getUsers()) { 19668 final int flags; 19669 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19670 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19671 } else if (umInternal.isUserRunning(user.id)) { 19672 flags = StorageManager.FLAG_STORAGE_DE; 19673 } else { 19674 continue; 19675 } 19676 19677 if (ps.getInstalled(user.id)) { 19678 // Whenever an app changes, force a restorecon of its data 19679 // TODO: when user data is locked, mark that we're still dirty 19680 prepareAppDataLIF(pkg, user.id, flags, true); 19681 } 19682 } 19683 } 19684 19685 /** 19686 * Prepare app data for the given app. 19687 * <p> 19688 * Verifies that directories exist and that ownership and labeling is 19689 * correct for all installed apps. If there is an ownership mismatch, this 19690 * will try recovering system apps by wiping data; third-party app data is 19691 * left intact. 19692 */ 19693 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19694 boolean restoreconNeeded) { 19695 if (pkg == null) { 19696 Slog.wtf(TAG, "Package was null!", new Throwable()); 19697 return; 19698 } 19699 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19700 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19701 for (int i = 0; i < childCount; i++) { 19702 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19703 } 19704 } 19705 19706 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19707 boolean restoreconNeeded) { 19708 if (DEBUG_APP_DATA) { 19709 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19710 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19711 } 19712 19713 final String volumeUuid = pkg.volumeUuid; 19714 final String packageName = pkg.packageName; 19715 final ApplicationInfo app = pkg.applicationInfo; 19716 final int appId = UserHandle.getAppId(app.uid); 19717 19718 Preconditions.checkNotNull(app.seinfo); 19719 19720 try { 19721 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19722 appId, app.seinfo, app.targetSdkVersion); 19723 } catch (InstallerException e) { 19724 if (app.isSystemApp()) { 19725 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19726 + ", but trying to recover: " + e); 19727 destroyAppDataLeafLIF(pkg, userId, flags); 19728 try { 19729 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19730 appId, app.seinfo, app.targetSdkVersion); 19731 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19732 } catch (InstallerException e2) { 19733 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19734 } 19735 } else { 19736 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19737 } 19738 } 19739 19740 if (restoreconNeeded) { 19741 try { 19742 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19743 app.seinfo); 19744 } catch (InstallerException e) { 19745 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19746 } 19747 } 19748 19749 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19750 try { 19751 // CE storage is unlocked right now, so read out the inode and 19752 // remember for use later when it's locked 19753 // TODO: mark this structure as dirty so we persist it! 19754 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19755 StorageManager.FLAG_STORAGE_CE); 19756 synchronized (mPackages) { 19757 final PackageSetting ps = mSettings.mPackages.get(packageName); 19758 if (ps != null) { 19759 ps.setCeDataInode(ceDataInode, userId); 19760 } 19761 } 19762 } catch (InstallerException e) { 19763 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19764 } 19765 } 19766 19767 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19768 } 19769 19770 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19771 if (pkg == null) { 19772 Slog.wtf(TAG, "Package was null!", new Throwable()); 19773 return; 19774 } 19775 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19776 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19777 for (int i = 0; i < childCount; i++) { 19778 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19779 } 19780 } 19781 19782 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19783 final String volumeUuid = pkg.volumeUuid; 19784 final String packageName = pkg.packageName; 19785 final ApplicationInfo app = pkg.applicationInfo; 19786 19787 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19788 // Create a native library symlink only if we have native libraries 19789 // and if the native libraries are 32 bit libraries. We do not provide 19790 // this symlink for 64 bit libraries. 19791 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19792 final String nativeLibPath = app.nativeLibraryDir; 19793 try { 19794 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19795 nativeLibPath, userId); 19796 } catch (InstallerException e) { 19797 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19798 } 19799 } 19800 } 19801 } 19802 19803 /** 19804 * For system apps on non-FBE devices, this method migrates any existing 19805 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19806 * requested by the app. 19807 */ 19808 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19809 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19810 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19811 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19812 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19813 try { 19814 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19815 storageTarget); 19816 } catch (InstallerException e) { 19817 logCriticalInfo(Log.WARN, 19818 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19819 } 19820 return true; 19821 } else { 19822 return false; 19823 } 19824 } 19825 19826 public PackageFreezer freezePackage(String packageName, String killReason) { 19827 return new PackageFreezer(packageName, killReason); 19828 } 19829 19830 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19831 String killReason) { 19832 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19833 return new PackageFreezer(); 19834 } else { 19835 return freezePackage(packageName, killReason); 19836 } 19837 } 19838 19839 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19840 String killReason) { 19841 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19842 return new PackageFreezer(); 19843 } else { 19844 return freezePackage(packageName, killReason); 19845 } 19846 } 19847 19848 /** 19849 * Class that freezes and kills the given package upon creation, and 19850 * unfreezes it upon closing. This is typically used when doing surgery on 19851 * app code/data to prevent the app from running while you're working. 19852 */ 19853 private class PackageFreezer implements AutoCloseable { 19854 private final String mPackageName; 19855 private final PackageFreezer[] mChildren; 19856 19857 private final boolean mWeFroze; 19858 19859 private final AtomicBoolean mClosed = new AtomicBoolean(); 19860 private final CloseGuard mCloseGuard = CloseGuard.get(); 19861 19862 /** 19863 * Create and return a stub freezer that doesn't actually do anything, 19864 * typically used when someone requested 19865 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19866 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19867 */ 19868 public PackageFreezer() { 19869 mPackageName = null; 19870 mChildren = null; 19871 mWeFroze = false; 19872 mCloseGuard.open("close"); 19873 } 19874 19875 public PackageFreezer(String packageName, String killReason) { 19876 synchronized (mPackages) { 19877 mPackageName = packageName; 19878 mWeFroze = mFrozenPackages.add(mPackageName); 19879 19880 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19881 if (ps != null) { 19882 killApplication(ps.name, ps.appId, killReason); 19883 } 19884 19885 final PackageParser.Package p = mPackages.get(packageName); 19886 if (p != null && p.childPackages != null) { 19887 final int N = p.childPackages.size(); 19888 mChildren = new PackageFreezer[N]; 19889 for (int i = 0; i < N; i++) { 19890 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19891 killReason); 19892 } 19893 } else { 19894 mChildren = null; 19895 } 19896 } 19897 mCloseGuard.open("close"); 19898 } 19899 19900 @Override 19901 protected void finalize() throws Throwable { 19902 try { 19903 mCloseGuard.warnIfOpen(); 19904 close(); 19905 } finally { 19906 super.finalize(); 19907 } 19908 } 19909 19910 @Override 19911 public void close() { 19912 mCloseGuard.close(); 19913 if (mClosed.compareAndSet(false, true)) { 19914 synchronized (mPackages) { 19915 if (mWeFroze) { 19916 mFrozenPackages.remove(mPackageName); 19917 } 19918 19919 if (mChildren != null) { 19920 for (PackageFreezer freezer : mChildren) { 19921 freezer.close(); 19922 } 19923 } 19924 } 19925 } 19926 } 19927 } 19928 19929 /** 19930 * Verify that given package is currently frozen. 19931 */ 19932 private void checkPackageFrozen(String packageName) { 19933 synchronized (mPackages) { 19934 if (!mFrozenPackages.contains(packageName)) { 19935 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19936 } 19937 } 19938 } 19939 19940 @Override 19941 public int movePackage(final String packageName, final String volumeUuid) { 19942 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19943 19944 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19945 final int moveId = mNextMoveId.getAndIncrement(); 19946 mHandler.post(new Runnable() { 19947 @Override 19948 public void run() { 19949 try { 19950 movePackageInternal(packageName, volumeUuid, moveId, user); 19951 } catch (PackageManagerException e) { 19952 Slog.w(TAG, "Failed to move " + packageName, e); 19953 mMoveCallbacks.notifyStatusChanged(moveId, 19954 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19955 } 19956 } 19957 }); 19958 return moveId; 19959 } 19960 19961 private void movePackageInternal(final String packageName, final String volumeUuid, 19962 final int moveId, UserHandle user) throws PackageManagerException { 19963 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19964 final PackageManager pm = mContext.getPackageManager(); 19965 19966 final boolean currentAsec; 19967 final String currentVolumeUuid; 19968 final File codeFile; 19969 final String installerPackageName; 19970 final String packageAbiOverride; 19971 final int appId; 19972 final String seinfo; 19973 final String label; 19974 final int targetSdkVersion; 19975 final PackageFreezer freezer; 19976 final int[] installedUserIds; 19977 19978 // reader 19979 synchronized (mPackages) { 19980 final PackageParser.Package pkg = mPackages.get(packageName); 19981 final PackageSetting ps = mSettings.mPackages.get(packageName); 19982 if (pkg == null || ps == null) { 19983 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19984 } 19985 19986 if (pkg.applicationInfo.isSystemApp()) { 19987 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19988 "Cannot move system application"); 19989 } 19990 19991 if (pkg.applicationInfo.isExternalAsec()) { 19992 currentAsec = true; 19993 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19994 } else if (pkg.applicationInfo.isForwardLocked()) { 19995 currentAsec = true; 19996 currentVolumeUuid = "forward_locked"; 19997 } else { 19998 currentAsec = false; 19999 currentVolumeUuid = ps.volumeUuid; 20000 20001 final File probe = new File(pkg.codePath); 20002 final File probeOat = new File(probe, "oat"); 20003 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20004 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20005 "Move only supported for modern cluster style installs"); 20006 } 20007 } 20008 20009 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20010 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20011 "Package already moved to " + volumeUuid); 20012 } 20013 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20014 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20015 "Device admin cannot be moved"); 20016 } 20017 20018 if (mFrozenPackages.contains(packageName)) { 20019 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20020 "Failed to move already frozen package"); 20021 } 20022 20023 codeFile = new File(pkg.codePath); 20024 installerPackageName = ps.installerPackageName; 20025 packageAbiOverride = ps.cpuAbiOverrideString; 20026 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20027 seinfo = pkg.applicationInfo.seinfo; 20028 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20029 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20030 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20031 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20032 } 20033 20034 final Bundle extras = new Bundle(); 20035 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20036 extras.putString(Intent.EXTRA_TITLE, label); 20037 mMoveCallbacks.notifyCreated(moveId, extras); 20038 20039 int installFlags; 20040 final boolean moveCompleteApp; 20041 final File measurePath; 20042 20043 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20044 installFlags = INSTALL_INTERNAL; 20045 moveCompleteApp = !currentAsec; 20046 measurePath = Environment.getDataAppDirectory(volumeUuid); 20047 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20048 installFlags = INSTALL_EXTERNAL; 20049 moveCompleteApp = false; 20050 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20051 } else { 20052 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20053 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20054 || !volume.isMountedWritable()) { 20055 freezer.close(); 20056 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20057 "Move location not mounted private volume"); 20058 } 20059 20060 Preconditions.checkState(!currentAsec); 20061 20062 installFlags = INSTALL_INTERNAL; 20063 moveCompleteApp = true; 20064 measurePath = Environment.getDataAppDirectory(volumeUuid); 20065 } 20066 20067 final PackageStats stats = new PackageStats(null, -1); 20068 synchronized (mInstaller) { 20069 for (int userId : installedUserIds) { 20070 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20071 freezer.close(); 20072 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20073 "Failed to measure package size"); 20074 } 20075 } 20076 } 20077 20078 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20079 + stats.dataSize); 20080 20081 final long startFreeBytes = measurePath.getFreeSpace(); 20082 final long sizeBytes; 20083 if (moveCompleteApp) { 20084 sizeBytes = stats.codeSize + stats.dataSize; 20085 } else { 20086 sizeBytes = stats.codeSize; 20087 } 20088 20089 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20090 freezer.close(); 20091 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20092 "Not enough free space to move"); 20093 } 20094 20095 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20096 20097 final CountDownLatch installedLatch = new CountDownLatch(1); 20098 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20099 @Override 20100 public void onUserActionRequired(Intent intent) throws RemoteException { 20101 throw new IllegalStateException(); 20102 } 20103 20104 @Override 20105 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20106 Bundle extras) throws RemoteException { 20107 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20108 + PackageManager.installStatusToString(returnCode, msg)); 20109 20110 installedLatch.countDown(); 20111 freezer.close(); 20112 20113 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20114 switch (status) { 20115 case PackageInstaller.STATUS_SUCCESS: 20116 mMoveCallbacks.notifyStatusChanged(moveId, 20117 PackageManager.MOVE_SUCCEEDED); 20118 break; 20119 case PackageInstaller.STATUS_FAILURE_STORAGE: 20120 mMoveCallbacks.notifyStatusChanged(moveId, 20121 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20122 break; 20123 default: 20124 mMoveCallbacks.notifyStatusChanged(moveId, 20125 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20126 break; 20127 } 20128 } 20129 }; 20130 20131 final MoveInfo move; 20132 if (moveCompleteApp) { 20133 // Kick off a thread to report progress estimates 20134 new Thread() { 20135 @Override 20136 public void run() { 20137 while (true) { 20138 try { 20139 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20140 break; 20141 } 20142 } catch (InterruptedException ignored) { 20143 } 20144 20145 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20146 final int progress = 10 + (int) MathUtils.constrain( 20147 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20148 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20149 } 20150 } 20151 }.start(); 20152 20153 final String dataAppName = codeFile.getName(); 20154 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20155 dataAppName, appId, seinfo, targetSdkVersion); 20156 } else { 20157 move = null; 20158 } 20159 20160 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20161 20162 final Message msg = mHandler.obtainMessage(INIT_COPY); 20163 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20164 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20165 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20166 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20167 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20168 msg.obj = params; 20169 20170 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20171 System.identityHashCode(msg.obj)); 20172 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20173 System.identityHashCode(msg.obj)); 20174 20175 mHandler.sendMessage(msg); 20176 } 20177 20178 @Override 20179 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20180 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20181 20182 final int realMoveId = mNextMoveId.getAndIncrement(); 20183 final Bundle extras = new Bundle(); 20184 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20185 mMoveCallbacks.notifyCreated(realMoveId, extras); 20186 20187 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20188 @Override 20189 public void onCreated(int moveId, Bundle extras) { 20190 // Ignored 20191 } 20192 20193 @Override 20194 public void onStatusChanged(int moveId, int status, long estMillis) { 20195 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20196 } 20197 }; 20198 20199 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20200 storage.setPrimaryStorageUuid(volumeUuid, callback); 20201 return realMoveId; 20202 } 20203 20204 @Override 20205 public int getMoveStatus(int moveId) { 20206 mContext.enforceCallingOrSelfPermission( 20207 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20208 return mMoveCallbacks.mLastStatus.get(moveId); 20209 } 20210 20211 @Override 20212 public void registerMoveCallback(IPackageMoveObserver callback) { 20213 mContext.enforceCallingOrSelfPermission( 20214 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20215 mMoveCallbacks.register(callback); 20216 } 20217 20218 @Override 20219 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20220 mContext.enforceCallingOrSelfPermission( 20221 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20222 mMoveCallbacks.unregister(callback); 20223 } 20224 20225 @Override 20226 public boolean setInstallLocation(int loc) { 20227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20228 null); 20229 if (getInstallLocation() == loc) { 20230 return true; 20231 } 20232 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20233 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20234 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20235 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20236 return true; 20237 } 20238 return false; 20239 } 20240 20241 @Override 20242 public int getInstallLocation() { 20243 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20244 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20245 PackageHelper.APP_INSTALL_AUTO); 20246 } 20247 20248 /** Called by UserManagerService */ 20249 void cleanUpUser(UserManagerService userManager, int userHandle) { 20250 synchronized (mPackages) { 20251 mDirtyUsers.remove(userHandle); 20252 mUserNeedsBadging.delete(userHandle); 20253 mSettings.removeUserLPw(userHandle); 20254 mPendingBroadcasts.remove(userHandle); 20255 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20256 removeUnusedPackagesLPw(userManager, userHandle); 20257 } 20258 } 20259 20260 /** 20261 * We're removing userHandle and would like to remove any downloaded packages 20262 * that are no longer in use by any other user. 20263 * @param userHandle the user being removed 20264 */ 20265 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20266 final boolean DEBUG_CLEAN_APKS = false; 20267 int [] users = userManager.getUserIds(); 20268 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20269 while (psit.hasNext()) { 20270 PackageSetting ps = psit.next(); 20271 if (ps.pkg == null) { 20272 continue; 20273 } 20274 final String packageName = ps.pkg.packageName; 20275 // Skip over if system app 20276 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20277 continue; 20278 } 20279 if (DEBUG_CLEAN_APKS) { 20280 Slog.i(TAG, "Checking package " + packageName); 20281 } 20282 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20283 if (keep) { 20284 if (DEBUG_CLEAN_APKS) { 20285 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20286 } 20287 } else { 20288 for (int i = 0; i < users.length; i++) { 20289 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20290 keep = true; 20291 if (DEBUG_CLEAN_APKS) { 20292 Slog.i(TAG, " Keeping package " + packageName + " for user " 20293 + users[i]); 20294 } 20295 break; 20296 } 20297 } 20298 } 20299 if (!keep) { 20300 if (DEBUG_CLEAN_APKS) { 20301 Slog.i(TAG, " Removing package " + packageName); 20302 } 20303 mHandler.post(new Runnable() { 20304 public void run() { 20305 deletePackageX(packageName, userHandle, 0); 20306 } //end run 20307 }); 20308 } 20309 } 20310 } 20311 20312 /** Called by UserManagerService */ 20313 void createNewUser(int userId) { 20314 synchronized (mInstallLock) { 20315 mSettings.createNewUserLI(this, mInstaller, userId); 20316 } 20317 synchronized (mPackages) { 20318 scheduleWritePackageRestrictionsLocked(userId); 20319 scheduleWritePackageListLocked(userId); 20320 applyFactoryDefaultBrowserLPw(userId); 20321 primeDomainVerificationsLPw(userId); 20322 } 20323 } 20324 20325 void onBeforeUserStartUninitialized(final int userId) { 20326 synchronized (mPackages) { 20327 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20328 return; 20329 } 20330 } 20331 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20332 // If permission review for legacy apps is required, we represent 20333 // dagerous permissions for such apps as always granted runtime 20334 // permissions to keep per user flag state whether review is needed. 20335 // Hence, if a new user is added we have to propagate dangerous 20336 // permission grants for these legacy apps. 20337 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20338 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20339 | UPDATE_PERMISSIONS_REPLACE_ALL); 20340 } 20341 } 20342 20343 @Override 20344 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20345 mContext.enforceCallingOrSelfPermission( 20346 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20347 "Only package verification agents can read the verifier device identity"); 20348 20349 synchronized (mPackages) { 20350 return mSettings.getVerifierDeviceIdentityLPw(); 20351 } 20352 } 20353 20354 @Override 20355 public void setPermissionEnforced(String permission, boolean enforced) { 20356 // TODO: Now that we no longer change GID for storage, this should to away. 20357 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20358 "setPermissionEnforced"); 20359 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20360 synchronized (mPackages) { 20361 if (mSettings.mReadExternalStorageEnforced == null 20362 || mSettings.mReadExternalStorageEnforced != enforced) { 20363 mSettings.mReadExternalStorageEnforced = enforced; 20364 mSettings.writeLPr(); 20365 } 20366 } 20367 // kill any non-foreground processes so we restart them and 20368 // grant/revoke the GID. 20369 final IActivityManager am = ActivityManagerNative.getDefault(); 20370 if (am != null) { 20371 final long token = Binder.clearCallingIdentity(); 20372 try { 20373 am.killProcessesBelowForeground("setPermissionEnforcement"); 20374 } catch (RemoteException e) { 20375 } finally { 20376 Binder.restoreCallingIdentity(token); 20377 } 20378 } 20379 } else { 20380 throw new IllegalArgumentException("No selective enforcement for " + permission); 20381 } 20382 } 20383 20384 @Override 20385 @Deprecated 20386 public boolean isPermissionEnforced(String permission) { 20387 return true; 20388 } 20389 20390 @Override 20391 public boolean isStorageLow() { 20392 final long token = Binder.clearCallingIdentity(); 20393 try { 20394 final DeviceStorageMonitorInternal 20395 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20396 if (dsm != null) { 20397 return dsm.isMemoryLow(); 20398 } else { 20399 return false; 20400 } 20401 } finally { 20402 Binder.restoreCallingIdentity(token); 20403 } 20404 } 20405 20406 @Override 20407 public IPackageInstaller getPackageInstaller() { 20408 return mInstallerService; 20409 } 20410 20411 private boolean userNeedsBadging(int userId) { 20412 int index = mUserNeedsBadging.indexOfKey(userId); 20413 if (index < 0) { 20414 final UserInfo userInfo; 20415 final long token = Binder.clearCallingIdentity(); 20416 try { 20417 userInfo = sUserManager.getUserInfo(userId); 20418 } finally { 20419 Binder.restoreCallingIdentity(token); 20420 } 20421 final boolean b; 20422 if (userInfo != null && userInfo.isManagedProfile()) { 20423 b = true; 20424 } else { 20425 b = false; 20426 } 20427 mUserNeedsBadging.put(userId, b); 20428 return b; 20429 } 20430 return mUserNeedsBadging.valueAt(index); 20431 } 20432 20433 @Override 20434 public KeySet getKeySetByAlias(String packageName, String alias) { 20435 if (packageName == null || alias == null) { 20436 return null; 20437 } 20438 synchronized(mPackages) { 20439 final PackageParser.Package pkg = mPackages.get(packageName); 20440 if (pkg == null) { 20441 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20442 throw new IllegalArgumentException("Unknown package: " + packageName); 20443 } 20444 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20445 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20446 } 20447 } 20448 20449 @Override 20450 public KeySet getSigningKeySet(String packageName) { 20451 if (packageName == null) { 20452 return null; 20453 } 20454 synchronized(mPackages) { 20455 final PackageParser.Package pkg = mPackages.get(packageName); 20456 if (pkg == null) { 20457 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20458 throw new IllegalArgumentException("Unknown package: " + packageName); 20459 } 20460 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20461 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20462 throw new SecurityException("May not access signing KeySet of other apps."); 20463 } 20464 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20465 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20466 } 20467 } 20468 20469 @Override 20470 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20471 if (packageName == null || ks == null) { 20472 return false; 20473 } 20474 synchronized(mPackages) { 20475 final PackageParser.Package pkg = mPackages.get(packageName); 20476 if (pkg == null) { 20477 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20478 throw new IllegalArgumentException("Unknown package: " + packageName); 20479 } 20480 IBinder ksh = ks.getToken(); 20481 if (ksh instanceof KeySetHandle) { 20482 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20483 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20484 } 20485 return false; 20486 } 20487 } 20488 20489 @Override 20490 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20491 if (packageName == null || ks == null) { 20492 return false; 20493 } 20494 synchronized(mPackages) { 20495 final PackageParser.Package pkg = mPackages.get(packageName); 20496 if (pkg == null) { 20497 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20498 throw new IllegalArgumentException("Unknown package: " + packageName); 20499 } 20500 IBinder ksh = ks.getToken(); 20501 if (ksh instanceof KeySetHandle) { 20502 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20503 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20504 } 20505 return false; 20506 } 20507 } 20508 20509 private void deletePackageIfUnusedLPr(final String packageName) { 20510 PackageSetting ps = mSettings.mPackages.get(packageName); 20511 if (ps == null) { 20512 return; 20513 } 20514 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20515 // TODO Implement atomic delete if package is unused 20516 // It is currently possible that the package will be deleted even if it is installed 20517 // after this method returns. 20518 mHandler.post(new Runnable() { 20519 public void run() { 20520 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20521 } 20522 }); 20523 } 20524 } 20525 20526 /** 20527 * Check and throw if the given before/after packages would be considered a 20528 * downgrade. 20529 */ 20530 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20531 throws PackageManagerException { 20532 if (after.versionCode < before.mVersionCode) { 20533 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20534 "Update version code " + after.versionCode + " is older than current " 20535 + before.mVersionCode); 20536 } else if (after.versionCode == before.mVersionCode) { 20537 if (after.baseRevisionCode < before.baseRevisionCode) { 20538 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20539 "Update base revision code " + after.baseRevisionCode 20540 + " is older than current " + before.baseRevisionCode); 20541 } 20542 20543 if (!ArrayUtils.isEmpty(after.splitNames)) { 20544 for (int i = 0; i < after.splitNames.length; i++) { 20545 final String splitName = after.splitNames[i]; 20546 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20547 if (j != -1) { 20548 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20549 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20550 "Update split " + splitName + " revision code " 20551 + after.splitRevisionCodes[i] + " is older than current " 20552 + before.splitRevisionCodes[j]); 20553 } 20554 } 20555 } 20556 } 20557 } 20558 } 20559 20560 private static class MoveCallbacks extends Handler { 20561 private static final int MSG_CREATED = 1; 20562 private static final int MSG_STATUS_CHANGED = 2; 20563 20564 private final RemoteCallbackList<IPackageMoveObserver> 20565 mCallbacks = new RemoteCallbackList<>(); 20566 20567 private final SparseIntArray mLastStatus = new SparseIntArray(); 20568 20569 public MoveCallbacks(Looper looper) { 20570 super(looper); 20571 } 20572 20573 public void register(IPackageMoveObserver callback) { 20574 mCallbacks.register(callback); 20575 } 20576 20577 public void unregister(IPackageMoveObserver callback) { 20578 mCallbacks.unregister(callback); 20579 } 20580 20581 @Override 20582 public void handleMessage(Message msg) { 20583 final SomeArgs args = (SomeArgs) msg.obj; 20584 final int n = mCallbacks.beginBroadcast(); 20585 for (int i = 0; i < n; i++) { 20586 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20587 try { 20588 invokeCallback(callback, msg.what, args); 20589 } catch (RemoteException ignored) { 20590 } 20591 } 20592 mCallbacks.finishBroadcast(); 20593 args.recycle(); 20594 } 20595 20596 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20597 throws RemoteException { 20598 switch (what) { 20599 case MSG_CREATED: { 20600 callback.onCreated(args.argi1, (Bundle) args.arg2); 20601 break; 20602 } 20603 case MSG_STATUS_CHANGED: { 20604 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20605 break; 20606 } 20607 } 20608 } 20609 20610 private void notifyCreated(int moveId, Bundle extras) { 20611 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20612 20613 final SomeArgs args = SomeArgs.obtain(); 20614 args.argi1 = moveId; 20615 args.arg2 = extras; 20616 obtainMessage(MSG_CREATED, args).sendToTarget(); 20617 } 20618 20619 private void notifyStatusChanged(int moveId, int status) { 20620 notifyStatusChanged(moveId, status, -1); 20621 } 20622 20623 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20624 Slog.v(TAG, "Move " + moveId + " status " + status); 20625 20626 final SomeArgs args = SomeArgs.obtain(); 20627 args.argi1 = moveId; 20628 args.argi2 = status; 20629 args.arg3 = estMillis; 20630 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20631 20632 synchronized (mLastStatus) { 20633 mLastStatus.put(moveId, status); 20634 } 20635 } 20636 } 20637 20638 private final static class OnPermissionChangeListeners extends Handler { 20639 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20640 20641 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20642 new RemoteCallbackList<>(); 20643 20644 public OnPermissionChangeListeners(Looper looper) { 20645 super(looper); 20646 } 20647 20648 @Override 20649 public void handleMessage(Message msg) { 20650 switch (msg.what) { 20651 case MSG_ON_PERMISSIONS_CHANGED: { 20652 final int uid = msg.arg1; 20653 handleOnPermissionsChanged(uid); 20654 } break; 20655 } 20656 } 20657 20658 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20659 mPermissionListeners.register(listener); 20660 20661 } 20662 20663 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20664 mPermissionListeners.unregister(listener); 20665 } 20666 20667 public void onPermissionsChanged(int uid) { 20668 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20669 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20670 } 20671 } 20672 20673 private void handleOnPermissionsChanged(int uid) { 20674 final int count = mPermissionListeners.beginBroadcast(); 20675 try { 20676 for (int i = 0; i < count; i++) { 20677 IOnPermissionsChangeListener callback = mPermissionListeners 20678 .getBroadcastItem(i); 20679 try { 20680 callback.onPermissionsChanged(uid); 20681 } catch (RemoteException e) { 20682 Log.e(TAG, "Permission listener is dead", e); 20683 } 20684 } 20685 } finally { 20686 mPermissionListeners.finishBroadcast(); 20687 } 20688 } 20689 } 20690 20691 private class PackageManagerInternalImpl extends PackageManagerInternal { 20692 @Override 20693 public void setLocationPackagesProvider(PackagesProvider provider) { 20694 synchronized (mPackages) { 20695 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20696 } 20697 } 20698 20699 @Override 20700 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20701 synchronized (mPackages) { 20702 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20703 } 20704 } 20705 20706 @Override 20707 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20708 synchronized (mPackages) { 20709 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20710 } 20711 } 20712 20713 @Override 20714 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20715 synchronized (mPackages) { 20716 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20717 } 20718 } 20719 20720 @Override 20721 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20722 synchronized (mPackages) { 20723 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20724 } 20725 } 20726 20727 @Override 20728 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20729 synchronized (mPackages) { 20730 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20731 } 20732 } 20733 20734 @Override 20735 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20736 synchronized (mPackages) { 20737 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20738 packageName, userId); 20739 } 20740 } 20741 20742 @Override 20743 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20744 synchronized (mPackages) { 20745 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20746 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20747 packageName, userId); 20748 } 20749 } 20750 20751 @Override 20752 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20753 synchronized (mPackages) { 20754 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20755 packageName, userId); 20756 } 20757 } 20758 20759 @Override 20760 public void setKeepUninstalledPackages(final List<String> packageList) { 20761 Preconditions.checkNotNull(packageList); 20762 List<String> removedFromList = null; 20763 synchronized (mPackages) { 20764 if (mKeepUninstalledPackages != null) { 20765 final int packagesCount = mKeepUninstalledPackages.size(); 20766 for (int i = 0; i < packagesCount; i++) { 20767 String oldPackage = mKeepUninstalledPackages.get(i); 20768 if (packageList != null && packageList.contains(oldPackage)) { 20769 continue; 20770 } 20771 if (removedFromList == null) { 20772 removedFromList = new ArrayList<>(); 20773 } 20774 removedFromList.add(oldPackage); 20775 } 20776 } 20777 mKeepUninstalledPackages = new ArrayList<>(packageList); 20778 if (removedFromList != null) { 20779 final int removedCount = removedFromList.size(); 20780 for (int i = 0; i < removedCount; i++) { 20781 deletePackageIfUnusedLPr(removedFromList.get(i)); 20782 } 20783 } 20784 } 20785 } 20786 20787 @Override 20788 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20789 synchronized (mPackages) { 20790 // If we do not support permission review, done. 20791 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20792 return false; 20793 } 20794 20795 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20796 if (packageSetting == null) { 20797 return false; 20798 } 20799 20800 // Permission review applies only to apps not supporting the new permission model. 20801 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20802 return false; 20803 } 20804 20805 // Legacy apps have the permission and get user consent on launch. 20806 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20807 return permissionsState.isPermissionReviewRequired(userId); 20808 } 20809 } 20810 20811 @Override 20812 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20813 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20814 } 20815 20816 @Override 20817 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20818 int userId) { 20819 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20820 } 20821 } 20822 20823 @Override 20824 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20825 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20826 synchronized (mPackages) { 20827 final long identity = Binder.clearCallingIdentity(); 20828 try { 20829 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20830 packageNames, userId); 20831 } finally { 20832 Binder.restoreCallingIdentity(identity); 20833 } 20834 } 20835 } 20836 20837 private static void enforceSystemOrPhoneCaller(String tag) { 20838 int callingUid = Binder.getCallingUid(); 20839 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20840 throw new SecurityException( 20841 "Cannot call " + tag + " from UID " + callingUid); 20842 } 20843 } 20844 20845 boolean isHistoricalPackageUsageAvailable() { 20846 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20847 } 20848 20849 /** 20850 * Return a <b>copy</b> of the collection of packages known to the package manager. 20851 * @return A copy of the values of mPackages. 20852 */ 20853 Collection<PackageParser.Package> getPackages() { 20854 synchronized (mPackages) { 20855 return new ArrayList<>(mPackages.values()); 20856 } 20857 } 20858 20859 /** 20860 * Logs process start information (including base APK hash) to the security log. 20861 * @hide 20862 */ 20863 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20864 String apkFile, int pid) { 20865 if (!SecurityLog.isLoggingEnabled()) { 20866 return; 20867 } 20868 Bundle data = new Bundle(); 20869 data.putLong("startTimestamp", System.currentTimeMillis()); 20870 data.putString("processName", processName); 20871 data.putInt("uid", uid); 20872 data.putString("seinfo", seinfo); 20873 data.putString("apkFile", apkFile); 20874 data.putInt("pid", pid); 20875 Message msg = mProcessLoggingHandler.obtainMessage( 20876 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20877 msg.setData(data); 20878 mProcessLoggingHandler.sendMessage(msg); 20879 } 20880} 20881