PackageManagerService.java revision 5133b6204c33be30b30daa21e61f2a7ad39b3da0
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.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 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.EphemeralDigest; 129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.PackageLite; 153import android.content.pm.PackageParser.PackageParserException; 154import android.content.pm.PackageStats; 155import android.content.pm.PackageUserState; 156import android.content.pm.ParceledListSlice; 157import android.content.pm.PermissionGroupInfo; 158import android.content.pm.PermissionInfo; 159import android.content.pm.ProviderInfo; 160import android.content.pm.ResolveInfo; 161import android.content.pm.ServiceInfo; 162import android.content.pm.Signature; 163import android.content.pm.UserInfo; 164import android.content.pm.VerifierDeviceIdentity; 165import android.content.pm.VerifierInfo; 166import android.content.res.Resources; 167import android.graphics.Bitmap; 168import android.hardware.display.DisplayManager; 169import android.net.Uri; 170import android.os.Binder; 171import android.os.Build; 172import android.os.Bundle; 173import android.os.Debug; 174import android.os.Environment; 175import android.os.Environment.UserEnvironment; 176import android.os.FileUtils; 177import android.os.Handler; 178import android.os.IBinder; 179import android.os.Looper; 180import android.os.Message; 181import android.os.Parcel; 182import android.os.ParcelFileDescriptor; 183import android.os.Process; 184import android.os.RemoteCallbackList; 185import android.os.RemoteException; 186import android.os.ResultReceiver; 187import android.os.SELinux; 188import android.os.ServiceManager; 189import android.os.SystemClock; 190import android.os.SystemProperties; 191import android.os.Trace; 192import android.os.UserHandle; 193import android.os.UserManager; 194import android.os.UserManagerInternal; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.provider.Settings.Global; 202import android.security.KeyStore; 203import android.security.SystemKeyStore; 204import android.system.ErrnoException; 205import android.system.Os; 206import android.text.TextUtils; 207import android.text.format.DateUtils; 208import android.util.ArrayMap; 209import android.util.ArraySet; 210import android.util.AtomicFile; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.PrintStreamPrinter; 218import android.util.Slog; 219import android.util.SparseArray; 220import android.util.SparseBooleanArray; 221import android.util.SparseIntArray; 222import android.util.Xml; 223import android.util.jar.StrictJarFile; 224import android.view.Display; 225 226import com.android.internal.R; 227import com.android.internal.annotations.GuardedBy; 228import com.android.internal.app.IMediaContainerService; 229import com.android.internal.app.ResolverActivity; 230import com.android.internal.content.NativeLibraryHelper; 231import com.android.internal.content.PackageHelper; 232import com.android.internal.logging.MetricsLogger; 233import com.android.internal.os.IParcelFileDescriptorFactory; 234import com.android.internal.os.InstallerConnection.InstallerException; 235import com.android.internal.os.SomeArgs; 236import com.android.internal.os.Zygote; 237import com.android.internal.telephony.CarrierAppUtils; 238import com.android.internal.util.ArrayUtils; 239import com.android.internal.util.FastPrintWriter; 240import com.android.internal.util.FastXmlSerializer; 241import com.android.internal.util.IndentingPrintWriter; 242import com.android.internal.util.Preconditions; 243import com.android.internal.util.XmlUtils; 244import com.android.server.AttributeCache; 245import com.android.server.EventLogTags; 246import com.android.server.FgThread; 247import com.android.server.IntentResolver; 248import com.android.server.LocalServices; 249import com.android.server.ServiceThread; 250import com.android.server.SystemConfig; 251import com.android.server.Watchdog; 252import com.android.server.net.NetworkPolicyManagerInternal; 253import com.android.server.pm.PermissionsState.PermissionState; 254import com.android.server.pm.Settings.DatabaseVersion; 255import com.android.server.pm.Settings.VersionInfo; 256import com.android.server.storage.DeviceStorageMonitorInternal; 257 258import dalvik.system.CloseGuard; 259import dalvik.system.DexFile; 260import dalvik.system.VMRuntime; 261 262import libcore.io.IoUtils; 263import libcore.util.EmptyArray; 264 265import org.xmlpull.v1.XmlPullParser; 266import org.xmlpull.v1.XmlPullParserException; 267import org.xmlpull.v1.XmlSerializer; 268 269import java.io.BufferedInputStream; 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.InputStream; 283import java.io.PrintWriter; 284import java.nio.charset.StandardCharsets; 285import java.security.DigestInputStream; 286import java.security.MessageDigest; 287import java.security.NoSuchAlgorithmException; 288import java.security.PublicKey; 289import java.security.cert.Certificate; 290import java.security.cert.CertificateEncodingException; 291import java.security.cert.CertificateException; 292import java.text.SimpleDateFormat; 293import java.util.ArrayList; 294import java.util.Arrays; 295import java.util.Collection; 296import java.util.Collections; 297import java.util.Comparator; 298import java.util.Date; 299import java.util.HashSet; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309import java.util.concurrent.atomic.AtomicLong; 310 311/** 312 * Keep track of all those APKs everywhere. 313 * <p> 314 * Internally there are two important locks: 315 * <ul> 316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 317 * and other related state. It is a fine-grained lock that should only be held 318 * momentarily, as it's one of the most contended locks in the system. 319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 320 * operations typically involve heavy lifting of application data on disk. Since 321 * {@code installd} is single-threaded, and it's operations can often be slow, 322 * this lock should never be acquired while already holding {@link #mPackages}. 323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 324 * holding {@link #mInstallLock}. 325 * </ul> 326 * Many internal methods rely on the caller to hold the appropriate locks, and 327 * this contract is expressed through method name suffixes: 328 * <ul> 329 * <li>fooLI(): the caller must hold {@link #mInstallLock} 330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 331 * being modified must be frozen 332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 334 * </ul> 335 * <p> 336 * Because this class is very central to the platform's security; please run all 337 * CTS and unit tests whenever making modifications: 338 * 339 * <pre> 340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 342 * </pre> 343 */ 344public class PackageManagerService extends IPackageManager.Stub { 345 static final String TAG = "PackageManager"; 346 static final boolean DEBUG_SETTINGS = false; 347 static final boolean DEBUG_PREFERRED = false; 348 static final boolean DEBUG_UPGRADE = false; 349 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 350 private static final boolean DEBUG_BACKUP = false; 351 private static final boolean DEBUG_INSTALL = false; 352 private static final boolean DEBUG_REMOVE = false; 353 private static final boolean DEBUG_BROADCASTS = false; 354 private static final boolean DEBUG_SHOW_INFO = false; 355 private static final boolean DEBUG_PACKAGE_INFO = false; 356 private static final boolean DEBUG_INTENT_MATCHING = false; 357 private static final boolean DEBUG_PACKAGE_SCANNING = false; 358 private static final boolean DEBUG_VERIFY = false; 359 private static final boolean DEBUG_FILTERS = false; 360 361 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 362 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 363 // user, but by default initialize to this. 364 static final boolean DEBUG_DEXOPT = false; 365 366 private static final boolean DEBUG_ABI_SELECTION = false; 367 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 368 private static final boolean DEBUG_TRIAGED_MISSING = false; 369 private static final boolean DEBUG_APP_DATA = false; 370 371 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 372 373 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 374 375 private static final int RADIO_UID = Process.PHONE_UID; 376 private static final int LOG_UID = Process.LOG_UID; 377 private static final int NFC_UID = Process.NFC_UID; 378 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 379 private static final int SHELL_UID = Process.SHELL_UID; 380 381 // Cap the size of permission trees that 3rd party apps can define 382 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 383 384 // Suffix used during package installation when copying/moving 385 // package apks to install directory. 386 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 387 388 static final int SCAN_NO_DEX = 1<<1; 389 static final int SCAN_FORCE_DEX = 1<<2; 390 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 391 static final int SCAN_NEW_INSTALL = 1<<4; 392 static final int SCAN_NO_PATHS = 1<<5; 393 static final int SCAN_UPDATE_TIME = 1<<6; 394 static final int SCAN_DEFER_DEX = 1<<7; 395 static final int SCAN_BOOTING = 1<<8; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 398 static final int SCAN_REPLACING = 1<<11; 399 static final int SCAN_REQUIRE_KNOWN = 1<<12; 400 static final int SCAN_MOVE = 1<<13; 401 static final int SCAN_INITIAL = 1<<14; 402 static final int SCAN_CHECK_ONLY = 1<<15; 403 static final int SCAN_DONT_KILL_APP = 1<<17; 404 static final int SCAN_IGNORE_FROZEN = 1<<18; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 466 467 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 468 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 469 470 /** Permission grant: not grant the permission. */ 471 private static final int GRANT_DENIED = 1; 472 473 /** Permission grant: grant the permission as an install permission. */ 474 private static final int GRANT_INSTALL = 2; 475 476 /** Permission grant: grant the permission as a runtime one. */ 477 private static final int GRANT_RUNTIME = 3; 478 479 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 480 private static final int GRANT_UPGRADE = 4; 481 482 /** Canonical intent used to identify what counts as a "web browser" app */ 483 private static final Intent sBrowserIntent; 484 static { 485 sBrowserIntent = new Intent(); 486 sBrowserIntent.setAction(Intent.ACTION_VIEW); 487 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 488 sBrowserIntent.setData(Uri.parse("http:")); 489 } 490 491 /** 492 * The set of all protected actions [i.e. those actions for which a high priority 493 * intent filter is disallowed]. 494 */ 495 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 496 static { 497 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 498 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 499 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 500 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 501 } 502 503 // Compilation reasons. 504 public static final int REASON_FIRST_BOOT = 0; 505 public static final int REASON_BOOT = 1; 506 public static final int REASON_INSTALL = 2; 507 public static final int REASON_BACKGROUND_DEXOPT = 3; 508 public static final int REASON_AB_OTA = 4; 509 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 510 public static final int REASON_SHARED_APK = 6; 511 public static final int REASON_FORCED_DEXOPT = 7; 512 public static final int REASON_CORE_APP = 8; 513 514 public static final int REASON_LAST = REASON_CORE_APP; 515 516 /** Special library name that skips shared libraries check during compilation. */ 517 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 518 519 final ServiceThread mHandlerThread; 520 521 final PackageHandler mHandler; 522 523 private final ProcessLoggingHandler mProcessLoggingHandler; 524 525 /** 526 * Messages for {@link #mHandler} that need to wait for system ready before 527 * being dispatched. 528 */ 529 private ArrayList<Message> mPostSystemReadyMessages; 530 531 final int mSdkVersion = Build.VERSION.SDK_INT; 532 533 final Context mContext; 534 final boolean mFactoryTest; 535 final boolean mOnlyCore; 536 final DisplayMetrics mMetrics; 537 final int mDefParseFlags; 538 final String[] mSeparateProcesses; 539 final boolean mIsUpgrade; 540 final boolean mIsPreNUpgrade; 541 542 /** The location for ASEC container files on internal storage. */ 543 final String mAsecInternalPath; 544 545 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 546 // LOCK HELD. Can be called with mInstallLock held. 547 @GuardedBy("mInstallLock") 548 final Installer mInstaller; 549 550 /** Directory where installed third-party apps stored */ 551 final File mAppInstallDir; 552 final File mEphemeralInstallDir; 553 554 /** 555 * Directory to which applications installed internally have their 556 * 32 bit native libraries copied. 557 */ 558 private File mAppLib32InstallDir; 559 560 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 561 // apps. 562 final File mDrmAppPrivateInstallDir; 563 564 // ---------------------------------------------------------------- 565 566 // Lock for state used when installing and doing other long running 567 // operations. Methods that must be called with this lock held have 568 // the suffix "LI". 569 final Object mInstallLock = new Object(); 570 571 // ---------------------------------------------------------------- 572 573 // Keys are String (package name), values are Package. This also serves 574 // as the lock for the global state. Methods that must be called with 575 // this lock held have the prefix "LP". 576 @GuardedBy("mPackages") 577 final ArrayMap<String, PackageParser.Package> mPackages = 578 new ArrayMap<String, PackageParser.Package>(); 579 580 final ArrayMap<String, Set<String>> mKnownCodebase = 581 new ArrayMap<String, Set<String>>(); 582 583 // Tracks available target package names -> overlay package paths. 584 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 585 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 586 587 /** 588 * Tracks new system packages [received in an OTA] that we expect to 589 * find updated user-installed versions. Keys are package name, values 590 * are package location. 591 */ 592 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 593 /** 594 * Tracks high priority intent filters for protected actions. During boot, certain 595 * filter actions are protected and should never be allowed to have a high priority 596 * intent filter for them. However, there is one, and only one exception -- the 597 * setup wizard. It must be able to define a high priority intent filter for these 598 * actions to ensure there are no escapes from the wizard. We need to delay processing 599 * of these during boot as we need to look at all of the system packages in order 600 * to know which component is the setup wizard. 601 */ 602 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 603 /** 604 * Whether or not processing protected filters should be deferred. 605 */ 606 private boolean mDeferProtectedFilters = true; 607 608 /** 609 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 610 */ 611 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 612 /** 613 * Whether or not system app permissions should be promoted from install to runtime. 614 */ 615 boolean mPromoteSystemApps; 616 617 @GuardedBy("mPackages") 618 final Settings mSettings; 619 620 /** 621 * Set of package names that are currently "frozen", which means active 622 * surgery is being done on the code/data for that package. The platform 623 * will refuse to launch frozen packages to avoid race conditions. 624 * 625 * @see PackageFreezer 626 */ 627 @GuardedBy("mPackages") 628 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 629 630 final ProtectedPackages mProtectedPackages; 631 632 boolean mFirstBoot; 633 634 // System configuration read by SystemConfig. 635 final int[] mGlobalGids; 636 final SparseArray<ArraySet<String>> mSystemPermissions; 637 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 638 639 // If mac_permissions.xml was found for seinfo labeling. 640 boolean mFoundPolicyFile; 641 642 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 643 644 public static final class SharedLibraryEntry { 645 public final String path; 646 public final String apk; 647 648 SharedLibraryEntry(String _path, String _apk) { 649 path = _path; 650 apk = _apk; 651 } 652 } 653 654 // Currently known shared libraries. 655 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 656 new ArrayMap<String, SharedLibraryEntry>(); 657 658 // All available activities, for your resolving pleasure. 659 final ActivityIntentResolver mActivities = 660 new ActivityIntentResolver(); 661 662 // All available receivers, for your resolving pleasure. 663 final ActivityIntentResolver mReceivers = 664 new ActivityIntentResolver(); 665 666 // All available services, for your resolving pleasure. 667 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 668 669 // All available providers, for your resolving pleasure. 670 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 671 672 // Mapping from provider base names (first directory in content URI codePath) 673 // to the provider information. 674 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 675 new ArrayMap<String, PackageParser.Provider>(); 676 677 // Mapping from instrumentation class names to info about them. 678 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 679 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 680 681 // Mapping from permission names to info about them. 682 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 683 new ArrayMap<String, PackageParser.PermissionGroup>(); 684 685 // Packages whose data we have transfered into another package, thus 686 // should no longer exist. 687 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 688 689 // Broadcast actions that are only available to the system. 690 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 691 692 /** List of packages waiting for verification. */ 693 final SparseArray<PackageVerificationState> mPendingVerification 694 = new SparseArray<PackageVerificationState>(); 695 696 /** Set of packages associated with each app op permission. */ 697 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 698 699 final PackageInstallerService mInstallerService; 700 701 private final PackageDexOptimizer mPackageDexOptimizer; 702 703 private AtomicInteger mNextMoveId = new AtomicInteger(); 704 private final MoveCallbacks mMoveCallbacks; 705 706 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 707 708 // Cache of users who need badging. 709 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 710 711 /** Token for keys in mPendingVerification. */ 712 private int mPendingVerificationToken = 0; 713 714 volatile boolean mSystemReady; 715 volatile boolean mSafeMode; 716 volatile boolean mHasSystemUidErrors; 717 718 ApplicationInfo mAndroidApplication; 719 final ActivityInfo mResolveActivity = new ActivityInfo(); 720 final ResolveInfo mResolveInfo = new ResolveInfo(); 721 ComponentName mResolveComponentName; 722 PackageParser.Package mPlatformPackage; 723 ComponentName mCustomResolverComponentName; 724 725 boolean mResolverReplaced = false; 726 727 private final @Nullable ComponentName mIntentFilterVerifierComponent; 728 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 729 730 private int mIntentFilterVerificationToken = 0; 731 732 /** Component that knows whether or not an ephemeral application exists */ 733 final ComponentName mEphemeralResolverComponent; 734 /** The service connection to the ephemeral resolver */ 735 final EphemeralResolverConnection mEphemeralResolverConnection; 736 737 /** Component used to install ephemeral applications */ 738 final ComponentName mEphemeralInstallerComponent; 739 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 740 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 741 742 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 743 = new SparseArray<IntentFilterVerificationState>(); 744 745 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 746 new DefaultPermissionGrantPolicy(this); 747 748 // List of packages names to keep cached, even if they are uninstalled for all users 749 private List<String> mKeepUninstalledPackages; 750 751 private UserManagerInternal mUserManagerInternal; 752 753 private static class IFVerificationParams { 754 PackageParser.Package pkg; 755 boolean replacing; 756 int userId; 757 int verifierUid; 758 759 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 760 int _userId, int _verifierUid) { 761 pkg = _pkg; 762 replacing = _replacing; 763 userId = _userId; 764 replacing = _replacing; 765 verifierUid = _verifierUid; 766 } 767 } 768 769 private interface IntentFilterVerifier<T extends IntentFilter> { 770 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 771 T filter, String packageName); 772 void startVerifications(int userId); 773 void receiveVerificationResponse(int verificationId); 774 } 775 776 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 777 private Context mContext; 778 private ComponentName mIntentFilterVerifierComponent; 779 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 780 781 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 782 mContext = context; 783 mIntentFilterVerifierComponent = verifierComponent; 784 } 785 786 private String getDefaultScheme() { 787 return IntentFilter.SCHEME_HTTPS; 788 } 789 790 @Override 791 public void startVerifications(int userId) { 792 // Launch verifications requests 793 int count = mCurrentIntentFilterVerifications.size(); 794 for (int n=0; n<count; n++) { 795 int verificationId = mCurrentIntentFilterVerifications.get(n); 796 final IntentFilterVerificationState ivs = 797 mIntentFilterVerificationStates.get(verificationId); 798 799 String packageName = ivs.getPackageName(); 800 801 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 802 final int filterCount = filters.size(); 803 ArraySet<String> domainsSet = new ArraySet<>(); 804 for (int m=0; m<filterCount; m++) { 805 PackageParser.ActivityIntentInfo filter = filters.get(m); 806 domainsSet.addAll(filter.getHostsList()); 807 } 808 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 809 synchronized (mPackages) { 810 if (mSettings.createIntentFilterVerificationIfNeededLPw( 811 packageName, domainsList) != null) { 812 scheduleWriteSettingsLocked(); 813 } 814 } 815 sendVerificationRequest(userId, verificationId, ivs); 816 } 817 mCurrentIntentFilterVerifications.clear(); 818 } 819 820 private void sendVerificationRequest(int userId, int verificationId, 821 IntentFilterVerificationState ivs) { 822 823 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 826 verificationId); 827 verificationIntent.putExtra( 828 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 829 getDefaultScheme()); 830 verificationIntent.putExtra( 831 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 832 ivs.getHostsString()); 833 verificationIntent.putExtra( 834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 835 ivs.getPackageName()); 836 verificationIntent.setComponent(mIntentFilterVerifierComponent); 837 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 838 839 UserHandle user = new UserHandle(userId); 840 mContext.sendBroadcastAsUser(verificationIntent, user); 841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 842 "Sending IntentFilter verification broadcast"); 843 } 844 845 public void receiveVerificationResponse(int verificationId) { 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 848 final boolean verified = ivs.isVerified(); 849 850 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 851 final int count = filters.size(); 852 if (DEBUG_DOMAIN_VERIFICATION) { 853 Slog.i(TAG, "Received verification response " + verificationId 854 + " for " + count + " filters, verified=" + verified); 855 } 856 for (int n=0; n<count; n++) { 857 PackageParser.ActivityIntentInfo filter = filters.get(n); 858 filter.setVerified(verified); 859 860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 861 + " verified with result:" + verified + " and hosts:" 862 + ivs.getHostsString()); 863 } 864 865 mIntentFilterVerificationStates.remove(verificationId); 866 867 final String packageName = ivs.getPackageName(); 868 IntentFilterVerificationInfo ivi = null; 869 870 synchronized (mPackages) { 871 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 872 } 873 if (ivi == null) { 874 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 875 + verificationId + " packageName:" + packageName); 876 return; 877 } 878 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 879 "Updating IntentFilterVerificationInfo for package " + packageName 880 +" verificationId:" + verificationId); 881 882 synchronized (mPackages) { 883 if (verified) { 884 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 885 } else { 886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 887 } 888 scheduleWriteSettingsLocked(); 889 890 final int userId = ivs.getUserId(); 891 if (userId != UserHandle.USER_ALL) { 892 final int userStatus = 893 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 894 895 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 896 boolean needUpdate = false; 897 898 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 899 // already been set by the User thru the Disambiguation dialog 900 switch (userStatus) { 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 } else { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 906 } 907 needUpdate = true; 908 break; 909 910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 911 if (verified) { 912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 913 needUpdate = true; 914 } 915 break; 916 917 default: 918 // Nothing to do 919 } 920 921 if (needUpdate) { 922 mSettings.updateIntentFilterVerificationStatusLPw( 923 packageName, updatedStatus, userId); 924 scheduleWritePackageRestrictionsLocked(userId); 925 } 926 } 927 } 928 } 929 930 @Override 931 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 932 ActivityIntentInfo filter, String packageName) { 933 if (!hasValidDomains(filter)) { 934 return false; 935 } 936 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 937 if (ivs == null) { 938 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 939 packageName); 940 } 941 if (DEBUG_DOMAIN_VERIFICATION) { 942 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 943 } 944 ivs.addFilter(filter); 945 return true; 946 } 947 948 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 949 int userId, int verificationId, String packageName) { 950 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 951 verifierUid, userId, packageName); 952 ivs.setPendingState(); 953 synchronized (mPackages) { 954 mIntentFilterVerificationStates.append(verificationId, ivs); 955 mCurrentIntentFilterVerifications.add(verificationId); 956 } 957 return ivs; 958 } 959 } 960 961 private static boolean hasValidDomains(ActivityIntentInfo filter) { 962 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 963 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 964 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 965 } 966 967 // Set of pending broadcasts for aggregating enable/disable of components. 968 static class PendingPackageBroadcasts { 969 // for each user id, a map of <package name -> components within that package> 970 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 971 972 public PendingPackageBroadcasts() { 973 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 974 } 975 976 public ArrayList<String> get(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 return packages.get(packageName); 979 } 980 981 public void put(int userId, String packageName, ArrayList<String> components) { 982 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 983 packages.put(packageName, components); 984 } 985 986 public void remove(int userId, String packageName) { 987 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 988 if (packages != null) { 989 packages.remove(packageName); 990 } 991 } 992 993 public void remove(int userId) { 994 mUidMap.remove(userId); 995 } 996 997 public int userIdCount() { 998 return mUidMap.size(); 999 } 1000 1001 public int userIdAt(int n) { 1002 return mUidMap.keyAt(n); 1003 } 1004 1005 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1006 return mUidMap.get(userId); 1007 } 1008 1009 public int size() { 1010 // total number of pending broadcast entries across all userIds 1011 int num = 0; 1012 for (int i = 0; i< mUidMap.size(); i++) { 1013 num += mUidMap.valueAt(i).size(); 1014 } 1015 return num; 1016 } 1017 1018 public void clear() { 1019 mUidMap.clear(); 1020 } 1021 1022 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1023 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1024 if (map == null) { 1025 map = new ArrayMap<String, ArrayList<String>>(); 1026 mUidMap.put(userId, map); 1027 } 1028 return map; 1029 } 1030 } 1031 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1032 1033 // Service Connection to remote media container service to copy 1034 // package uri's from external media onto secure containers 1035 // or internal storage. 1036 private IMediaContainerService mContainerService = null; 1037 1038 static final int SEND_PENDING_BROADCAST = 1; 1039 static final int MCS_BOUND = 3; 1040 static final int END_COPY = 4; 1041 static final int INIT_COPY = 5; 1042 static final int MCS_UNBIND = 6; 1043 static final int START_CLEANING_PACKAGE = 7; 1044 static final int FIND_INSTALL_LOC = 8; 1045 static final int POST_INSTALL = 9; 1046 static final int MCS_RECONNECT = 10; 1047 static final int MCS_GIVE_UP = 11; 1048 static final int UPDATED_MEDIA_STATUS = 12; 1049 static final int WRITE_SETTINGS = 13; 1050 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1051 static final int PACKAGE_VERIFIED = 15; 1052 static final int CHECK_PENDING_VERIFICATION = 16; 1053 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1054 static final int INTENT_FILTER_VERIFIED = 18; 1055 static final int WRITE_PACKAGE_LIST = 19; 1056 1057 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1058 1059 // Delay time in millisecs 1060 static final int BROADCAST_DELAY = 10 * 1000; 1061 1062 static UserManagerService sUserManager; 1063 1064 // Stores a list of users whose package restrictions file needs to be updated 1065 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1066 1067 final private DefaultContainerConnection mDefContainerConn = 1068 new DefaultContainerConnection(); 1069 class DefaultContainerConnection implements ServiceConnection { 1070 public void onServiceConnected(ComponentName name, IBinder service) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1072 IMediaContainerService imcs = 1073 IMediaContainerService.Stub.asInterface(service); 1074 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1075 } 1076 1077 public void onServiceDisconnected(ComponentName name) { 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1079 } 1080 } 1081 1082 // Recordkeeping of restore-after-install operations that are currently in flight 1083 // between the Package Manager and the Backup Manager 1084 static class PostInstallData { 1085 public InstallArgs args; 1086 public PackageInstalledInfo res; 1087 1088 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1089 args = _a; 1090 res = _r; 1091 } 1092 } 1093 1094 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1095 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1096 1097 // XML tags for backup/restore of various bits of state 1098 private static final String TAG_PREFERRED_BACKUP = "pa"; 1099 private static final String TAG_DEFAULT_APPS = "da"; 1100 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1101 1102 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1103 private static final String TAG_ALL_GRANTS = "rt-grants"; 1104 private static final String TAG_GRANT = "grant"; 1105 private static final String ATTR_PACKAGE_NAME = "pkg"; 1106 1107 private static final String TAG_PERMISSION = "perm"; 1108 private static final String ATTR_PERMISSION_NAME = "name"; 1109 private static final String ATTR_IS_GRANTED = "g"; 1110 private static final String ATTR_USER_SET = "set"; 1111 private static final String ATTR_USER_FIXED = "fixed"; 1112 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1113 1114 // System/policy permission grants are not backed up 1115 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1116 FLAG_PERMISSION_POLICY_FIXED 1117 | FLAG_PERMISSION_SYSTEM_FIXED 1118 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1119 1120 // And we back up these user-adjusted states 1121 private static final int USER_RUNTIME_GRANT_MASK = 1122 FLAG_PERMISSION_USER_SET 1123 | FLAG_PERMISSION_USER_FIXED 1124 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1125 1126 final @Nullable String mRequiredVerifierPackage; 1127 final @NonNull String mRequiredInstallerPackage; 1128 final @Nullable String mSetupWizardPackage; 1129 final @NonNull String mServicesSystemSharedLibraryPackageName; 1130 final @NonNull String mSharedSystemSharedLibraryPackageName; 1131 1132 private final PackageUsage mPackageUsage = new PackageUsage(); 1133 1134 private class PackageUsage { 1135 private static final int WRITE_INTERVAL 1136 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1137 1138 private final Object mFileLock = new Object(); 1139 private final AtomicLong mLastWritten = new AtomicLong(0); 1140 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1141 1142 private boolean mIsHistoricalPackageUsageAvailable = true; 1143 1144 boolean isHistoricalPackageUsageAvailable() { 1145 return mIsHistoricalPackageUsageAvailable; 1146 } 1147 1148 void write(boolean force) { 1149 if (force) { 1150 writeInternal(); 1151 return; 1152 } 1153 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1154 && !DEBUG_DEXOPT) { 1155 return; 1156 } 1157 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1158 new Thread("PackageUsage_DiskWriter") { 1159 @Override 1160 public void run() { 1161 try { 1162 writeInternal(); 1163 } finally { 1164 mBackgroundWriteRunning.set(false); 1165 } 1166 } 1167 }.start(); 1168 } 1169 } 1170 1171 private void writeInternal() { 1172 synchronized (mPackages) { 1173 synchronized (mFileLock) { 1174 AtomicFile file = getFile(); 1175 FileOutputStream f = null; 1176 try { 1177 f = file.startWrite(); 1178 BufferedOutputStream out = new BufferedOutputStream(f); 1179 FileUtils.setPermissions(file.getBaseFile().getPath(), 1180 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1181 StringBuilder sb = new StringBuilder(); 1182 1183 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1184 sb.append('\n'); 1185 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1186 1187 for (PackageParser.Package pkg : mPackages.values()) { 1188 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1189 continue; 1190 } 1191 sb.setLength(0); 1192 sb.append(pkg.packageName); 1193 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1194 sb.append(' '); 1195 sb.append(usageTimeInMillis); 1196 } 1197 sb.append('\n'); 1198 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1199 } 1200 out.flush(); 1201 file.finishWrite(f); 1202 } catch (IOException e) { 1203 if (f != null) { 1204 file.failWrite(f); 1205 } 1206 Log.e(TAG, "Failed to write package usage times", e); 1207 } 1208 } 1209 } 1210 mLastWritten.set(SystemClock.elapsedRealtime()); 1211 } 1212 1213 void readLP() { 1214 synchronized (mFileLock) { 1215 AtomicFile file = getFile(); 1216 BufferedInputStream in = null; 1217 try { 1218 in = new BufferedInputStream(file.openRead()); 1219 StringBuffer sb = new StringBuffer(); 1220 1221 String firstLine = readLine(in, sb); 1222 if (firstLine == null) { 1223 // Empty file. Do nothing. 1224 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1225 readVersion1LP(in, sb); 1226 } else { 1227 readVersion0LP(in, sb, firstLine); 1228 } 1229 } catch (FileNotFoundException expected) { 1230 mIsHistoricalPackageUsageAvailable = false; 1231 } catch (IOException e) { 1232 Log.w(TAG, "Failed to read package usage times", e); 1233 } finally { 1234 IoUtils.closeQuietly(in); 1235 } 1236 } 1237 mLastWritten.set(SystemClock.elapsedRealtime()); 1238 } 1239 1240 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1241 throws IOException { 1242 // Initial version of the file had no version number and stored one 1243 // package-timestamp pair per line. 1244 // Note that the first line has already been read from the InputStream. 1245 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1246 String[] tokens = line.split(" "); 1247 if (tokens.length != 2) { 1248 throw new IOException("Failed to parse " + line + 1249 " as package-timestamp pair."); 1250 } 1251 1252 String packageName = tokens[0]; 1253 PackageParser.Package pkg = mPackages.get(packageName); 1254 if (pkg == null) { 1255 continue; 1256 } 1257 1258 long timestamp = parseAsLong(tokens[1]); 1259 for (int reason = 0; 1260 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1261 reason++) { 1262 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1263 } 1264 } 1265 } 1266 1267 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1268 // Version 1 of the file started with the corresponding version 1269 // number and then stored a package name and eight timestamps per line. 1270 String line; 1271 while ((line = readLine(in, sb)) != null) { 1272 String[] tokens = line.split(" "); 1273 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1274 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1275 } 1276 1277 String packageName = tokens[0]; 1278 PackageParser.Package pkg = mPackages.get(packageName); 1279 if (pkg == null) { 1280 continue; 1281 } 1282 1283 for (int reason = 0; 1284 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1285 reason++) { 1286 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1287 } 1288 } 1289 } 1290 1291 private long parseAsLong(String token) throws IOException { 1292 try { 1293 return Long.parseLong(token); 1294 } catch (NumberFormatException e) { 1295 throw new IOException("Failed to parse " + token + " as a long.", e); 1296 } 1297 } 1298 1299 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1300 return readToken(in, sb, '\n'); 1301 } 1302 1303 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1304 throws IOException { 1305 sb.setLength(0); 1306 while (true) { 1307 int ch = in.read(); 1308 if (ch == -1) { 1309 if (sb.length() == 0) { 1310 return null; 1311 } 1312 throw new IOException("Unexpected EOF"); 1313 } 1314 if (ch == endOfToken) { 1315 return sb.toString(); 1316 } 1317 sb.append((char)ch); 1318 } 1319 } 1320 1321 private AtomicFile getFile() { 1322 File dataDir = Environment.getDataDirectory(); 1323 File systemDir = new File(dataDir, "system"); 1324 File fname = new File(systemDir, "package-usage.list"); 1325 return new AtomicFile(fname); 1326 } 1327 1328 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1329 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1330 } 1331 1332 class PackageHandler extends Handler { 1333 private boolean mBound = false; 1334 final ArrayList<HandlerParams> mPendingInstalls = 1335 new ArrayList<HandlerParams>(); 1336 1337 private boolean connectToService() { 1338 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1339 " DefaultContainerService"); 1340 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1343 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1345 mBound = true; 1346 return true; 1347 } 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 return false; 1350 } 1351 1352 private void disconnectService() { 1353 mContainerService = null; 1354 mBound = false; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 mContext.unbindService(mDefContainerConn); 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 } 1359 1360 PackageHandler(Looper looper) { 1361 super(looper); 1362 } 1363 1364 public void handleMessage(Message msg) { 1365 try { 1366 doHandleMessage(msg); 1367 } finally { 1368 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1369 } 1370 } 1371 1372 void doHandleMessage(Message msg) { 1373 switch (msg.what) { 1374 case INIT_COPY: { 1375 HandlerParams params = (HandlerParams) msg.obj; 1376 int idx = mPendingInstalls.size(); 1377 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1378 // If a bind was already initiated we dont really 1379 // need to do anything. The pending install 1380 // will be processed later on. 1381 if (!mBound) { 1382 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1383 System.identityHashCode(mHandler)); 1384 // If this is the only one pending we might 1385 // have to bind to the service again. 1386 if (!connectToService()) { 1387 Slog.e(TAG, "Failed to bind to media container service"); 1388 params.serviceError(); 1389 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1390 System.identityHashCode(mHandler)); 1391 if (params.traceMethod != null) { 1392 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1393 params.traceCookie); 1394 } 1395 return; 1396 } else { 1397 // Once we bind to the service, the first 1398 // pending request will be processed. 1399 mPendingInstalls.add(idx, params); 1400 } 1401 } else { 1402 mPendingInstalls.add(idx, params); 1403 // Already bound to the service. Just make 1404 // sure we trigger off processing the first request. 1405 if (idx == 0) { 1406 mHandler.sendEmptyMessage(MCS_BOUND); 1407 } 1408 } 1409 break; 1410 } 1411 case MCS_BOUND: { 1412 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1413 if (msg.obj != null) { 1414 mContainerService = (IMediaContainerService) msg.obj; 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1416 System.identityHashCode(mHandler)); 1417 } 1418 if (mContainerService == null) { 1419 if (!mBound) { 1420 // Something seriously wrong since we are not bound and we are not 1421 // waiting for connection. Bail out. 1422 Slog.e(TAG, "Cannot bind to media container service"); 1423 for (HandlerParams params : mPendingInstalls) { 1424 // Indicate service bind error 1425 params.serviceError(); 1426 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1427 System.identityHashCode(params)); 1428 if (params.traceMethod != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1430 params.traceMethod, params.traceCookie); 1431 } 1432 return; 1433 } 1434 mPendingInstalls.clear(); 1435 } else { 1436 Slog.w(TAG, "Waiting to connect to media container service"); 1437 } 1438 } else if (mPendingInstalls.size() > 0) { 1439 HandlerParams params = mPendingInstalls.get(0); 1440 if (params != null) { 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1442 System.identityHashCode(params)); 1443 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1444 if (params.startCopy()) { 1445 // We are done... look for more work or to 1446 // go idle. 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, 1448 "Checking for more work or unbind..."); 1449 // Delete pending install 1450 if (mPendingInstalls.size() > 0) { 1451 mPendingInstalls.remove(0); 1452 } 1453 if (mPendingInstalls.size() == 0) { 1454 if (mBound) { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting delayed MCS_UNBIND"); 1457 removeMessages(MCS_UNBIND); 1458 Message ubmsg = obtainMessage(MCS_UNBIND); 1459 // Unbind after a little delay, to avoid 1460 // continual thrashing. 1461 sendMessageDelayed(ubmsg, 10000); 1462 } 1463 } else { 1464 // There are more pending requests in queue. 1465 // Just post MCS_BOUND message to trigger processing 1466 // of next pending install. 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, 1468 "Posting MCS_BOUND for next work"); 1469 mHandler.sendEmptyMessage(MCS_BOUND); 1470 } 1471 } 1472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1473 } 1474 } else { 1475 // Should never happen ideally. 1476 Slog.w(TAG, "Empty queue"); 1477 } 1478 break; 1479 } 1480 case MCS_RECONNECT: { 1481 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1482 if (mPendingInstalls.size() > 0) { 1483 if (mBound) { 1484 disconnectService(); 1485 } 1486 if (!connectToService()) { 1487 Slog.e(TAG, "Failed to bind to media container service"); 1488 for (HandlerParams params : mPendingInstalls) { 1489 // Indicate service bind error 1490 params.serviceError(); 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1492 System.identityHashCode(params)); 1493 } 1494 mPendingInstalls.clear(); 1495 } 1496 } 1497 break; 1498 } 1499 case MCS_UNBIND: { 1500 // If there is no actual work left, then time to unbind. 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1502 1503 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1504 if (mBound) { 1505 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1506 1507 disconnectService(); 1508 } 1509 } else if (mPendingInstalls.size() > 0) { 1510 // There are more pending requests in queue. 1511 // Just post MCS_BOUND message to trigger processing 1512 // of next pending install. 1513 mHandler.sendEmptyMessage(MCS_BOUND); 1514 } 1515 1516 break; 1517 } 1518 case MCS_GIVE_UP: { 1519 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1520 HandlerParams params = mPendingInstalls.remove(0); 1521 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1522 System.identityHashCode(params)); 1523 break; 1524 } 1525 case SEND_PENDING_BROADCAST: { 1526 String packages[]; 1527 ArrayList<String> components[]; 1528 int size = 0; 1529 int uids[]; 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 if (mPendingBroadcasts == null) { 1533 return; 1534 } 1535 size = mPendingBroadcasts.size(); 1536 if (size <= 0) { 1537 // Nothing to be done. Just return 1538 return; 1539 } 1540 packages = new String[size]; 1541 components = new ArrayList[size]; 1542 uids = new int[size]; 1543 int i = 0; // filling out the above arrays 1544 1545 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1546 int packageUserId = mPendingBroadcasts.userIdAt(n); 1547 Iterator<Map.Entry<String, ArrayList<String>>> it 1548 = mPendingBroadcasts.packagesForUserId(packageUserId) 1549 .entrySet().iterator(); 1550 while (it.hasNext() && i < size) { 1551 Map.Entry<String, ArrayList<String>> ent = it.next(); 1552 packages[i] = ent.getKey(); 1553 components[i] = ent.getValue(); 1554 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1555 uids[i] = (ps != null) 1556 ? UserHandle.getUid(packageUserId, ps.appId) 1557 : -1; 1558 i++; 1559 } 1560 } 1561 size = i; 1562 mPendingBroadcasts.clear(); 1563 } 1564 // Send broadcasts 1565 for (int i = 0; i < size; i++) { 1566 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 break; 1570 } 1571 case START_CLEANING_PACKAGE: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 final String packageName = (String)msg.obj; 1574 final int userId = msg.arg1; 1575 final boolean andCode = msg.arg2 != 0; 1576 synchronized (mPackages) { 1577 if (userId == UserHandle.USER_ALL) { 1578 int[] users = sUserManager.getUserIds(); 1579 for (int user : users) { 1580 mSettings.addPackageToCleanLPw( 1581 new PackageCleanItem(user, packageName, andCode)); 1582 } 1583 } else { 1584 mSettings.addPackageToCleanLPw( 1585 new PackageCleanItem(userId, packageName, andCode)); 1586 } 1587 } 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1589 startCleaningPackages(); 1590 } break; 1591 case POST_INSTALL: { 1592 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1593 1594 PostInstallData data = mRunningInstalls.get(msg.arg1); 1595 final boolean didRestore = (msg.arg2 != 0); 1596 mRunningInstalls.delete(msg.arg1); 1597 1598 if (data != null) { 1599 InstallArgs args = data.args; 1600 PackageInstalledInfo parentRes = data.res; 1601 1602 final boolean grantPermissions = (args.installFlags 1603 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1604 final boolean killApp = (args.installFlags 1605 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1606 final String[] grantedPermissions = args.installGrantPermissions; 1607 1608 // Handle the parent package 1609 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1610 grantedPermissions, didRestore, args.installerPackageName, 1611 args.observer); 1612 1613 // Handle the child packages 1614 final int childCount = (parentRes.addedChildPackages != null) 1615 ? parentRes.addedChildPackages.size() : 0; 1616 for (int i = 0; i < childCount; i++) { 1617 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1618 handlePackagePostInstall(childRes, grantPermissions, killApp, 1619 grantedPermissions, false, args.installerPackageName, 1620 args.observer); 1621 } 1622 1623 // Log tracing if needed 1624 if (args.traceMethod != null) { 1625 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1626 args.traceCookie); 1627 } 1628 } else { 1629 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1630 } 1631 1632 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1633 } break; 1634 case UPDATED_MEDIA_STATUS: { 1635 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1636 boolean reportStatus = msg.arg1 == 1; 1637 boolean doGc = msg.arg2 == 1; 1638 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1639 if (doGc) { 1640 // Force a gc to clear up stale containers. 1641 Runtime.getRuntime().gc(); 1642 } 1643 if (msg.obj != null) { 1644 @SuppressWarnings("unchecked") 1645 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1647 // Unload containers 1648 unloadAllContainers(args); 1649 } 1650 if (reportStatus) { 1651 try { 1652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1653 PackageHelper.getMountService().finishMediaUpdate(); 1654 } catch (RemoteException e) { 1655 Log.e(TAG, "MountService not running?"); 1656 } 1657 } 1658 } break; 1659 case WRITE_SETTINGS: { 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1661 synchronized (mPackages) { 1662 removeMessages(WRITE_SETTINGS); 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 mSettings.writeLPr(); 1665 mDirtyUsers.clear(); 1666 } 1667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1668 } break; 1669 case WRITE_PACKAGE_RESTRICTIONS: { 1670 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1671 synchronized (mPackages) { 1672 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1673 for (int userId : mDirtyUsers) { 1674 mSettings.writePackageRestrictionsLPr(userId); 1675 } 1676 mDirtyUsers.clear(); 1677 } 1678 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1679 } break; 1680 case WRITE_PACKAGE_LIST: { 1681 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1682 synchronized (mPackages) { 1683 removeMessages(WRITE_PACKAGE_LIST); 1684 mSettings.writePackageListLPr(msg.arg1); 1685 } 1686 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1687 } break; 1688 case CHECK_PENDING_VERIFICATION: { 1689 final int verificationId = msg.arg1; 1690 final PackageVerificationState state = mPendingVerification.get(verificationId); 1691 1692 if ((state != null) && !state.timeoutExtended()) { 1693 final InstallArgs args = state.getInstallArgs(); 1694 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1695 1696 Slog.i(TAG, "Verification timed out for " + originUri); 1697 mPendingVerification.remove(verificationId); 1698 1699 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1700 1701 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1702 Slog.i(TAG, "Continuing with installation of " + originUri); 1703 state.setVerifierResponse(Binder.getCallingUid(), 1704 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_ALLOW, 1707 state.getInstallArgs().getUser()); 1708 try { 1709 ret = args.copyApk(mContainerService, true); 1710 } catch (RemoteException e) { 1711 Slog.e(TAG, "Could not contact the ContainerService"); 1712 } 1713 } else { 1714 broadcastPackageVerified(verificationId, originUri, 1715 PackageManager.VERIFICATION_REJECT, 1716 state.getInstallArgs().getUser()); 1717 } 1718 1719 Trace.asyncTraceEnd( 1720 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1721 1722 processPendingInstall(args, ret); 1723 mHandler.sendEmptyMessage(MCS_UNBIND); 1724 } 1725 break; 1726 } 1727 case PACKAGE_VERIFIED: { 1728 final int verificationId = msg.arg1; 1729 1730 final PackageVerificationState state = mPendingVerification.get(verificationId); 1731 if (state == null) { 1732 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1733 break; 1734 } 1735 1736 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1737 1738 state.setVerifierResponse(response.callerUid, response.code); 1739 1740 if (state.isVerificationComplete()) { 1741 mPendingVerification.remove(verificationId); 1742 1743 final InstallArgs args = state.getInstallArgs(); 1744 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1745 1746 int ret; 1747 if (state.isInstallAllowed()) { 1748 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1749 broadcastPackageVerified(verificationId, originUri, 1750 response.code, state.getInstallArgs().getUser()); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1758 } 1759 1760 Trace.asyncTraceEnd( 1761 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1762 1763 processPendingInstall(args, ret); 1764 mHandler.sendEmptyMessage(MCS_UNBIND); 1765 } 1766 1767 break; 1768 } 1769 case START_INTENT_FILTER_VERIFICATIONS: { 1770 IFVerificationParams params = (IFVerificationParams) msg.obj; 1771 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1772 params.replacing, params.pkg); 1773 break; 1774 } 1775 case INTENT_FILTER_VERIFIED: { 1776 final int verificationId = msg.arg1; 1777 1778 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1779 verificationId); 1780 if (state == null) { 1781 Slog.w(TAG, "Invalid IntentFilter verification token " 1782 + verificationId + " received"); 1783 break; 1784 } 1785 1786 final int userId = state.getUserId(); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "Processing IntentFilter verification with token:" 1790 + verificationId + " and userId:" + userId); 1791 1792 final IntentFilterVerificationResponse response = 1793 (IntentFilterVerificationResponse) msg.obj; 1794 1795 state.setVerifierResponse(response.callerUid, response.code); 1796 1797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1798 "IntentFilter verification with token:" + verificationId 1799 + " and userId:" + userId 1800 + " is settings verifier response with response code:" 1801 + response.code); 1802 1803 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1805 + response.getFailedDomainsString()); 1806 } 1807 1808 if (state.isVerificationComplete()) { 1809 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1810 } else { 1811 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1812 "IntentFilter verification with token:" + verificationId 1813 + " was not said to be complete"); 1814 } 1815 1816 break; 1817 } 1818 } 1819 } 1820 } 1821 1822 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1823 boolean killApp, String[] grantedPermissions, 1824 boolean launchedForRestore, String installerPackage, 1825 IPackageInstallObserver2 installObserver) { 1826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1827 // Send the removed broadcasts 1828 if (res.removedInfo != null) { 1829 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1830 } 1831 1832 // Now that we successfully installed the package, grant runtime 1833 // permissions if requested before broadcasting the install. 1834 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1835 >= Build.VERSION_CODES.M) { 1836 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1837 } 1838 1839 final boolean update = res.removedInfo != null 1840 && res.removedInfo.removedPackage != null; 1841 1842 // If this is the first time we have child packages for a disabled privileged 1843 // app that had no children, we grant requested runtime permissions to the new 1844 // children if the parent on the system image had them already granted. 1845 if (res.pkg.parentPackage != null) { 1846 synchronized (mPackages) { 1847 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1848 } 1849 } 1850 1851 synchronized (mPackages) { 1852 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1853 } 1854 1855 final String packageName = res.pkg.applicationInfo.packageName; 1856 Bundle extras = new Bundle(1); 1857 extras.putInt(Intent.EXTRA_UID, res.uid); 1858 1859 // Determine the set of users who are adding this package for 1860 // the first time vs. those who are seeing an update. 1861 int[] firstUsers = EMPTY_INT_ARRAY; 1862 int[] updateUsers = EMPTY_INT_ARRAY; 1863 if (res.origUsers == null || res.origUsers.length == 0) { 1864 firstUsers = res.newUsers; 1865 } else { 1866 for (int newUser : res.newUsers) { 1867 boolean isNew = true; 1868 for (int origUser : res.origUsers) { 1869 if (origUser == newUser) { 1870 isNew = false; 1871 break; 1872 } 1873 } 1874 if (isNew) { 1875 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1876 } else { 1877 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1878 } 1879 } 1880 } 1881 1882 // Send installed broadcasts if the install/update is not ephemeral 1883 if (!isEphemeral(res.pkg)) { 1884 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1885 1886 // Send added for users that see the package for the first time 1887 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1888 extras, 0 /*flags*/, null /*targetPackage*/, 1889 null /*finishedReceiver*/, firstUsers); 1890 1891 // Send added for users that don't see the package for the first time 1892 if (update) { 1893 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1894 } 1895 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1896 extras, 0 /*flags*/, null /*targetPackage*/, 1897 null /*finishedReceiver*/, updateUsers); 1898 1899 // Send replaced for users that don't see the package for the first time 1900 if (update) { 1901 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1902 packageName, extras, 0 /*flags*/, 1903 null /*targetPackage*/, null /*finishedReceiver*/, 1904 updateUsers); 1905 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1906 null /*package*/, null /*extras*/, 0 /*flags*/, 1907 packageName /*targetPackage*/, 1908 null /*finishedReceiver*/, updateUsers); 1909 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1910 // First-install and we did a restore, so we're responsible for the 1911 // first-launch broadcast. 1912 if (DEBUG_BACKUP) { 1913 Slog.i(TAG, "Post-restore of " + packageName 1914 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1915 } 1916 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1917 } 1918 1919 // Send broadcast package appeared if forward locked/external for all users 1920 // treat asec-hosted packages like removable media on upgrade 1921 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1922 if (DEBUG_INSTALL) { 1923 Slog.i(TAG, "upgrading pkg " + res.pkg 1924 + " is ASEC-hosted -> AVAILABLE"); 1925 } 1926 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1927 ArrayList<String> pkgList = new ArrayList<>(1); 1928 pkgList.add(packageName); 1929 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1930 } 1931 } 1932 1933 // Work that needs to happen on first install within each user 1934 if (firstUsers != null && firstUsers.length > 0) { 1935 synchronized (mPackages) { 1936 for (int userId : firstUsers) { 1937 // If this app is a browser and it's newly-installed for some 1938 // users, clear any default-browser state in those users. The 1939 // app's nature doesn't depend on the user, so we can just check 1940 // its browser nature in any user and generalize. 1941 if (packageIsBrowser(packageName, userId)) { 1942 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1943 } 1944 1945 // We may also need to apply pending (restored) runtime 1946 // permission grants within these users. 1947 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1948 } 1949 } 1950 } 1951 1952 // Log current value of "unknown sources" setting 1953 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1954 getUnknownSourcesSettings()); 1955 1956 // Force a gc to clear up things 1957 Runtime.getRuntime().gc(); 1958 1959 // Remove the replaced package's older resources safely now 1960 // We delete after a gc for applications on sdcard. 1961 if (res.removedInfo != null && res.removedInfo.args != null) { 1962 synchronized (mInstallLock) { 1963 res.removedInfo.args.doPostDeleteLI(true); 1964 } 1965 } 1966 } 1967 1968 // If someone is watching installs - notify them 1969 if (installObserver != null) { 1970 try { 1971 Bundle extras = extrasForInstallResult(res); 1972 installObserver.onPackageInstalled(res.name, res.returnCode, 1973 res.returnMsg, extras); 1974 } catch (RemoteException e) { 1975 Slog.i(TAG, "Observer no longer exists."); 1976 } 1977 } 1978 } 1979 1980 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1981 PackageParser.Package pkg) { 1982 if (pkg.parentPackage == null) { 1983 return; 1984 } 1985 if (pkg.requestedPermissions == null) { 1986 return; 1987 } 1988 final PackageSetting disabledSysParentPs = mSettings 1989 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1990 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1991 || !disabledSysParentPs.isPrivileged() 1992 || (disabledSysParentPs.childPackageNames != null 1993 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1994 return; 1995 } 1996 final int[] allUserIds = sUserManager.getUserIds(); 1997 final int permCount = pkg.requestedPermissions.size(); 1998 for (int i = 0; i < permCount; i++) { 1999 String permission = pkg.requestedPermissions.get(i); 2000 BasePermission bp = mSettings.mPermissions.get(permission); 2001 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2002 continue; 2003 } 2004 for (int userId : allUserIds) { 2005 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2006 permission, userId)) { 2007 grantRuntimePermission(pkg.packageName, permission, userId); 2008 } 2009 } 2010 } 2011 } 2012 2013 private StorageEventListener mStorageListener = new StorageEventListener() { 2014 @Override 2015 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2016 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 final String volumeUuid = vol.getFsUuid(); 2019 2020 // Clean up any users or apps that were removed or recreated 2021 // while this volume was missing 2022 reconcileUsers(volumeUuid); 2023 reconcileApps(volumeUuid); 2024 2025 // Clean up any install sessions that expired or were 2026 // cancelled while this volume was missing 2027 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2028 2029 loadPrivatePackages(vol); 2030 2031 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2032 unloadPrivatePackages(vol); 2033 } 2034 } 2035 2036 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2037 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2038 updateExternalMediaStatus(true, false); 2039 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2040 updateExternalMediaStatus(false, false); 2041 } 2042 } 2043 } 2044 2045 @Override 2046 public void onVolumeForgotten(String fsUuid) { 2047 if (TextUtils.isEmpty(fsUuid)) { 2048 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2049 return; 2050 } 2051 2052 // Remove any apps installed on the forgotten volume 2053 synchronized (mPackages) { 2054 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2055 for (PackageSetting ps : packages) { 2056 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2057 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2058 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2059 } 2060 2061 mSettings.onVolumeForgotten(fsUuid); 2062 mSettings.writeLPr(); 2063 } 2064 } 2065 }; 2066 2067 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2068 String[] grantedPermissions) { 2069 for (int userId : userIds) { 2070 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2071 } 2072 2073 // We could have touched GID membership, so flush out packages.list 2074 synchronized (mPackages) { 2075 mSettings.writePackageListLPr(); 2076 } 2077 } 2078 2079 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2080 String[] grantedPermissions) { 2081 SettingBase sb = (SettingBase) pkg.mExtras; 2082 if (sb == null) { 2083 return; 2084 } 2085 2086 PermissionsState permissionsState = sb.getPermissionsState(); 2087 2088 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2089 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2090 2091 for (String permission : pkg.requestedPermissions) { 2092 final BasePermission bp; 2093 synchronized (mPackages) { 2094 bp = mSettings.mPermissions.get(permission); 2095 } 2096 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2097 && (grantedPermissions == null 2098 || ArrayUtils.contains(grantedPermissions, permission))) { 2099 final int flags = permissionsState.getPermissionFlags(permission, userId); 2100 // Installer cannot change immutable permissions. 2101 if ((flags & immutableFlags) == 0) { 2102 grantRuntimePermission(pkg.packageName, permission, userId); 2103 } 2104 } 2105 } 2106 } 2107 2108 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2109 Bundle extras = null; 2110 switch (res.returnCode) { 2111 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2112 extras = new Bundle(); 2113 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2114 res.origPermission); 2115 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2116 res.origPackage); 2117 break; 2118 } 2119 case PackageManager.INSTALL_SUCCEEDED: { 2120 extras = new Bundle(); 2121 extras.putBoolean(Intent.EXTRA_REPLACING, 2122 res.removedInfo != null && res.removedInfo.removedPackage != null); 2123 break; 2124 } 2125 } 2126 return extras; 2127 } 2128 2129 void scheduleWriteSettingsLocked() { 2130 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2131 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2132 } 2133 } 2134 2135 void scheduleWritePackageListLocked(int userId) { 2136 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2137 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2138 msg.arg1 = userId; 2139 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2140 } 2141 } 2142 2143 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2144 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2145 scheduleWritePackageRestrictionsLocked(userId); 2146 } 2147 2148 void scheduleWritePackageRestrictionsLocked(int userId) { 2149 final int[] userIds = (userId == UserHandle.USER_ALL) 2150 ? sUserManager.getUserIds() : new int[]{userId}; 2151 for (int nextUserId : userIds) { 2152 if (!sUserManager.exists(nextUserId)) return; 2153 mDirtyUsers.add(nextUserId); 2154 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2155 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2156 } 2157 } 2158 } 2159 2160 public static PackageManagerService main(Context context, Installer installer, 2161 boolean factoryTest, boolean onlyCore) { 2162 // Self-check for initial settings. 2163 PackageManagerServiceCompilerMapping.checkProperties(); 2164 2165 PackageManagerService m = new PackageManagerService(context, installer, 2166 factoryTest, onlyCore); 2167 m.enableSystemUserPackages(); 2168 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2169 // disabled after already being started. 2170 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2171 UserHandle.USER_SYSTEM); 2172 ServiceManager.addService("package", m); 2173 return m; 2174 } 2175 2176 private void enableSystemUserPackages() { 2177 if (!UserManager.isSplitSystemUser()) { 2178 return; 2179 } 2180 // For system user, enable apps based on the following conditions: 2181 // - app is whitelisted or belong to one of these groups: 2182 // -- system app which has no launcher icons 2183 // -- system app which has INTERACT_ACROSS_USERS permission 2184 // -- system IME app 2185 // - app is not in the blacklist 2186 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2187 Set<String> enableApps = new ArraySet<>(); 2188 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2189 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2190 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2191 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2192 enableApps.addAll(wlApps); 2193 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2194 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2195 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2196 enableApps.removeAll(blApps); 2197 Log.i(TAG, "Applications installed for system user: " + enableApps); 2198 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2199 UserHandle.SYSTEM); 2200 final int allAppsSize = allAps.size(); 2201 synchronized (mPackages) { 2202 for (int i = 0; i < allAppsSize; i++) { 2203 String pName = allAps.get(i); 2204 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2205 // Should not happen, but we shouldn't be failing if it does 2206 if (pkgSetting == null) { 2207 continue; 2208 } 2209 boolean install = enableApps.contains(pName); 2210 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2211 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2212 + " for system user"); 2213 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2214 } 2215 } 2216 } 2217 } 2218 2219 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2220 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2221 Context.DISPLAY_SERVICE); 2222 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2223 } 2224 2225 /** 2226 * Requests that files preopted on a secondary system partition be copied to the data partition 2227 * if possible. Note that the actual copying of the files is accomplished by init for security 2228 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2229 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2230 */ 2231 private static void requestCopyPreoptedFiles() { 2232 final int WAIT_TIME_MS = 100; 2233 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2234 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2235 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2236 // We will wait for up to 100 seconds. 2237 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2238 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2239 try { 2240 Thread.sleep(WAIT_TIME_MS); 2241 } catch (InterruptedException e) { 2242 // Do nothing 2243 } 2244 if (SystemClock.uptimeMillis() > timeEnd) { 2245 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2246 Slog.wtf(TAG, "cppreopt did not finish!"); 2247 break; 2248 } 2249 } 2250 } 2251 } 2252 2253 public PackageManagerService(Context context, Installer installer, 2254 boolean factoryTest, boolean onlyCore) { 2255 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2256 SystemClock.uptimeMillis()); 2257 2258 if (mSdkVersion <= 0) { 2259 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2260 } 2261 2262 mContext = context; 2263 mFactoryTest = factoryTest; 2264 mOnlyCore = onlyCore; 2265 mMetrics = new DisplayMetrics(); 2266 mSettings = new Settings(mPackages); 2267 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2268 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2269 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2270 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2271 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2272 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2273 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2274 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2275 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2276 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2277 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2278 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2279 2280 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2281 if (separateProcesses != null && separateProcesses.length() > 0) { 2282 if ("*".equals(separateProcesses)) { 2283 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2284 mSeparateProcesses = null; 2285 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2286 } else { 2287 mDefParseFlags = 0; 2288 mSeparateProcesses = separateProcesses.split(","); 2289 Slog.w(TAG, "Running with debug.separate_processes: " 2290 + separateProcesses); 2291 } 2292 } else { 2293 mDefParseFlags = 0; 2294 mSeparateProcesses = null; 2295 } 2296 2297 mInstaller = installer; 2298 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2299 "*dexopt*"); 2300 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2301 2302 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2303 FgThread.get().getLooper()); 2304 2305 getDefaultDisplayMetrics(context, mMetrics); 2306 2307 SystemConfig systemConfig = SystemConfig.getInstance(); 2308 mGlobalGids = systemConfig.getGlobalGids(); 2309 mSystemPermissions = systemConfig.getSystemPermissions(); 2310 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2311 2312 mProtectedPackages = new ProtectedPackages(mContext); 2313 2314 synchronized (mInstallLock) { 2315 // writer 2316 synchronized (mPackages) { 2317 mHandlerThread = new ServiceThread(TAG, 2318 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2319 mHandlerThread.start(); 2320 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2321 mProcessLoggingHandler = new ProcessLoggingHandler(); 2322 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2323 2324 File dataDir = Environment.getDataDirectory(); 2325 mAppInstallDir = new File(dataDir, "app"); 2326 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2327 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2328 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2329 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2330 2331 sUserManager = new UserManagerService(context, this, mPackages); 2332 2333 // Propagate permission configuration in to package manager. 2334 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2335 = systemConfig.getPermissions(); 2336 for (int i=0; i<permConfig.size(); i++) { 2337 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2338 BasePermission bp = mSettings.mPermissions.get(perm.name); 2339 if (bp == null) { 2340 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2341 mSettings.mPermissions.put(perm.name, bp); 2342 } 2343 if (perm.gids != null) { 2344 bp.setGids(perm.gids, perm.perUser); 2345 } 2346 } 2347 2348 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2349 for (int i=0; i<libConfig.size(); i++) { 2350 mSharedLibraries.put(libConfig.keyAt(i), 2351 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2352 } 2353 2354 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2355 2356 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2357 2358 if (mFirstBoot) { 2359 requestCopyPreoptedFiles(); 2360 } 2361 2362 String customResolverActivity = Resources.getSystem().getString( 2363 R.string.config_customResolverActivity); 2364 if (TextUtils.isEmpty(customResolverActivity)) { 2365 customResolverActivity = null; 2366 } else { 2367 mCustomResolverComponentName = ComponentName.unflattenFromString( 2368 customResolverActivity); 2369 } 2370 2371 long startTime = SystemClock.uptimeMillis(); 2372 2373 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2374 startTime); 2375 2376 // Set flag to monitor and not change apk file paths when 2377 // scanning install directories. 2378 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2379 2380 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2381 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2382 2383 if (bootClassPath == null) { 2384 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2385 } 2386 2387 if (systemServerClassPath == null) { 2388 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2389 } 2390 2391 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2392 final String[] dexCodeInstructionSets = 2393 getDexCodeInstructionSets( 2394 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2395 2396 /** 2397 * Ensure all external libraries have had dexopt run on them. 2398 */ 2399 if (mSharedLibraries.size() > 0) { 2400 // NOTE: For now, we're compiling these system "shared libraries" 2401 // (and framework jars) into all available architectures. It's possible 2402 // to compile them only when we come across an app that uses them (there's 2403 // already logic for that in scanPackageLI) but that adds some complexity. 2404 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2405 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2406 final String lib = libEntry.path; 2407 if (lib == null) { 2408 continue; 2409 } 2410 2411 try { 2412 // Shared libraries do not have profiles so we perform a full 2413 // AOT compilation (if needed). 2414 int dexoptNeeded = DexFile.getDexOptNeeded( 2415 lib, dexCodeInstructionSet, 2416 getCompilerFilterForReason(REASON_SHARED_APK), 2417 false /* newProfile */); 2418 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2419 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2420 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2421 getCompilerFilterForReason(REASON_SHARED_APK), 2422 StorageManager.UUID_PRIVATE_INTERNAL, 2423 SKIP_SHARED_LIBRARY_CHECK); 2424 } 2425 } catch (FileNotFoundException e) { 2426 Slog.w(TAG, "Library not found: " + lib); 2427 } catch (IOException | InstallerException e) { 2428 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2429 + e.getMessage()); 2430 } 2431 } 2432 } 2433 } 2434 2435 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2436 2437 final VersionInfo ver = mSettings.getInternalVersion(); 2438 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2439 2440 // when upgrading from pre-M, promote system app permissions from install to runtime 2441 mPromoteSystemApps = 2442 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2443 2444 // When upgrading from pre-N, we need to handle package extraction like first boot, 2445 // as there is no profiling data available. 2446 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2447 2448 // save off the names of pre-existing system packages prior to scanning; we don't 2449 // want to automatically grant runtime permissions for new system apps 2450 if (mPromoteSystemApps) { 2451 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2452 while (pkgSettingIter.hasNext()) { 2453 PackageSetting ps = pkgSettingIter.next(); 2454 if (isSystemApp(ps)) { 2455 mExistingSystemPackages.add(ps.name); 2456 } 2457 } 2458 } 2459 2460 // Collect vendor overlay packages. 2461 // (Do this before scanning any apps.) 2462 // For security and version matching reason, only consider 2463 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2464 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2465 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2466 | PackageParser.PARSE_IS_SYSTEM 2467 | PackageParser.PARSE_IS_SYSTEM_DIR 2468 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2469 2470 // Find base frameworks (resource packages without code). 2471 scanDirTracedLI(frameworkDir, mDefParseFlags 2472 | PackageParser.PARSE_IS_SYSTEM 2473 | PackageParser.PARSE_IS_SYSTEM_DIR 2474 | PackageParser.PARSE_IS_PRIVILEGED, 2475 scanFlags | SCAN_NO_DEX, 0); 2476 2477 // Collected privileged system packages. 2478 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2479 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2480 | PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR 2482 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2483 2484 // Collect ordinary system packages. 2485 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2486 scanDirTracedLI(systemAppDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2489 2490 // Collect all vendor packages. 2491 File vendorAppDir = new File("/vendor/app"); 2492 try { 2493 vendorAppDir = vendorAppDir.getCanonicalFile(); 2494 } catch (IOException e) { 2495 // failed to look up canonical path, continue with original one 2496 } 2497 scanDirTracedLI(vendorAppDir, mDefParseFlags 2498 | PackageParser.PARSE_IS_SYSTEM 2499 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2500 2501 // Collect all OEM packages. 2502 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2503 scanDirTracedLI(oemAppDir, mDefParseFlags 2504 | PackageParser.PARSE_IS_SYSTEM 2505 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2506 2507 // Prune any system packages that no longer exist. 2508 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2509 if (!mOnlyCore) { 2510 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2511 while (psit.hasNext()) { 2512 PackageSetting ps = psit.next(); 2513 2514 /* 2515 * If this is not a system app, it can't be a 2516 * disable system app. 2517 */ 2518 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2519 continue; 2520 } 2521 2522 /* 2523 * If the package is scanned, it's not erased. 2524 */ 2525 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2526 if (scannedPkg != null) { 2527 /* 2528 * If the system app is both scanned and in the 2529 * disabled packages list, then it must have been 2530 * added via OTA. Remove it from the currently 2531 * scanned package so the previously user-installed 2532 * application can be scanned. 2533 */ 2534 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2535 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2536 + ps.name + "; removing system app. Last known codePath=" 2537 + ps.codePathString + ", installStatus=" + ps.installStatus 2538 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2539 + scannedPkg.mVersionCode); 2540 removePackageLI(scannedPkg, true); 2541 mExpectingBetter.put(ps.name, ps.codePath); 2542 } 2543 2544 continue; 2545 } 2546 2547 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2548 psit.remove(); 2549 logCriticalInfo(Log.WARN, "System package " + ps.name 2550 + " no longer exists; it's data will be wiped"); 2551 // Actual deletion of code and data will be handled by later 2552 // reconciliation step 2553 } else { 2554 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2555 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2556 possiblyDeletedUpdatedSystemApps.add(ps.name); 2557 } 2558 } 2559 } 2560 } 2561 2562 //look for any incomplete package installations 2563 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2564 for (int i = 0; i < deletePkgsList.size(); i++) { 2565 // Actual deletion of code and data will be handled by later 2566 // reconciliation step 2567 final String packageName = deletePkgsList.get(i).name; 2568 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2569 synchronized (mPackages) { 2570 mSettings.removePackageLPw(packageName); 2571 } 2572 } 2573 2574 //delete tmp files 2575 deleteTempPackageFiles(); 2576 2577 // Remove any shared userIDs that have no associated packages 2578 mSettings.pruneSharedUsersLPw(); 2579 2580 if (!mOnlyCore) { 2581 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2582 SystemClock.uptimeMillis()); 2583 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2584 2585 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2586 | PackageParser.PARSE_FORWARD_LOCK, 2587 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2588 2589 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2590 | PackageParser.PARSE_IS_EPHEMERAL, 2591 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2592 2593 /** 2594 * Remove disable package settings for any updated system 2595 * apps that were removed via an OTA. If they're not a 2596 * previously-updated app, remove them completely. 2597 * Otherwise, just revoke their system-level permissions. 2598 */ 2599 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2600 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2601 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2602 2603 String msg; 2604 if (deletedPkg == null) { 2605 msg = "Updated system package " + deletedAppName 2606 + " no longer exists; it's data will be wiped"; 2607 // Actual deletion of code and data will be handled by later 2608 // reconciliation step 2609 } else { 2610 msg = "Updated system app + " + deletedAppName 2611 + " no longer present; removing system privileges for " 2612 + deletedAppName; 2613 2614 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2615 2616 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2617 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 } 2619 logCriticalInfo(Log.WARN, msg); 2620 } 2621 2622 /** 2623 * Make sure all system apps that we expected to appear on 2624 * the userdata partition actually showed up. If they never 2625 * appeared, crawl back and revive the system version. 2626 */ 2627 for (int i = 0; i < mExpectingBetter.size(); i++) { 2628 final String packageName = mExpectingBetter.keyAt(i); 2629 if (!mPackages.containsKey(packageName)) { 2630 final File scanFile = mExpectingBetter.valueAt(i); 2631 2632 logCriticalInfo(Log.WARN, "Expected better " + packageName 2633 + " but never showed up; reverting to system"); 2634 2635 int reparseFlags = mDefParseFlags; 2636 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2637 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2638 | PackageParser.PARSE_IS_SYSTEM_DIR 2639 | PackageParser.PARSE_IS_PRIVILEGED; 2640 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2641 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2642 | PackageParser.PARSE_IS_SYSTEM_DIR; 2643 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else { 2650 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2651 continue; 2652 } 2653 2654 mSettings.enableSystemPackageLPw(packageName); 2655 2656 try { 2657 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2658 } catch (PackageManagerException e) { 2659 Slog.e(TAG, "Failed to parse original system package: " 2660 + e.getMessage()); 2661 } 2662 } 2663 } 2664 } 2665 mExpectingBetter.clear(); 2666 2667 // Resolve protected action filters. Only the setup wizard is allowed to 2668 // have a high priority filter for these actions. 2669 mSetupWizardPackage = getSetupWizardPackageName(); 2670 if (mProtectedFilters.size() > 0) { 2671 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2672 Slog.i(TAG, "No setup wizard;" 2673 + " All protected intents capped to priority 0"); 2674 } 2675 for (ActivityIntentInfo filter : mProtectedFilters) { 2676 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2677 if (DEBUG_FILTERS) { 2678 Slog.i(TAG, "Found setup wizard;" 2679 + " allow priority " + filter.getPriority() + ";" 2680 + " package: " + filter.activity.info.packageName 2681 + " activity: " + filter.activity.className 2682 + " priority: " + filter.getPriority()); 2683 } 2684 // skip setup wizard; allow it to keep the high priority filter 2685 continue; 2686 } 2687 Slog.w(TAG, "Protected action; cap priority to 0;" 2688 + " package: " + filter.activity.info.packageName 2689 + " activity: " + filter.activity.className 2690 + " origPrio: " + filter.getPriority()); 2691 filter.setPriority(0); 2692 } 2693 } 2694 mDeferProtectedFilters = false; 2695 mProtectedFilters.clear(); 2696 2697 // Now that we know all of the shared libraries, update all clients to have 2698 // the correct library paths. 2699 updateAllSharedLibrariesLPw(); 2700 2701 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2702 // NOTE: We ignore potential failures here during a system scan (like 2703 // the rest of the commands above) because there's precious little we 2704 // can do about it. A settings error is reported, though. 2705 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2706 false /* boot complete */); 2707 } 2708 2709 // Now that we know all the packages we are keeping, 2710 // read and update their last usage times. 2711 mPackageUsage.readLP(); 2712 2713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2714 SystemClock.uptimeMillis()); 2715 Slog.i(TAG, "Time to scan packages: " 2716 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2717 + " seconds"); 2718 2719 // If the platform SDK has changed since the last time we booted, 2720 // we need to re-grant app permission to catch any new ones that 2721 // appear. This is really a hack, and means that apps can in some 2722 // cases get permissions that the user didn't initially explicitly 2723 // allow... it would be nice to have some better way to handle 2724 // this situation. 2725 int updateFlags = UPDATE_PERMISSIONS_ALL; 2726 if (ver.sdkVersion != mSdkVersion) { 2727 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2728 + mSdkVersion + "; regranting permissions for internal storage"); 2729 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2730 } 2731 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2732 ver.sdkVersion = mSdkVersion; 2733 2734 // If this is the first boot or an update from pre-M, and it is a normal 2735 // boot, then we need to initialize the default preferred apps across 2736 // all defined users. 2737 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2738 for (UserInfo user : sUserManager.getUsers(true)) { 2739 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2740 applyFactoryDefaultBrowserLPw(user.id); 2741 primeDomainVerificationsLPw(user.id); 2742 } 2743 } 2744 2745 // Prepare storage for system user really early during boot, 2746 // since core system apps like SettingsProvider and SystemUI 2747 // can't wait for user to start 2748 final int storageFlags; 2749 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2750 storageFlags = StorageManager.FLAG_STORAGE_DE; 2751 } else { 2752 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2753 } 2754 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2755 storageFlags); 2756 2757 // If this is first boot after an OTA, and a normal boot, then 2758 // we need to clear code cache directories. 2759 // Note that we do *not* clear the application profiles. These remain valid 2760 // across OTAs and are used to drive profile verification (post OTA) and 2761 // profile compilation (without waiting to collect a fresh set of profiles). 2762 if (mIsUpgrade && !onlyCore) { 2763 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2764 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2765 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2766 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2767 // No apps are running this early, so no need to freeze 2768 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2769 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2770 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2771 } 2772 } 2773 ver.fingerprint = Build.FINGERPRINT; 2774 } 2775 2776 checkDefaultBrowser(); 2777 2778 // clear only after permissions and other defaults have been updated 2779 mExistingSystemPackages.clear(); 2780 mPromoteSystemApps = false; 2781 2782 // All the changes are done during package scanning. 2783 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2784 2785 // can downgrade to reader 2786 mSettings.writeLPr(); 2787 2788 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2789 // early on (before the package manager declares itself as early) because other 2790 // components in the system server might ask for package contexts for these apps. 2791 // 2792 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2793 // (i.e, that the data partition is unavailable). 2794 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2795 long start = System.nanoTime(); 2796 List<PackageParser.Package> coreApps = new ArrayList<>(); 2797 for (PackageParser.Package pkg : mPackages.values()) { 2798 if (pkg.coreApp) { 2799 coreApps.add(pkg); 2800 } 2801 } 2802 2803 int[] stats = performDexOpt(coreApps, false, 2804 getCompilerFilterForReason(REASON_CORE_APP)); 2805 2806 final int elapsedTimeSeconds = 2807 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2808 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2809 2810 if (DEBUG_DEXOPT) { 2811 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2812 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2813 } 2814 2815 2816 // TODO: Should we log these stats to tron too ? 2817 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2818 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2819 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2820 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2821 } 2822 2823 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2824 SystemClock.uptimeMillis()); 2825 2826 if (!mOnlyCore) { 2827 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2828 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2829 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2830 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2831 mIntentFilterVerifierComponent); 2832 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2833 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2834 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2835 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2836 } else { 2837 mRequiredVerifierPackage = null; 2838 mRequiredInstallerPackage = null; 2839 mIntentFilterVerifierComponent = null; 2840 mIntentFilterVerifier = null; 2841 mServicesSystemSharedLibraryPackageName = null; 2842 mSharedSystemSharedLibraryPackageName = null; 2843 } 2844 2845 mInstallerService = new PackageInstallerService(context, this); 2846 2847 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2848 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2849 // both the installer and resolver must be present to enable ephemeral 2850 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2851 if (DEBUG_EPHEMERAL) { 2852 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2853 + " installer:" + ephemeralInstallerComponent); 2854 } 2855 mEphemeralResolverComponent = ephemeralResolverComponent; 2856 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2857 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2858 mEphemeralResolverConnection = 2859 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2860 } else { 2861 if (DEBUG_EPHEMERAL) { 2862 final String missingComponent = 2863 (ephemeralResolverComponent == null) 2864 ? (ephemeralInstallerComponent == null) 2865 ? "resolver and installer" 2866 : "resolver" 2867 : "installer"; 2868 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2869 } 2870 mEphemeralResolverComponent = null; 2871 mEphemeralInstallerComponent = null; 2872 mEphemeralResolverConnection = null; 2873 } 2874 2875 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2876 } // synchronized (mPackages) 2877 } // synchronized (mInstallLock) 2878 2879 // Now after opening every single application zip, make sure they 2880 // are all flushed. Not really needed, but keeps things nice and 2881 // tidy. 2882 Runtime.getRuntime().gc(); 2883 2884 // The initial scanning above does many calls into installd while 2885 // holding the mPackages lock, but we're mostly interested in yelling 2886 // once we have a booted system. 2887 mInstaller.setWarnIfHeld(mPackages); 2888 2889 // Expose private service for system components to use. 2890 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2891 } 2892 2893 @Override 2894 public boolean isFirstBoot() { 2895 return mFirstBoot; 2896 } 2897 2898 @Override 2899 public boolean isOnlyCoreApps() { 2900 return mOnlyCore; 2901 } 2902 2903 @Override 2904 public boolean isUpgrade() { 2905 return mIsUpgrade; 2906 } 2907 2908 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2909 final Intent intent = new Intent(Intent.ACTION_PACKAGE_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 if (matches.size() == 1) { 2915 return matches.get(0).getComponentInfo().packageName; 2916 } else { 2917 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2918 return null; 2919 } 2920 } 2921 2922 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2923 synchronized (mPackages) { 2924 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2925 if (libraryEntry == null) { 2926 throw new IllegalStateException("Missing required shared library:" + libraryName); 2927 } 2928 return libraryEntry.apk; 2929 } 2930 } 2931 2932 private @NonNull String getRequiredInstallerLPr() { 2933 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2934 intent.addCategory(Intent.CATEGORY_DEFAULT); 2935 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2936 2937 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2938 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2939 UserHandle.USER_SYSTEM); 2940 if (matches.size() == 1) { 2941 ResolveInfo resolveInfo = matches.get(0); 2942 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2943 throw new RuntimeException("The installer must be a privileged app"); 2944 } 2945 return matches.get(0).getComponentInfo().packageName; 2946 } else { 2947 throw new RuntimeException("There must be exactly one installer; found " + matches); 2948 } 2949 } 2950 2951 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2952 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2953 2954 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2955 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2956 UserHandle.USER_SYSTEM); 2957 ResolveInfo best = null; 2958 final int N = matches.size(); 2959 for (int i = 0; i < N; i++) { 2960 final ResolveInfo cur = matches.get(i); 2961 final String packageName = cur.getComponentInfo().packageName; 2962 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2963 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2964 continue; 2965 } 2966 2967 if (best == null || cur.priority > best.priority) { 2968 best = cur; 2969 } 2970 } 2971 2972 if (best != null) { 2973 return best.getComponentInfo().getComponentName(); 2974 } else { 2975 throw new RuntimeException("There must be at least one intent filter verifier"); 2976 } 2977 } 2978 2979 private @Nullable ComponentName getEphemeralResolverLPr() { 2980 final String[] packageArray = 2981 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2982 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2983 if (DEBUG_EPHEMERAL) { 2984 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2985 } 2986 return null; 2987 } 2988 2989 final int resolveFlags = 2990 MATCH_DIRECT_BOOT_AWARE 2991 | MATCH_DIRECT_BOOT_UNAWARE 2992 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2993 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2994 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2995 resolveFlags, UserHandle.USER_SYSTEM); 2996 2997 final int N = resolvers.size(); 2998 if (N == 0) { 2999 if (DEBUG_EPHEMERAL) { 3000 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3001 } 3002 return null; 3003 } 3004 3005 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3006 for (int i = 0; i < N; i++) { 3007 final ResolveInfo info = resolvers.get(i); 3008 3009 if (info.serviceInfo == null) { 3010 continue; 3011 } 3012 3013 final String packageName = info.serviceInfo.packageName; 3014 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3015 if (DEBUG_EPHEMERAL) { 3016 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3017 + " pkg: " + packageName + ", info:" + info); 3018 } 3019 continue; 3020 } 3021 3022 if (DEBUG_EPHEMERAL) { 3023 Slog.v(TAG, "Ephemeral resolver found;" 3024 + " pkg: " + packageName + ", info:" + info); 3025 } 3026 return new ComponentName(packageName, info.serviceInfo.name); 3027 } 3028 if (DEBUG_EPHEMERAL) { 3029 Slog.v(TAG, "Ephemeral resolver NOT found"); 3030 } 3031 return null; 3032 } 3033 3034 private @Nullable ComponentName getEphemeralInstallerLPr() { 3035 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3036 intent.addCategory(Intent.CATEGORY_DEFAULT); 3037 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3038 3039 final int resolveFlags = 3040 MATCH_DIRECT_BOOT_AWARE 3041 | MATCH_DIRECT_BOOT_UNAWARE 3042 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3043 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3044 resolveFlags, UserHandle.USER_SYSTEM); 3045 if (matches.size() == 0) { 3046 return null; 3047 } else if (matches.size() == 1) { 3048 return matches.get(0).getComponentInfo().getComponentName(); 3049 } else { 3050 throw new RuntimeException( 3051 "There must be at most one ephemeral installer; found " + matches); 3052 } 3053 } 3054 3055 private void primeDomainVerificationsLPw(int userId) { 3056 if (DEBUG_DOMAIN_VERIFICATION) { 3057 Slog.d(TAG, "Priming domain verifications in user " + userId); 3058 } 3059 3060 SystemConfig systemConfig = SystemConfig.getInstance(); 3061 ArraySet<String> packages = systemConfig.getLinkedApps(); 3062 ArraySet<String> domains = new ArraySet<String>(); 3063 3064 for (String packageName : packages) { 3065 PackageParser.Package pkg = mPackages.get(packageName); 3066 if (pkg != null) { 3067 if (!pkg.isSystemApp()) { 3068 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3069 continue; 3070 } 3071 3072 domains.clear(); 3073 for (PackageParser.Activity a : pkg.activities) { 3074 for (ActivityIntentInfo filter : a.intents) { 3075 if (hasValidDomains(filter)) { 3076 domains.addAll(filter.getHostsList()); 3077 } 3078 } 3079 } 3080 3081 if (domains.size() > 0) { 3082 if (DEBUG_DOMAIN_VERIFICATION) { 3083 Slog.v(TAG, " + " + packageName); 3084 } 3085 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3086 // state w.r.t. the formal app-linkage "no verification attempted" state; 3087 // and then 'always' in the per-user state actually used for intent resolution. 3088 final IntentFilterVerificationInfo ivi; 3089 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3090 new ArrayList<String>(domains)); 3091 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3092 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3093 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3094 } else { 3095 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3096 + "' does not handle web links"); 3097 } 3098 } else { 3099 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3100 } 3101 } 3102 3103 scheduleWritePackageRestrictionsLocked(userId); 3104 scheduleWriteSettingsLocked(); 3105 } 3106 3107 private void applyFactoryDefaultBrowserLPw(int userId) { 3108 // The default browser app's package name is stored in a string resource, 3109 // with a product-specific overlay used for vendor customization. 3110 String browserPkg = mContext.getResources().getString( 3111 com.android.internal.R.string.default_browser); 3112 if (!TextUtils.isEmpty(browserPkg)) { 3113 // non-empty string => required to be a known package 3114 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3115 if (ps == null) { 3116 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3117 browserPkg = null; 3118 } else { 3119 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3120 } 3121 } 3122 3123 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3124 // default. If there's more than one, just leave everything alone. 3125 if (browserPkg == null) { 3126 calculateDefaultBrowserLPw(userId); 3127 } 3128 } 3129 3130 private void calculateDefaultBrowserLPw(int userId) { 3131 List<String> allBrowsers = resolveAllBrowserApps(userId); 3132 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3133 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3134 } 3135 3136 private List<String> resolveAllBrowserApps(int userId) { 3137 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3138 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3139 PackageManager.MATCH_ALL, userId); 3140 3141 final int count = list.size(); 3142 List<String> result = new ArrayList<String>(count); 3143 for (int i=0; i<count; i++) { 3144 ResolveInfo info = list.get(i); 3145 if (info.activityInfo == null 3146 || !info.handleAllWebDataURI 3147 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3148 || result.contains(info.activityInfo.packageName)) { 3149 continue; 3150 } 3151 result.add(info.activityInfo.packageName); 3152 } 3153 3154 return result; 3155 } 3156 3157 private boolean packageIsBrowser(String packageName, int userId) { 3158 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3159 PackageManager.MATCH_ALL, userId); 3160 final int N = list.size(); 3161 for (int i = 0; i < N; i++) { 3162 ResolveInfo info = list.get(i); 3163 if (packageName.equals(info.activityInfo.packageName)) { 3164 return true; 3165 } 3166 } 3167 return false; 3168 } 3169 3170 private void checkDefaultBrowser() { 3171 final int myUserId = UserHandle.myUserId(); 3172 final String packageName = getDefaultBrowserPackageName(myUserId); 3173 if (packageName != null) { 3174 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3175 if (info == null) { 3176 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3177 synchronized (mPackages) { 3178 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3179 } 3180 } 3181 } 3182 } 3183 3184 @Override 3185 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3186 throws RemoteException { 3187 try { 3188 return super.onTransact(code, data, reply, flags); 3189 } catch (RuntimeException e) { 3190 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3191 Slog.wtf(TAG, "Package Manager Crash", e); 3192 } 3193 throw e; 3194 } 3195 } 3196 3197 static int[] appendInts(int[] cur, int[] add) { 3198 if (add == null) return cur; 3199 if (cur == null) return add; 3200 final int N = add.length; 3201 for (int i=0; i<N; i++) { 3202 cur = appendInt(cur, add[i]); 3203 } 3204 return cur; 3205 } 3206 3207 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3208 if (!sUserManager.exists(userId)) return null; 3209 if (ps == null) { 3210 return null; 3211 } 3212 final PackageParser.Package p = ps.pkg; 3213 if (p == null) { 3214 return null; 3215 } 3216 3217 final PermissionsState permissionsState = ps.getPermissionsState(); 3218 3219 // Compute GIDs only if requested 3220 final int[] gids = (flags & PackageManager.GET_GIDS) != 0 3221 ? permissionsState.computeGids(userId) : EMPTY_INT_ARRAY; 3222 // TODO b/29879962 Calculate granted permissions only if needed in generatePackageInfo 3223 final Set<String> permissions = permissionsState.getPermissions(userId); 3224 final PackageUserState state = ps.readUserState(userId); 3225 3226 return PackageParser.generatePackageInfo(p, gids, flags, 3227 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3228 } 3229 3230 @Override 3231 public void checkPackageStartable(String packageName, int userId) { 3232 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3233 3234 synchronized (mPackages) { 3235 final PackageSetting ps = mSettings.mPackages.get(packageName); 3236 if (ps == null) { 3237 throw new SecurityException("Package " + packageName + " was not found!"); 3238 } 3239 3240 if (!ps.getInstalled(userId)) { 3241 throw new SecurityException( 3242 "Package " + packageName + " was not installed for user " + userId + "!"); 3243 } 3244 3245 if (mSafeMode && !ps.isSystem()) { 3246 throw new SecurityException("Package " + packageName + " not a system app!"); 3247 } 3248 3249 if (mFrozenPackages.contains(packageName)) { 3250 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3251 } 3252 3253 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3254 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3255 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3256 } 3257 } 3258 } 3259 3260 @Override 3261 public boolean isPackageAvailable(String packageName, int userId) { 3262 if (!sUserManager.exists(userId)) return false; 3263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3264 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3265 synchronized (mPackages) { 3266 PackageParser.Package p = mPackages.get(packageName); 3267 if (p != null) { 3268 final PackageSetting ps = (PackageSetting) p.mExtras; 3269 if (ps != null) { 3270 final PackageUserState state = ps.readUserState(userId); 3271 if (state != null) { 3272 return PackageParser.isAvailable(state); 3273 } 3274 } 3275 } 3276 } 3277 return false; 3278 } 3279 3280 @Override 3281 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3282 if (!sUserManager.exists(userId)) return null; 3283 flags = updateFlagsForPackage(flags, userId, packageName); 3284 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3285 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3286 // reader 3287 synchronized (mPackages) { 3288 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3289 PackageParser.Package p = null; 3290 if (matchFactoryOnly) { 3291 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3292 if (ps != null) { 3293 return generatePackageInfo(ps, flags, userId); 3294 } 3295 } 3296 if (p == null) { 3297 p = mPackages.get(packageName); 3298 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3299 return null; 3300 } 3301 } 3302 if (DEBUG_PACKAGE_INFO) 3303 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3304 if (p != null) { 3305 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3306 } 3307 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3308 final PackageSetting ps = mSettings.mPackages.get(packageName); 3309 return generatePackageInfo(ps, flags, userId); 3310 } 3311 } 3312 return null; 3313 } 3314 3315 @Override 3316 public String[] currentToCanonicalPackageNames(String[] names) { 3317 String[] out = new String[names.length]; 3318 // reader 3319 synchronized (mPackages) { 3320 for (int i=names.length-1; i>=0; i--) { 3321 PackageSetting ps = mSettings.mPackages.get(names[i]); 3322 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3323 } 3324 } 3325 return out; 3326 } 3327 3328 @Override 3329 public String[] canonicalToCurrentPackageNames(String[] names) { 3330 String[] out = new String[names.length]; 3331 // reader 3332 synchronized (mPackages) { 3333 for (int i=names.length-1; i>=0; i--) { 3334 String cur = mSettings.mRenamedPackages.get(names[i]); 3335 out[i] = cur != null ? cur : names[i]; 3336 } 3337 } 3338 return out; 3339 } 3340 3341 @Override 3342 public int getPackageUid(String packageName, int flags, int userId) { 3343 if (!sUserManager.exists(userId)) return -1; 3344 flags = updateFlagsForPackage(flags, userId, packageName); 3345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3346 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3347 3348 // reader 3349 synchronized (mPackages) { 3350 final PackageParser.Package p = mPackages.get(packageName); 3351 if (p != null && p.isMatch(flags)) { 3352 return UserHandle.getUid(userId, p.applicationInfo.uid); 3353 } 3354 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3355 final PackageSetting ps = mSettings.mPackages.get(packageName); 3356 if (ps != null && ps.isMatch(flags)) { 3357 return UserHandle.getUid(userId, ps.appId); 3358 } 3359 } 3360 } 3361 3362 return -1; 3363 } 3364 3365 @Override 3366 public int[] getPackageGids(String packageName, int flags, int userId) { 3367 if (!sUserManager.exists(userId)) return null; 3368 flags = updateFlagsForPackage(flags, userId, packageName); 3369 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3370 false /* requireFullPermission */, false /* checkShell */, 3371 "getPackageGids"); 3372 3373 // reader 3374 synchronized (mPackages) { 3375 final PackageParser.Package p = mPackages.get(packageName); 3376 if (p != null && p.isMatch(flags)) { 3377 PackageSetting ps = (PackageSetting) p.mExtras; 3378 return ps.getPermissionsState().computeGids(userId); 3379 } 3380 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3381 final PackageSetting ps = mSettings.mPackages.get(packageName); 3382 if (ps != null && ps.isMatch(flags)) { 3383 return ps.getPermissionsState().computeGids(userId); 3384 } 3385 } 3386 } 3387 3388 return null; 3389 } 3390 3391 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3392 if (bp.perm != null) { 3393 return PackageParser.generatePermissionInfo(bp.perm, flags); 3394 } 3395 PermissionInfo pi = new PermissionInfo(); 3396 pi.name = bp.name; 3397 pi.packageName = bp.sourcePackage; 3398 pi.nonLocalizedLabel = bp.name; 3399 pi.protectionLevel = bp.protectionLevel; 3400 return pi; 3401 } 3402 3403 @Override 3404 public PermissionInfo getPermissionInfo(String name, int flags) { 3405 // reader 3406 synchronized (mPackages) { 3407 final BasePermission p = mSettings.mPermissions.get(name); 3408 if (p != null) { 3409 return generatePermissionInfo(p, flags); 3410 } 3411 return null; 3412 } 3413 } 3414 3415 @Override 3416 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3417 int flags) { 3418 // reader 3419 synchronized (mPackages) { 3420 if (group != null && !mPermissionGroups.containsKey(group)) { 3421 // This is thrown as NameNotFoundException 3422 return null; 3423 } 3424 3425 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3426 for (BasePermission p : mSettings.mPermissions.values()) { 3427 if (group == null) { 3428 if (p.perm == null || p.perm.info.group == null) { 3429 out.add(generatePermissionInfo(p, flags)); 3430 } 3431 } else { 3432 if (p.perm != null && group.equals(p.perm.info.group)) { 3433 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3434 } 3435 } 3436 } 3437 return new ParceledListSlice<>(out); 3438 } 3439 } 3440 3441 @Override 3442 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3443 // reader 3444 synchronized (mPackages) { 3445 return PackageParser.generatePermissionGroupInfo( 3446 mPermissionGroups.get(name), flags); 3447 } 3448 } 3449 3450 @Override 3451 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3452 // reader 3453 synchronized (mPackages) { 3454 final int N = mPermissionGroups.size(); 3455 ArrayList<PermissionGroupInfo> out 3456 = new ArrayList<PermissionGroupInfo>(N); 3457 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3458 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3459 } 3460 return new ParceledListSlice<>(out); 3461 } 3462 } 3463 3464 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3465 int userId) { 3466 if (!sUserManager.exists(userId)) return null; 3467 PackageSetting ps = mSettings.mPackages.get(packageName); 3468 if (ps != null) { 3469 if (ps.pkg == null) { 3470 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3471 if (pInfo != null) { 3472 return pInfo.applicationInfo; 3473 } 3474 return null; 3475 } 3476 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3477 ps.readUserState(userId), userId); 3478 } 3479 return null; 3480 } 3481 3482 @Override 3483 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3484 if (!sUserManager.exists(userId)) return null; 3485 flags = updateFlagsForApplication(flags, userId, packageName); 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3487 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3488 // writer 3489 synchronized (mPackages) { 3490 PackageParser.Package p = mPackages.get(packageName); 3491 if (DEBUG_PACKAGE_INFO) Log.v( 3492 TAG, "getApplicationInfo " + packageName 3493 + ": " + p); 3494 if (p != null) { 3495 PackageSetting ps = mSettings.mPackages.get(packageName); 3496 if (ps == null) return null; 3497 // Note: isEnabledLP() does not apply here - always return info 3498 return PackageParser.generateApplicationInfo( 3499 p, flags, ps.readUserState(userId), userId); 3500 } 3501 if ("android".equals(packageName)||"system".equals(packageName)) { 3502 return mAndroidApplication; 3503 } 3504 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3505 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3506 } 3507 } 3508 return null; 3509 } 3510 3511 @Override 3512 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3513 final IPackageDataObserver observer) { 3514 mContext.enforceCallingOrSelfPermission( 3515 android.Manifest.permission.CLEAR_APP_CACHE, null); 3516 // Queue up an async operation since clearing cache may take a little while. 3517 mHandler.post(new Runnable() { 3518 public void run() { 3519 mHandler.removeCallbacks(this); 3520 boolean success = true; 3521 synchronized (mInstallLock) { 3522 try { 3523 mInstaller.freeCache(volumeUuid, freeStorageSize); 3524 } catch (InstallerException e) { 3525 Slog.w(TAG, "Couldn't clear application caches: " + e); 3526 success = false; 3527 } 3528 } 3529 if (observer != null) { 3530 try { 3531 observer.onRemoveCompleted(null, success); 3532 } catch (RemoteException e) { 3533 Slog.w(TAG, "RemoveException when invoking call back"); 3534 } 3535 } 3536 } 3537 }); 3538 } 3539 3540 @Override 3541 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3542 final IntentSender pi) { 3543 mContext.enforceCallingOrSelfPermission( 3544 android.Manifest.permission.CLEAR_APP_CACHE, null); 3545 // Queue up an async operation since clearing cache may take a little while. 3546 mHandler.post(new Runnable() { 3547 public void run() { 3548 mHandler.removeCallbacks(this); 3549 boolean success = true; 3550 synchronized (mInstallLock) { 3551 try { 3552 mInstaller.freeCache(volumeUuid, freeStorageSize); 3553 } catch (InstallerException e) { 3554 Slog.w(TAG, "Couldn't clear application caches: " + e); 3555 success = false; 3556 } 3557 } 3558 if(pi != null) { 3559 try { 3560 // Callback via pending intent 3561 int code = success ? 1 : 0; 3562 pi.sendIntent(null, code, null, 3563 null, null); 3564 } catch (SendIntentException e1) { 3565 Slog.i(TAG, "Failed to send pending intent"); 3566 } 3567 } 3568 } 3569 }); 3570 } 3571 3572 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3573 synchronized (mInstallLock) { 3574 try { 3575 mInstaller.freeCache(volumeUuid, freeStorageSize); 3576 } catch (InstallerException e) { 3577 throw new IOException("Failed to free enough space", e); 3578 } 3579 } 3580 } 3581 3582 /** 3583 * Update given flags based on encryption status of current user. 3584 */ 3585 private int updateFlags(int flags, int userId) { 3586 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3587 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3588 // Caller expressed an explicit opinion about what encryption 3589 // aware/unaware components they want to see, so fall through and 3590 // give them what they want 3591 } else { 3592 // Caller expressed no opinion, so match based on user state 3593 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3594 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3595 } else { 3596 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3597 } 3598 } 3599 return flags; 3600 } 3601 3602 private UserManagerInternal getUserManagerInternal() { 3603 if (mUserManagerInternal == null) { 3604 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3605 } 3606 return mUserManagerInternal; 3607 } 3608 3609 /** 3610 * Update given flags when being used to request {@link PackageInfo}. 3611 */ 3612 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3613 boolean triaged = true; 3614 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3615 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3616 // Caller is asking for component details, so they'd better be 3617 // asking for specific encryption matching behavior, or be triaged 3618 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3619 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3620 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3621 triaged = false; 3622 } 3623 } 3624 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3625 | PackageManager.MATCH_SYSTEM_ONLY 3626 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3627 triaged = false; 3628 } 3629 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3630 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3631 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3632 } 3633 return updateFlags(flags, userId); 3634 } 3635 3636 /** 3637 * Update given flags when being used to request {@link ApplicationInfo}. 3638 */ 3639 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3640 return updateFlagsForPackage(flags, userId, cookie); 3641 } 3642 3643 /** 3644 * Update given flags when being used to request {@link ComponentInfo}. 3645 */ 3646 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3647 if (cookie instanceof Intent) { 3648 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3649 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3650 } 3651 } 3652 3653 boolean triaged = true; 3654 // Caller is asking for component details, so they'd better be 3655 // asking for specific encryption matching behavior, or be triaged 3656 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3657 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3658 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3659 triaged = false; 3660 } 3661 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3662 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3663 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3664 } 3665 3666 return updateFlags(flags, userId); 3667 } 3668 3669 /** 3670 * Update given flags when being used to request {@link ResolveInfo}. 3671 */ 3672 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3673 // Safe mode means we shouldn't match any third-party components 3674 if (mSafeMode) { 3675 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3676 } 3677 3678 return updateFlagsForComponent(flags, userId, cookie); 3679 } 3680 3681 @Override 3682 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3683 if (!sUserManager.exists(userId)) return null; 3684 flags = updateFlagsForComponent(flags, userId, component); 3685 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3686 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3687 synchronized (mPackages) { 3688 PackageParser.Activity a = mActivities.mActivities.get(component); 3689 3690 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3691 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3692 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3693 if (ps == null) return null; 3694 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3695 userId); 3696 } 3697 if (mResolveComponentName.equals(component)) { 3698 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3699 new PackageUserState(), userId); 3700 } 3701 } 3702 return null; 3703 } 3704 3705 @Override 3706 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3707 String resolvedType) { 3708 synchronized (mPackages) { 3709 if (component.equals(mResolveComponentName)) { 3710 // The resolver supports EVERYTHING! 3711 return true; 3712 } 3713 PackageParser.Activity a = mActivities.mActivities.get(component); 3714 if (a == null) { 3715 return false; 3716 } 3717 for (int i=0; i<a.intents.size(); i++) { 3718 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3719 intent.getData(), intent.getCategories(), TAG) >= 0) { 3720 return true; 3721 } 3722 } 3723 return false; 3724 } 3725 } 3726 3727 @Override 3728 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3729 if (!sUserManager.exists(userId)) return null; 3730 flags = updateFlagsForComponent(flags, userId, component); 3731 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3732 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3733 synchronized (mPackages) { 3734 PackageParser.Activity a = mReceivers.mActivities.get(component); 3735 if (DEBUG_PACKAGE_INFO) Log.v( 3736 TAG, "getReceiverInfo " + component + ": " + a); 3737 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3738 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3739 if (ps == null) return null; 3740 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3741 userId); 3742 } 3743 } 3744 return null; 3745 } 3746 3747 @Override 3748 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3749 if (!sUserManager.exists(userId)) return null; 3750 flags = updateFlagsForComponent(flags, userId, component); 3751 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3752 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3753 synchronized (mPackages) { 3754 PackageParser.Service s = mServices.mServices.get(component); 3755 if (DEBUG_PACKAGE_INFO) Log.v( 3756 TAG, "getServiceInfo " + component + ": " + s); 3757 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3758 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3759 if (ps == null) return null; 3760 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3761 userId); 3762 } 3763 } 3764 return null; 3765 } 3766 3767 @Override 3768 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3769 if (!sUserManager.exists(userId)) return null; 3770 flags = updateFlagsForComponent(flags, userId, component); 3771 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3772 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3773 synchronized (mPackages) { 3774 PackageParser.Provider p = mProviders.mProviders.get(component); 3775 if (DEBUG_PACKAGE_INFO) Log.v( 3776 TAG, "getProviderInfo " + component + ": " + p); 3777 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3778 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3779 if (ps == null) return null; 3780 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3781 userId); 3782 } 3783 } 3784 return null; 3785 } 3786 3787 @Override 3788 public String[] getSystemSharedLibraryNames() { 3789 Set<String> libSet; 3790 synchronized (mPackages) { 3791 libSet = mSharedLibraries.keySet(); 3792 int size = libSet.size(); 3793 if (size > 0) { 3794 String[] libs = new String[size]; 3795 libSet.toArray(libs); 3796 return libs; 3797 } 3798 } 3799 return null; 3800 } 3801 3802 @Override 3803 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3804 synchronized (mPackages) { 3805 return mServicesSystemSharedLibraryPackageName; 3806 } 3807 } 3808 3809 @Override 3810 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3811 synchronized (mPackages) { 3812 return mSharedSystemSharedLibraryPackageName; 3813 } 3814 } 3815 3816 @Override 3817 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3818 synchronized (mPackages) { 3819 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3820 3821 final FeatureInfo fi = new FeatureInfo(); 3822 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3823 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3824 res.add(fi); 3825 3826 return new ParceledListSlice<>(res); 3827 } 3828 } 3829 3830 @Override 3831 public boolean hasSystemFeature(String name, int version) { 3832 synchronized (mPackages) { 3833 final FeatureInfo feat = mAvailableFeatures.get(name); 3834 if (feat == null) { 3835 return false; 3836 } else { 3837 return feat.version >= version; 3838 } 3839 } 3840 } 3841 3842 @Override 3843 public int checkPermission(String permName, String pkgName, int userId) { 3844 if (!sUserManager.exists(userId)) { 3845 return PackageManager.PERMISSION_DENIED; 3846 } 3847 3848 synchronized (mPackages) { 3849 final PackageParser.Package p = mPackages.get(pkgName); 3850 if (p != null && p.mExtras != null) { 3851 final PackageSetting ps = (PackageSetting) p.mExtras; 3852 final PermissionsState permissionsState = ps.getPermissionsState(); 3853 if (permissionsState.hasPermission(permName, userId)) { 3854 return PackageManager.PERMISSION_GRANTED; 3855 } 3856 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3857 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3858 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3859 return PackageManager.PERMISSION_GRANTED; 3860 } 3861 } 3862 } 3863 3864 return PackageManager.PERMISSION_DENIED; 3865 } 3866 3867 @Override 3868 public int checkUidPermission(String permName, int uid) { 3869 final int userId = UserHandle.getUserId(uid); 3870 3871 if (!sUserManager.exists(userId)) { 3872 return PackageManager.PERMISSION_DENIED; 3873 } 3874 3875 synchronized (mPackages) { 3876 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3877 if (obj != null) { 3878 final SettingBase ps = (SettingBase) obj; 3879 final PermissionsState permissionsState = ps.getPermissionsState(); 3880 if (permissionsState.hasPermission(permName, userId)) { 3881 return PackageManager.PERMISSION_GRANTED; 3882 } 3883 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3884 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3885 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3886 return PackageManager.PERMISSION_GRANTED; 3887 } 3888 } else { 3889 ArraySet<String> perms = mSystemPermissions.get(uid); 3890 if (perms != null) { 3891 if (perms.contains(permName)) { 3892 return PackageManager.PERMISSION_GRANTED; 3893 } 3894 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3895 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3896 return PackageManager.PERMISSION_GRANTED; 3897 } 3898 } 3899 } 3900 } 3901 3902 return PackageManager.PERMISSION_DENIED; 3903 } 3904 3905 @Override 3906 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3907 if (UserHandle.getCallingUserId() != userId) { 3908 mContext.enforceCallingPermission( 3909 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3910 "isPermissionRevokedByPolicy for user " + userId); 3911 } 3912 3913 if (checkPermission(permission, packageName, userId) 3914 == PackageManager.PERMISSION_GRANTED) { 3915 return false; 3916 } 3917 3918 final long identity = Binder.clearCallingIdentity(); 3919 try { 3920 final int flags = getPermissionFlags(permission, packageName, userId); 3921 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3922 } finally { 3923 Binder.restoreCallingIdentity(identity); 3924 } 3925 } 3926 3927 @Override 3928 public String getPermissionControllerPackageName() { 3929 synchronized (mPackages) { 3930 return mRequiredInstallerPackage; 3931 } 3932 } 3933 3934 /** 3935 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3936 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3937 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3938 * @param message the message to log on security exception 3939 */ 3940 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3941 boolean checkShell, String message) { 3942 if (userId < 0) { 3943 throw new IllegalArgumentException("Invalid userId " + userId); 3944 } 3945 if (checkShell) { 3946 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3947 } 3948 if (userId == UserHandle.getUserId(callingUid)) return; 3949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3950 if (requireFullPermission) { 3951 mContext.enforceCallingOrSelfPermission( 3952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3953 } else { 3954 try { 3955 mContext.enforceCallingOrSelfPermission( 3956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3957 } catch (SecurityException se) { 3958 mContext.enforceCallingOrSelfPermission( 3959 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3960 } 3961 } 3962 } 3963 } 3964 3965 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3966 if (callingUid == Process.SHELL_UID) { 3967 if (userHandle >= 0 3968 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3969 throw new SecurityException("Shell does not have permission to access user " 3970 + userHandle); 3971 } else if (userHandle < 0) { 3972 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3973 + Debug.getCallers(3)); 3974 } 3975 } 3976 } 3977 3978 private BasePermission findPermissionTreeLP(String permName) { 3979 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3980 if (permName.startsWith(bp.name) && 3981 permName.length() > bp.name.length() && 3982 permName.charAt(bp.name.length()) == '.') { 3983 return bp; 3984 } 3985 } 3986 return null; 3987 } 3988 3989 private BasePermission checkPermissionTreeLP(String permName) { 3990 if (permName != null) { 3991 BasePermission bp = findPermissionTreeLP(permName); 3992 if (bp != null) { 3993 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3994 return bp; 3995 } 3996 throw new SecurityException("Calling uid " 3997 + Binder.getCallingUid() 3998 + " is not allowed to add to permission tree " 3999 + bp.name + " owned by uid " + bp.uid); 4000 } 4001 } 4002 throw new SecurityException("No permission tree found for " + permName); 4003 } 4004 4005 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4006 if (s1 == null) { 4007 return s2 == null; 4008 } 4009 if (s2 == null) { 4010 return false; 4011 } 4012 if (s1.getClass() != s2.getClass()) { 4013 return false; 4014 } 4015 return s1.equals(s2); 4016 } 4017 4018 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4019 if (pi1.icon != pi2.icon) return false; 4020 if (pi1.logo != pi2.logo) return false; 4021 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4022 if (!compareStrings(pi1.name, pi2.name)) return false; 4023 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4024 // We'll take care of setting this one. 4025 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4026 // These are not currently stored in settings. 4027 //if (!compareStrings(pi1.group, pi2.group)) return false; 4028 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4029 //if (pi1.labelRes != pi2.labelRes) return false; 4030 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4031 return true; 4032 } 4033 4034 int permissionInfoFootprint(PermissionInfo info) { 4035 int size = info.name.length(); 4036 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4037 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4038 return size; 4039 } 4040 4041 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4042 int size = 0; 4043 for (BasePermission perm : mSettings.mPermissions.values()) { 4044 if (perm.uid == tree.uid) { 4045 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4046 } 4047 } 4048 return size; 4049 } 4050 4051 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4052 // We calculate the max size of permissions defined by this uid and throw 4053 // if that plus the size of 'info' would exceed our stated maximum. 4054 if (tree.uid != Process.SYSTEM_UID) { 4055 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4056 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4057 throw new SecurityException("Permission tree size cap exceeded"); 4058 } 4059 } 4060 } 4061 4062 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4063 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4064 throw new SecurityException("Label must be specified in permission"); 4065 } 4066 BasePermission tree = checkPermissionTreeLP(info.name); 4067 BasePermission bp = mSettings.mPermissions.get(info.name); 4068 boolean added = bp == null; 4069 boolean changed = true; 4070 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4071 if (added) { 4072 enforcePermissionCapLocked(info, tree); 4073 bp = new BasePermission(info.name, tree.sourcePackage, 4074 BasePermission.TYPE_DYNAMIC); 4075 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4076 throw new SecurityException( 4077 "Not allowed to modify non-dynamic permission " 4078 + info.name); 4079 } else { 4080 if (bp.protectionLevel == fixedLevel 4081 && bp.perm.owner.equals(tree.perm.owner) 4082 && bp.uid == tree.uid 4083 && comparePermissionInfos(bp.perm.info, info)) { 4084 changed = false; 4085 } 4086 } 4087 bp.protectionLevel = fixedLevel; 4088 info = new PermissionInfo(info); 4089 info.protectionLevel = fixedLevel; 4090 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4091 bp.perm.info.packageName = tree.perm.info.packageName; 4092 bp.uid = tree.uid; 4093 if (added) { 4094 mSettings.mPermissions.put(info.name, bp); 4095 } 4096 if (changed) { 4097 if (!async) { 4098 mSettings.writeLPr(); 4099 } else { 4100 scheduleWriteSettingsLocked(); 4101 } 4102 } 4103 return added; 4104 } 4105 4106 @Override 4107 public boolean addPermission(PermissionInfo info) { 4108 synchronized (mPackages) { 4109 return addPermissionLocked(info, false); 4110 } 4111 } 4112 4113 @Override 4114 public boolean addPermissionAsync(PermissionInfo info) { 4115 synchronized (mPackages) { 4116 return addPermissionLocked(info, true); 4117 } 4118 } 4119 4120 @Override 4121 public void removePermission(String name) { 4122 synchronized (mPackages) { 4123 checkPermissionTreeLP(name); 4124 BasePermission bp = mSettings.mPermissions.get(name); 4125 if (bp != null) { 4126 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4127 throw new SecurityException( 4128 "Not allowed to modify non-dynamic permission " 4129 + name); 4130 } 4131 mSettings.mPermissions.remove(name); 4132 mSettings.writeLPr(); 4133 } 4134 } 4135 } 4136 4137 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4138 BasePermission bp) { 4139 int index = pkg.requestedPermissions.indexOf(bp.name); 4140 if (index == -1) { 4141 throw new SecurityException("Package " + pkg.packageName 4142 + " has not requested permission " + bp.name); 4143 } 4144 if (!bp.isRuntime() && !bp.isDevelopment()) { 4145 throw new SecurityException("Permission " + bp.name 4146 + " is not a changeable permission type"); 4147 } 4148 } 4149 4150 @Override 4151 public void grantRuntimePermission(String packageName, String name, final int userId) { 4152 if (!sUserManager.exists(userId)) { 4153 Log.e(TAG, "No such user:" + userId); 4154 return; 4155 } 4156 4157 mContext.enforceCallingOrSelfPermission( 4158 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4159 "grantRuntimePermission"); 4160 4161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4162 true /* requireFullPermission */, true /* checkShell */, 4163 "grantRuntimePermission"); 4164 4165 final int uid; 4166 final SettingBase sb; 4167 4168 synchronized (mPackages) { 4169 final PackageParser.Package pkg = mPackages.get(packageName); 4170 if (pkg == null) { 4171 throw new IllegalArgumentException("Unknown package: " + packageName); 4172 } 4173 4174 final BasePermission bp = mSettings.mPermissions.get(name); 4175 if (bp == null) { 4176 throw new IllegalArgumentException("Unknown permission: " + name); 4177 } 4178 4179 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4180 4181 // If a permission review is required for legacy apps we represent 4182 // their permissions as always granted runtime ones since we need 4183 // to keep the review required permission flag per user while an 4184 // install permission's state is shared across all users. 4185 if (Build.PERMISSIONS_REVIEW_REQUIRED 4186 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4187 && bp.isRuntime()) { 4188 return; 4189 } 4190 4191 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4192 sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 final int flags = permissionsState.getPermissionFlags(name, userId); 4200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4201 throw new SecurityException("Cannot grant system fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 4205 if (bp.isDevelopment()) { 4206 // Development permissions must be handled specially, since they are not 4207 // normal runtime permissions. For now they apply to all users. 4208 if (permissionsState.grantInstallPermission(bp) != 4209 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4210 scheduleWriteSettingsLocked(); 4211 } 4212 return; 4213 } 4214 4215 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4216 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4217 return; 4218 } 4219 4220 final int result = permissionsState.grantRuntimePermission(bp, userId); 4221 switch (result) { 4222 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4223 return; 4224 } 4225 4226 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4227 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4228 mHandler.post(new Runnable() { 4229 @Override 4230 public void run() { 4231 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4232 } 4233 }); 4234 } 4235 break; 4236 } 4237 4238 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4239 4240 // Not critical if that is lost - app has to request again. 4241 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4242 } 4243 4244 // Only need to do this if user is initialized. Otherwise it's a new user 4245 // and there are no processes running as the user yet and there's no need 4246 // to make an expensive call to remount processes for the changed permissions. 4247 if (READ_EXTERNAL_STORAGE.equals(name) 4248 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4249 final long token = Binder.clearCallingIdentity(); 4250 try { 4251 if (sUserManager.isInitialized(userId)) { 4252 MountServiceInternal mountServiceInternal = LocalServices.getService( 4253 MountServiceInternal.class); 4254 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4255 } 4256 } finally { 4257 Binder.restoreCallingIdentity(token); 4258 } 4259 } 4260 } 4261 4262 @Override 4263 public void revokeRuntimePermission(String packageName, String name, int userId) { 4264 if (!sUserManager.exists(userId)) { 4265 Log.e(TAG, "No such user:" + userId); 4266 return; 4267 } 4268 4269 mContext.enforceCallingOrSelfPermission( 4270 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4271 "revokeRuntimePermission"); 4272 4273 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4274 true /* requireFullPermission */, true /* checkShell */, 4275 "revokeRuntimePermission"); 4276 4277 final int appId; 4278 4279 synchronized (mPackages) { 4280 final PackageParser.Package pkg = mPackages.get(packageName); 4281 if (pkg == null) { 4282 throw new IllegalArgumentException("Unknown package: " + packageName); 4283 } 4284 4285 final BasePermission bp = mSettings.mPermissions.get(name); 4286 if (bp == null) { 4287 throw new IllegalArgumentException("Unknown permission: " + name); 4288 } 4289 4290 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4291 4292 // If a permission review is required for legacy apps we represent 4293 // their permissions as always granted runtime ones since we need 4294 // to keep the review required permission flag per user while an 4295 // install permission's state is shared across all users. 4296 if (Build.PERMISSIONS_REVIEW_REQUIRED 4297 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4298 && bp.isRuntime()) { 4299 return; 4300 } 4301 4302 SettingBase sb = (SettingBase) pkg.mExtras; 4303 if (sb == null) { 4304 throw new IllegalArgumentException("Unknown package: " + packageName); 4305 } 4306 4307 final PermissionsState permissionsState = sb.getPermissionsState(); 4308 4309 final int flags = permissionsState.getPermissionFlags(name, userId); 4310 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4311 throw new SecurityException("Cannot revoke system fixed permission " 4312 + name + " for package " + packageName); 4313 } 4314 4315 if (bp.isDevelopment()) { 4316 // Development permissions must be handled specially, since they are not 4317 // normal runtime permissions. For now they apply to all users. 4318 if (permissionsState.revokeInstallPermission(bp) != 4319 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4320 scheduleWriteSettingsLocked(); 4321 } 4322 return; 4323 } 4324 4325 if (permissionsState.revokeRuntimePermission(bp, userId) == 4326 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4327 return; 4328 } 4329 4330 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4331 4332 // Critical, after this call app should never have the permission. 4333 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4334 4335 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4336 } 4337 4338 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4339 } 4340 4341 @Override 4342 public void resetRuntimePermissions() { 4343 mContext.enforceCallingOrSelfPermission( 4344 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4345 "revokeRuntimePermission"); 4346 4347 int callingUid = Binder.getCallingUid(); 4348 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4349 mContext.enforceCallingOrSelfPermission( 4350 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4351 "resetRuntimePermissions"); 4352 } 4353 4354 synchronized (mPackages) { 4355 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4356 for (int userId : UserManagerService.getInstance().getUserIds()) { 4357 final int packageCount = mPackages.size(); 4358 for (int i = 0; i < packageCount; i++) { 4359 PackageParser.Package pkg = mPackages.valueAt(i); 4360 if (!(pkg.mExtras instanceof PackageSetting)) { 4361 continue; 4362 } 4363 PackageSetting ps = (PackageSetting) pkg.mExtras; 4364 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4365 } 4366 } 4367 } 4368 } 4369 4370 @Override 4371 public int getPermissionFlags(String name, String packageName, int userId) { 4372 if (!sUserManager.exists(userId)) { 4373 return 0; 4374 } 4375 4376 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4377 4378 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4379 true /* requireFullPermission */, false /* checkShell */, 4380 "getPermissionFlags"); 4381 4382 synchronized (mPackages) { 4383 final PackageParser.Package pkg = mPackages.get(packageName); 4384 if (pkg == null) { 4385 return 0; 4386 } 4387 4388 final BasePermission bp = mSettings.mPermissions.get(name); 4389 if (bp == null) { 4390 return 0; 4391 } 4392 4393 SettingBase sb = (SettingBase) pkg.mExtras; 4394 if (sb == null) { 4395 return 0; 4396 } 4397 4398 PermissionsState permissionsState = sb.getPermissionsState(); 4399 return permissionsState.getPermissionFlags(name, userId); 4400 } 4401 } 4402 4403 @Override 4404 public void updatePermissionFlags(String name, String packageName, int flagMask, 4405 int flagValues, int userId) { 4406 if (!sUserManager.exists(userId)) { 4407 return; 4408 } 4409 4410 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4411 4412 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4413 true /* requireFullPermission */, true /* checkShell */, 4414 "updatePermissionFlags"); 4415 4416 // Only the system can change these flags and nothing else. 4417 if (getCallingUid() != Process.SYSTEM_UID) { 4418 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4419 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4420 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4421 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4422 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4423 } 4424 4425 synchronized (mPackages) { 4426 final PackageParser.Package pkg = mPackages.get(packageName); 4427 if (pkg == null) { 4428 throw new IllegalArgumentException("Unknown package: " + packageName); 4429 } 4430 4431 final BasePermission bp = mSettings.mPermissions.get(name); 4432 if (bp == null) { 4433 throw new IllegalArgumentException("Unknown permission: " + name); 4434 } 4435 4436 SettingBase sb = (SettingBase) pkg.mExtras; 4437 if (sb == null) { 4438 throw new IllegalArgumentException("Unknown package: " + packageName); 4439 } 4440 4441 PermissionsState permissionsState = sb.getPermissionsState(); 4442 4443 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4444 4445 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4446 // Install and runtime permissions are stored in different places, 4447 // so figure out what permission changed and persist the change. 4448 if (permissionsState.getInstallPermissionState(name) != null) { 4449 scheduleWriteSettingsLocked(); 4450 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4451 || hadState) { 4452 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4453 } 4454 } 4455 } 4456 } 4457 4458 /** 4459 * Update the permission flags for all packages and runtime permissions of a user in order 4460 * to allow device or profile owner to remove POLICY_FIXED. 4461 */ 4462 @Override 4463 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4464 if (!sUserManager.exists(userId)) { 4465 return; 4466 } 4467 4468 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4469 4470 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4471 true /* requireFullPermission */, true /* checkShell */, 4472 "updatePermissionFlagsForAllApps"); 4473 4474 // Only the system can change system fixed flags. 4475 if (getCallingUid() != Process.SYSTEM_UID) { 4476 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4477 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4478 } 4479 4480 synchronized (mPackages) { 4481 boolean changed = false; 4482 final int packageCount = mPackages.size(); 4483 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4484 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4485 SettingBase sb = (SettingBase) pkg.mExtras; 4486 if (sb == null) { 4487 continue; 4488 } 4489 PermissionsState permissionsState = sb.getPermissionsState(); 4490 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4491 userId, flagMask, flagValues); 4492 } 4493 if (changed) { 4494 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4495 } 4496 } 4497 } 4498 4499 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4500 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4501 != PackageManager.PERMISSION_GRANTED 4502 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4503 != PackageManager.PERMISSION_GRANTED) { 4504 throw new SecurityException(message + " requires " 4505 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4506 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4507 } 4508 } 4509 4510 @Override 4511 public boolean shouldShowRequestPermissionRationale(String permissionName, 4512 String packageName, int userId) { 4513 if (UserHandle.getCallingUserId() != userId) { 4514 mContext.enforceCallingPermission( 4515 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4516 "canShowRequestPermissionRationale for user " + userId); 4517 } 4518 4519 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4520 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4521 return false; 4522 } 4523 4524 if (checkPermission(permissionName, packageName, userId) 4525 == PackageManager.PERMISSION_GRANTED) { 4526 return false; 4527 } 4528 4529 final int flags; 4530 4531 final long identity = Binder.clearCallingIdentity(); 4532 try { 4533 flags = getPermissionFlags(permissionName, 4534 packageName, userId); 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 4539 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4540 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4541 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4542 4543 if ((flags & fixedFlags) != 0) { 4544 return false; 4545 } 4546 4547 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4548 } 4549 4550 @Override 4551 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4552 mContext.enforceCallingOrSelfPermission( 4553 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4554 "addOnPermissionsChangeListener"); 4555 4556 synchronized (mPackages) { 4557 mOnPermissionChangeListeners.addListenerLocked(listener); 4558 } 4559 } 4560 4561 @Override 4562 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4563 synchronized (mPackages) { 4564 mOnPermissionChangeListeners.removeListenerLocked(listener); 4565 } 4566 } 4567 4568 @Override 4569 public boolean isProtectedBroadcast(String actionName) { 4570 synchronized (mPackages) { 4571 if (mProtectedBroadcasts.contains(actionName)) { 4572 return true; 4573 } else if (actionName != null) { 4574 // TODO: remove these terrible hacks 4575 if (actionName.startsWith("android.net.netmon.lingerExpired") 4576 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4577 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4578 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4579 return true; 4580 } 4581 } 4582 } 4583 return false; 4584 } 4585 4586 @Override 4587 public int checkSignatures(String pkg1, String pkg2) { 4588 synchronized (mPackages) { 4589 final PackageParser.Package p1 = mPackages.get(pkg1); 4590 final PackageParser.Package p2 = mPackages.get(pkg2); 4591 if (p1 == null || p1.mExtras == null 4592 || p2 == null || p2.mExtras == null) { 4593 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4594 } 4595 return compareSignatures(p1.mSignatures, p2.mSignatures); 4596 } 4597 } 4598 4599 @Override 4600 public int checkUidSignatures(int uid1, int uid2) { 4601 // Map to base uids. 4602 uid1 = UserHandle.getAppId(uid1); 4603 uid2 = UserHandle.getAppId(uid2); 4604 // reader 4605 synchronized (mPackages) { 4606 Signature[] s1; 4607 Signature[] s2; 4608 Object obj = mSettings.getUserIdLPr(uid1); 4609 if (obj != null) { 4610 if (obj instanceof SharedUserSetting) { 4611 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4612 } else if (obj instanceof PackageSetting) { 4613 s1 = ((PackageSetting)obj).signatures.mSignatures; 4614 } else { 4615 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4616 } 4617 } else { 4618 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4619 } 4620 obj = mSettings.getUserIdLPr(uid2); 4621 if (obj != null) { 4622 if (obj instanceof SharedUserSetting) { 4623 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4624 } else if (obj instanceof PackageSetting) { 4625 s2 = ((PackageSetting)obj).signatures.mSignatures; 4626 } else { 4627 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4628 } 4629 } else { 4630 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4631 } 4632 return compareSignatures(s1, s2); 4633 } 4634 } 4635 4636 /** 4637 * This method should typically only be used when granting or revoking 4638 * permissions, since the app may immediately restart after this call. 4639 * <p> 4640 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4641 * guard your work against the app being relaunched. 4642 */ 4643 private void killUid(int appId, int userId, String reason) { 4644 final long identity = Binder.clearCallingIdentity(); 4645 try { 4646 IActivityManager am = ActivityManagerNative.getDefault(); 4647 if (am != null) { 4648 try { 4649 am.killUid(appId, userId, reason); 4650 } catch (RemoteException e) { 4651 /* ignore - same process */ 4652 } 4653 } 4654 } finally { 4655 Binder.restoreCallingIdentity(identity); 4656 } 4657 } 4658 4659 /** 4660 * Compares two sets of signatures. Returns: 4661 * <br /> 4662 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4663 * <br /> 4664 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4665 * <br /> 4666 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4667 * <br /> 4668 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4669 * <br /> 4670 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4671 */ 4672 static int compareSignatures(Signature[] s1, Signature[] s2) { 4673 if (s1 == null) { 4674 return s2 == null 4675 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4676 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4677 } 4678 4679 if (s2 == null) { 4680 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4681 } 4682 4683 if (s1.length != s2.length) { 4684 return PackageManager.SIGNATURE_NO_MATCH; 4685 } 4686 4687 // Since both signature sets are of size 1, we can compare without HashSets. 4688 if (s1.length == 1) { 4689 return s1[0].equals(s2[0]) ? 4690 PackageManager.SIGNATURE_MATCH : 4691 PackageManager.SIGNATURE_NO_MATCH; 4692 } 4693 4694 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4695 for (Signature sig : s1) { 4696 set1.add(sig); 4697 } 4698 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4699 for (Signature sig : s2) { 4700 set2.add(sig); 4701 } 4702 // Make sure s2 contains all signatures in s1. 4703 if (set1.equals(set2)) { 4704 return PackageManager.SIGNATURE_MATCH; 4705 } 4706 return PackageManager.SIGNATURE_NO_MATCH; 4707 } 4708 4709 /** 4710 * If the database version for this type of package (internal storage or 4711 * external storage) is less than the version where package signatures 4712 * were updated, return true. 4713 */ 4714 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4715 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4716 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4717 } 4718 4719 /** 4720 * Used for backward compatibility to make sure any packages with 4721 * certificate chains get upgraded to the new style. {@code existingSigs} 4722 * will be in the old format (since they were stored on disk from before the 4723 * system upgrade) and {@code scannedSigs} will be in the newer format. 4724 */ 4725 private int compareSignaturesCompat(PackageSignatures existingSigs, 4726 PackageParser.Package scannedPkg) { 4727 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4728 return PackageManager.SIGNATURE_NO_MATCH; 4729 } 4730 4731 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4732 for (Signature sig : existingSigs.mSignatures) { 4733 existingSet.add(sig); 4734 } 4735 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4736 for (Signature sig : scannedPkg.mSignatures) { 4737 try { 4738 Signature[] chainSignatures = sig.getChainSignatures(); 4739 for (Signature chainSig : chainSignatures) { 4740 scannedCompatSet.add(chainSig); 4741 } 4742 } catch (CertificateEncodingException e) { 4743 scannedCompatSet.add(sig); 4744 } 4745 } 4746 /* 4747 * Make sure the expanded scanned set contains all signatures in the 4748 * existing one. 4749 */ 4750 if (scannedCompatSet.equals(existingSet)) { 4751 // Migrate the old signatures to the new scheme. 4752 existingSigs.assignSignatures(scannedPkg.mSignatures); 4753 // The new KeySets will be re-added later in the scanning process. 4754 synchronized (mPackages) { 4755 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4756 } 4757 return PackageManager.SIGNATURE_MATCH; 4758 } 4759 return PackageManager.SIGNATURE_NO_MATCH; 4760 } 4761 4762 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4763 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4764 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4765 } 4766 4767 private int compareSignaturesRecover(PackageSignatures existingSigs, 4768 PackageParser.Package scannedPkg) { 4769 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4770 return PackageManager.SIGNATURE_NO_MATCH; 4771 } 4772 4773 String msg = null; 4774 try { 4775 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4776 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4777 + scannedPkg.packageName); 4778 return PackageManager.SIGNATURE_MATCH; 4779 } 4780 } catch (CertificateException e) { 4781 msg = e.getMessage(); 4782 } 4783 4784 logCriticalInfo(Log.INFO, 4785 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4786 return PackageManager.SIGNATURE_NO_MATCH; 4787 } 4788 4789 @Override 4790 public List<String> getAllPackages() { 4791 synchronized (mPackages) { 4792 return new ArrayList<String>(mPackages.keySet()); 4793 } 4794 } 4795 4796 @Override 4797 public String[] getPackagesForUid(int uid) { 4798 uid = UserHandle.getAppId(uid); 4799 // reader 4800 synchronized (mPackages) { 4801 Object obj = mSettings.getUserIdLPr(uid); 4802 if (obj instanceof SharedUserSetting) { 4803 final SharedUserSetting sus = (SharedUserSetting) obj; 4804 final int N = sus.packages.size(); 4805 final String[] res = new String[N]; 4806 for (int i = 0; i < N; i++) { 4807 res[i] = sus.packages.valueAt(i).name; 4808 } 4809 return res; 4810 } else if (obj instanceof PackageSetting) { 4811 final PackageSetting ps = (PackageSetting) obj; 4812 return new String[] { ps.name }; 4813 } 4814 } 4815 return null; 4816 } 4817 4818 @Override 4819 public String getNameForUid(int uid) { 4820 // reader 4821 synchronized (mPackages) { 4822 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4823 if (obj instanceof SharedUserSetting) { 4824 final SharedUserSetting sus = (SharedUserSetting) obj; 4825 return sus.name + ":" + sus.userId; 4826 } else if (obj instanceof PackageSetting) { 4827 final PackageSetting ps = (PackageSetting) obj; 4828 return ps.name; 4829 } 4830 } 4831 return null; 4832 } 4833 4834 @Override 4835 public int getUidForSharedUser(String sharedUserName) { 4836 if(sharedUserName == null) { 4837 return -1; 4838 } 4839 // reader 4840 synchronized (mPackages) { 4841 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4842 if (suid == null) { 4843 return -1; 4844 } 4845 return suid.userId; 4846 } 4847 } 4848 4849 @Override 4850 public int getFlagsForUid(int uid) { 4851 synchronized (mPackages) { 4852 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4853 if (obj instanceof SharedUserSetting) { 4854 final SharedUserSetting sus = (SharedUserSetting) obj; 4855 return sus.pkgFlags; 4856 } else if (obj instanceof PackageSetting) { 4857 final PackageSetting ps = (PackageSetting) obj; 4858 return ps.pkgFlags; 4859 } 4860 } 4861 return 0; 4862 } 4863 4864 @Override 4865 public int getPrivateFlagsForUid(int uid) { 4866 synchronized (mPackages) { 4867 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4868 if (obj instanceof SharedUserSetting) { 4869 final SharedUserSetting sus = (SharedUserSetting) obj; 4870 return sus.pkgPrivateFlags; 4871 } else if (obj instanceof PackageSetting) { 4872 final PackageSetting ps = (PackageSetting) obj; 4873 return ps.pkgPrivateFlags; 4874 } 4875 } 4876 return 0; 4877 } 4878 4879 @Override 4880 public boolean isUidPrivileged(int uid) { 4881 uid = UserHandle.getAppId(uid); 4882 // reader 4883 synchronized (mPackages) { 4884 Object obj = mSettings.getUserIdLPr(uid); 4885 if (obj instanceof SharedUserSetting) { 4886 final SharedUserSetting sus = (SharedUserSetting) obj; 4887 final Iterator<PackageSetting> it = sus.packages.iterator(); 4888 while (it.hasNext()) { 4889 if (it.next().isPrivileged()) { 4890 return true; 4891 } 4892 } 4893 } else if (obj instanceof PackageSetting) { 4894 final PackageSetting ps = (PackageSetting) obj; 4895 return ps.isPrivileged(); 4896 } 4897 } 4898 return false; 4899 } 4900 4901 @Override 4902 public String[] getAppOpPermissionPackages(String permissionName) { 4903 synchronized (mPackages) { 4904 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4905 if (pkgs == null) { 4906 return null; 4907 } 4908 return pkgs.toArray(new String[pkgs.size()]); 4909 } 4910 } 4911 4912 @Override 4913 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4914 int flags, int userId) { 4915 try { 4916 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4917 4918 if (!sUserManager.exists(userId)) return null; 4919 flags = updateFlagsForResolve(flags, userId, intent); 4920 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4921 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4922 4923 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4924 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4925 flags, userId); 4926 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4927 4928 final ResolveInfo bestChoice = 4929 chooseBestActivity(intent, resolvedType, flags, query, userId); 4930 4931 if (isEphemeralAllowed(intent, query, userId)) { 4932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4933 final EphemeralResolveInfo ai = 4934 getEphemeralResolveInfo(intent, resolvedType, userId); 4935 if (ai != null) { 4936 if (DEBUG_EPHEMERAL) { 4937 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4938 } 4939 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4940 bestChoice.ephemeralResolveInfo = ai; 4941 } 4942 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4943 } 4944 return bestChoice; 4945 } finally { 4946 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4947 } 4948 } 4949 4950 @Override 4951 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4952 IntentFilter filter, int match, ComponentName activity) { 4953 final int userId = UserHandle.getCallingUserId(); 4954 if (DEBUG_PREFERRED) { 4955 Log.v(TAG, "setLastChosenActivity intent=" + intent 4956 + " resolvedType=" + resolvedType 4957 + " flags=" + flags 4958 + " filter=" + filter 4959 + " match=" + match 4960 + " activity=" + activity); 4961 filter.dump(new PrintStreamPrinter(System.out), " "); 4962 } 4963 intent.setComponent(null); 4964 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4965 userId); 4966 // Find any earlier preferred or last chosen entries and nuke them 4967 findPreferredActivity(intent, resolvedType, 4968 flags, query, 0, false, true, false, userId); 4969 // Add the new activity as the last chosen for this filter 4970 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4971 "Setting last chosen"); 4972 } 4973 4974 @Override 4975 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4976 final int userId = UserHandle.getCallingUserId(); 4977 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4978 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4979 userId); 4980 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4981 false, false, false, userId); 4982 } 4983 4984 4985 private boolean isEphemeralAllowed( 4986 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4987 // Short circuit and return early if possible. 4988 if (DISABLE_EPHEMERAL_APPS) { 4989 return false; 4990 } 4991 final int callingUser = UserHandle.getCallingUserId(); 4992 if (callingUser != UserHandle.USER_SYSTEM) { 4993 return false; 4994 } 4995 if (mEphemeralResolverConnection == null) { 4996 return false; 4997 } 4998 if (intent.getComponent() != null) { 4999 return false; 5000 } 5001 if (intent.getPackage() != null) { 5002 return false; 5003 } 5004 final boolean isWebUri = hasWebURI(intent); 5005 if (!isWebUri) { 5006 return false; 5007 } 5008 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5009 synchronized (mPackages) { 5010 final int count = resolvedActivites.size(); 5011 for (int n = 0; n < count; n++) { 5012 ResolveInfo info = resolvedActivites.get(n); 5013 String packageName = info.activityInfo.packageName; 5014 PackageSetting ps = mSettings.mPackages.get(packageName); 5015 if (ps != null) { 5016 // Try to get the status from User settings first 5017 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5018 int status = (int) (packedStatus >> 32); 5019 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5020 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5021 if (DEBUG_EPHEMERAL) { 5022 Slog.v(TAG, "DENY ephemeral apps;" 5023 + " pkg: " + packageName + ", status: " + status); 5024 } 5025 return false; 5026 } 5027 } 5028 } 5029 } 5030 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5031 return true; 5032 } 5033 5034 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5035 int userId) { 5036 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5037 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5038 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5039 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5040 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 5041 ephemeralPrefixCount); 5042 final int[] shaPrefix = digest.getDigestPrefix(); 5043 final byte[][] digestBytes = digest.getDigestBytes(); 5044 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5045 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5046 shaPrefix, ephemeralPrefixMask); 5047 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5048 // No hash prefix match; there are no ephemeral apps for this domain. 5049 return null; 5050 } 5051 5052 // Go in reverse order so we match the narrowest scope first. 5053 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5054 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5055 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5056 continue; 5057 } 5058 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5059 // No filters; this should never happen. 5060 if (filters.isEmpty()) { 5061 continue; 5062 } 5063 // We have a domain match; resolve the filters to see if anything matches. 5064 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5065 for (int j = filters.size() - 1; j >= 0; --j) { 5066 final EphemeralResolveIntentInfo intentInfo = 5067 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5068 ephemeralResolver.addFilter(intentInfo); 5069 } 5070 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5071 intent, resolvedType, false /*defaultOnly*/, userId); 5072 if (!matchedResolveInfoList.isEmpty()) { 5073 return matchedResolveInfoList.get(0); 5074 } 5075 } 5076 } 5077 // Hash or filter mis-match; no ephemeral apps for this domain. 5078 return null; 5079 } 5080 5081 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5082 int flags, List<ResolveInfo> query, int userId) { 5083 if (query != null) { 5084 final int N = query.size(); 5085 if (N == 1) { 5086 return query.get(0); 5087 } else if (N > 1) { 5088 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5089 // If there is more than one activity with the same priority, 5090 // then let the user decide between them. 5091 ResolveInfo r0 = query.get(0); 5092 ResolveInfo r1 = query.get(1); 5093 if (DEBUG_INTENT_MATCHING || debug) { 5094 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5095 + r1.activityInfo.name + "=" + r1.priority); 5096 } 5097 // If the first activity has a higher priority, or a different 5098 // default, then it is always desirable to pick it. 5099 if (r0.priority != r1.priority 5100 || r0.preferredOrder != r1.preferredOrder 5101 || r0.isDefault != r1.isDefault) { 5102 return query.get(0); 5103 } 5104 // If we have saved a preference for a preferred activity for 5105 // this Intent, use that. 5106 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5107 flags, query, r0.priority, true, false, debug, userId); 5108 if (ri != null) { 5109 return ri; 5110 } 5111 ri = new ResolveInfo(mResolveInfo); 5112 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5113 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5114 // If all of the options come from the same package, show the application's 5115 // label and icon instead of the generic resolver's. 5116 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5117 // and then throw away the ResolveInfo itself, meaning that the caller loses 5118 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5119 // a fallback for this case; we only set the target package's resources on 5120 // the ResolveInfo, not the ActivityInfo. 5121 final String intentPackage = intent.getPackage(); 5122 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5123 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5124 ri.resolvePackageName = intentPackage; 5125 if (userNeedsBadging(userId)) { 5126 ri.noResourceId = true; 5127 } else { 5128 ri.icon = appi.icon; 5129 } 5130 ri.iconResourceId = appi.icon; 5131 ri.labelRes = appi.labelRes; 5132 } 5133 ri.activityInfo.applicationInfo = new ApplicationInfo( 5134 ri.activityInfo.applicationInfo); 5135 if (userId != 0) { 5136 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5137 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5138 } 5139 // Make sure that the resolver is displayable in car mode 5140 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5141 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5142 return ri; 5143 } 5144 } 5145 return null; 5146 } 5147 5148 /** 5149 * Return true if the given list is not empty and all of its contents have 5150 * an activityInfo with the given package name. 5151 */ 5152 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5153 if (ArrayUtils.isEmpty(list)) { 5154 return false; 5155 } 5156 for (int i = 0, N = list.size(); i < N; i++) { 5157 final ResolveInfo ri = list.get(i); 5158 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5159 if (ai == null || !packageName.equals(ai.packageName)) { 5160 return false; 5161 } 5162 } 5163 return true; 5164 } 5165 5166 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5167 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5168 final int N = query.size(); 5169 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5170 .get(userId); 5171 // Get the list of persistent preferred activities that handle the intent 5172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5173 List<PersistentPreferredActivity> pprefs = ppir != null 5174 ? ppir.queryIntent(intent, resolvedType, 5175 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5176 : null; 5177 if (pprefs != null && pprefs.size() > 0) { 5178 final int M = pprefs.size(); 5179 for (int i=0; i<M; i++) { 5180 final PersistentPreferredActivity ppa = pprefs.get(i); 5181 if (DEBUG_PREFERRED || debug) { 5182 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5183 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5184 + "\n component=" + ppa.mComponent); 5185 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5186 } 5187 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5188 flags | MATCH_DISABLED_COMPONENTS, userId); 5189 if (DEBUG_PREFERRED || debug) { 5190 Slog.v(TAG, "Found persistent preferred activity:"); 5191 if (ai != null) { 5192 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5193 } else { 5194 Slog.v(TAG, " null"); 5195 } 5196 } 5197 if (ai == null) { 5198 // This previously registered persistent preferred activity 5199 // component is no longer known. Ignore it and do NOT remove it. 5200 continue; 5201 } 5202 for (int j=0; j<N; j++) { 5203 final ResolveInfo ri = query.get(j); 5204 if (!ri.activityInfo.applicationInfo.packageName 5205 .equals(ai.applicationInfo.packageName)) { 5206 continue; 5207 } 5208 if (!ri.activityInfo.name.equals(ai.name)) { 5209 continue; 5210 } 5211 // Found a persistent preference that can handle the intent. 5212 if (DEBUG_PREFERRED || debug) { 5213 Slog.v(TAG, "Returning persistent preferred activity: " + 5214 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5215 } 5216 return ri; 5217 } 5218 } 5219 } 5220 return null; 5221 } 5222 5223 // TODO: handle preferred activities missing while user has amnesia 5224 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5225 List<ResolveInfo> query, int priority, boolean always, 5226 boolean removeMatches, boolean debug, int userId) { 5227 if (!sUserManager.exists(userId)) return null; 5228 flags = updateFlagsForResolve(flags, userId, intent); 5229 // writer 5230 synchronized (mPackages) { 5231 if (intent.getSelector() != null) { 5232 intent = intent.getSelector(); 5233 } 5234 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5235 5236 // Try to find a matching persistent preferred activity. 5237 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5238 debug, userId); 5239 5240 // If a persistent preferred activity matched, use it. 5241 if (pri != null) { 5242 return pri; 5243 } 5244 5245 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5246 // Get the list of preferred activities that handle the intent 5247 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5248 List<PreferredActivity> prefs = pir != null 5249 ? pir.queryIntent(intent, resolvedType, 5250 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5251 : null; 5252 if (prefs != null && prefs.size() > 0) { 5253 boolean changed = false; 5254 try { 5255 // First figure out how good the original match set is. 5256 // We will only allow preferred activities that came 5257 // from the same match quality. 5258 int match = 0; 5259 5260 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5261 5262 final int N = query.size(); 5263 for (int j=0; j<N; j++) { 5264 final ResolveInfo ri = query.get(j); 5265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5266 + ": 0x" + Integer.toHexString(match)); 5267 if (ri.match > match) { 5268 match = ri.match; 5269 } 5270 } 5271 5272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5273 + Integer.toHexString(match)); 5274 5275 match &= IntentFilter.MATCH_CATEGORY_MASK; 5276 final int M = prefs.size(); 5277 for (int i=0; i<M; i++) { 5278 final PreferredActivity pa = prefs.get(i); 5279 if (DEBUG_PREFERRED || debug) { 5280 Slog.v(TAG, "Checking PreferredActivity ds=" 5281 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5282 + "\n component=" + pa.mPref.mComponent); 5283 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5284 } 5285 if (pa.mPref.mMatch != match) { 5286 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5287 + Integer.toHexString(pa.mPref.mMatch)); 5288 continue; 5289 } 5290 // If it's not an "always" type preferred activity and that's what we're 5291 // looking for, skip it. 5292 if (always && !pa.mPref.mAlways) { 5293 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5294 continue; 5295 } 5296 final ActivityInfo ai = getActivityInfo( 5297 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5298 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5299 userId); 5300 if (DEBUG_PREFERRED || debug) { 5301 Slog.v(TAG, "Found preferred activity:"); 5302 if (ai != null) { 5303 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5304 } else { 5305 Slog.v(TAG, " null"); 5306 } 5307 } 5308 if (ai == null) { 5309 // This previously registered preferred activity 5310 // component is no longer known. Most likely an update 5311 // to the app was installed and in the new version this 5312 // component no longer exists. Clean it up by removing 5313 // it from the preferred activities list, and skip it. 5314 Slog.w(TAG, "Removing dangling preferred activity: " 5315 + pa.mPref.mComponent); 5316 pir.removeFilter(pa); 5317 changed = true; 5318 continue; 5319 } 5320 for (int j=0; j<N; j++) { 5321 final ResolveInfo ri = query.get(j); 5322 if (!ri.activityInfo.applicationInfo.packageName 5323 .equals(ai.applicationInfo.packageName)) { 5324 continue; 5325 } 5326 if (!ri.activityInfo.name.equals(ai.name)) { 5327 continue; 5328 } 5329 5330 if (removeMatches) { 5331 pir.removeFilter(pa); 5332 changed = true; 5333 if (DEBUG_PREFERRED) { 5334 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5335 } 5336 break; 5337 } 5338 5339 // Okay we found a previously set preferred or last chosen app. 5340 // If the result set is different from when this 5341 // was created, we need to clear it and re-ask the 5342 // user their preference, if we're looking for an "always" type entry. 5343 if (always && !pa.mPref.sameSet(query)) { 5344 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5345 + intent + " type " + resolvedType); 5346 if (DEBUG_PREFERRED) { 5347 Slog.v(TAG, "Removing preferred activity since set changed " 5348 + pa.mPref.mComponent); 5349 } 5350 pir.removeFilter(pa); 5351 // Re-add the filter as a "last chosen" entry (!always) 5352 PreferredActivity lastChosen = new PreferredActivity( 5353 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5354 pir.addFilter(lastChosen); 5355 changed = true; 5356 return null; 5357 } 5358 5359 // Yay! Either the set matched or we're looking for the last chosen 5360 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5361 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5362 return ri; 5363 } 5364 } 5365 } finally { 5366 if (changed) { 5367 if (DEBUG_PREFERRED) { 5368 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5369 } 5370 scheduleWritePackageRestrictionsLocked(userId); 5371 } 5372 } 5373 } 5374 } 5375 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5376 return null; 5377 } 5378 5379 /* 5380 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5381 */ 5382 @Override 5383 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5384 int targetUserId) { 5385 mContext.enforceCallingOrSelfPermission( 5386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5387 List<CrossProfileIntentFilter> matches = 5388 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5389 if (matches != null) { 5390 int size = matches.size(); 5391 for (int i = 0; i < size; i++) { 5392 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5393 } 5394 } 5395 if (hasWebURI(intent)) { 5396 // cross-profile app linking works only towards the parent. 5397 final UserInfo parent = getProfileParent(sourceUserId); 5398 synchronized(mPackages) { 5399 int flags = updateFlagsForResolve(0, parent.id, intent); 5400 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5401 intent, resolvedType, flags, sourceUserId, parent.id); 5402 return xpDomainInfo != null; 5403 } 5404 } 5405 return false; 5406 } 5407 5408 private UserInfo getProfileParent(int userId) { 5409 final long identity = Binder.clearCallingIdentity(); 5410 try { 5411 return sUserManager.getProfileParent(userId); 5412 } finally { 5413 Binder.restoreCallingIdentity(identity); 5414 } 5415 } 5416 5417 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5418 String resolvedType, int userId) { 5419 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5420 if (resolver != null) { 5421 return resolver.queryIntent(intent, resolvedType, false, userId); 5422 } 5423 return null; 5424 } 5425 5426 @Override 5427 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5428 String resolvedType, int flags, int userId) { 5429 try { 5430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5431 5432 return new ParceledListSlice<>( 5433 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5434 } finally { 5435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5436 } 5437 } 5438 5439 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5440 String resolvedType, int flags, int userId) { 5441 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5442 flags = updateFlagsForResolve(flags, userId, intent); 5443 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5444 false /* requireFullPermission */, false /* checkShell */, 5445 "query intent activities"); 5446 ComponentName comp = intent.getComponent(); 5447 if (comp == null) { 5448 if (intent.getSelector() != null) { 5449 intent = intent.getSelector(); 5450 comp = intent.getComponent(); 5451 } 5452 } 5453 5454 if (comp != null) { 5455 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5456 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5457 if (ai != null) { 5458 final ResolveInfo ri = new ResolveInfo(); 5459 ri.activityInfo = ai; 5460 list.add(ri); 5461 } 5462 return list; 5463 } 5464 5465 // reader 5466 synchronized (mPackages) { 5467 final String pkgName = intent.getPackage(); 5468 if (pkgName == null) { 5469 List<CrossProfileIntentFilter> matchingFilters = 5470 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5471 // Check for results that need to skip the current profile. 5472 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5473 resolvedType, flags, userId); 5474 if (xpResolveInfo != null) { 5475 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5476 result.add(xpResolveInfo); 5477 return filterIfNotSystemUser(result, userId); 5478 } 5479 5480 // Check for results in the current profile. 5481 List<ResolveInfo> result = mActivities.queryIntent( 5482 intent, resolvedType, flags, userId); 5483 result = filterIfNotSystemUser(result, userId); 5484 5485 // Check for cross profile results. 5486 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5487 xpResolveInfo = queryCrossProfileIntents( 5488 matchingFilters, intent, resolvedType, flags, userId, 5489 hasNonNegativePriorityResult); 5490 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5491 boolean isVisibleToUser = filterIfNotSystemUser( 5492 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5493 if (isVisibleToUser) { 5494 result.add(xpResolveInfo); 5495 Collections.sort(result, mResolvePrioritySorter); 5496 } 5497 } 5498 if (hasWebURI(intent)) { 5499 CrossProfileDomainInfo xpDomainInfo = null; 5500 final UserInfo parent = getProfileParent(userId); 5501 if (parent != null) { 5502 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5503 flags, userId, parent.id); 5504 } 5505 if (xpDomainInfo != null) { 5506 if (xpResolveInfo != null) { 5507 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5508 // in the result. 5509 result.remove(xpResolveInfo); 5510 } 5511 if (result.size() == 0) { 5512 result.add(xpDomainInfo.resolveInfo); 5513 return result; 5514 } 5515 } else if (result.size() <= 1) { 5516 return result; 5517 } 5518 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5519 xpDomainInfo, userId); 5520 Collections.sort(result, mResolvePrioritySorter); 5521 } 5522 return result; 5523 } 5524 final PackageParser.Package pkg = mPackages.get(pkgName); 5525 if (pkg != null) { 5526 return filterIfNotSystemUser( 5527 mActivities.queryIntentForPackage( 5528 intent, resolvedType, flags, pkg.activities, userId), 5529 userId); 5530 } 5531 return new ArrayList<ResolveInfo>(); 5532 } 5533 } 5534 5535 private static class CrossProfileDomainInfo { 5536 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5537 ResolveInfo resolveInfo; 5538 /* Best domain verification status of the activities found in the other profile */ 5539 int bestDomainVerificationStatus; 5540 } 5541 5542 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5543 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5544 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5545 sourceUserId)) { 5546 return null; 5547 } 5548 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5549 resolvedType, flags, parentUserId); 5550 5551 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5552 return null; 5553 } 5554 CrossProfileDomainInfo result = null; 5555 int size = resultTargetUser.size(); 5556 for (int i = 0; i < size; i++) { 5557 ResolveInfo riTargetUser = resultTargetUser.get(i); 5558 // Intent filter verification is only for filters that specify a host. So don't return 5559 // those that handle all web uris. 5560 if (riTargetUser.handleAllWebDataURI) { 5561 continue; 5562 } 5563 String packageName = riTargetUser.activityInfo.packageName; 5564 PackageSetting ps = mSettings.mPackages.get(packageName); 5565 if (ps == null) { 5566 continue; 5567 } 5568 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5569 int status = (int)(verificationState >> 32); 5570 if (result == null) { 5571 result = new CrossProfileDomainInfo(); 5572 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5573 sourceUserId, parentUserId); 5574 result.bestDomainVerificationStatus = status; 5575 } else { 5576 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5577 result.bestDomainVerificationStatus); 5578 } 5579 } 5580 // Don't consider matches with status NEVER across profiles. 5581 if (result != null && result.bestDomainVerificationStatus 5582 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5583 return null; 5584 } 5585 return result; 5586 } 5587 5588 /** 5589 * Verification statuses are ordered from the worse to the best, except for 5590 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5591 */ 5592 private int bestDomainVerificationStatus(int status1, int status2) { 5593 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5594 return status2; 5595 } 5596 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5597 return status1; 5598 } 5599 return (int) MathUtils.max(status1, status2); 5600 } 5601 5602 private boolean isUserEnabled(int userId) { 5603 long callingId = Binder.clearCallingIdentity(); 5604 try { 5605 UserInfo userInfo = sUserManager.getUserInfo(userId); 5606 return userInfo != null && userInfo.isEnabled(); 5607 } finally { 5608 Binder.restoreCallingIdentity(callingId); 5609 } 5610 } 5611 5612 /** 5613 * Filter out activities with systemUserOnly flag set, when current user is not System. 5614 * 5615 * @return filtered list 5616 */ 5617 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5618 if (userId == UserHandle.USER_SYSTEM) { 5619 return resolveInfos; 5620 } 5621 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5622 ResolveInfo info = resolveInfos.get(i); 5623 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5624 resolveInfos.remove(i); 5625 } 5626 } 5627 return resolveInfos; 5628 } 5629 5630 /** 5631 * @param resolveInfos list of resolve infos in descending priority order 5632 * @return if the list contains a resolve info with non-negative priority 5633 */ 5634 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5635 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5636 } 5637 5638 private static boolean hasWebURI(Intent intent) { 5639 if (intent.getData() == null) { 5640 return false; 5641 } 5642 final String scheme = intent.getScheme(); 5643 if (TextUtils.isEmpty(scheme)) { 5644 return false; 5645 } 5646 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5647 } 5648 5649 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5650 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5651 int userId) { 5652 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5653 5654 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5655 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5656 candidates.size()); 5657 } 5658 5659 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5660 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5661 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5662 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5663 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5664 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5665 5666 synchronized (mPackages) { 5667 final int count = candidates.size(); 5668 // First, try to use linked apps. Partition the candidates into four lists: 5669 // one for the final results, one for the "do not use ever", one for "undefined status" 5670 // and finally one for "browser app type". 5671 for (int n=0; n<count; n++) { 5672 ResolveInfo info = candidates.get(n); 5673 String packageName = info.activityInfo.packageName; 5674 PackageSetting ps = mSettings.mPackages.get(packageName); 5675 if (ps != null) { 5676 // Add to the special match all list (Browser use case) 5677 if (info.handleAllWebDataURI) { 5678 matchAllList.add(info); 5679 continue; 5680 } 5681 // Try to get the status from User settings first 5682 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5683 int status = (int)(packedStatus >> 32); 5684 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5685 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5686 if (DEBUG_DOMAIN_VERIFICATION) { 5687 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5688 + " : linkgen=" + linkGeneration); 5689 } 5690 // Use link-enabled generation as preferredOrder, i.e. 5691 // prefer newly-enabled over earlier-enabled. 5692 info.preferredOrder = linkGeneration; 5693 alwaysList.add(info); 5694 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5695 if (DEBUG_DOMAIN_VERIFICATION) { 5696 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5697 } 5698 neverList.add(info); 5699 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5700 if (DEBUG_DOMAIN_VERIFICATION) { 5701 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5702 } 5703 alwaysAskList.add(info); 5704 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5705 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5706 if (DEBUG_DOMAIN_VERIFICATION) { 5707 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5708 } 5709 undefinedList.add(info); 5710 } 5711 } 5712 } 5713 5714 // We'll want to include browser possibilities in a few cases 5715 boolean includeBrowser = false; 5716 5717 // First try to add the "always" resolution(s) for the current user, if any 5718 if (alwaysList.size() > 0) { 5719 result.addAll(alwaysList); 5720 } else { 5721 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5722 result.addAll(undefinedList); 5723 // Maybe add one for the other profile. 5724 if (xpDomainInfo != null && ( 5725 xpDomainInfo.bestDomainVerificationStatus 5726 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5727 result.add(xpDomainInfo.resolveInfo); 5728 } 5729 includeBrowser = true; 5730 } 5731 5732 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5733 // If there were 'always' entries their preferred order has been set, so we also 5734 // back that off to make the alternatives equivalent 5735 if (alwaysAskList.size() > 0) { 5736 for (ResolveInfo i : result) { 5737 i.preferredOrder = 0; 5738 } 5739 result.addAll(alwaysAskList); 5740 includeBrowser = true; 5741 } 5742 5743 if (includeBrowser) { 5744 // Also add browsers (all of them or only the default one) 5745 if (DEBUG_DOMAIN_VERIFICATION) { 5746 Slog.v(TAG, " ...including browsers in candidate set"); 5747 } 5748 if ((matchFlags & MATCH_ALL) != 0) { 5749 result.addAll(matchAllList); 5750 } else { 5751 // Browser/generic handling case. If there's a default browser, go straight 5752 // to that (but only if there is no other higher-priority match). 5753 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5754 int maxMatchPrio = 0; 5755 ResolveInfo defaultBrowserMatch = null; 5756 final int numCandidates = matchAllList.size(); 5757 for (int n = 0; n < numCandidates; n++) { 5758 ResolveInfo info = matchAllList.get(n); 5759 // track the highest overall match priority... 5760 if (info.priority > maxMatchPrio) { 5761 maxMatchPrio = info.priority; 5762 } 5763 // ...and the highest-priority default browser match 5764 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5765 if (defaultBrowserMatch == null 5766 || (defaultBrowserMatch.priority < info.priority)) { 5767 if (debug) { 5768 Slog.v(TAG, "Considering default browser match " + info); 5769 } 5770 defaultBrowserMatch = info; 5771 } 5772 } 5773 } 5774 if (defaultBrowserMatch != null 5775 && defaultBrowserMatch.priority >= maxMatchPrio 5776 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5777 { 5778 if (debug) { 5779 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5780 } 5781 result.add(defaultBrowserMatch); 5782 } else { 5783 result.addAll(matchAllList); 5784 } 5785 } 5786 5787 // If there is nothing selected, add all candidates and remove the ones that the user 5788 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5789 if (result.size() == 0) { 5790 result.addAll(candidates); 5791 result.removeAll(neverList); 5792 } 5793 } 5794 } 5795 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5796 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5797 result.size()); 5798 for (ResolveInfo info : result) { 5799 Slog.v(TAG, " + " + info.activityInfo); 5800 } 5801 } 5802 return result; 5803 } 5804 5805 // Returns a packed value as a long: 5806 // 5807 // high 'int'-sized word: link status: undefined/ask/never/always. 5808 // low 'int'-sized word: relative priority among 'always' results. 5809 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5810 long result = ps.getDomainVerificationStatusForUser(userId); 5811 // if none available, get the master status 5812 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5813 if (ps.getIntentFilterVerificationInfo() != null) { 5814 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5815 } 5816 } 5817 return result; 5818 } 5819 5820 private ResolveInfo querySkipCurrentProfileIntents( 5821 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5822 int flags, int sourceUserId) { 5823 if (matchingFilters != null) { 5824 int size = matchingFilters.size(); 5825 for (int i = 0; i < size; i ++) { 5826 CrossProfileIntentFilter filter = matchingFilters.get(i); 5827 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5828 // Checking if there are activities in the target user that can handle the 5829 // intent. 5830 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5831 resolvedType, flags, sourceUserId); 5832 if (resolveInfo != null) { 5833 return resolveInfo; 5834 } 5835 } 5836 } 5837 } 5838 return null; 5839 } 5840 5841 // Return matching ResolveInfo in target user if any. 5842 private ResolveInfo queryCrossProfileIntents( 5843 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5844 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5845 if (matchingFilters != null) { 5846 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5847 // match the same intent. For performance reasons, it is better not to 5848 // run queryIntent twice for the same userId 5849 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5850 int size = matchingFilters.size(); 5851 for (int i = 0; i < size; i++) { 5852 CrossProfileIntentFilter filter = matchingFilters.get(i); 5853 int targetUserId = filter.getTargetUserId(); 5854 boolean skipCurrentProfile = 5855 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5856 boolean skipCurrentProfileIfNoMatchFound = 5857 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5858 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5859 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5860 // Checking if there are activities in the target user that can handle the 5861 // intent. 5862 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5863 resolvedType, flags, sourceUserId); 5864 if (resolveInfo != null) return resolveInfo; 5865 alreadyTriedUserIds.put(targetUserId, true); 5866 } 5867 } 5868 } 5869 return null; 5870 } 5871 5872 /** 5873 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5874 * will forward the intent to the filter's target user. 5875 * Otherwise, returns null. 5876 */ 5877 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5878 String resolvedType, int flags, int sourceUserId) { 5879 int targetUserId = filter.getTargetUserId(); 5880 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5881 resolvedType, flags, targetUserId); 5882 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5883 // If all the matches in the target profile are suspended, return null. 5884 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5885 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5886 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5887 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5888 targetUserId); 5889 } 5890 } 5891 } 5892 return null; 5893 } 5894 5895 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5896 int sourceUserId, int targetUserId) { 5897 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5898 long ident = Binder.clearCallingIdentity(); 5899 boolean targetIsProfile; 5900 try { 5901 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5902 } finally { 5903 Binder.restoreCallingIdentity(ident); 5904 } 5905 String className; 5906 if (targetIsProfile) { 5907 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5908 } else { 5909 className = FORWARD_INTENT_TO_PARENT; 5910 } 5911 ComponentName forwardingActivityComponentName = new ComponentName( 5912 mAndroidApplication.packageName, className); 5913 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5914 sourceUserId); 5915 if (!targetIsProfile) { 5916 forwardingActivityInfo.showUserIcon = targetUserId; 5917 forwardingResolveInfo.noResourceId = true; 5918 } 5919 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5920 forwardingResolveInfo.priority = 0; 5921 forwardingResolveInfo.preferredOrder = 0; 5922 forwardingResolveInfo.match = 0; 5923 forwardingResolveInfo.isDefault = true; 5924 forwardingResolveInfo.filter = filter; 5925 forwardingResolveInfo.targetUserId = targetUserId; 5926 return forwardingResolveInfo; 5927 } 5928 5929 @Override 5930 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5931 Intent[] specifics, String[] specificTypes, Intent intent, 5932 String resolvedType, int flags, int userId) { 5933 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5934 specificTypes, intent, resolvedType, flags, userId)); 5935 } 5936 5937 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5938 Intent[] specifics, String[] specificTypes, Intent intent, 5939 String resolvedType, int flags, int userId) { 5940 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5941 flags = updateFlagsForResolve(flags, userId, intent); 5942 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5943 false /* requireFullPermission */, false /* checkShell */, 5944 "query intent activity options"); 5945 final String resultsAction = intent.getAction(); 5946 5947 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5948 | PackageManager.GET_RESOLVED_FILTER, userId); 5949 5950 if (DEBUG_INTENT_MATCHING) { 5951 Log.v(TAG, "Query " + intent + ": " + results); 5952 } 5953 5954 int specificsPos = 0; 5955 int N; 5956 5957 // todo: note that the algorithm used here is O(N^2). This 5958 // isn't a problem in our current environment, but if we start running 5959 // into situations where we have more than 5 or 10 matches then this 5960 // should probably be changed to something smarter... 5961 5962 // First we go through and resolve each of the specific items 5963 // that were supplied, taking care of removing any corresponding 5964 // duplicate items in the generic resolve list. 5965 if (specifics != null) { 5966 for (int i=0; i<specifics.length; i++) { 5967 final Intent sintent = specifics[i]; 5968 if (sintent == null) { 5969 continue; 5970 } 5971 5972 if (DEBUG_INTENT_MATCHING) { 5973 Log.v(TAG, "Specific #" + i + ": " + sintent); 5974 } 5975 5976 String action = sintent.getAction(); 5977 if (resultsAction != null && resultsAction.equals(action)) { 5978 // If this action was explicitly requested, then don't 5979 // remove things that have it. 5980 action = null; 5981 } 5982 5983 ResolveInfo ri = null; 5984 ActivityInfo ai = null; 5985 5986 ComponentName comp = sintent.getComponent(); 5987 if (comp == null) { 5988 ri = resolveIntent( 5989 sintent, 5990 specificTypes != null ? specificTypes[i] : null, 5991 flags, userId); 5992 if (ri == null) { 5993 continue; 5994 } 5995 if (ri == mResolveInfo) { 5996 // ACK! Must do something better with this. 5997 } 5998 ai = ri.activityInfo; 5999 comp = new ComponentName(ai.applicationInfo.packageName, 6000 ai.name); 6001 } else { 6002 ai = getActivityInfo(comp, flags, userId); 6003 if (ai == null) { 6004 continue; 6005 } 6006 } 6007 6008 // Look for any generic query activities that are duplicates 6009 // of this specific one, and remove them from the results. 6010 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6011 N = results.size(); 6012 int j; 6013 for (j=specificsPos; j<N; j++) { 6014 ResolveInfo sri = results.get(j); 6015 if ((sri.activityInfo.name.equals(comp.getClassName()) 6016 && sri.activityInfo.applicationInfo.packageName.equals( 6017 comp.getPackageName())) 6018 || (action != null && sri.filter.matchAction(action))) { 6019 results.remove(j); 6020 if (DEBUG_INTENT_MATCHING) Log.v( 6021 TAG, "Removing duplicate item from " + j 6022 + " due to specific " + specificsPos); 6023 if (ri == null) { 6024 ri = sri; 6025 } 6026 j--; 6027 N--; 6028 } 6029 } 6030 6031 // Add this specific item to its proper place. 6032 if (ri == null) { 6033 ri = new ResolveInfo(); 6034 ri.activityInfo = ai; 6035 } 6036 results.add(specificsPos, ri); 6037 ri.specificIndex = i; 6038 specificsPos++; 6039 } 6040 } 6041 6042 // Now we go through the remaining generic results and remove any 6043 // duplicate actions that are found here. 6044 N = results.size(); 6045 for (int i=specificsPos; i<N-1; i++) { 6046 final ResolveInfo rii = results.get(i); 6047 if (rii.filter == null) { 6048 continue; 6049 } 6050 6051 // Iterate over all of the actions of this result's intent 6052 // filter... typically this should be just one. 6053 final Iterator<String> it = rii.filter.actionsIterator(); 6054 if (it == null) { 6055 continue; 6056 } 6057 while (it.hasNext()) { 6058 final String action = it.next(); 6059 if (resultsAction != null && resultsAction.equals(action)) { 6060 // If this action was explicitly requested, then don't 6061 // remove things that have it. 6062 continue; 6063 } 6064 for (int j=i+1; j<N; j++) { 6065 final ResolveInfo rij = results.get(j); 6066 if (rij.filter != null && rij.filter.hasAction(action)) { 6067 results.remove(j); 6068 if (DEBUG_INTENT_MATCHING) Log.v( 6069 TAG, "Removing duplicate item from " + j 6070 + " due to action " + action + " at " + i); 6071 j--; 6072 N--; 6073 } 6074 } 6075 } 6076 6077 // If the caller didn't request filter information, drop it now 6078 // so we don't have to marshall/unmarshall it. 6079 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6080 rii.filter = null; 6081 } 6082 } 6083 6084 // Filter out the caller activity if so requested. 6085 if (caller != null) { 6086 N = results.size(); 6087 for (int i=0; i<N; i++) { 6088 ActivityInfo ainfo = results.get(i).activityInfo; 6089 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6090 && caller.getClassName().equals(ainfo.name)) { 6091 results.remove(i); 6092 break; 6093 } 6094 } 6095 } 6096 6097 // If the caller didn't request filter information, 6098 // drop them now so we don't have to 6099 // marshall/unmarshall it. 6100 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6101 N = results.size(); 6102 for (int i=0; i<N; i++) { 6103 results.get(i).filter = null; 6104 } 6105 } 6106 6107 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6108 return results; 6109 } 6110 6111 @Override 6112 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6113 String resolvedType, int flags, int userId) { 6114 return new ParceledListSlice<>( 6115 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6116 } 6117 6118 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6119 String resolvedType, int flags, int userId) { 6120 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6121 flags = updateFlagsForResolve(flags, userId, intent); 6122 ComponentName comp = intent.getComponent(); 6123 if (comp == null) { 6124 if (intent.getSelector() != null) { 6125 intent = intent.getSelector(); 6126 comp = intent.getComponent(); 6127 } 6128 } 6129 if (comp != null) { 6130 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6131 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6132 if (ai != null) { 6133 ResolveInfo ri = new ResolveInfo(); 6134 ri.activityInfo = ai; 6135 list.add(ri); 6136 } 6137 return list; 6138 } 6139 6140 // reader 6141 synchronized (mPackages) { 6142 String pkgName = intent.getPackage(); 6143 if (pkgName == null) { 6144 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6145 } 6146 final PackageParser.Package pkg = mPackages.get(pkgName); 6147 if (pkg != null) { 6148 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6149 userId); 6150 } 6151 return Collections.emptyList(); 6152 } 6153 } 6154 6155 @Override 6156 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6157 if (!sUserManager.exists(userId)) return null; 6158 flags = updateFlagsForResolve(flags, userId, intent); 6159 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6160 if (query != null) { 6161 if (query.size() >= 1) { 6162 // If there is more than one service with the same priority, 6163 // just arbitrarily pick the first one. 6164 return query.get(0); 6165 } 6166 } 6167 return null; 6168 } 6169 6170 @Override 6171 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6172 String resolvedType, int flags, int userId) { 6173 return new ParceledListSlice<>( 6174 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6175 } 6176 6177 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6178 String resolvedType, int flags, int userId) { 6179 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6180 flags = updateFlagsForResolve(flags, userId, intent); 6181 ComponentName comp = intent.getComponent(); 6182 if (comp == null) { 6183 if (intent.getSelector() != null) { 6184 intent = intent.getSelector(); 6185 comp = intent.getComponent(); 6186 } 6187 } 6188 if (comp != null) { 6189 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6190 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6191 if (si != null) { 6192 final ResolveInfo ri = new ResolveInfo(); 6193 ri.serviceInfo = si; 6194 list.add(ri); 6195 } 6196 return list; 6197 } 6198 6199 // reader 6200 synchronized (mPackages) { 6201 String pkgName = intent.getPackage(); 6202 if (pkgName == null) { 6203 return mServices.queryIntent(intent, resolvedType, flags, userId); 6204 } 6205 final PackageParser.Package pkg = mPackages.get(pkgName); 6206 if (pkg != null) { 6207 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6208 userId); 6209 } 6210 return Collections.emptyList(); 6211 } 6212 } 6213 6214 @Override 6215 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6216 String resolvedType, int flags, int userId) { 6217 return new ParceledListSlice<>( 6218 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6219 } 6220 6221 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6222 Intent intent, String resolvedType, int flags, int userId) { 6223 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6224 flags = updateFlagsForResolve(flags, userId, intent); 6225 ComponentName comp = intent.getComponent(); 6226 if (comp == null) { 6227 if (intent.getSelector() != null) { 6228 intent = intent.getSelector(); 6229 comp = intent.getComponent(); 6230 } 6231 } 6232 if (comp != null) { 6233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6234 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6235 if (pi != null) { 6236 final ResolveInfo ri = new ResolveInfo(); 6237 ri.providerInfo = pi; 6238 list.add(ri); 6239 } 6240 return list; 6241 } 6242 6243 // reader 6244 synchronized (mPackages) { 6245 String pkgName = intent.getPackage(); 6246 if (pkgName == null) { 6247 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6248 } 6249 final PackageParser.Package pkg = mPackages.get(pkgName); 6250 if (pkg != null) { 6251 return mProviders.queryIntentForPackage( 6252 intent, resolvedType, flags, pkg.providers, userId); 6253 } 6254 return Collections.emptyList(); 6255 } 6256 } 6257 6258 @Override 6259 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6260 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6261 flags = updateFlagsForPackage(flags, userId, null); 6262 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6264 true /* requireFullPermission */, false /* checkShell */, 6265 "get installed packages"); 6266 6267 // writer 6268 synchronized (mPackages) { 6269 ArrayList<PackageInfo> list; 6270 if (listUninstalled) { 6271 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6272 for (PackageSetting ps : mSettings.mPackages.values()) { 6273 final PackageInfo pi; 6274 if (ps.pkg != null) { 6275 pi = generatePackageInfo(ps, flags, userId); 6276 } else { 6277 pi = generatePackageInfo(ps, flags, userId); 6278 } 6279 if (pi != null) { 6280 list.add(pi); 6281 } 6282 } 6283 } else { 6284 list = new ArrayList<PackageInfo>(mPackages.size()); 6285 for (PackageParser.Package p : mPackages.values()) { 6286 final PackageInfo pi = 6287 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6288 if (pi != null) { 6289 list.add(pi); 6290 } 6291 } 6292 } 6293 6294 return new ParceledListSlice<PackageInfo>(list); 6295 } 6296 } 6297 6298 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6299 String[] permissions, boolean[] tmp, int flags, int userId) { 6300 int numMatch = 0; 6301 final PermissionsState permissionsState = ps.getPermissionsState(); 6302 for (int i=0; i<permissions.length; i++) { 6303 final String permission = permissions[i]; 6304 if (permissionsState.hasPermission(permission, userId)) { 6305 tmp[i] = true; 6306 numMatch++; 6307 } else { 6308 tmp[i] = false; 6309 } 6310 } 6311 if (numMatch == 0) { 6312 return; 6313 } 6314 final PackageInfo pi; 6315 if (ps.pkg != null) { 6316 pi = generatePackageInfo(ps, flags, userId); 6317 } else { 6318 pi = generatePackageInfo(ps, flags, userId); 6319 } 6320 // The above might return null in cases of uninstalled apps or install-state 6321 // skew across users/profiles. 6322 if (pi != null) { 6323 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6324 if (numMatch == permissions.length) { 6325 pi.requestedPermissions = permissions; 6326 } else { 6327 pi.requestedPermissions = new String[numMatch]; 6328 numMatch = 0; 6329 for (int i=0; i<permissions.length; i++) { 6330 if (tmp[i]) { 6331 pi.requestedPermissions[numMatch] = permissions[i]; 6332 numMatch++; 6333 } 6334 } 6335 } 6336 } 6337 list.add(pi); 6338 } 6339 } 6340 6341 @Override 6342 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6343 String[] permissions, int flags, int userId) { 6344 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6345 flags = updateFlagsForPackage(flags, userId, permissions); 6346 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6347 6348 // writer 6349 synchronized (mPackages) { 6350 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6351 boolean[] tmpBools = new boolean[permissions.length]; 6352 if (listUninstalled) { 6353 for (PackageSetting ps : mSettings.mPackages.values()) { 6354 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6355 } 6356 } else { 6357 for (PackageParser.Package pkg : mPackages.values()) { 6358 PackageSetting ps = (PackageSetting)pkg.mExtras; 6359 if (ps != null) { 6360 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6361 userId); 6362 } 6363 } 6364 } 6365 6366 return new ParceledListSlice<PackageInfo>(list); 6367 } 6368 } 6369 6370 @Override 6371 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6372 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6373 flags = updateFlagsForApplication(flags, userId, null); 6374 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6375 6376 // writer 6377 synchronized (mPackages) { 6378 ArrayList<ApplicationInfo> list; 6379 if (listUninstalled) { 6380 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6381 for (PackageSetting ps : mSettings.mPackages.values()) { 6382 ApplicationInfo ai; 6383 if (ps.pkg != null) { 6384 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6385 ps.readUserState(userId), userId); 6386 } else { 6387 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6388 } 6389 if (ai != null) { 6390 list.add(ai); 6391 } 6392 } 6393 } else { 6394 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6395 for (PackageParser.Package p : mPackages.values()) { 6396 if (p.mExtras != null) { 6397 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6398 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6399 if (ai != null) { 6400 list.add(ai); 6401 } 6402 } 6403 } 6404 } 6405 6406 return new ParceledListSlice<ApplicationInfo>(list); 6407 } 6408 } 6409 6410 @Override 6411 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6412 if (DISABLE_EPHEMERAL_APPS) { 6413 return null; 6414 } 6415 6416 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6417 "getEphemeralApplications"); 6418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6419 true /* requireFullPermission */, false /* checkShell */, 6420 "getEphemeralApplications"); 6421 synchronized (mPackages) { 6422 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6423 .getEphemeralApplicationsLPw(userId); 6424 if (ephemeralApps != null) { 6425 return new ParceledListSlice<>(ephemeralApps); 6426 } 6427 } 6428 return null; 6429 } 6430 6431 @Override 6432 public boolean isEphemeralApplication(String packageName, int userId) { 6433 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6434 true /* requireFullPermission */, false /* checkShell */, 6435 "isEphemeral"); 6436 if (DISABLE_EPHEMERAL_APPS) { 6437 return false; 6438 } 6439 6440 if (!isCallerSameApp(packageName)) { 6441 return false; 6442 } 6443 synchronized (mPackages) { 6444 PackageParser.Package pkg = mPackages.get(packageName); 6445 if (pkg != null) { 6446 return pkg.applicationInfo.isEphemeralApp(); 6447 } 6448 } 6449 return false; 6450 } 6451 6452 @Override 6453 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6454 if (DISABLE_EPHEMERAL_APPS) { 6455 return null; 6456 } 6457 6458 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6459 true /* requireFullPermission */, false /* checkShell */, 6460 "getCookie"); 6461 if (!isCallerSameApp(packageName)) { 6462 return null; 6463 } 6464 synchronized (mPackages) { 6465 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6466 packageName, userId); 6467 } 6468 } 6469 6470 @Override 6471 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6472 if (DISABLE_EPHEMERAL_APPS) { 6473 return true; 6474 } 6475 6476 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6477 true /* requireFullPermission */, true /* checkShell */, 6478 "setCookie"); 6479 if (!isCallerSameApp(packageName)) { 6480 return false; 6481 } 6482 synchronized (mPackages) { 6483 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6484 packageName, cookie, userId); 6485 } 6486 } 6487 6488 @Override 6489 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6490 if (DISABLE_EPHEMERAL_APPS) { 6491 return null; 6492 } 6493 6494 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6495 "getEphemeralApplicationIcon"); 6496 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6497 true /* requireFullPermission */, false /* checkShell */, 6498 "getEphemeralApplicationIcon"); 6499 synchronized (mPackages) { 6500 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6501 packageName, userId); 6502 } 6503 } 6504 6505 private boolean isCallerSameApp(String packageName) { 6506 PackageParser.Package pkg = mPackages.get(packageName); 6507 return pkg != null 6508 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6509 } 6510 6511 @Override 6512 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6513 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6514 } 6515 6516 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6517 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6518 6519 // reader 6520 synchronized (mPackages) { 6521 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6522 final int userId = UserHandle.getCallingUserId(); 6523 while (i.hasNext()) { 6524 final PackageParser.Package p = i.next(); 6525 if (p.applicationInfo == null) continue; 6526 6527 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6528 && !p.applicationInfo.isDirectBootAware(); 6529 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6530 && p.applicationInfo.isDirectBootAware(); 6531 6532 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6533 && (!mSafeMode || isSystemApp(p)) 6534 && (matchesUnaware || matchesAware)) { 6535 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6536 if (ps != null) { 6537 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6538 ps.readUserState(userId), userId); 6539 if (ai != null) { 6540 finalList.add(ai); 6541 } 6542 } 6543 } 6544 } 6545 } 6546 6547 return finalList; 6548 } 6549 6550 @Override 6551 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6552 if (!sUserManager.exists(userId)) return null; 6553 flags = updateFlagsForComponent(flags, userId, name); 6554 // reader 6555 synchronized (mPackages) { 6556 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6557 PackageSetting ps = provider != null 6558 ? mSettings.mPackages.get(provider.owner.packageName) 6559 : null; 6560 return ps != null 6561 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6562 ? PackageParser.generateProviderInfo(provider, flags, 6563 ps.readUserState(userId), userId) 6564 : null; 6565 } 6566 } 6567 6568 /** 6569 * @deprecated 6570 */ 6571 @Deprecated 6572 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6573 // reader 6574 synchronized (mPackages) { 6575 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6576 .entrySet().iterator(); 6577 final int userId = UserHandle.getCallingUserId(); 6578 while (i.hasNext()) { 6579 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6580 PackageParser.Provider p = entry.getValue(); 6581 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6582 6583 if (ps != null && p.syncable 6584 && (!mSafeMode || (p.info.applicationInfo.flags 6585 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6586 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6587 ps.readUserState(userId), userId); 6588 if (info != null) { 6589 outNames.add(entry.getKey()); 6590 outInfo.add(info); 6591 } 6592 } 6593 } 6594 } 6595 } 6596 6597 @Override 6598 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6599 int uid, int flags) { 6600 final int userId = processName != null ? UserHandle.getUserId(uid) 6601 : UserHandle.getCallingUserId(); 6602 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6603 flags = updateFlagsForComponent(flags, userId, processName); 6604 6605 ArrayList<ProviderInfo> finalList = null; 6606 // reader 6607 synchronized (mPackages) { 6608 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6609 while (i.hasNext()) { 6610 final PackageParser.Provider p = i.next(); 6611 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6612 if (ps != null && p.info.authority != null 6613 && (processName == null 6614 || (p.info.processName.equals(processName) 6615 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6616 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6617 if (finalList == null) { 6618 finalList = new ArrayList<ProviderInfo>(3); 6619 } 6620 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6621 ps.readUserState(userId), userId); 6622 if (info != null) { 6623 finalList.add(info); 6624 } 6625 } 6626 } 6627 } 6628 6629 if (finalList != null) { 6630 Collections.sort(finalList, mProviderInitOrderSorter); 6631 return new ParceledListSlice<ProviderInfo>(finalList); 6632 } 6633 6634 return ParceledListSlice.emptyList(); 6635 } 6636 6637 @Override 6638 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6639 // reader 6640 synchronized (mPackages) { 6641 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6642 return PackageParser.generateInstrumentationInfo(i, flags); 6643 } 6644 } 6645 6646 @Override 6647 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6648 String targetPackage, int flags) { 6649 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6650 } 6651 6652 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6653 int flags) { 6654 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6655 6656 // reader 6657 synchronized (mPackages) { 6658 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6659 while (i.hasNext()) { 6660 final PackageParser.Instrumentation p = i.next(); 6661 if (targetPackage == null 6662 || targetPackage.equals(p.info.targetPackage)) { 6663 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6664 flags); 6665 if (ii != null) { 6666 finalList.add(ii); 6667 } 6668 } 6669 } 6670 } 6671 6672 return finalList; 6673 } 6674 6675 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6676 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6677 if (overlays == null) { 6678 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6679 return; 6680 } 6681 for (PackageParser.Package opkg : overlays.values()) { 6682 // Not much to do if idmap fails: we already logged the error 6683 // and we certainly don't want to abort installation of pkg simply 6684 // because an overlay didn't fit properly. For these reasons, 6685 // ignore the return value of createIdmapForPackagePairLI. 6686 createIdmapForPackagePairLI(pkg, opkg); 6687 } 6688 } 6689 6690 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6691 PackageParser.Package opkg) { 6692 if (!opkg.mTrustedOverlay) { 6693 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6694 opkg.baseCodePath + ": overlay not trusted"); 6695 return false; 6696 } 6697 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6698 if (overlaySet == null) { 6699 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6700 opkg.baseCodePath + " but target package has no known overlays"); 6701 return false; 6702 } 6703 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6704 // TODO: generate idmap for split APKs 6705 try { 6706 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6707 } catch (InstallerException e) { 6708 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6709 + opkg.baseCodePath); 6710 return false; 6711 } 6712 PackageParser.Package[] overlayArray = 6713 overlaySet.values().toArray(new PackageParser.Package[0]); 6714 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6715 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6716 return p1.mOverlayPriority - p2.mOverlayPriority; 6717 } 6718 }; 6719 Arrays.sort(overlayArray, cmp); 6720 6721 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6722 int i = 0; 6723 for (PackageParser.Package p : overlayArray) { 6724 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6725 } 6726 return true; 6727 } 6728 6729 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6730 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6731 try { 6732 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6733 } finally { 6734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6735 } 6736 } 6737 6738 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6739 final File[] files = dir.listFiles(); 6740 if (ArrayUtils.isEmpty(files)) { 6741 Log.d(TAG, "No files in app dir " + dir); 6742 return; 6743 } 6744 6745 if (DEBUG_PACKAGE_SCANNING) { 6746 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6747 + " flags=0x" + Integer.toHexString(parseFlags)); 6748 } 6749 6750 for (File file : files) { 6751 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6752 && !PackageInstallerService.isStageName(file.getName()); 6753 if (!isPackage) { 6754 // Ignore entries which are not packages 6755 continue; 6756 } 6757 try { 6758 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6759 scanFlags, currentTime, null); 6760 } catch (PackageManagerException e) { 6761 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6762 6763 // Delete invalid userdata apps 6764 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6765 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6766 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6767 removeCodePathLI(file); 6768 } 6769 } 6770 } 6771 } 6772 6773 private static File getSettingsProblemFile() { 6774 File dataDir = Environment.getDataDirectory(); 6775 File systemDir = new File(dataDir, "system"); 6776 File fname = new File(systemDir, "uiderrors.txt"); 6777 return fname; 6778 } 6779 6780 static void reportSettingsProblem(int priority, String msg) { 6781 logCriticalInfo(priority, msg); 6782 } 6783 6784 static void logCriticalInfo(int priority, String msg) { 6785 Slog.println(priority, TAG, msg); 6786 EventLogTags.writePmCriticalInfo(msg); 6787 try { 6788 File fname = getSettingsProblemFile(); 6789 FileOutputStream out = new FileOutputStream(fname, true); 6790 PrintWriter pw = new FastPrintWriter(out); 6791 SimpleDateFormat formatter = new SimpleDateFormat(); 6792 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6793 pw.println(dateString + ": " + msg); 6794 pw.close(); 6795 FileUtils.setPermissions( 6796 fname.toString(), 6797 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6798 -1, -1); 6799 } catch (java.io.IOException e) { 6800 } 6801 } 6802 6803 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6804 if (srcFile.isDirectory()) { 6805 final File baseFile = new File(pkg.baseCodePath); 6806 long maxModifiedTime = baseFile.lastModified(); 6807 if (pkg.splitCodePaths != null) { 6808 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6809 final File splitFile = new File(pkg.splitCodePaths[i]); 6810 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6811 } 6812 } 6813 return maxModifiedTime; 6814 } 6815 return srcFile.lastModified(); 6816 } 6817 6818 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6819 final int policyFlags) throws PackageManagerException { 6820 if (ps != null 6821 && ps.codePath.equals(srcFile) 6822 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6823 && !isCompatSignatureUpdateNeeded(pkg) 6824 && !isRecoverSignatureUpdateNeeded(pkg)) { 6825 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6826 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6827 ArraySet<PublicKey> signingKs; 6828 synchronized (mPackages) { 6829 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6830 } 6831 if (ps.signatures.mSignatures != null 6832 && ps.signatures.mSignatures.length != 0 6833 && signingKs != null) { 6834 // Optimization: reuse the existing cached certificates 6835 // if the package appears to be unchanged. 6836 pkg.mSignatures = ps.signatures.mSignatures; 6837 pkg.mSigningKeys = signingKs; 6838 return; 6839 } 6840 6841 Slog.w(TAG, "PackageSetting for " + ps.name 6842 + " is missing signatures. Collecting certs again to recover them."); 6843 } else { 6844 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6845 } 6846 6847 try { 6848 PackageParser.collectCertificates(pkg, policyFlags); 6849 } catch (PackageParserException e) { 6850 throw PackageManagerException.from(e); 6851 } 6852 } 6853 6854 /** 6855 * Traces a package scan. 6856 * @see #scanPackageLI(File, int, int, long, UserHandle) 6857 */ 6858 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6859 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6860 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6861 try { 6862 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6863 } finally { 6864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6865 } 6866 } 6867 6868 /** 6869 * Scans a package and returns the newly parsed package. 6870 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6871 */ 6872 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6873 long currentTime, UserHandle user) throws PackageManagerException { 6874 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6875 PackageParser pp = new PackageParser(); 6876 pp.setSeparateProcesses(mSeparateProcesses); 6877 pp.setOnlyCoreApps(mOnlyCore); 6878 pp.setDisplayMetrics(mMetrics); 6879 6880 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6881 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6882 } 6883 6884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6885 final PackageParser.Package pkg; 6886 try { 6887 pkg = pp.parsePackage(scanFile, parseFlags); 6888 } catch (PackageParserException e) { 6889 throw PackageManagerException.from(e); 6890 } finally { 6891 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6892 } 6893 6894 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6895 } 6896 6897 /** 6898 * Scans a package and returns the newly parsed package. 6899 * @throws PackageManagerException on a parse error. 6900 */ 6901 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6902 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6903 throws PackageManagerException { 6904 // If the package has children and this is the first dive in the function 6905 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6906 // packages (parent and children) would be successfully scanned before the 6907 // actual scan since scanning mutates internal state and we want to atomically 6908 // install the package and its children. 6909 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6910 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6911 scanFlags |= SCAN_CHECK_ONLY; 6912 } 6913 } else { 6914 scanFlags &= ~SCAN_CHECK_ONLY; 6915 } 6916 6917 // Scan the parent 6918 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6919 scanFlags, currentTime, user); 6920 6921 // Scan the children 6922 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6923 for (int i = 0; i < childCount; i++) { 6924 PackageParser.Package childPackage = pkg.childPackages.get(i); 6925 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6926 currentTime, user); 6927 } 6928 6929 6930 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6931 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6932 } 6933 6934 return scannedPkg; 6935 } 6936 6937 /** 6938 * Scans a package and returns the newly parsed package. 6939 * @throws PackageManagerException on a parse error. 6940 */ 6941 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6942 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6943 throws PackageManagerException { 6944 PackageSetting ps = null; 6945 PackageSetting updatedPkg; 6946 // reader 6947 synchronized (mPackages) { 6948 // Look to see if we already know about this package. 6949 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6950 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6951 // This package has been renamed to its original name. Let's 6952 // use that. 6953 ps = mSettings.peekPackageLPr(oldName); 6954 } 6955 // If there was no original package, see one for the real package name. 6956 if (ps == null) { 6957 ps = mSettings.peekPackageLPr(pkg.packageName); 6958 } 6959 // Check to see if this package could be hiding/updating a system 6960 // package. Must look for it either under the original or real 6961 // package name depending on our state. 6962 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6963 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6964 6965 // If this is a package we don't know about on the system partition, we 6966 // may need to remove disabled child packages on the system partition 6967 // or may need to not add child packages if the parent apk is updated 6968 // on the data partition and no longer defines this child package. 6969 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6970 // If this is a parent package for an updated system app and this system 6971 // app got an OTA update which no longer defines some of the child packages 6972 // we have to prune them from the disabled system packages. 6973 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6974 if (disabledPs != null) { 6975 final int scannedChildCount = (pkg.childPackages != null) 6976 ? pkg.childPackages.size() : 0; 6977 final int disabledChildCount = disabledPs.childPackageNames != null 6978 ? disabledPs.childPackageNames.size() : 0; 6979 for (int i = 0; i < disabledChildCount; i++) { 6980 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6981 boolean disabledPackageAvailable = false; 6982 for (int j = 0; j < scannedChildCount; j++) { 6983 PackageParser.Package childPkg = pkg.childPackages.get(j); 6984 if (childPkg.packageName.equals(disabledChildPackageName)) { 6985 disabledPackageAvailable = true; 6986 break; 6987 } 6988 } 6989 if (!disabledPackageAvailable) { 6990 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6991 } 6992 } 6993 } 6994 } 6995 } 6996 6997 boolean updatedPkgBetter = false; 6998 // First check if this is a system package that may involve an update 6999 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7000 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7001 // it needs to drop FLAG_PRIVILEGED. 7002 if (locationIsPrivileged(scanFile)) { 7003 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7004 } else { 7005 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7006 } 7007 7008 if (ps != null && !ps.codePath.equals(scanFile)) { 7009 // The path has changed from what was last scanned... check the 7010 // version of the new path against what we have stored to determine 7011 // what to do. 7012 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7013 if (pkg.mVersionCode <= ps.versionCode) { 7014 // The system package has been updated and the code path does not match 7015 // Ignore entry. Skip it. 7016 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7017 + " ignored: updated version " + ps.versionCode 7018 + " better than this " + pkg.mVersionCode); 7019 if (!updatedPkg.codePath.equals(scanFile)) { 7020 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7021 + ps.name + " changing from " + updatedPkg.codePathString 7022 + " to " + scanFile); 7023 updatedPkg.codePath = scanFile; 7024 updatedPkg.codePathString = scanFile.toString(); 7025 updatedPkg.resourcePath = scanFile; 7026 updatedPkg.resourcePathString = scanFile.toString(); 7027 } 7028 updatedPkg.pkg = pkg; 7029 updatedPkg.versionCode = pkg.mVersionCode; 7030 7031 // Update the disabled system child packages to point to the package too. 7032 final int childCount = updatedPkg.childPackageNames != null 7033 ? updatedPkg.childPackageNames.size() : 0; 7034 for (int i = 0; i < childCount; i++) { 7035 String childPackageName = updatedPkg.childPackageNames.get(i); 7036 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7037 childPackageName); 7038 if (updatedChildPkg != null) { 7039 updatedChildPkg.pkg = pkg; 7040 updatedChildPkg.versionCode = pkg.mVersionCode; 7041 } 7042 } 7043 7044 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7045 + scanFile + " ignored: updated version " + ps.versionCode 7046 + " better than this " + pkg.mVersionCode); 7047 } else { 7048 // The current app on the system partition is better than 7049 // what we have updated to on the data partition; switch 7050 // back to the system partition version. 7051 // At this point, its safely assumed that package installation for 7052 // apps in system partition will go through. If not there won't be a working 7053 // version of the app 7054 // writer 7055 synchronized (mPackages) { 7056 // Just remove the loaded entries from package lists. 7057 mPackages.remove(ps.name); 7058 } 7059 7060 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7061 + " reverting from " + ps.codePathString 7062 + ": new version " + pkg.mVersionCode 7063 + " better than installed " + ps.versionCode); 7064 7065 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7066 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7067 synchronized (mInstallLock) { 7068 args.cleanUpResourcesLI(); 7069 } 7070 synchronized (mPackages) { 7071 mSettings.enableSystemPackageLPw(ps.name); 7072 } 7073 updatedPkgBetter = true; 7074 } 7075 } 7076 } 7077 7078 if (updatedPkg != null) { 7079 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7080 // initially 7081 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7082 7083 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7084 // flag set initially 7085 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7086 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7087 } 7088 } 7089 7090 // Verify certificates against what was last scanned 7091 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7092 7093 /* 7094 * A new system app appeared, but we already had a non-system one of the 7095 * same name installed earlier. 7096 */ 7097 boolean shouldHideSystemApp = false; 7098 if (updatedPkg == null && ps != null 7099 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7100 /* 7101 * Check to make sure the signatures match first. If they don't, 7102 * wipe the installed application and its data. 7103 */ 7104 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7105 != PackageManager.SIGNATURE_MATCH) { 7106 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7107 + " signatures don't match existing userdata copy; removing"); 7108 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7109 "scanPackageInternalLI")) { 7110 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7111 } 7112 ps = null; 7113 } else { 7114 /* 7115 * If the newly-added system app is an older version than the 7116 * already installed version, hide it. It will be scanned later 7117 * and re-added like an update. 7118 */ 7119 if (pkg.mVersionCode <= ps.versionCode) { 7120 shouldHideSystemApp = true; 7121 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7122 + " but new version " + pkg.mVersionCode + " better than installed " 7123 + ps.versionCode + "; hiding system"); 7124 } else { 7125 /* 7126 * The newly found system app is a newer version that the 7127 * one previously installed. Simply remove the 7128 * already-installed application and replace it with our own 7129 * while keeping the application data. 7130 */ 7131 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7132 + " reverting from " + ps.codePathString + ": new version " 7133 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7134 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7135 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7136 synchronized (mInstallLock) { 7137 args.cleanUpResourcesLI(); 7138 } 7139 } 7140 } 7141 } 7142 7143 // The apk is forward locked (not public) if its code and resources 7144 // are kept in different files. (except for app in either system or 7145 // vendor path). 7146 // TODO grab this value from PackageSettings 7147 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7148 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7149 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7150 } 7151 } 7152 7153 // TODO: extend to support forward-locked splits 7154 String resourcePath = null; 7155 String baseResourcePath = null; 7156 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7157 if (ps != null && ps.resourcePathString != null) { 7158 resourcePath = ps.resourcePathString; 7159 baseResourcePath = ps.resourcePathString; 7160 } else { 7161 // Should not happen at all. Just log an error. 7162 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7163 } 7164 } else { 7165 resourcePath = pkg.codePath; 7166 baseResourcePath = pkg.baseCodePath; 7167 } 7168 7169 // Set application objects path explicitly. 7170 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7171 pkg.setApplicationInfoCodePath(pkg.codePath); 7172 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7173 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7174 pkg.setApplicationInfoResourcePath(resourcePath); 7175 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7176 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7177 7178 // Note that we invoke the following method only if we are about to unpack an application 7179 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7180 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7181 7182 /* 7183 * If the system app should be overridden by a previously installed 7184 * data, hide the system app now and let the /data/app scan pick it up 7185 * again. 7186 */ 7187 if (shouldHideSystemApp) { 7188 synchronized (mPackages) { 7189 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7190 } 7191 } 7192 7193 return scannedPkg; 7194 } 7195 7196 private static String fixProcessName(String defProcessName, 7197 String processName, int uid) { 7198 if (processName == null) { 7199 return defProcessName; 7200 } 7201 return processName; 7202 } 7203 7204 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7205 throws PackageManagerException { 7206 if (pkgSetting.signatures.mSignatures != null) { 7207 // Already existing package. Make sure signatures match 7208 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7209 == PackageManager.SIGNATURE_MATCH; 7210 if (!match) { 7211 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7212 == PackageManager.SIGNATURE_MATCH; 7213 } 7214 if (!match) { 7215 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7216 == PackageManager.SIGNATURE_MATCH; 7217 } 7218 if (!match) { 7219 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7220 + pkg.packageName + " signatures do not match the " 7221 + "previously installed version; ignoring!"); 7222 } 7223 } 7224 7225 // Check for shared user signatures 7226 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7227 // Already existing package. Make sure signatures match 7228 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7229 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7230 if (!match) { 7231 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7232 == PackageManager.SIGNATURE_MATCH; 7233 } 7234 if (!match) { 7235 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7236 == PackageManager.SIGNATURE_MATCH; 7237 } 7238 if (!match) { 7239 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7240 "Package " + pkg.packageName 7241 + " has no signatures that match those in shared user " 7242 + pkgSetting.sharedUser.name + "; ignoring!"); 7243 } 7244 } 7245 } 7246 7247 /** 7248 * Enforces that only the system UID or root's UID can call a method exposed 7249 * via Binder. 7250 * 7251 * @param message used as message if SecurityException is thrown 7252 * @throws SecurityException if the caller is not system or root 7253 */ 7254 private static final void enforceSystemOrRoot(String message) { 7255 final int uid = Binder.getCallingUid(); 7256 if (uid != Process.SYSTEM_UID && uid != 0) { 7257 throw new SecurityException(message); 7258 } 7259 } 7260 7261 @Override 7262 public void performFstrimIfNeeded() { 7263 enforceSystemOrRoot("Only the system can request fstrim"); 7264 7265 // Before everything else, see whether we need to fstrim. 7266 try { 7267 IMountService ms = PackageHelper.getMountService(); 7268 if (ms != null) { 7269 final boolean isUpgrade = isUpgrade(); 7270 boolean doTrim = isUpgrade; 7271 if (doTrim) { 7272 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7273 } else { 7274 final long interval = android.provider.Settings.Global.getLong( 7275 mContext.getContentResolver(), 7276 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7277 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7278 if (interval > 0) { 7279 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7280 if (timeSinceLast > interval) { 7281 doTrim = true; 7282 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7283 + "; running immediately"); 7284 } 7285 } 7286 } 7287 if (doTrim) { 7288 if (!isFirstBoot()) { 7289 try { 7290 ActivityManagerNative.getDefault().showBootMessage( 7291 mContext.getResources().getString( 7292 R.string.android_upgrading_fstrim), true); 7293 } catch (RemoteException e) { 7294 } 7295 } 7296 ms.runMaintenance(); 7297 } 7298 } else { 7299 Slog.e(TAG, "Mount service unavailable!"); 7300 } 7301 } catch (RemoteException e) { 7302 // Can't happen; MountService is local 7303 } 7304 } 7305 7306 @Override 7307 public void updatePackagesIfNeeded() { 7308 enforceSystemOrRoot("Only the system can request package update"); 7309 7310 // We need to re-extract after an OTA. 7311 boolean causeUpgrade = isUpgrade(); 7312 7313 // First boot or factory reset. 7314 // Note: we also handle devices that are upgrading to N right now as if it is their 7315 // first boot, as they do not have profile data. 7316 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7317 7318 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7319 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7320 7321 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7322 return; 7323 } 7324 7325 List<PackageParser.Package> pkgs; 7326 synchronized (mPackages) { 7327 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7328 } 7329 7330 final long startTime = System.nanoTime(); 7331 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7332 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7333 7334 final int elapsedTimeSeconds = 7335 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7336 7337 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7338 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7339 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7340 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7341 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7342 } 7343 7344 /** 7345 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7346 * containing statistics about the invocation. The array consists of three elements, 7347 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7348 * and {@code numberOfPackagesFailed}. 7349 */ 7350 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7351 String compilerFilter) { 7352 7353 int numberOfPackagesVisited = 0; 7354 int numberOfPackagesOptimized = 0; 7355 int numberOfPackagesSkipped = 0; 7356 int numberOfPackagesFailed = 0; 7357 final int numberOfPackagesToDexopt = pkgs.size(); 7358 7359 for (PackageParser.Package pkg : pkgs) { 7360 numberOfPackagesVisited++; 7361 7362 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7363 if (DEBUG_DEXOPT) { 7364 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7365 } 7366 numberOfPackagesSkipped++; 7367 continue; 7368 } 7369 7370 if (DEBUG_DEXOPT) { 7371 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7372 numberOfPackagesToDexopt + ": " + pkg.packageName); 7373 } 7374 7375 if (showDialog) { 7376 try { 7377 ActivityManagerNative.getDefault().showBootMessage( 7378 mContext.getResources().getString(R.string.android_upgrading_apk, 7379 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7380 } catch (RemoteException e) { 7381 } 7382 } 7383 7384 // checkProfiles is false to avoid merging profiles during boot which 7385 // might interfere with background compilation (b/28612421). 7386 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7387 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7388 // trade-off worth doing to save boot time work. 7389 int dexOptStatus = performDexOptTraced(pkg.packageName, 7390 false /* checkProfiles */, 7391 compilerFilter, 7392 false /* force */); 7393 switch (dexOptStatus) { 7394 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7395 numberOfPackagesOptimized++; 7396 break; 7397 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7398 numberOfPackagesSkipped++; 7399 break; 7400 case PackageDexOptimizer.DEX_OPT_FAILED: 7401 numberOfPackagesFailed++; 7402 break; 7403 default: 7404 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7405 break; 7406 } 7407 } 7408 7409 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7410 numberOfPackagesFailed }; 7411 } 7412 7413 @Override 7414 public void notifyPackageUse(String packageName, int reason) { 7415 synchronized (mPackages) { 7416 PackageParser.Package p = mPackages.get(packageName); 7417 if (p == null) { 7418 return; 7419 } 7420 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7421 } 7422 } 7423 7424 // TODO: this is not used nor needed. Delete it. 7425 @Override 7426 public boolean performDexOptIfNeeded(String packageName) { 7427 int dexOptStatus = performDexOptTraced(packageName, 7428 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7429 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7430 } 7431 7432 @Override 7433 public boolean performDexOpt(String packageName, 7434 boolean checkProfiles, int compileReason, boolean force) { 7435 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7436 getCompilerFilterForReason(compileReason), force); 7437 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7438 } 7439 7440 @Override 7441 public boolean performDexOptMode(String packageName, 7442 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7443 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7444 targetCompilerFilter, force); 7445 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7446 } 7447 7448 private int performDexOptTraced(String packageName, 7449 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7451 try { 7452 return performDexOptInternal(packageName, checkProfiles, 7453 targetCompilerFilter, force); 7454 } finally { 7455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7456 } 7457 } 7458 7459 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7460 // if the package can now be considered up to date for the given filter. 7461 private int performDexOptInternal(String packageName, 7462 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7463 PackageParser.Package p; 7464 synchronized (mPackages) { 7465 p = mPackages.get(packageName); 7466 if (p == null) { 7467 // Package could not be found. Report failure. 7468 return PackageDexOptimizer.DEX_OPT_FAILED; 7469 } 7470 mPackageUsage.write(false); 7471 } 7472 long callingId = Binder.clearCallingIdentity(); 7473 try { 7474 synchronized (mInstallLock) { 7475 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7476 targetCompilerFilter, force); 7477 } 7478 } finally { 7479 Binder.restoreCallingIdentity(callingId); 7480 } 7481 } 7482 7483 public ArraySet<String> getOptimizablePackages() { 7484 ArraySet<String> pkgs = new ArraySet<String>(); 7485 synchronized (mPackages) { 7486 for (PackageParser.Package p : mPackages.values()) { 7487 if (PackageDexOptimizer.canOptimizePackage(p)) { 7488 pkgs.add(p.packageName); 7489 } 7490 } 7491 } 7492 return pkgs; 7493 } 7494 7495 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7496 boolean checkProfiles, String targetCompilerFilter, 7497 boolean force) { 7498 // Select the dex optimizer based on the force parameter. 7499 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7500 // allocate an object here. 7501 PackageDexOptimizer pdo = force 7502 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7503 : mPackageDexOptimizer; 7504 7505 // Optimize all dependencies first. Note: we ignore the return value and march on 7506 // on errors. 7507 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7508 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7509 if (!deps.isEmpty()) { 7510 for (PackageParser.Package depPackage : deps) { 7511 // TODO: Analyze and investigate if we (should) profile libraries. 7512 // Currently this will do a full compilation of the library by default. 7513 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7514 false /* checkProfiles */, 7515 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7516 } 7517 } 7518 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7519 targetCompilerFilter); 7520 } 7521 7522 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7523 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7524 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7525 Set<String> collectedNames = new HashSet<>(); 7526 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7527 7528 retValue.remove(p); 7529 7530 return retValue; 7531 } else { 7532 return Collections.emptyList(); 7533 } 7534 } 7535 7536 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7537 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7538 if (!collectedNames.contains(p.packageName)) { 7539 collectedNames.add(p.packageName); 7540 collected.add(p); 7541 7542 if (p.usesLibraries != null) { 7543 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7544 } 7545 if (p.usesOptionalLibraries != null) { 7546 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7547 collectedNames); 7548 } 7549 } 7550 } 7551 7552 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7553 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7554 for (String libName : libs) { 7555 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7556 if (libPkg != null) { 7557 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7558 } 7559 } 7560 } 7561 7562 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7563 synchronized (mPackages) { 7564 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7565 if (lib != null && lib.apk != null) { 7566 return mPackages.get(lib.apk); 7567 } 7568 } 7569 return null; 7570 } 7571 7572 public void shutdown() { 7573 mPackageUsage.write(true); 7574 } 7575 7576 @Override 7577 public void dumpProfiles(String packageName) { 7578 PackageParser.Package pkg; 7579 synchronized (mPackages) { 7580 pkg = mPackages.get(packageName); 7581 if (pkg == null) { 7582 throw new IllegalArgumentException("Unknown package: " + packageName); 7583 } 7584 } 7585 /* Only the shell, root, or the app user should be able to dump profiles. */ 7586 int callingUid = Binder.getCallingUid(); 7587 if (callingUid != Process.SHELL_UID && 7588 callingUid != Process.ROOT_UID && 7589 callingUid != pkg.applicationInfo.uid) { 7590 throw new SecurityException("dumpProfiles"); 7591 } 7592 7593 synchronized (mInstallLock) { 7594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7595 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7596 try { 7597 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7598 String gid = Integer.toString(sharedGid); 7599 String codePaths = TextUtils.join(";", allCodePaths); 7600 mInstaller.dumpProfiles(gid, packageName, codePaths); 7601 } catch (InstallerException e) { 7602 Slog.w(TAG, "Failed to dump profiles", e); 7603 } 7604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7605 } 7606 } 7607 7608 @Override 7609 public void forceDexOpt(String packageName) { 7610 enforceSystemOrRoot("forceDexOpt"); 7611 7612 PackageParser.Package pkg; 7613 synchronized (mPackages) { 7614 pkg = mPackages.get(packageName); 7615 if (pkg == null) { 7616 throw new IllegalArgumentException("Unknown package: " + packageName); 7617 } 7618 } 7619 7620 synchronized (mInstallLock) { 7621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7622 7623 // Whoever is calling forceDexOpt wants a fully compiled package. 7624 // Don't use profiles since that may cause compilation to be skipped. 7625 final int res = performDexOptInternalWithDependenciesLI(pkg, 7626 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7627 true /* force */); 7628 7629 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7630 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7631 throw new IllegalStateException("Failed to dexopt: " + res); 7632 } 7633 } 7634 } 7635 7636 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7637 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7638 Slog.w(TAG, "Unable to update from " + oldPkg.name 7639 + " to " + newPkg.packageName 7640 + ": old package not in system partition"); 7641 return false; 7642 } else if (mPackages.get(oldPkg.name) != null) { 7643 Slog.w(TAG, "Unable to update from " + oldPkg.name 7644 + " to " + newPkg.packageName 7645 + ": old package still exists"); 7646 return false; 7647 } 7648 return true; 7649 } 7650 7651 void removeCodePathLI(File codePath) { 7652 if (codePath.isDirectory()) { 7653 try { 7654 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7655 } catch (InstallerException e) { 7656 Slog.w(TAG, "Failed to remove code path", e); 7657 } 7658 } else { 7659 codePath.delete(); 7660 } 7661 } 7662 7663 private int[] resolveUserIds(int userId) { 7664 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7665 } 7666 7667 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7668 if (pkg == null) { 7669 Slog.wtf(TAG, "Package was null!", new Throwable()); 7670 return; 7671 } 7672 clearAppDataLeafLIF(pkg, userId, flags); 7673 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7674 for (int i = 0; i < childCount; i++) { 7675 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7676 } 7677 } 7678 7679 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7680 final PackageSetting ps; 7681 synchronized (mPackages) { 7682 ps = mSettings.mPackages.get(pkg.packageName); 7683 } 7684 for (int realUserId : resolveUserIds(userId)) { 7685 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7686 try { 7687 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7688 ceDataInode); 7689 } catch (InstallerException e) { 7690 Slog.w(TAG, String.valueOf(e)); 7691 } 7692 } 7693 } 7694 7695 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7696 if (pkg == null) { 7697 Slog.wtf(TAG, "Package was null!", new Throwable()); 7698 return; 7699 } 7700 destroyAppDataLeafLIF(pkg, userId, flags); 7701 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7702 for (int i = 0; i < childCount; i++) { 7703 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7704 } 7705 } 7706 7707 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7708 final PackageSetting ps; 7709 synchronized (mPackages) { 7710 ps = mSettings.mPackages.get(pkg.packageName); 7711 } 7712 for (int realUserId : resolveUserIds(userId)) { 7713 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7714 try { 7715 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7716 ceDataInode); 7717 } catch (InstallerException e) { 7718 Slog.w(TAG, String.valueOf(e)); 7719 } 7720 } 7721 } 7722 7723 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7724 if (pkg == null) { 7725 Slog.wtf(TAG, "Package was null!", new Throwable()); 7726 return; 7727 } 7728 destroyAppProfilesLeafLIF(pkg); 7729 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7730 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7731 for (int i = 0; i < childCount; i++) { 7732 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7733 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7734 true /* removeBaseMarker */); 7735 } 7736 } 7737 7738 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7739 boolean removeBaseMarker) { 7740 if (pkg.isForwardLocked()) { 7741 return; 7742 } 7743 7744 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7745 try { 7746 path = PackageManagerServiceUtils.realpath(new File(path)); 7747 } catch (IOException e) { 7748 // TODO: Should we return early here ? 7749 Slog.w(TAG, "Failed to get canonical path", e); 7750 continue; 7751 } 7752 7753 final String useMarker = path.replace('/', '@'); 7754 for (int realUserId : resolveUserIds(userId)) { 7755 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7756 if (removeBaseMarker) { 7757 File foreignUseMark = new File(profileDir, useMarker); 7758 if (foreignUseMark.exists()) { 7759 if (!foreignUseMark.delete()) { 7760 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7761 + pkg.packageName); 7762 } 7763 } 7764 } 7765 7766 File[] markers = profileDir.listFiles(); 7767 if (markers != null) { 7768 final String searchString = "@" + pkg.packageName + "@"; 7769 // We also delete all markers that contain the package name we're 7770 // uninstalling. These are associated with secondary dex-files belonging 7771 // to the package. Reconstructing the path of these dex files is messy 7772 // in general. 7773 for (File marker : markers) { 7774 if (marker.getName().indexOf(searchString) > 0) { 7775 if (!marker.delete()) { 7776 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7777 + pkg.packageName); 7778 } 7779 } 7780 } 7781 } 7782 } 7783 } 7784 } 7785 7786 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7787 try { 7788 mInstaller.destroyAppProfiles(pkg.packageName); 7789 } catch (InstallerException e) { 7790 Slog.w(TAG, String.valueOf(e)); 7791 } 7792 } 7793 7794 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7795 if (pkg == null) { 7796 Slog.wtf(TAG, "Package was null!", new Throwable()); 7797 return; 7798 } 7799 clearAppProfilesLeafLIF(pkg); 7800 // We don't remove the base foreign use marker when clearing profiles because 7801 // we will rename it when the app is updated. Unlike the actual profile contents, 7802 // the foreign use marker is good across installs. 7803 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7805 for (int i = 0; i < childCount; i++) { 7806 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7807 } 7808 } 7809 7810 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7811 try { 7812 mInstaller.clearAppProfiles(pkg.packageName); 7813 } catch (InstallerException e) { 7814 Slog.w(TAG, String.valueOf(e)); 7815 } 7816 } 7817 7818 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7819 long lastUpdateTime) { 7820 // Set parent install/update time 7821 PackageSetting ps = (PackageSetting) pkg.mExtras; 7822 if (ps != null) { 7823 ps.firstInstallTime = firstInstallTime; 7824 ps.lastUpdateTime = lastUpdateTime; 7825 } 7826 // Set children install/update time 7827 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7828 for (int i = 0; i < childCount; i++) { 7829 PackageParser.Package childPkg = pkg.childPackages.get(i); 7830 ps = (PackageSetting) childPkg.mExtras; 7831 if (ps != null) { 7832 ps.firstInstallTime = firstInstallTime; 7833 ps.lastUpdateTime = lastUpdateTime; 7834 } 7835 } 7836 } 7837 7838 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7839 PackageParser.Package changingLib) { 7840 if (file.path != null) { 7841 usesLibraryFiles.add(file.path); 7842 return; 7843 } 7844 PackageParser.Package p = mPackages.get(file.apk); 7845 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7846 // If we are doing this while in the middle of updating a library apk, 7847 // then we need to make sure to use that new apk for determining the 7848 // dependencies here. (We haven't yet finished committing the new apk 7849 // to the package manager state.) 7850 if (p == null || p.packageName.equals(changingLib.packageName)) { 7851 p = changingLib; 7852 } 7853 } 7854 if (p != null) { 7855 usesLibraryFiles.addAll(p.getAllCodePaths()); 7856 } 7857 } 7858 7859 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7860 PackageParser.Package changingLib) throws PackageManagerException { 7861 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7862 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7863 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7864 for (int i=0; i<N; i++) { 7865 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7866 if (file == null) { 7867 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7868 "Package " + pkg.packageName + " requires unavailable shared library " 7869 + pkg.usesLibraries.get(i) + "; failing!"); 7870 } 7871 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7872 } 7873 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7874 for (int i=0; i<N; i++) { 7875 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7876 if (file == null) { 7877 Slog.w(TAG, "Package " + pkg.packageName 7878 + " desires unavailable shared library " 7879 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7880 } else { 7881 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7882 } 7883 } 7884 N = usesLibraryFiles.size(); 7885 if (N > 0) { 7886 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7887 } else { 7888 pkg.usesLibraryFiles = null; 7889 } 7890 } 7891 } 7892 7893 private static boolean hasString(List<String> list, List<String> which) { 7894 if (list == null) { 7895 return false; 7896 } 7897 for (int i=list.size()-1; i>=0; i--) { 7898 for (int j=which.size()-1; j>=0; j--) { 7899 if (which.get(j).equals(list.get(i))) { 7900 return true; 7901 } 7902 } 7903 } 7904 return false; 7905 } 7906 7907 private void updateAllSharedLibrariesLPw() { 7908 for (PackageParser.Package pkg : mPackages.values()) { 7909 try { 7910 updateSharedLibrariesLPw(pkg, null); 7911 } catch (PackageManagerException e) { 7912 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7913 } 7914 } 7915 } 7916 7917 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7918 PackageParser.Package changingPkg) { 7919 ArrayList<PackageParser.Package> res = null; 7920 for (PackageParser.Package pkg : mPackages.values()) { 7921 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7922 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7923 if (res == null) { 7924 res = new ArrayList<PackageParser.Package>(); 7925 } 7926 res.add(pkg); 7927 try { 7928 updateSharedLibrariesLPw(pkg, changingPkg); 7929 } catch (PackageManagerException e) { 7930 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7931 } 7932 } 7933 } 7934 return res; 7935 } 7936 7937 /** 7938 * Derive the value of the {@code cpuAbiOverride} based on the provided 7939 * value and an optional stored value from the package settings. 7940 */ 7941 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7942 String cpuAbiOverride = null; 7943 7944 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7945 cpuAbiOverride = null; 7946 } else if (abiOverride != null) { 7947 cpuAbiOverride = abiOverride; 7948 } else if (settings != null) { 7949 cpuAbiOverride = settings.cpuAbiOverrideString; 7950 } 7951 7952 return cpuAbiOverride; 7953 } 7954 7955 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7956 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7957 throws PackageManagerException { 7958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7959 // If the package has children and this is the first dive in the function 7960 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7961 // whether all packages (parent and children) would be successfully scanned 7962 // before the actual scan since scanning mutates internal state and we want 7963 // to atomically install the package and its children. 7964 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7965 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7966 scanFlags |= SCAN_CHECK_ONLY; 7967 } 7968 } else { 7969 scanFlags &= ~SCAN_CHECK_ONLY; 7970 } 7971 7972 final PackageParser.Package scannedPkg; 7973 try { 7974 // Scan the parent 7975 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7976 // Scan the children 7977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7978 for (int i = 0; i < childCount; i++) { 7979 PackageParser.Package childPkg = pkg.childPackages.get(i); 7980 scanPackageLI(childPkg, policyFlags, 7981 scanFlags, currentTime, user); 7982 } 7983 } finally { 7984 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7985 } 7986 7987 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7988 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7989 } 7990 7991 return scannedPkg; 7992 } 7993 7994 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7995 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7996 boolean success = false; 7997 try { 7998 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7999 currentTime, user); 8000 success = true; 8001 return res; 8002 } finally { 8003 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8004 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8005 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8006 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8007 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8008 } 8009 } 8010 } 8011 8012 /** 8013 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8014 */ 8015 private static boolean apkHasCode(String fileName) { 8016 StrictJarFile jarFile = null; 8017 try { 8018 jarFile = new StrictJarFile(fileName, 8019 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8020 return jarFile.findEntry("classes.dex") != null; 8021 } catch (IOException ignore) { 8022 } finally { 8023 try { 8024 jarFile.close(); 8025 } catch (IOException ignore) {} 8026 } 8027 return false; 8028 } 8029 8030 /** 8031 * Enforces code policy for the package. This ensures that if an APK has 8032 * declared hasCode="true" in its manifest that the APK actually contains 8033 * code. 8034 * 8035 * @throws PackageManagerException If bytecode could not be found when it should exist 8036 */ 8037 private static void enforceCodePolicy(PackageParser.Package pkg) 8038 throws PackageManagerException { 8039 final boolean shouldHaveCode = 8040 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8041 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8042 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8043 "Package " + pkg.baseCodePath + " code is missing"); 8044 } 8045 8046 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8047 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8048 final boolean splitShouldHaveCode = 8049 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8050 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8051 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8052 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8053 } 8054 } 8055 } 8056 } 8057 8058 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8059 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8060 throws PackageManagerException { 8061 final File scanFile = new File(pkg.codePath); 8062 if (pkg.applicationInfo.getCodePath() == null || 8063 pkg.applicationInfo.getResourcePath() == null) { 8064 // Bail out. The resource and code paths haven't been set. 8065 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8066 "Code and resource paths haven't been set correctly"); 8067 } 8068 8069 // Apply policy 8070 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8071 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8072 if (pkg.applicationInfo.isDirectBootAware()) { 8073 // we're direct boot aware; set for all components 8074 for (PackageParser.Service s : pkg.services) { 8075 s.info.encryptionAware = s.info.directBootAware = true; 8076 } 8077 for (PackageParser.Provider p : pkg.providers) { 8078 p.info.encryptionAware = p.info.directBootAware = true; 8079 } 8080 for (PackageParser.Activity a : pkg.activities) { 8081 a.info.encryptionAware = a.info.directBootAware = true; 8082 } 8083 for (PackageParser.Activity r : pkg.receivers) { 8084 r.info.encryptionAware = r.info.directBootAware = true; 8085 } 8086 } 8087 } else { 8088 // Only allow system apps to be flagged as core apps. 8089 pkg.coreApp = false; 8090 // clear flags not applicable to regular apps 8091 pkg.applicationInfo.privateFlags &= 8092 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8093 pkg.applicationInfo.privateFlags &= 8094 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8095 } 8096 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8097 8098 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8099 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8100 } 8101 8102 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8103 enforceCodePolicy(pkg); 8104 } 8105 8106 if (mCustomResolverComponentName != null && 8107 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8108 setUpCustomResolverActivity(pkg); 8109 } 8110 8111 if (pkg.packageName.equals("android")) { 8112 synchronized (mPackages) { 8113 if (mAndroidApplication != null) { 8114 Slog.w(TAG, "*************************************************"); 8115 Slog.w(TAG, "Core android package being redefined. Skipping."); 8116 Slog.w(TAG, " file=" + scanFile); 8117 Slog.w(TAG, "*************************************************"); 8118 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8119 "Core android package being redefined. Skipping."); 8120 } 8121 8122 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8123 // Set up information for our fall-back user intent resolution activity. 8124 mPlatformPackage = pkg; 8125 pkg.mVersionCode = mSdkVersion; 8126 mAndroidApplication = pkg.applicationInfo; 8127 8128 if (!mResolverReplaced) { 8129 mResolveActivity.applicationInfo = mAndroidApplication; 8130 mResolveActivity.name = ResolverActivity.class.getName(); 8131 mResolveActivity.packageName = mAndroidApplication.packageName; 8132 mResolveActivity.processName = "system:ui"; 8133 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8134 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8135 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8136 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8137 mResolveActivity.exported = true; 8138 mResolveActivity.enabled = true; 8139 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8140 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8141 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8142 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8143 | ActivityInfo.CONFIG_ORIENTATION 8144 | ActivityInfo.CONFIG_KEYBOARD 8145 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8146 mResolveInfo.activityInfo = mResolveActivity; 8147 mResolveInfo.priority = 0; 8148 mResolveInfo.preferredOrder = 0; 8149 mResolveInfo.match = 0; 8150 mResolveComponentName = new ComponentName( 8151 mAndroidApplication.packageName, mResolveActivity.name); 8152 } 8153 } 8154 } 8155 } 8156 8157 if (DEBUG_PACKAGE_SCANNING) { 8158 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8159 Log.d(TAG, "Scanning package " + pkg.packageName); 8160 } 8161 8162 synchronized (mPackages) { 8163 if (mPackages.containsKey(pkg.packageName) 8164 || mSharedLibraries.containsKey(pkg.packageName)) { 8165 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8166 "Application package " + pkg.packageName 8167 + " already installed. Skipping duplicate."); 8168 } 8169 8170 // If we're only installing presumed-existing packages, require that the 8171 // scanned APK is both already known and at the path previously established 8172 // for it. Previously unknown packages we pick up normally, but if we have an 8173 // a priori expectation about this package's install presence, enforce it. 8174 // With a singular exception for new system packages. When an OTA contains 8175 // a new system package, we allow the codepath to change from a system location 8176 // to the user-installed location. If we don't allow this change, any newer, 8177 // user-installed version of the application will be ignored. 8178 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8179 if (mExpectingBetter.containsKey(pkg.packageName)) { 8180 logCriticalInfo(Log.WARN, 8181 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8182 } else { 8183 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8184 if (known != null) { 8185 if (DEBUG_PACKAGE_SCANNING) { 8186 Log.d(TAG, "Examining " + pkg.codePath 8187 + " and requiring known paths " + known.codePathString 8188 + " & " + known.resourcePathString); 8189 } 8190 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8191 || !pkg.applicationInfo.getResourcePath().equals( 8192 known.resourcePathString)) { 8193 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8194 "Application package " + pkg.packageName 8195 + " found at " + pkg.applicationInfo.getCodePath() 8196 + " but expected at " + known.codePathString 8197 + "; ignoring."); 8198 } 8199 } 8200 } 8201 } 8202 } 8203 8204 // Initialize package source and resource directories 8205 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8206 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8207 8208 SharedUserSetting suid = null; 8209 PackageSetting pkgSetting = null; 8210 8211 if (!isSystemApp(pkg)) { 8212 // Only system apps can use these features. 8213 pkg.mOriginalPackages = null; 8214 pkg.mRealPackage = null; 8215 pkg.mAdoptPermissions = null; 8216 } 8217 8218 // Getting the package setting may have a side-effect, so if we 8219 // are only checking if scan would succeed, stash a copy of the 8220 // old setting to restore at the end. 8221 PackageSetting nonMutatedPs = null; 8222 8223 // writer 8224 synchronized (mPackages) { 8225 if (pkg.mSharedUserId != null) { 8226 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8227 if (suid == null) { 8228 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8229 "Creating application package " + pkg.packageName 8230 + " for shared user failed"); 8231 } 8232 if (DEBUG_PACKAGE_SCANNING) { 8233 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8234 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8235 + "): packages=" + suid.packages); 8236 } 8237 } 8238 8239 // Check if we are renaming from an original package name. 8240 PackageSetting origPackage = null; 8241 String realName = null; 8242 if (pkg.mOriginalPackages != null) { 8243 // This package may need to be renamed to a previously 8244 // installed name. Let's check on that... 8245 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8246 if (pkg.mOriginalPackages.contains(renamed)) { 8247 // This package had originally been installed as the 8248 // original name, and we have already taken care of 8249 // transitioning to the new one. Just update the new 8250 // one to continue using the old name. 8251 realName = pkg.mRealPackage; 8252 if (!pkg.packageName.equals(renamed)) { 8253 // Callers into this function may have already taken 8254 // care of renaming the package; only do it here if 8255 // it is not already done. 8256 pkg.setPackageName(renamed); 8257 } 8258 8259 } else { 8260 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8261 if ((origPackage = mSettings.peekPackageLPr( 8262 pkg.mOriginalPackages.get(i))) != null) { 8263 // We do have the package already installed under its 8264 // original name... should we use it? 8265 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8266 // New package is not compatible with original. 8267 origPackage = null; 8268 continue; 8269 } else if (origPackage.sharedUser != null) { 8270 // Make sure uid is compatible between packages. 8271 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8272 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8273 + " to " + pkg.packageName + ": old uid " 8274 + origPackage.sharedUser.name 8275 + " differs from " + pkg.mSharedUserId); 8276 origPackage = null; 8277 continue; 8278 } 8279 // TODO: Add case when shared user id is added [b/28144775] 8280 } else { 8281 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8282 + pkg.packageName + " to old name " + origPackage.name); 8283 } 8284 break; 8285 } 8286 } 8287 } 8288 } 8289 8290 if (mTransferedPackages.contains(pkg.packageName)) { 8291 Slog.w(TAG, "Package " + pkg.packageName 8292 + " was transferred to another, but its .apk remains"); 8293 } 8294 8295 // See comments in nonMutatedPs declaration 8296 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8297 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8298 if (foundPs != null) { 8299 nonMutatedPs = new PackageSetting(foundPs); 8300 } 8301 } 8302 8303 // Just create the setting, don't add it yet. For already existing packages 8304 // the PkgSetting exists already and doesn't have to be created. 8305 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8306 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8307 pkg.applicationInfo.primaryCpuAbi, 8308 pkg.applicationInfo.secondaryCpuAbi, 8309 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8310 user, false); 8311 if (pkgSetting == null) { 8312 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8313 "Creating application package " + pkg.packageName + " failed"); 8314 } 8315 8316 if (pkgSetting.origPackage != null) { 8317 // If we are first transitioning from an original package, 8318 // fix up the new package's name now. We need to do this after 8319 // looking up the package under its new name, so getPackageLP 8320 // can take care of fiddling things correctly. 8321 pkg.setPackageName(origPackage.name); 8322 8323 // File a report about this. 8324 String msg = "New package " + pkgSetting.realName 8325 + " renamed to replace old package " + pkgSetting.name; 8326 reportSettingsProblem(Log.WARN, msg); 8327 8328 // Make a note of it. 8329 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8330 mTransferedPackages.add(origPackage.name); 8331 } 8332 8333 // No longer need to retain this. 8334 pkgSetting.origPackage = null; 8335 } 8336 8337 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8338 // Make a note of it. 8339 mTransferedPackages.add(pkg.packageName); 8340 } 8341 8342 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8343 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8344 } 8345 8346 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8347 // Check all shared libraries and map to their actual file path. 8348 // We only do this here for apps not on a system dir, because those 8349 // are the only ones that can fail an install due to this. We 8350 // will take care of the system apps by updating all of their 8351 // library paths after the scan is done. 8352 updateSharedLibrariesLPw(pkg, null); 8353 } 8354 8355 if (mFoundPolicyFile) { 8356 SELinuxMMAC.assignSeinfoValue(pkg); 8357 } 8358 8359 pkg.applicationInfo.uid = pkgSetting.appId; 8360 pkg.mExtras = pkgSetting; 8361 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8362 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8363 // We just determined the app is signed correctly, so bring 8364 // over the latest parsed certs. 8365 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8366 } else { 8367 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8368 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8369 "Package " + pkg.packageName + " upgrade keys do not match the " 8370 + "previously installed version"); 8371 } else { 8372 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8373 String msg = "System package " + pkg.packageName 8374 + " signature changed; retaining data."; 8375 reportSettingsProblem(Log.WARN, msg); 8376 } 8377 } 8378 } else { 8379 try { 8380 verifySignaturesLP(pkgSetting, pkg); 8381 // We just determined the app is signed correctly, so bring 8382 // over the latest parsed certs. 8383 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8384 } catch (PackageManagerException e) { 8385 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8386 throw e; 8387 } 8388 // The signature has changed, but this package is in the system 8389 // image... let's recover! 8390 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8391 // However... if this package is part of a shared user, but it 8392 // doesn't match the signature of the shared user, let's fail. 8393 // What this means is that you can't change the signatures 8394 // associated with an overall shared user, which doesn't seem all 8395 // that unreasonable. 8396 if (pkgSetting.sharedUser != null) { 8397 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8398 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8399 throw new PackageManagerException( 8400 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8401 "Signature mismatch for shared user: " 8402 + pkgSetting.sharedUser); 8403 } 8404 } 8405 // File a report about this. 8406 String msg = "System package " + pkg.packageName 8407 + " signature changed; retaining data."; 8408 reportSettingsProblem(Log.WARN, msg); 8409 } 8410 } 8411 // Verify that this new package doesn't have any content providers 8412 // that conflict with existing packages. Only do this if the 8413 // package isn't already installed, since we don't want to break 8414 // things that are installed. 8415 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8416 final int N = pkg.providers.size(); 8417 int i; 8418 for (i=0; i<N; i++) { 8419 PackageParser.Provider p = pkg.providers.get(i); 8420 if (p.info.authority != null) { 8421 String names[] = p.info.authority.split(";"); 8422 for (int j = 0; j < names.length; j++) { 8423 if (mProvidersByAuthority.containsKey(names[j])) { 8424 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8425 final String otherPackageName = 8426 ((other != null && other.getComponentName() != null) ? 8427 other.getComponentName().getPackageName() : "?"); 8428 throw new PackageManagerException( 8429 INSTALL_FAILED_CONFLICTING_PROVIDER, 8430 "Can't install because provider name " + names[j] 8431 + " (in package " + pkg.applicationInfo.packageName 8432 + ") is already used by " + otherPackageName); 8433 } 8434 } 8435 } 8436 } 8437 } 8438 8439 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8440 // This package wants to adopt ownership of permissions from 8441 // another package. 8442 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8443 final String origName = pkg.mAdoptPermissions.get(i); 8444 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8445 if (orig != null) { 8446 if (verifyPackageUpdateLPr(orig, pkg)) { 8447 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8448 + pkg.packageName); 8449 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8450 } 8451 } 8452 } 8453 } 8454 } 8455 8456 final String pkgName = pkg.packageName; 8457 8458 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8459 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8460 pkg.applicationInfo.processName = fixProcessName( 8461 pkg.applicationInfo.packageName, 8462 pkg.applicationInfo.processName, 8463 pkg.applicationInfo.uid); 8464 8465 if (pkg != mPlatformPackage) { 8466 // Get all of our default paths setup 8467 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8468 } 8469 8470 final String path = scanFile.getPath(); 8471 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8472 8473 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8474 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8475 8476 // Some system apps still use directory structure for native libraries 8477 // in which case we might end up not detecting abi solely based on apk 8478 // structure. Try to detect abi based on directory structure. 8479 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8480 pkg.applicationInfo.primaryCpuAbi == null) { 8481 setBundledAppAbisAndRoots(pkg, pkgSetting); 8482 setNativeLibraryPaths(pkg); 8483 } 8484 8485 } else { 8486 if ((scanFlags & SCAN_MOVE) != 0) { 8487 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8488 // but we already have this packages package info in the PackageSetting. We just 8489 // use that and derive the native library path based on the new codepath. 8490 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8491 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8492 } 8493 8494 // Set native library paths again. For moves, the path will be updated based on the 8495 // ABIs we've determined above. For non-moves, the path will be updated based on the 8496 // ABIs we determined during compilation, but the path will depend on the final 8497 // package path (after the rename away from the stage path). 8498 setNativeLibraryPaths(pkg); 8499 } 8500 8501 // This is a special case for the "system" package, where the ABI is 8502 // dictated by the zygote configuration (and init.rc). We should keep track 8503 // of this ABI so that we can deal with "normal" applications that run under 8504 // the same UID correctly. 8505 if (mPlatformPackage == pkg) { 8506 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8507 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8508 } 8509 8510 // If there's a mismatch between the abi-override in the package setting 8511 // and the abiOverride specified for the install. Warn about this because we 8512 // would've already compiled the app without taking the package setting into 8513 // account. 8514 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8515 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8516 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8517 " for package " + pkg.packageName); 8518 } 8519 } 8520 8521 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8522 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8523 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8524 8525 // Copy the derived override back to the parsed package, so that we can 8526 // update the package settings accordingly. 8527 pkg.cpuAbiOverride = cpuAbiOverride; 8528 8529 if (DEBUG_ABI_SELECTION) { 8530 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8531 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8532 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8533 } 8534 8535 // Push the derived path down into PackageSettings so we know what to 8536 // clean up at uninstall time. 8537 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8538 8539 if (DEBUG_ABI_SELECTION) { 8540 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8541 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8542 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8543 } 8544 8545 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8546 // We don't do this here during boot because we can do it all 8547 // at once after scanning all existing packages. 8548 // 8549 // We also do this *before* we perform dexopt on this package, so that 8550 // we can avoid redundant dexopts, and also to make sure we've got the 8551 // code and package path correct. 8552 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8553 pkg, true /* boot complete */); 8554 } 8555 8556 if (mFactoryTest && pkg.requestedPermissions.contains( 8557 android.Manifest.permission.FACTORY_TEST)) { 8558 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8559 } 8560 8561 ArrayList<PackageParser.Package> clientLibPkgs = null; 8562 8563 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8564 if (nonMutatedPs != null) { 8565 synchronized (mPackages) { 8566 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8567 } 8568 } 8569 return pkg; 8570 } 8571 8572 // Only privileged apps and updated privileged apps can add child packages. 8573 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8574 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8575 throw new PackageManagerException("Only privileged apps and updated " 8576 + "privileged apps can add child packages. Ignoring package " 8577 + pkg.packageName); 8578 } 8579 final int childCount = pkg.childPackages.size(); 8580 for (int i = 0; i < childCount; i++) { 8581 PackageParser.Package childPkg = pkg.childPackages.get(i); 8582 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8583 childPkg.packageName)) { 8584 throw new PackageManagerException("Cannot override a child package of " 8585 + "another disabled system app. Ignoring package " + pkg.packageName); 8586 } 8587 } 8588 } 8589 8590 // writer 8591 synchronized (mPackages) { 8592 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8593 // Only system apps can add new shared libraries. 8594 if (pkg.libraryNames != null) { 8595 for (int i=0; i<pkg.libraryNames.size(); i++) { 8596 String name = pkg.libraryNames.get(i); 8597 boolean allowed = false; 8598 if (pkg.isUpdatedSystemApp()) { 8599 // New library entries can only be added through the 8600 // system image. This is important to get rid of a lot 8601 // of nasty edge cases: for example if we allowed a non- 8602 // system update of the app to add a library, then uninstalling 8603 // the update would make the library go away, and assumptions 8604 // we made such as through app install filtering would now 8605 // have allowed apps on the device which aren't compatible 8606 // with it. Better to just have the restriction here, be 8607 // conservative, and create many fewer cases that can negatively 8608 // impact the user experience. 8609 final PackageSetting sysPs = mSettings 8610 .getDisabledSystemPkgLPr(pkg.packageName); 8611 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8612 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8613 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8614 allowed = true; 8615 break; 8616 } 8617 } 8618 } 8619 } else { 8620 allowed = true; 8621 } 8622 if (allowed) { 8623 if (!mSharedLibraries.containsKey(name)) { 8624 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8625 } else if (!name.equals(pkg.packageName)) { 8626 Slog.w(TAG, "Package " + pkg.packageName + " library " 8627 + name + " already exists; skipping"); 8628 } 8629 } else { 8630 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8631 + name + " that is not declared on system image; skipping"); 8632 } 8633 } 8634 if ((scanFlags & SCAN_BOOTING) == 0) { 8635 // If we are not booting, we need to update any applications 8636 // that are clients of our shared library. If we are booting, 8637 // this will all be done once the scan is complete. 8638 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8639 } 8640 } 8641 } 8642 } 8643 8644 if ((scanFlags & SCAN_BOOTING) != 0) { 8645 // No apps can run during boot scan, so they don't need to be frozen 8646 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8647 // Caller asked to not kill app, so it's probably not frozen 8648 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8649 // Caller asked us to ignore frozen check for some reason; they 8650 // probably didn't know the package name 8651 } else { 8652 // We're doing major surgery on this package, so it better be frozen 8653 // right now to keep it from launching 8654 checkPackageFrozen(pkgName); 8655 } 8656 8657 // Also need to kill any apps that are dependent on the library. 8658 if (clientLibPkgs != null) { 8659 for (int i=0; i<clientLibPkgs.size(); i++) { 8660 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8661 killApplication(clientPkg.applicationInfo.packageName, 8662 clientPkg.applicationInfo.uid, "update lib"); 8663 } 8664 } 8665 8666 // Make sure we're not adding any bogus keyset info 8667 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8668 ksms.assertScannedPackageValid(pkg); 8669 8670 // writer 8671 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8672 8673 boolean createIdmapFailed = false; 8674 synchronized (mPackages) { 8675 // We don't expect installation to fail beyond this point 8676 8677 if (pkgSetting.pkg != null) { 8678 // Note that |user| might be null during the initial boot scan. If a codePath 8679 // for an app has changed during a boot scan, it's due to an app update that's 8680 // part of the system partition and marker changes must be applied to all users. 8681 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8682 (user != null) ? user : UserHandle.ALL); 8683 } 8684 8685 // Add the new setting to mSettings 8686 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8687 // Add the new setting to mPackages 8688 mPackages.put(pkg.applicationInfo.packageName, pkg); 8689 // Make sure we don't accidentally delete its data. 8690 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8691 while (iter.hasNext()) { 8692 PackageCleanItem item = iter.next(); 8693 if (pkgName.equals(item.packageName)) { 8694 iter.remove(); 8695 } 8696 } 8697 8698 // Take care of first install / last update times. 8699 if (currentTime != 0) { 8700 if (pkgSetting.firstInstallTime == 0) { 8701 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8702 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8703 pkgSetting.lastUpdateTime = currentTime; 8704 } 8705 } else if (pkgSetting.firstInstallTime == 0) { 8706 // We need *something*. Take time time stamp of the file. 8707 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8708 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8709 if (scanFileTime != pkgSetting.timeStamp) { 8710 // A package on the system image has changed; consider this 8711 // to be an update. 8712 pkgSetting.lastUpdateTime = scanFileTime; 8713 } 8714 } 8715 8716 // Add the package's KeySets to the global KeySetManagerService 8717 ksms.addScannedPackageLPw(pkg); 8718 8719 int N = pkg.providers.size(); 8720 StringBuilder r = null; 8721 int i; 8722 for (i=0; i<N; i++) { 8723 PackageParser.Provider p = pkg.providers.get(i); 8724 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8725 p.info.processName, pkg.applicationInfo.uid); 8726 mProviders.addProvider(p); 8727 p.syncable = p.info.isSyncable; 8728 if (p.info.authority != null) { 8729 String names[] = p.info.authority.split(";"); 8730 p.info.authority = null; 8731 for (int j = 0; j < names.length; j++) { 8732 if (j == 1 && p.syncable) { 8733 // We only want the first authority for a provider to possibly be 8734 // syncable, so if we already added this provider using a different 8735 // authority clear the syncable flag. We copy the provider before 8736 // changing it because the mProviders object contains a reference 8737 // to a provider that we don't want to change. 8738 // Only do this for the second authority since the resulting provider 8739 // object can be the same for all future authorities for this provider. 8740 p = new PackageParser.Provider(p); 8741 p.syncable = false; 8742 } 8743 if (!mProvidersByAuthority.containsKey(names[j])) { 8744 mProvidersByAuthority.put(names[j], p); 8745 if (p.info.authority == null) { 8746 p.info.authority = names[j]; 8747 } else { 8748 p.info.authority = p.info.authority + ";" + names[j]; 8749 } 8750 if (DEBUG_PACKAGE_SCANNING) { 8751 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8752 Log.d(TAG, "Registered content provider: " + names[j] 8753 + ", className = " + p.info.name + ", isSyncable = " 8754 + p.info.isSyncable); 8755 } 8756 } else { 8757 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8758 Slog.w(TAG, "Skipping provider name " + names[j] + 8759 " (in package " + pkg.applicationInfo.packageName + 8760 "): name already used by " 8761 + ((other != null && other.getComponentName() != null) 8762 ? other.getComponentName().getPackageName() : "?")); 8763 } 8764 } 8765 } 8766 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8767 if (r == null) { 8768 r = new StringBuilder(256); 8769 } else { 8770 r.append(' '); 8771 } 8772 r.append(p.info.name); 8773 } 8774 } 8775 if (r != null) { 8776 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8777 } 8778 8779 N = pkg.services.size(); 8780 r = null; 8781 for (i=0; i<N; i++) { 8782 PackageParser.Service s = pkg.services.get(i); 8783 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8784 s.info.processName, pkg.applicationInfo.uid); 8785 mServices.addService(s); 8786 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8787 if (r == null) { 8788 r = new StringBuilder(256); 8789 } else { 8790 r.append(' '); 8791 } 8792 r.append(s.info.name); 8793 } 8794 } 8795 if (r != null) { 8796 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8797 } 8798 8799 N = pkg.receivers.size(); 8800 r = null; 8801 for (i=0; i<N; i++) { 8802 PackageParser.Activity a = pkg.receivers.get(i); 8803 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8804 a.info.processName, pkg.applicationInfo.uid); 8805 mReceivers.addActivity(a, "receiver"); 8806 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8807 if (r == null) { 8808 r = new StringBuilder(256); 8809 } else { 8810 r.append(' '); 8811 } 8812 r.append(a.info.name); 8813 } 8814 } 8815 if (r != null) { 8816 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8817 } 8818 8819 N = pkg.activities.size(); 8820 r = null; 8821 for (i=0; i<N; i++) { 8822 PackageParser.Activity a = pkg.activities.get(i); 8823 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8824 a.info.processName, pkg.applicationInfo.uid); 8825 mActivities.addActivity(a, "activity"); 8826 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8827 if (r == null) { 8828 r = new StringBuilder(256); 8829 } else { 8830 r.append(' '); 8831 } 8832 r.append(a.info.name); 8833 } 8834 } 8835 if (r != null) { 8836 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8837 } 8838 8839 N = pkg.permissionGroups.size(); 8840 r = null; 8841 for (i=0; i<N; i++) { 8842 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8843 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8844 if (cur == null) { 8845 mPermissionGroups.put(pg.info.name, pg); 8846 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8847 if (r == null) { 8848 r = new StringBuilder(256); 8849 } else { 8850 r.append(' '); 8851 } 8852 r.append(pg.info.name); 8853 } 8854 } else { 8855 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8856 + pg.info.packageName + " ignored: original from " 8857 + cur.info.packageName); 8858 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8859 if (r == null) { 8860 r = new StringBuilder(256); 8861 } else { 8862 r.append(' '); 8863 } 8864 r.append("DUP:"); 8865 r.append(pg.info.name); 8866 } 8867 } 8868 } 8869 if (r != null) { 8870 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8871 } 8872 8873 N = pkg.permissions.size(); 8874 r = null; 8875 for (i=0; i<N; i++) { 8876 PackageParser.Permission p = pkg.permissions.get(i); 8877 8878 // Assume by default that we did not install this permission into the system. 8879 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8880 8881 // Now that permission groups have a special meaning, we ignore permission 8882 // groups for legacy apps to prevent unexpected behavior. In particular, 8883 // permissions for one app being granted to someone just becase they happen 8884 // to be in a group defined by another app (before this had no implications). 8885 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8886 p.group = mPermissionGroups.get(p.info.group); 8887 // Warn for a permission in an unknown group. 8888 if (p.info.group != null && p.group == null) { 8889 Slog.w(TAG, "Permission " + p.info.name + " from package " 8890 + p.info.packageName + " in an unknown group " + p.info.group); 8891 } 8892 } 8893 8894 ArrayMap<String, BasePermission> permissionMap = 8895 p.tree ? mSettings.mPermissionTrees 8896 : mSettings.mPermissions; 8897 BasePermission bp = permissionMap.get(p.info.name); 8898 8899 // Allow system apps to redefine non-system permissions 8900 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8901 final boolean currentOwnerIsSystem = (bp.perm != null 8902 && isSystemApp(bp.perm.owner)); 8903 if (isSystemApp(p.owner)) { 8904 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8905 // It's a built-in permission and no owner, take ownership now 8906 bp.packageSetting = pkgSetting; 8907 bp.perm = p; 8908 bp.uid = pkg.applicationInfo.uid; 8909 bp.sourcePackage = p.info.packageName; 8910 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8911 } else if (!currentOwnerIsSystem) { 8912 String msg = "New decl " + p.owner + " of permission " 8913 + p.info.name + " is system; overriding " + bp.sourcePackage; 8914 reportSettingsProblem(Log.WARN, msg); 8915 bp = null; 8916 } 8917 } 8918 } 8919 8920 if (bp == null) { 8921 bp = new BasePermission(p.info.name, p.info.packageName, 8922 BasePermission.TYPE_NORMAL); 8923 permissionMap.put(p.info.name, bp); 8924 } 8925 8926 if (bp.perm == null) { 8927 if (bp.sourcePackage == null 8928 || bp.sourcePackage.equals(p.info.packageName)) { 8929 BasePermission tree = findPermissionTreeLP(p.info.name); 8930 if (tree == null 8931 || tree.sourcePackage.equals(p.info.packageName)) { 8932 bp.packageSetting = pkgSetting; 8933 bp.perm = p; 8934 bp.uid = pkg.applicationInfo.uid; 8935 bp.sourcePackage = p.info.packageName; 8936 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8937 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8938 if (r == null) { 8939 r = new StringBuilder(256); 8940 } else { 8941 r.append(' '); 8942 } 8943 r.append(p.info.name); 8944 } 8945 } else { 8946 Slog.w(TAG, "Permission " + p.info.name + " from package " 8947 + p.info.packageName + " ignored: base tree " 8948 + tree.name + " is from package " 8949 + tree.sourcePackage); 8950 } 8951 } else { 8952 Slog.w(TAG, "Permission " + p.info.name + " from package " 8953 + p.info.packageName + " ignored: original from " 8954 + bp.sourcePackage); 8955 } 8956 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8957 if (r == null) { 8958 r = new StringBuilder(256); 8959 } else { 8960 r.append(' '); 8961 } 8962 r.append("DUP:"); 8963 r.append(p.info.name); 8964 } 8965 if (bp.perm == p) { 8966 bp.protectionLevel = p.info.protectionLevel; 8967 } 8968 } 8969 8970 if (r != null) { 8971 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8972 } 8973 8974 N = pkg.instrumentation.size(); 8975 r = null; 8976 for (i=0; i<N; i++) { 8977 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8978 a.info.packageName = pkg.applicationInfo.packageName; 8979 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8980 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8981 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8982 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8983 a.info.dataDir = pkg.applicationInfo.dataDir; 8984 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8985 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8986 8987 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8988 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8989 mInstrumentation.put(a.getComponentName(), a); 8990 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8991 if (r == null) { 8992 r = new StringBuilder(256); 8993 } else { 8994 r.append(' '); 8995 } 8996 r.append(a.info.name); 8997 } 8998 } 8999 if (r != null) { 9000 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9001 } 9002 9003 if (pkg.protectedBroadcasts != null) { 9004 N = pkg.protectedBroadcasts.size(); 9005 for (i=0; i<N; i++) { 9006 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9007 } 9008 } 9009 9010 pkgSetting.setTimeStamp(scanFileTime); 9011 9012 // Create idmap files for pairs of (packages, overlay packages). 9013 // Note: "android", ie framework-res.apk, is handled by native layers. 9014 if (pkg.mOverlayTarget != null) { 9015 // This is an overlay package. 9016 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9017 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9018 mOverlays.put(pkg.mOverlayTarget, 9019 new ArrayMap<String, PackageParser.Package>()); 9020 } 9021 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9022 map.put(pkg.packageName, pkg); 9023 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9024 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9025 createIdmapFailed = true; 9026 } 9027 } 9028 } else if (mOverlays.containsKey(pkg.packageName) && 9029 !pkg.packageName.equals("android")) { 9030 // This is a regular package, with one or more known overlay packages. 9031 createIdmapsForPackageLI(pkg); 9032 } 9033 } 9034 9035 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9036 9037 if (createIdmapFailed) { 9038 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9039 "scanPackageLI failed to createIdmap"); 9040 } 9041 return pkg; 9042 } 9043 9044 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9045 PackageParser.Package update, UserHandle user) { 9046 if (existing.applicationInfo == null || update.applicationInfo == null) { 9047 // This isn't due to an app installation. 9048 return; 9049 } 9050 9051 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9052 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9053 9054 // The codePath hasn't changed, so there's nothing for us to do. 9055 if (Objects.equals(oldCodePath, newCodePath)) { 9056 return; 9057 } 9058 9059 File canonicalNewCodePath; 9060 try { 9061 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9062 } catch (IOException e) { 9063 Slog.w(TAG, "Failed to get canonical path.", e); 9064 return; 9065 } 9066 9067 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9068 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9069 // that the last component of the path (i.e, the name) doesn't need canonicalization 9070 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9071 // but may change in the future. Hopefully this function won't exist at that point. 9072 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9073 oldCodePath.getName()); 9074 9075 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9076 // with "@". 9077 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9078 if (!oldMarkerPrefix.endsWith("@")) { 9079 oldMarkerPrefix += "@"; 9080 } 9081 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9082 if (!newMarkerPrefix.endsWith("@")) { 9083 newMarkerPrefix += "@"; 9084 } 9085 9086 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9087 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9088 for (String updatedPath : updatedPaths) { 9089 String updatedPathName = new File(updatedPath).getName(); 9090 markerSuffixes.add(updatedPathName.replace('/', '@')); 9091 } 9092 9093 for (int userId : resolveUserIds(user.getIdentifier())) { 9094 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9095 9096 for (String markerSuffix : markerSuffixes) { 9097 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9098 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9099 if (oldForeignUseMark.exists()) { 9100 try { 9101 Os.rename(oldForeignUseMark.getAbsolutePath(), 9102 newForeignUseMark.getAbsolutePath()); 9103 } catch (ErrnoException e) { 9104 Slog.w(TAG, "Failed to rename foreign use marker", e); 9105 oldForeignUseMark.delete(); 9106 } 9107 } 9108 } 9109 } 9110 } 9111 9112 /** 9113 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9114 * is derived purely on the basis of the contents of {@code scanFile} and 9115 * {@code cpuAbiOverride}. 9116 * 9117 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9118 */ 9119 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9120 String cpuAbiOverride, boolean extractLibs) 9121 throws PackageManagerException { 9122 // TODO: We can probably be smarter about this stuff. For installed apps, 9123 // we can calculate this information at install time once and for all. For 9124 // system apps, we can probably assume that this information doesn't change 9125 // after the first boot scan. As things stand, we do lots of unnecessary work. 9126 9127 // Give ourselves some initial paths; we'll come back for another 9128 // pass once we've determined ABI below. 9129 setNativeLibraryPaths(pkg); 9130 9131 // We would never need to extract libs for forward-locked and external packages, 9132 // since the container service will do it for us. We shouldn't attempt to 9133 // extract libs from system app when it was not updated. 9134 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9135 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9136 extractLibs = false; 9137 } 9138 9139 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9140 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9141 9142 NativeLibraryHelper.Handle handle = null; 9143 try { 9144 handle = NativeLibraryHelper.Handle.create(pkg); 9145 // TODO(multiArch): This can be null for apps that didn't go through the 9146 // usual installation process. We can calculate it again, like we 9147 // do during install time. 9148 // 9149 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9150 // unnecessary. 9151 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9152 9153 // Null out the abis so that they can be recalculated. 9154 pkg.applicationInfo.primaryCpuAbi = null; 9155 pkg.applicationInfo.secondaryCpuAbi = null; 9156 if (isMultiArch(pkg.applicationInfo)) { 9157 // Warn if we've set an abiOverride for multi-lib packages.. 9158 // By definition, we need to copy both 32 and 64 bit libraries for 9159 // such packages. 9160 if (pkg.cpuAbiOverride != null 9161 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9162 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9163 } 9164 9165 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9166 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9167 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9168 if (extractLibs) { 9169 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9170 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9171 useIsaSpecificSubdirs); 9172 } else { 9173 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9174 } 9175 } 9176 9177 maybeThrowExceptionForMultiArchCopy( 9178 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9179 9180 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9181 if (extractLibs) { 9182 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9183 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9184 useIsaSpecificSubdirs); 9185 } else { 9186 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9187 } 9188 } 9189 9190 maybeThrowExceptionForMultiArchCopy( 9191 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9192 9193 if (abi64 >= 0) { 9194 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9195 } 9196 9197 if (abi32 >= 0) { 9198 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9199 if (abi64 >= 0) { 9200 if (pkg.use32bitAbi) { 9201 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9202 pkg.applicationInfo.primaryCpuAbi = abi; 9203 } else { 9204 pkg.applicationInfo.secondaryCpuAbi = abi; 9205 } 9206 } else { 9207 pkg.applicationInfo.primaryCpuAbi = abi; 9208 } 9209 } 9210 9211 } else { 9212 String[] abiList = (cpuAbiOverride != null) ? 9213 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9214 9215 // Enable gross and lame hacks for apps that are built with old 9216 // SDK tools. We must scan their APKs for renderscript bitcode and 9217 // not launch them if it's present. Don't bother checking on devices 9218 // that don't have 64 bit support. 9219 boolean needsRenderScriptOverride = false; 9220 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9221 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9222 abiList = Build.SUPPORTED_32_BIT_ABIS; 9223 needsRenderScriptOverride = true; 9224 } 9225 9226 final int copyRet; 9227 if (extractLibs) { 9228 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9229 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9230 } else { 9231 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9232 } 9233 9234 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9235 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9236 "Error unpackaging native libs for app, errorCode=" + copyRet); 9237 } 9238 9239 if (copyRet >= 0) { 9240 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9241 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9242 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9243 } else if (needsRenderScriptOverride) { 9244 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9245 } 9246 } 9247 } catch (IOException ioe) { 9248 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9249 } finally { 9250 IoUtils.closeQuietly(handle); 9251 } 9252 9253 // Now that we've calculated the ABIs and determined if it's an internal app, 9254 // we will go ahead and populate the nativeLibraryPath. 9255 setNativeLibraryPaths(pkg); 9256 } 9257 9258 /** 9259 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9260 * i.e, so that all packages can be run inside a single process if required. 9261 * 9262 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9263 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9264 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9265 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9266 * updating a package that belongs to a shared user. 9267 * 9268 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9269 * adds unnecessary complexity. 9270 */ 9271 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9272 PackageParser.Package scannedPackage, boolean bootComplete) { 9273 String requiredInstructionSet = null; 9274 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9275 requiredInstructionSet = VMRuntime.getInstructionSet( 9276 scannedPackage.applicationInfo.primaryCpuAbi); 9277 } 9278 9279 PackageSetting requirer = null; 9280 for (PackageSetting ps : packagesForUser) { 9281 // If packagesForUser contains scannedPackage, we skip it. This will happen 9282 // when scannedPackage is an update of an existing package. Without this check, 9283 // we will never be able to change the ABI of any package belonging to a shared 9284 // user, even if it's compatible with other packages. 9285 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9286 if (ps.primaryCpuAbiString == null) { 9287 continue; 9288 } 9289 9290 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9291 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9292 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9293 // this but there's not much we can do. 9294 String errorMessage = "Instruction set mismatch, " 9295 + ((requirer == null) ? "[caller]" : requirer) 9296 + " requires " + requiredInstructionSet + " whereas " + ps 9297 + " requires " + instructionSet; 9298 Slog.w(TAG, errorMessage); 9299 } 9300 9301 if (requiredInstructionSet == null) { 9302 requiredInstructionSet = instructionSet; 9303 requirer = ps; 9304 } 9305 } 9306 } 9307 9308 if (requiredInstructionSet != null) { 9309 String adjustedAbi; 9310 if (requirer != null) { 9311 // requirer != null implies that either scannedPackage was null or that scannedPackage 9312 // did not require an ABI, in which case we have to adjust scannedPackage to match 9313 // the ABI of the set (which is the same as requirer's ABI) 9314 adjustedAbi = requirer.primaryCpuAbiString; 9315 if (scannedPackage != null) { 9316 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9317 } 9318 } else { 9319 // requirer == null implies that we're updating all ABIs in the set to 9320 // match scannedPackage. 9321 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9322 } 9323 9324 for (PackageSetting ps : packagesForUser) { 9325 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9326 if (ps.primaryCpuAbiString != null) { 9327 continue; 9328 } 9329 9330 ps.primaryCpuAbiString = adjustedAbi; 9331 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9332 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9333 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9334 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9335 + " (requirer=" 9336 + (requirer == null ? "null" : requirer.pkg.packageName) 9337 + ", scannedPackage=" 9338 + (scannedPackage != null ? scannedPackage.packageName : "null") 9339 + ")"); 9340 try { 9341 mInstaller.rmdex(ps.codePathString, 9342 getDexCodeInstructionSet(getPreferredInstructionSet())); 9343 } catch (InstallerException ignored) { 9344 } 9345 } 9346 } 9347 } 9348 } 9349 } 9350 9351 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9352 synchronized (mPackages) { 9353 mResolverReplaced = true; 9354 // Set up information for custom user intent resolution activity. 9355 mResolveActivity.applicationInfo = pkg.applicationInfo; 9356 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9357 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9358 mResolveActivity.processName = pkg.applicationInfo.packageName; 9359 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9360 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9361 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9362 mResolveActivity.theme = 0; 9363 mResolveActivity.exported = true; 9364 mResolveActivity.enabled = true; 9365 mResolveInfo.activityInfo = mResolveActivity; 9366 mResolveInfo.priority = 0; 9367 mResolveInfo.preferredOrder = 0; 9368 mResolveInfo.match = 0; 9369 mResolveComponentName = mCustomResolverComponentName; 9370 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9371 mResolveComponentName); 9372 } 9373 } 9374 9375 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9376 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9377 9378 // Set up information for ephemeral installer activity 9379 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9380 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9381 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9382 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9383 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9384 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9385 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9386 mEphemeralInstallerActivity.theme = 0; 9387 mEphemeralInstallerActivity.exported = true; 9388 mEphemeralInstallerActivity.enabled = true; 9389 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9390 mEphemeralInstallerInfo.priority = 0; 9391 mEphemeralInstallerInfo.preferredOrder = 0; 9392 mEphemeralInstallerInfo.match = 0; 9393 9394 if (DEBUG_EPHEMERAL) { 9395 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9396 } 9397 } 9398 9399 private static String calculateBundledApkRoot(final String codePathString) { 9400 final File codePath = new File(codePathString); 9401 final File codeRoot; 9402 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9403 codeRoot = Environment.getRootDirectory(); 9404 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9405 codeRoot = Environment.getOemDirectory(); 9406 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9407 codeRoot = Environment.getVendorDirectory(); 9408 } else { 9409 // Unrecognized code path; take its top real segment as the apk root: 9410 // e.g. /something/app/blah.apk => /something 9411 try { 9412 File f = codePath.getCanonicalFile(); 9413 File parent = f.getParentFile(); // non-null because codePath is a file 9414 File tmp; 9415 while ((tmp = parent.getParentFile()) != null) { 9416 f = parent; 9417 parent = tmp; 9418 } 9419 codeRoot = f; 9420 Slog.w(TAG, "Unrecognized code path " 9421 + codePath + " - using " + codeRoot); 9422 } catch (IOException e) { 9423 // Can't canonicalize the code path -- shenanigans? 9424 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9425 return Environment.getRootDirectory().getPath(); 9426 } 9427 } 9428 return codeRoot.getPath(); 9429 } 9430 9431 /** 9432 * Derive and set the location of native libraries for the given package, 9433 * which varies depending on where and how the package was installed. 9434 */ 9435 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9436 final ApplicationInfo info = pkg.applicationInfo; 9437 final String codePath = pkg.codePath; 9438 final File codeFile = new File(codePath); 9439 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9440 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9441 9442 info.nativeLibraryRootDir = null; 9443 info.nativeLibraryRootRequiresIsa = false; 9444 info.nativeLibraryDir = null; 9445 info.secondaryNativeLibraryDir = null; 9446 9447 if (isApkFile(codeFile)) { 9448 // Monolithic install 9449 if (bundledApp) { 9450 // If "/system/lib64/apkname" exists, assume that is the per-package 9451 // native library directory to use; otherwise use "/system/lib/apkname". 9452 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9453 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9454 getPrimaryInstructionSet(info)); 9455 9456 // This is a bundled system app so choose the path based on the ABI. 9457 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9458 // is just the default path. 9459 final String apkName = deriveCodePathName(codePath); 9460 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9461 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9462 apkName).getAbsolutePath(); 9463 9464 if (info.secondaryCpuAbi != null) { 9465 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9466 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9467 secondaryLibDir, apkName).getAbsolutePath(); 9468 } 9469 } else if (asecApp) { 9470 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9471 .getAbsolutePath(); 9472 } else { 9473 final String apkName = deriveCodePathName(codePath); 9474 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9475 .getAbsolutePath(); 9476 } 9477 9478 info.nativeLibraryRootRequiresIsa = false; 9479 info.nativeLibraryDir = info.nativeLibraryRootDir; 9480 } else { 9481 // Cluster install 9482 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9483 info.nativeLibraryRootRequiresIsa = true; 9484 9485 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9486 getPrimaryInstructionSet(info)).getAbsolutePath(); 9487 9488 if (info.secondaryCpuAbi != null) { 9489 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9490 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9491 } 9492 } 9493 } 9494 9495 /** 9496 * Calculate the abis and roots for a bundled app. These can uniquely 9497 * be determined from the contents of the system partition, i.e whether 9498 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9499 * of this information, and instead assume that the system was built 9500 * sensibly. 9501 */ 9502 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9503 PackageSetting pkgSetting) { 9504 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9505 9506 // If "/system/lib64/apkname" exists, assume that is the per-package 9507 // native library directory to use; otherwise use "/system/lib/apkname". 9508 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9509 setBundledAppAbi(pkg, apkRoot, apkName); 9510 // pkgSetting might be null during rescan following uninstall of updates 9511 // to a bundled app, so accommodate that possibility. The settings in 9512 // that case will be established later from the parsed package. 9513 // 9514 // If the settings aren't null, sync them up with what we've just derived. 9515 // note that apkRoot isn't stored in the package settings. 9516 if (pkgSetting != null) { 9517 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9518 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9519 } 9520 } 9521 9522 /** 9523 * Deduces the ABI of a bundled app and sets the relevant fields on the 9524 * parsed pkg object. 9525 * 9526 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9527 * under which system libraries are installed. 9528 * @param apkName the name of the installed package. 9529 */ 9530 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9531 final File codeFile = new File(pkg.codePath); 9532 9533 final boolean has64BitLibs; 9534 final boolean has32BitLibs; 9535 if (isApkFile(codeFile)) { 9536 // Monolithic install 9537 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9538 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9539 } else { 9540 // Cluster install 9541 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9542 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9543 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9544 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9545 has64BitLibs = (new File(rootDir, isa)).exists(); 9546 } else { 9547 has64BitLibs = false; 9548 } 9549 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9550 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9551 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9552 has32BitLibs = (new File(rootDir, isa)).exists(); 9553 } else { 9554 has32BitLibs = false; 9555 } 9556 } 9557 9558 if (has64BitLibs && !has32BitLibs) { 9559 // The package has 64 bit libs, but not 32 bit libs. Its primary 9560 // ABI should be 64 bit. We can safely assume here that the bundled 9561 // native libraries correspond to the most preferred ABI in the list. 9562 9563 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9564 pkg.applicationInfo.secondaryCpuAbi = null; 9565 } else if (has32BitLibs && !has64BitLibs) { 9566 // The package has 32 bit libs but not 64 bit libs. Its primary 9567 // ABI should be 32 bit. 9568 9569 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9570 pkg.applicationInfo.secondaryCpuAbi = null; 9571 } else if (has32BitLibs && has64BitLibs) { 9572 // The application has both 64 and 32 bit bundled libraries. We check 9573 // here that the app declares multiArch support, and warn if it doesn't. 9574 // 9575 // We will be lenient here and record both ABIs. The primary will be the 9576 // ABI that's higher on the list, i.e, a device that's configured to prefer 9577 // 64 bit apps will see a 64 bit primary ABI, 9578 9579 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9580 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9581 } 9582 9583 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9584 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9585 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9586 } else { 9587 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9588 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9589 } 9590 } else { 9591 pkg.applicationInfo.primaryCpuAbi = null; 9592 pkg.applicationInfo.secondaryCpuAbi = null; 9593 } 9594 } 9595 9596 private void killApplication(String pkgName, int appId, String reason) { 9597 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9598 } 9599 9600 private void killApplication(String pkgName, int appId, int userId, String reason) { 9601 // Request the ActivityManager to kill the process(only for existing packages) 9602 // so that we do not end up in a confused state while the user is still using the older 9603 // version of the application while the new one gets installed. 9604 final long token = Binder.clearCallingIdentity(); 9605 try { 9606 IActivityManager am = ActivityManagerNative.getDefault(); 9607 if (am != null) { 9608 try { 9609 am.killApplication(pkgName, appId, userId, reason); 9610 } catch (RemoteException e) { 9611 } 9612 } 9613 } finally { 9614 Binder.restoreCallingIdentity(token); 9615 } 9616 } 9617 9618 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9619 // Remove the parent package setting 9620 PackageSetting ps = (PackageSetting) pkg.mExtras; 9621 if (ps != null) { 9622 removePackageLI(ps, chatty); 9623 } 9624 // Remove the child package setting 9625 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9626 for (int i = 0; i < childCount; i++) { 9627 PackageParser.Package childPkg = pkg.childPackages.get(i); 9628 ps = (PackageSetting) childPkg.mExtras; 9629 if (ps != null) { 9630 removePackageLI(ps, chatty); 9631 } 9632 } 9633 } 9634 9635 void removePackageLI(PackageSetting ps, boolean chatty) { 9636 if (DEBUG_INSTALL) { 9637 if (chatty) 9638 Log.d(TAG, "Removing package " + ps.name); 9639 } 9640 9641 // writer 9642 synchronized (mPackages) { 9643 mPackages.remove(ps.name); 9644 final PackageParser.Package pkg = ps.pkg; 9645 if (pkg != null) { 9646 cleanPackageDataStructuresLILPw(pkg, chatty); 9647 } 9648 } 9649 } 9650 9651 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9652 if (DEBUG_INSTALL) { 9653 if (chatty) 9654 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9655 } 9656 9657 // writer 9658 synchronized (mPackages) { 9659 // Remove the parent package 9660 mPackages.remove(pkg.applicationInfo.packageName); 9661 cleanPackageDataStructuresLILPw(pkg, chatty); 9662 9663 // Remove the child packages 9664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9665 for (int i = 0; i < childCount; i++) { 9666 PackageParser.Package childPkg = pkg.childPackages.get(i); 9667 mPackages.remove(childPkg.applicationInfo.packageName); 9668 cleanPackageDataStructuresLILPw(childPkg, chatty); 9669 } 9670 } 9671 } 9672 9673 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9674 int N = pkg.providers.size(); 9675 StringBuilder r = null; 9676 int i; 9677 for (i=0; i<N; i++) { 9678 PackageParser.Provider p = pkg.providers.get(i); 9679 mProviders.removeProvider(p); 9680 if (p.info.authority == null) { 9681 9682 /* There was another ContentProvider with this authority when 9683 * this app was installed so this authority is null, 9684 * Ignore it as we don't have to unregister the provider. 9685 */ 9686 continue; 9687 } 9688 String names[] = p.info.authority.split(";"); 9689 for (int j = 0; j < names.length; j++) { 9690 if (mProvidersByAuthority.get(names[j]) == p) { 9691 mProvidersByAuthority.remove(names[j]); 9692 if (DEBUG_REMOVE) { 9693 if (chatty) 9694 Log.d(TAG, "Unregistered content provider: " + names[j] 9695 + ", className = " + p.info.name + ", isSyncable = " 9696 + p.info.isSyncable); 9697 } 9698 } 9699 } 9700 if (DEBUG_REMOVE && chatty) { 9701 if (r == null) { 9702 r = new StringBuilder(256); 9703 } else { 9704 r.append(' '); 9705 } 9706 r.append(p.info.name); 9707 } 9708 } 9709 if (r != null) { 9710 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9711 } 9712 9713 N = pkg.services.size(); 9714 r = null; 9715 for (i=0; i<N; i++) { 9716 PackageParser.Service s = pkg.services.get(i); 9717 mServices.removeService(s); 9718 if (chatty) { 9719 if (r == null) { 9720 r = new StringBuilder(256); 9721 } else { 9722 r.append(' '); 9723 } 9724 r.append(s.info.name); 9725 } 9726 } 9727 if (r != null) { 9728 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9729 } 9730 9731 N = pkg.receivers.size(); 9732 r = null; 9733 for (i=0; i<N; i++) { 9734 PackageParser.Activity a = pkg.receivers.get(i); 9735 mReceivers.removeActivity(a, "receiver"); 9736 if (DEBUG_REMOVE && chatty) { 9737 if (r == null) { 9738 r = new StringBuilder(256); 9739 } else { 9740 r.append(' '); 9741 } 9742 r.append(a.info.name); 9743 } 9744 } 9745 if (r != null) { 9746 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9747 } 9748 9749 N = pkg.activities.size(); 9750 r = null; 9751 for (i=0; i<N; i++) { 9752 PackageParser.Activity a = pkg.activities.get(i); 9753 mActivities.removeActivity(a, "activity"); 9754 if (DEBUG_REMOVE && chatty) { 9755 if (r == null) { 9756 r = new StringBuilder(256); 9757 } else { 9758 r.append(' '); 9759 } 9760 r.append(a.info.name); 9761 } 9762 } 9763 if (r != null) { 9764 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9765 } 9766 9767 N = pkg.permissions.size(); 9768 r = null; 9769 for (i=0; i<N; i++) { 9770 PackageParser.Permission p = pkg.permissions.get(i); 9771 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9772 if (bp == null) { 9773 bp = mSettings.mPermissionTrees.get(p.info.name); 9774 } 9775 if (bp != null && bp.perm == p) { 9776 bp.perm = null; 9777 if (DEBUG_REMOVE && chatty) { 9778 if (r == null) { 9779 r = new StringBuilder(256); 9780 } else { 9781 r.append(' '); 9782 } 9783 r.append(p.info.name); 9784 } 9785 } 9786 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9787 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9788 if (appOpPkgs != null) { 9789 appOpPkgs.remove(pkg.packageName); 9790 } 9791 } 9792 } 9793 if (r != null) { 9794 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9795 } 9796 9797 N = pkg.requestedPermissions.size(); 9798 r = null; 9799 for (i=0; i<N; i++) { 9800 String perm = pkg.requestedPermissions.get(i); 9801 BasePermission bp = mSettings.mPermissions.get(perm); 9802 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9803 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9804 if (appOpPkgs != null) { 9805 appOpPkgs.remove(pkg.packageName); 9806 if (appOpPkgs.isEmpty()) { 9807 mAppOpPermissionPackages.remove(perm); 9808 } 9809 } 9810 } 9811 } 9812 if (r != null) { 9813 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9814 } 9815 9816 N = pkg.instrumentation.size(); 9817 r = null; 9818 for (i=0; i<N; i++) { 9819 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9820 mInstrumentation.remove(a.getComponentName()); 9821 if (DEBUG_REMOVE && chatty) { 9822 if (r == null) { 9823 r = new StringBuilder(256); 9824 } else { 9825 r.append(' '); 9826 } 9827 r.append(a.info.name); 9828 } 9829 } 9830 if (r != null) { 9831 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9832 } 9833 9834 r = null; 9835 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9836 // Only system apps can hold shared libraries. 9837 if (pkg.libraryNames != null) { 9838 for (i=0; i<pkg.libraryNames.size(); i++) { 9839 String name = pkg.libraryNames.get(i); 9840 SharedLibraryEntry cur = mSharedLibraries.get(name); 9841 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9842 mSharedLibraries.remove(name); 9843 if (DEBUG_REMOVE && chatty) { 9844 if (r == null) { 9845 r = new StringBuilder(256); 9846 } else { 9847 r.append(' '); 9848 } 9849 r.append(name); 9850 } 9851 } 9852 } 9853 } 9854 } 9855 if (r != null) { 9856 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9857 } 9858 } 9859 9860 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9861 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9862 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9863 return true; 9864 } 9865 } 9866 return false; 9867 } 9868 9869 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9870 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9871 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9872 9873 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9874 // Update the parent permissions 9875 updatePermissionsLPw(pkg.packageName, pkg, flags); 9876 // Update the child permissions 9877 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9878 for (int i = 0; i < childCount; i++) { 9879 PackageParser.Package childPkg = pkg.childPackages.get(i); 9880 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9881 } 9882 } 9883 9884 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9885 int flags) { 9886 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9887 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9888 } 9889 9890 private void updatePermissionsLPw(String changingPkg, 9891 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9892 // Make sure there are no dangling permission trees. 9893 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9894 while (it.hasNext()) { 9895 final BasePermission bp = it.next(); 9896 if (bp.packageSetting == null) { 9897 // We may not yet have parsed the package, so just see if 9898 // we still know about its settings. 9899 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9900 } 9901 if (bp.packageSetting == null) { 9902 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9903 + " from package " + bp.sourcePackage); 9904 it.remove(); 9905 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9906 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9907 Slog.i(TAG, "Removing old permission tree: " + bp.name 9908 + " from package " + bp.sourcePackage); 9909 flags |= UPDATE_PERMISSIONS_ALL; 9910 it.remove(); 9911 } 9912 } 9913 } 9914 9915 // Make sure all dynamic permissions have been assigned to a package, 9916 // and make sure there are no dangling permissions. 9917 it = mSettings.mPermissions.values().iterator(); 9918 while (it.hasNext()) { 9919 final BasePermission bp = it.next(); 9920 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9921 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9922 + bp.name + " pkg=" + bp.sourcePackage 9923 + " info=" + bp.pendingInfo); 9924 if (bp.packageSetting == null && bp.pendingInfo != null) { 9925 final BasePermission tree = findPermissionTreeLP(bp.name); 9926 if (tree != null && tree.perm != null) { 9927 bp.packageSetting = tree.packageSetting; 9928 bp.perm = new PackageParser.Permission(tree.perm.owner, 9929 new PermissionInfo(bp.pendingInfo)); 9930 bp.perm.info.packageName = tree.perm.info.packageName; 9931 bp.perm.info.name = bp.name; 9932 bp.uid = tree.uid; 9933 } 9934 } 9935 } 9936 if (bp.packageSetting == null) { 9937 // We may not yet have parsed the package, so just see if 9938 // we still know about its settings. 9939 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9940 } 9941 if (bp.packageSetting == null) { 9942 Slog.w(TAG, "Removing dangling permission: " + bp.name 9943 + " from package " + bp.sourcePackage); 9944 it.remove(); 9945 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9946 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9947 Slog.i(TAG, "Removing old permission: " + bp.name 9948 + " from package " + bp.sourcePackage); 9949 flags |= UPDATE_PERMISSIONS_ALL; 9950 it.remove(); 9951 } 9952 } 9953 } 9954 9955 // Now update the permissions for all packages, in particular 9956 // replace the granted permissions of the system packages. 9957 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9958 for (PackageParser.Package pkg : mPackages.values()) { 9959 if (pkg != pkgInfo) { 9960 // Only replace for packages on requested volume 9961 final String volumeUuid = getVolumeUuidForPackage(pkg); 9962 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9963 && Objects.equals(replaceVolumeUuid, volumeUuid); 9964 grantPermissionsLPw(pkg, replace, changingPkg); 9965 } 9966 } 9967 } 9968 9969 if (pkgInfo != null) { 9970 // Only replace for packages on requested volume 9971 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9972 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9973 && Objects.equals(replaceVolumeUuid, volumeUuid); 9974 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9975 } 9976 } 9977 9978 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9979 String packageOfInterest) { 9980 // IMPORTANT: There are two types of permissions: install and runtime. 9981 // Install time permissions are granted when the app is installed to 9982 // all device users and users added in the future. Runtime permissions 9983 // are granted at runtime explicitly to specific users. Normal and signature 9984 // protected permissions are install time permissions. Dangerous permissions 9985 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9986 // otherwise they are runtime permissions. This function does not manage 9987 // runtime permissions except for the case an app targeting Lollipop MR1 9988 // being upgraded to target a newer SDK, in which case dangerous permissions 9989 // are transformed from install time to runtime ones. 9990 9991 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9992 if (ps == null) { 9993 return; 9994 } 9995 9996 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9997 9998 PermissionsState permissionsState = ps.getPermissionsState(); 9999 PermissionsState origPermissions = permissionsState; 10000 10001 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10002 10003 boolean runtimePermissionsRevoked = false; 10004 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10005 10006 boolean changedInstallPermission = false; 10007 10008 if (replace) { 10009 ps.installPermissionsFixed = false; 10010 if (!ps.isSharedUser()) { 10011 origPermissions = new PermissionsState(permissionsState); 10012 permissionsState.reset(); 10013 } else { 10014 // We need to know only about runtime permission changes since the 10015 // calling code always writes the install permissions state but 10016 // the runtime ones are written only if changed. The only cases of 10017 // changed runtime permissions here are promotion of an install to 10018 // runtime and revocation of a runtime from a shared user. 10019 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10020 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10021 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10022 runtimePermissionsRevoked = true; 10023 } 10024 } 10025 } 10026 10027 permissionsState.setGlobalGids(mGlobalGids); 10028 10029 final int N = pkg.requestedPermissions.size(); 10030 for (int i=0; i<N; i++) { 10031 final String name = pkg.requestedPermissions.get(i); 10032 final BasePermission bp = mSettings.mPermissions.get(name); 10033 10034 if (DEBUG_INSTALL) { 10035 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10036 } 10037 10038 if (bp == null || bp.packageSetting == null) { 10039 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10040 Slog.w(TAG, "Unknown permission " + name 10041 + " in package " + pkg.packageName); 10042 } 10043 continue; 10044 } 10045 10046 final String perm = bp.name; 10047 boolean allowedSig = false; 10048 int grant = GRANT_DENIED; 10049 10050 // Keep track of app op permissions. 10051 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10052 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10053 if (pkgs == null) { 10054 pkgs = new ArraySet<>(); 10055 mAppOpPermissionPackages.put(bp.name, pkgs); 10056 } 10057 pkgs.add(pkg.packageName); 10058 } 10059 10060 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10061 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10062 >= Build.VERSION_CODES.M; 10063 switch (level) { 10064 case PermissionInfo.PROTECTION_NORMAL: { 10065 // For all apps normal permissions are install time ones. 10066 grant = GRANT_INSTALL; 10067 } break; 10068 10069 case PermissionInfo.PROTECTION_DANGEROUS: { 10070 // If a permission review is required for legacy apps we represent 10071 // their permissions as always granted runtime ones since we need 10072 // to keep the review required permission flag per user while an 10073 // install permission's state is shared across all users. 10074 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10075 // For legacy apps dangerous permissions are install time ones. 10076 grant = GRANT_INSTALL; 10077 } else if (origPermissions.hasInstallPermission(bp.name)) { 10078 // For legacy apps that became modern, install becomes runtime. 10079 grant = GRANT_UPGRADE; 10080 } else if (mPromoteSystemApps 10081 && isSystemApp(ps) 10082 && mExistingSystemPackages.contains(ps.name)) { 10083 // For legacy system apps, install becomes runtime. 10084 // We cannot check hasInstallPermission() for system apps since those 10085 // permissions were granted implicitly and not persisted pre-M. 10086 grant = GRANT_UPGRADE; 10087 } else { 10088 // For modern apps keep runtime permissions unchanged. 10089 grant = GRANT_RUNTIME; 10090 } 10091 } break; 10092 10093 case PermissionInfo.PROTECTION_SIGNATURE: { 10094 // For all apps signature permissions are install time ones. 10095 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10096 if (allowedSig) { 10097 grant = GRANT_INSTALL; 10098 } 10099 } break; 10100 } 10101 10102 if (DEBUG_INSTALL) { 10103 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10104 } 10105 10106 if (grant != GRANT_DENIED) { 10107 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10108 // If this is an existing, non-system package, then 10109 // we can't add any new permissions to it. 10110 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10111 // Except... if this is a permission that was added 10112 // to the platform (note: need to only do this when 10113 // updating the platform). 10114 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10115 grant = GRANT_DENIED; 10116 } 10117 } 10118 } 10119 10120 switch (grant) { 10121 case GRANT_INSTALL: { 10122 // Revoke this as runtime permission to handle the case of 10123 // a runtime permission being downgraded to an install one. 10124 // Also in permission review mode we keep dangerous permissions 10125 // for legacy apps 10126 for (int userId : UserManagerService.getInstance().getUserIds()) { 10127 if (origPermissions.getRuntimePermissionState( 10128 bp.name, userId) != null) { 10129 // Revoke the runtime permission and clear the flags. 10130 origPermissions.revokeRuntimePermission(bp, userId); 10131 origPermissions.updatePermissionFlags(bp, userId, 10132 PackageManager.MASK_PERMISSION_FLAGS, 0); 10133 // If we revoked a permission permission, we have to write. 10134 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10135 changedRuntimePermissionUserIds, userId); 10136 } 10137 } 10138 // Grant an install permission. 10139 if (permissionsState.grantInstallPermission(bp) != 10140 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10141 changedInstallPermission = true; 10142 } 10143 } break; 10144 10145 case GRANT_RUNTIME: { 10146 // Grant previously granted runtime permissions. 10147 for (int userId : UserManagerService.getInstance().getUserIds()) { 10148 PermissionState permissionState = origPermissions 10149 .getRuntimePermissionState(bp.name, userId); 10150 int flags = permissionState != null 10151 ? permissionState.getFlags() : 0; 10152 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10153 if (permissionsState.grantRuntimePermission(bp, userId) == 10154 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10155 // If we cannot put the permission as it was, we have to write. 10156 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10157 changedRuntimePermissionUserIds, userId); 10158 } 10159 // If the app supports runtime permissions no need for a review. 10160 if (Build.PERMISSIONS_REVIEW_REQUIRED 10161 && appSupportsRuntimePermissions 10162 && (flags & PackageManager 10163 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10164 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10165 // Since we changed the flags, we have to write. 10166 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10167 changedRuntimePermissionUserIds, userId); 10168 } 10169 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10170 && !appSupportsRuntimePermissions) { 10171 // For legacy apps that need a permission review, every new 10172 // runtime permission is granted but it is pending a review. 10173 // We also need to review only platform defined runtime 10174 // permissions as these are the only ones the platform knows 10175 // how to disable the API to simulate revocation as legacy 10176 // apps don't expect to run with revoked permissions. 10177 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10178 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10179 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10180 // We changed the flags, hence have to write. 10181 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10182 changedRuntimePermissionUserIds, userId); 10183 } 10184 } 10185 if (permissionsState.grantRuntimePermission(bp, userId) 10186 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10187 // We changed the permission, hence have to write. 10188 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10189 changedRuntimePermissionUserIds, userId); 10190 } 10191 } 10192 // Propagate the permission flags. 10193 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10194 } 10195 } break; 10196 10197 case GRANT_UPGRADE: { 10198 // Grant runtime permissions for a previously held install permission. 10199 PermissionState permissionState = origPermissions 10200 .getInstallPermissionState(bp.name); 10201 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10202 10203 if (origPermissions.revokeInstallPermission(bp) 10204 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10205 // We will be transferring the permission flags, so clear them. 10206 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10207 PackageManager.MASK_PERMISSION_FLAGS, 0); 10208 changedInstallPermission = true; 10209 } 10210 10211 // If the permission is not to be promoted to runtime we ignore it and 10212 // also its other flags as they are not applicable to install permissions. 10213 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10214 for (int userId : currentUserIds) { 10215 if (permissionsState.grantRuntimePermission(bp, userId) != 10216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10217 // Transfer the permission flags. 10218 permissionsState.updatePermissionFlags(bp, userId, 10219 flags, flags); 10220 // If we granted the permission, we have to write. 10221 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10222 changedRuntimePermissionUserIds, userId); 10223 } 10224 } 10225 } 10226 } break; 10227 10228 default: { 10229 if (packageOfInterest == null 10230 || packageOfInterest.equals(pkg.packageName)) { 10231 Slog.w(TAG, "Not granting permission " + perm 10232 + " to package " + pkg.packageName 10233 + " because it was previously installed without"); 10234 } 10235 } break; 10236 } 10237 } else { 10238 if (permissionsState.revokeInstallPermission(bp) != 10239 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10240 // Also drop the permission flags. 10241 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10242 PackageManager.MASK_PERMISSION_FLAGS, 0); 10243 changedInstallPermission = true; 10244 Slog.i(TAG, "Un-granting permission " + perm 10245 + " from package " + pkg.packageName 10246 + " (protectionLevel=" + bp.protectionLevel 10247 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10248 + ")"); 10249 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10250 // Don't print warning for app op permissions, since it is fine for them 10251 // not to be granted, there is a UI for the user to decide. 10252 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10253 Slog.w(TAG, "Not granting permission " + perm 10254 + " to package " + pkg.packageName 10255 + " (protectionLevel=" + bp.protectionLevel 10256 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10257 + ")"); 10258 } 10259 } 10260 } 10261 } 10262 10263 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10264 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10265 // This is the first that we have heard about this package, so the 10266 // permissions we have now selected are fixed until explicitly 10267 // changed. 10268 ps.installPermissionsFixed = true; 10269 } 10270 10271 // Persist the runtime permissions state for users with changes. If permissions 10272 // were revoked because no app in the shared user declares them we have to 10273 // write synchronously to avoid losing runtime permissions state. 10274 for (int userId : changedRuntimePermissionUserIds) { 10275 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10276 } 10277 10278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10279 } 10280 10281 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10282 boolean allowed = false; 10283 final int NP = PackageParser.NEW_PERMISSIONS.length; 10284 for (int ip=0; ip<NP; ip++) { 10285 final PackageParser.NewPermissionInfo npi 10286 = PackageParser.NEW_PERMISSIONS[ip]; 10287 if (npi.name.equals(perm) 10288 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10289 allowed = true; 10290 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10291 + pkg.packageName); 10292 break; 10293 } 10294 } 10295 return allowed; 10296 } 10297 10298 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10299 BasePermission bp, PermissionsState origPermissions) { 10300 boolean allowed; 10301 allowed = (compareSignatures( 10302 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10303 == PackageManager.SIGNATURE_MATCH) 10304 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10305 == PackageManager.SIGNATURE_MATCH); 10306 if (!allowed && (bp.protectionLevel 10307 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10308 if (isSystemApp(pkg)) { 10309 // For updated system applications, a system permission 10310 // is granted only if it had been defined by the original application. 10311 if (pkg.isUpdatedSystemApp()) { 10312 final PackageSetting sysPs = mSettings 10313 .getDisabledSystemPkgLPr(pkg.packageName); 10314 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10315 // If the original was granted this permission, we take 10316 // that grant decision as read and propagate it to the 10317 // update. 10318 if (sysPs.isPrivileged()) { 10319 allowed = true; 10320 } 10321 } else { 10322 // The system apk may have been updated with an older 10323 // version of the one on the data partition, but which 10324 // granted a new system permission that it didn't have 10325 // before. In this case we do want to allow the app to 10326 // now get the new permission if the ancestral apk is 10327 // privileged to get it. 10328 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10329 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10330 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10331 allowed = true; 10332 break; 10333 } 10334 } 10335 } 10336 // Also if a privileged parent package on the system image or any of 10337 // its children requested a privileged permission, the updated child 10338 // packages can also get the permission. 10339 if (pkg.parentPackage != null) { 10340 final PackageSetting disabledSysParentPs = mSettings 10341 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10342 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10343 && disabledSysParentPs.isPrivileged()) { 10344 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10345 allowed = true; 10346 } else if (disabledSysParentPs.pkg.childPackages != null) { 10347 final int count = disabledSysParentPs.pkg.childPackages.size(); 10348 for (int i = 0; i < count; i++) { 10349 PackageParser.Package disabledSysChildPkg = 10350 disabledSysParentPs.pkg.childPackages.get(i); 10351 if (isPackageRequestingPermission(disabledSysChildPkg, 10352 perm)) { 10353 allowed = true; 10354 break; 10355 } 10356 } 10357 } 10358 } 10359 } 10360 } 10361 } else { 10362 allowed = isPrivilegedApp(pkg); 10363 } 10364 } 10365 } 10366 if (!allowed) { 10367 if (!allowed && (bp.protectionLevel 10368 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10369 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10370 // If this was a previously normal/dangerous permission that got moved 10371 // to a system permission as part of the runtime permission redesign, then 10372 // we still want to blindly grant it to old apps. 10373 allowed = true; 10374 } 10375 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10376 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10377 // If this permission is to be granted to the system installer and 10378 // this app is an installer, then it gets the permission. 10379 allowed = true; 10380 } 10381 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10382 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10383 // If this permission is to be granted to the system verifier and 10384 // this app is a verifier, then it gets the permission. 10385 allowed = true; 10386 } 10387 if (!allowed && (bp.protectionLevel 10388 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10389 && isSystemApp(pkg)) { 10390 // Any pre-installed system app is allowed to get this permission. 10391 allowed = true; 10392 } 10393 if (!allowed && (bp.protectionLevel 10394 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10395 // For development permissions, a development permission 10396 // is granted only if it was already granted. 10397 allowed = origPermissions.hasInstallPermission(perm); 10398 } 10399 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10400 && pkg.packageName.equals(mSetupWizardPackage)) { 10401 // If this permission is to be granted to the system setup wizard and 10402 // this app is a setup wizard, then it gets the permission. 10403 allowed = true; 10404 } 10405 } 10406 return allowed; 10407 } 10408 10409 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10410 final int permCount = pkg.requestedPermissions.size(); 10411 for (int j = 0; j < permCount; j++) { 10412 String requestedPermission = pkg.requestedPermissions.get(j); 10413 if (permission.equals(requestedPermission)) { 10414 return true; 10415 } 10416 } 10417 return false; 10418 } 10419 10420 final class ActivityIntentResolver 10421 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10422 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10423 boolean defaultOnly, int userId) { 10424 if (!sUserManager.exists(userId)) return null; 10425 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10426 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10427 } 10428 10429 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10430 int userId) { 10431 if (!sUserManager.exists(userId)) return null; 10432 mFlags = flags; 10433 return super.queryIntent(intent, resolvedType, 10434 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10435 } 10436 10437 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10438 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10439 if (!sUserManager.exists(userId)) return null; 10440 if (packageActivities == null) { 10441 return null; 10442 } 10443 mFlags = flags; 10444 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10445 final int N = packageActivities.size(); 10446 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10447 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10448 10449 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10450 for (int i = 0; i < N; ++i) { 10451 intentFilters = packageActivities.get(i).intents; 10452 if (intentFilters != null && intentFilters.size() > 0) { 10453 PackageParser.ActivityIntentInfo[] array = 10454 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10455 intentFilters.toArray(array); 10456 listCut.add(array); 10457 } 10458 } 10459 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10460 } 10461 10462 /** 10463 * Finds a privileged activity that matches the specified activity names. 10464 */ 10465 private PackageParser.Activity findMatchingActivity( 10466 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10467 for (PackageParser.Activity sysActivity : activityList) { 10468 if (sysActivity.info.name.equals(activityInfo.name)) { 10469 return sysActivity; 10470 } 10471 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10472 return sysActivity; 10473 } 10474 if (sysActivity.info.targetActivity != null) { 10475 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10476 return sysActivity; 10477 } 10478 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10479 return sysActivity; 10480 } 10481 } 10482 } 10483 return null; 10484 } 10485 10486 public class IterGenerator<E> { 10487 public Iterator<E> generate(ActivityIntentInfo info) { 10488 return null; 10489 } 10490 } 10491 10492 public class ActionIterGenerator extends IterGenerator<String> { 10493 @Override 10494 public Iterator<String> generate(ActivityIntentInfo info) { 10495 return info.actionsIterator(); 10496 } 10497 } 10498 10499 public class CategoriesIterGenerator extends IterGenerator<String> { 10500 @Override 10501 public Iterator<String> generate(ActivityIntentInfo info) { 10502 return info.categoriesIterator(); 10503 } 10504 } 10505 10506 public class SchemesIterGenerator extends IterGenerator<String> { 10507 @Override 10508 public Iterator<String> generate(ActivityIntentInfo info) { 10509 return info.schemesIterator(); 10510 } 10511 } 10512 10513 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10514 @Override 10515 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10516 return info.authoritiesIterator(); 10517 } 10518 } 10519 10520 /** 10521 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10522 * MODIFIED. Do not pass in a list that should not be changed. 10523 */ 10524 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10525 IterGenerator<T> generator, Iterator<T> searchIterator) { 10526 // loop through the set of actions; every one must be found in the intent filter 10527 while (searchIterator.hasNext()) { 10528 // we must have at least one filter in the list to consider a match 10529 if (intentList.size() == 0) { 10530 break; 10531 } 10532 10533 final T searchAction = searchIterator.next(); 10534 10535 // loop through the set of intent filters 10536 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10537 while (intentIter.hasNext()) { 10538 final ActivityIntentInfo intentInfo = intentIter.next(); 10539 boolean selectionFound = false; 10540 10541 // loop through the intent filter's selection criteria; at least one 10542 // of them must match the searched criteria 10543 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10544 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10545 final T intentSelection = intentSelectionIter.next(); 10546 if (intentSelection != null && intentSelection.equals(searchAction)) { 10547 selectionFound = true; 10548 break; 10549 } 10550 } 10551 10552 // the selection criteria wasn't found in this filter's set; this filter 10553 // is not a potential match 10554 if (!selectionFound) { 10555 intentIter.remove(); 10556 } 10557 } 10558 } 10559 } 10560 10561 private boolean isProtectedAction(ActivityIntentInfo filter) { 10562 final Iterator<String> actionsIter = filter.actionsIterator(); 10563 while (actionsIter != null && actionsIter.hasNext()) { 10564 final String filterAction = actionsIter.next(); 10565 if (PROTECTED_ACTIONS.contains(filterAction)) { 10566 return true; 10567 } 10568 } 10569 return false; 10570 } 10571 10572 /** 10573 * Adjusts the priority of the given intent filter according to policy. 10574 * <p> 10575 * <ul> 10576 * <li>The priority for non privileged applications is capped to '0'</li> 10577 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10578 * <li>The priority for unbundled updates to privileged applications is capped to the 10579 * priority defined on the system partition</li> 10580 * </ul> 10581 * <p> 10582 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10583 * allowed to obtain any priority on any action. 10584 */ 10585 private void adjustPriority( 10586 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10587 // nothing to do; priority is fine as-is 10588 if (intent.getPriority() <= 0) { 10589 return; 10590 } 10591 10592 final ActivityInfo activityInfo = intent.activity.info; 10593 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10594 10595 final boolean privilegedApp = 10596 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10597 if (!privilegedApp) { 10598 // non-privileged applications can never define a priority >0 10599 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10600 + " package: " + applicationInfo.packageName 10601 + " activity: " + intent.activity.className 10602 + " origPrio: " + intent.getPriority()); 10603 intent.setPriority(0); 10604 return; 10605 } 10606 10607 if (systemActivities == null) { 10608 // the system package is not disabled; we're parsing the system partition 10609 if (isProtectedAction(intent)) { 10610 if (mDeferProtectedFilters) { 10611 // We can't deal with these just yet. No component should ever obtain a 10612 // >0 priority for a protected actions, with ONE exception -- the setup 10613 // wizard. The setup wizard, however, cannot be known until we're able to 10614 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10615 // until all intent filters have been processed. Chicken, meet egg. 10616 // Let the filter temporarily have a high priority and rectify the 10617 // priorities after all system packages have been scanned. 10618 mProtectedFilters.add(intent); 10619 if (DEBUG_FILTERS) { 10620 Slog.i(TAG, "Protected action; save for later;" 10621 + " package: " + applicationInfo.packageName 10622 + " activity: " + intent.activity.className 10623 + " origPrio: " + intent.getPriority()); 10624 } 10625 return; 10626 } else { 10627 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10628 Slog.i(TAG, "No setup wizard;" 10629 + " All protected intents capped to priority 0"); 10630 } 10631 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10632 if (DEBUG_FILTERS) { 10633 Slog.i(TAG, "Found setup wizard;" 10634 + " allow priority " + intent.getPriority() + ";" 10635 + " package: " + intent.activity.info.packageName 10636 + " activity: " + intent.activity.className 10637 + " priority: " + intent.getPriority()); 10638 } 10639 // setup wizard gets whatever it wants 10640 return; 10641 } 10642 Slog.w(TAG, "Protected action; cap priority to 0;" 10643 + " package: " + intent.activity.info.packageName 10644 + " activity: " + intent.activity.className 10645 + " origPrio: " + intent.getPriority()); 10646 intent.setPriority(0); 10647 return; 10648 } 10649 } 10650 // privileged apps on the system image get whatever priority they request 10651 return; 10652 } 10653 10654 // privileged app unbundled update ... try to find the same activity 10655 final PackageParser.Activity foundActivity = 10656 findMatchingActivity(systemActivities, activityInfo); 10657 if (foundActivity == null) { 10658 // this is a new activity; it cannot obtain >0 priority 10659 if (DEBUG_FILTERS) { 10660 Slog.i(TAG, "New activity; cap priority to 0;" 10661 + " package: " + applicationInfo.packageName 10662 + " activity: " + intent.activity.className 10663 + " origPrio: " + intent.getPriority()); 10664 } 10665 intent.setPriority(0); 10666 return; 10667 } 10668 10669 // found activity, now check for filter equivalence 10670 10671 // a shallow copy is enough; we modify the list, not its contents 10672 final List<ActivityIntentInfo> intentListCopy = 10673 new ArrayList<>(foundActivity.intents); 10674 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10675 10676 // find matching action subsets 10677 final Iterator<String> actionsIterator = intent.actionsIterator(); 10678 if (actionsIterator != null) { 10679 getIntentListSubset( 10680 intentListCopy, new ActionIterGenerator(), actionsIterator); 10681 if (intentListCopy.size() == 0) { 10682 // no more intents to match; we're not equivalent 10683 if (DEBUG_FILTERS) { 10684 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10685 + " package: " + applicationInfo.packageName 10686 + " activity: " + intent.activity.className 10687 + " origPrio: " + intent.getPriority()); 10688 } 10689 intent.setPriority(0); 10690 return; 10691 } 10692 } 10693 10694 // find matching category subsets 10695 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10696 if (categoriesIterator != null) { 10697 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10698 categoriesIterator); 10699 if (intentListCopy.size() == 0) { 10700 // no more intents to match; we're not equivalent 10701 if (DEBUG_FILTERS) { 10702 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10703 + " package: " + applicationInfo.packageName 10704 + " activity: " + intent.activity.className 10705 + " origPrio: " + intent.getPriority()); 10706 } 10707 intent.setPriority(0); 10708 return; 10709 } 10710 } 10711 10712 // find matching schemes subsets 10713 final Iterator<String> schemesIterator = intent.schemesIterator(); 10714 if (schemesIterator != null) { 10715 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10716 schemesIterator); 10717 if (intentListCopy.size() == 0) { 10718 // no more intents to match; we're not equivalent 10719 if (DEBUG_FILTERS) { 10720 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10721 + " package: " + applicationInfo.packageName 10722 + " activity: " + intent.activity.className 10723 + " origPrio: " + intent.getPriority()); 10724 } 10725 intent.setPriority(0); 10726 return; 10727 } 10728 } 10729 10730 // find matching authorities subsets 10731 final Iterator<IntentFilter.AuthorityEntry> 10732 authoritiesIterator = intent.authoritiesIterator(); 10733 if (authoritiesIterator != null) { 10734 getIntentListSubset(intentListCopy, 10735 new AuthoritiesIterGenerator(), 10736 authoritiesIterator); 10737 if (intentListCopy.size() == 0) { 10738 // no more intents to match; we're not equivalent 10739 if (DEBUG_FILTERS) { 10740 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10741 + " package: " + applicationInfo.packageName 10742 + " activity: " + intent.activity.className 10743 + " origPrio: " + intent.getPriority()); 10744 } 10745 intent.setPriority(0); 10746 return; 10747 } 10748 } 10749 10750 // we found matching filter(s); app gets the max priority of all intents 10751 int cappedPriority = 0; 10752 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10753 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10754 } 10755 if (intent.getPriority() > cappedPriority) { 10756 if (DEBUG_FILTERS) { 10757 Slog.i(TAG, "Found matching filter(s);" 10758 + " cap priority to " + cappedPriority + ";" 10759 + " package: " + applicationInfo.packageName 10760 + " activity: " + intent.activity.className 10761 + " origPrio: " + intent.getPriority()); 10762 } 10763 intent.setPriority(cappedPriority); 10764 return; 10765 } 10766 // all this for nothing; the requested priority was <= what was on the system 10767 } 10768 10769 public final void addActivity(PackageParser.Activity a, String type) { 10770 mActivities.put(a.getComponentName(), a); 10771 if (DEBUG_SHOW_INFO) 10772 Log.v( 10773 TAG, " " + type + " " + 10774 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10775 if (DEBUG_SHOW_INFO) 10776 Log.v(TAG, " Class=" + a.info.name); 10777 final int NI = a.intents.size(); 10778 for (int j=0; j<NI; j++) { 10779 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10780 if ("activity".equals(type)) { 10781 final PackageSetting ps = 10782 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10783 final List<PackageParser.Activity> systemActivities = 10784 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10785 adjustPriority(systemActivities, intent); 10786 } 10787 if (DEBUG_SHOW_INFO) { 10788 Log.v(TAG, " IntentFilter:"); 10789 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10790 } 10791 if (!intent.debugCheck()) { 10792 Log.w(TAG, "==> For Activity " + a.info.name); 10793 } 10794 addFilter(intent); 10795 } 10796 } 10797 10798 public final void removeActivity(PackageParser.Activity a, String type) { 10799 mActivities.remove(a.getComponentName()); 10800 if (DEBUG_SHOW_INFO) { 10801 Log.v(TAG, " " + type + " " 10802 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10803 : a.info.name) + ":"); 10804 Log.v(TAG, " Class=" + a.info.name); 10805 } 10806 final int NI = a.intents.size(); 10807 for (int j=0; j<NI; j++) { 10808 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10809 if (DEBUG_SHOW_INFO) { 10810 Log.v(TAG, " IntentFilter:"); 10811 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10812 } 10813 removeFilter(intent); 10814 } 10815 } 10816 10817 @Override 10818 protected boolean allowFilterResult( 10819 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10820 ActivityInfo filterAi = filter.activity.info; 10821 for (int i=dest.size()-1; i>=0; i--) { 10822 ActivityInfo destAi = dest.get(i).activityInfo; 10823 if (destAi.name == filterAi.name 10824 && destAi.packageName == filterAi.packageName) { 10825 return false; 10826 } 10827 } 10828 return true; 10829 } 10830 10831 @Override 10832 protected ActivityIntentInfo[] newArray(int size) { 10833 return new ActivityIntentInfo[size]; 10834 } 10835 10836 @Override 10837 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10838 if (!sUserManager.exists(userId)) return true; 10839 PackageParser.Package p = filter.activity.owner; 10840 if (p != null) { 10841 PackageSetting ps = (PackageSetting)p.mExtras; 10842 if (ps != null) { 10843 // System apps are never considered stopped for purposes of 10844 // filtering, because there may be no way for the user to 10845 // actually re-launch them. 10846 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10847 && ps.getStopped(userId); 10848 } 10849 } 10850 return false; 10851 } 10852 10853 @Override 10854 protected boolean isPackageForFilter(String packageName, 10855 PackageParser.ActivityIntentInfo info) { 10856 return packageName.equals(info.activity.owner.packageName); 10857 } 10858 10859 @Override 10860 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10861 int match, int userId) { 10862 if (!sUserManager.exists(userId)) return null; 10863 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10864 return null; 10865 } 10866 final PackageParser.Activity activity = info.activity; 10867 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10868 if (ps == null) { 10869 return null; 10870 } 10871 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10872 ps.readUserState(userId), userId); 10873 if (ai == null) { 10874 return null; 10875 } 10876 final ResolveInfo res = new ResolveInfo(); 10877 res.activityInfo = ai; 10878 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10879 res.filter = info; 10880 } 10881 if (info != null) { 10882 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10883 } 10884 res.priority = info.getPriority(); 10885 res.preferredOrder = activity.owner.mPreferredOrder; 10886 //System.out.println("Result: " + res.activityInfo.className + 10887 // " = " + res.priority); 10888 res.match = match; 10889 res.isDefault = info.hasDefault; 10890 res.labelRes = info.labelRes; 10891 res.nonLocalizedLabel = info.nonLocalizedLabel; 10892 if (userNeedsBadging(userId)) { 10893 res.noResourceId = true; 10894 } else { 10895 res.icon = info.icon; 10896 } 10897 res.iconResourceId = info.icon; 10898 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10899 return res; 10900 } 10901 10902 @Override 10903 protected void sortResults(List<ResolveInfo> results) { 10904 Collections.sort(results, mResolvePrioritySorter); 10905 } 10906 10907 @Override 10908 protected void dumpFilter(PrintWriter out, String prefix, 10909 PackageParser.ActivityIntentInfo filter) { 10910 out.print(prefix); out.print( 10911 Integer.toHexString(System.identityHashCode(filter.activity))); 10912 out.print(' '); 10913 filter.activity.printComponentShortName(out); 10914 out.print(" filter "); 10915 out.println(Integer.toHexString(System.identityHashCode(filter))); 10916 } 10917 10918 @Override 10919 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10920 return filter.activity; 10921 } 10922 10923 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10924 PackageParser.Activity activity = (PackageParser.Activity)label; 10925 out.print(prefix); out.print( 10926 Integer.toHexString(System.identityHashCode(activity))); 10927 out.print(' '); 10928 activity.printComponentShortName(out); 10929 if (count > 1) { 10930 out.print(" ("); out.print(count); out.print(" filters)"); 10931 } 10932 out.println(); 10933 } 10934 10935 // Keys are String (activity class name), values are Activity. 10936 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10937 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10938 private int mFlags; 10939 } 10940 10941 private final class ServiceIntentResolver 10942 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10943 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10944 boolean defaultOnly, int userId) { 10945 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10946 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10947 } 10948 10949 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10950 int userId) { 10951 if (!sUserManager.exists(userId)) return null; 10952 mFlags = flags; 10953 return super.queryIntent(intent, resolvedType, 10954 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10955 } 10956 10957 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10958 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10959 if (!sUserManager.exists(userId)) return null; 10960 if (packageServices == null) { 10961 return null; 10962 } 10963 mFlags = flags; 10964 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10965 final int N = packageServices.size(); 10966 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10967 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10968 10969 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10970 for (int i = 0; i < N; ++i) { 10971 intentFilters = packageServices.get(i).intents; 10972 if (intentFilters != null && intentFilters.size() > 0) { 10973 PackageParser.ServiceIntentInfo[] array = 10974 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10975 intentFilters.toArray(array); 10976 listCut.add(array); 10977 } 10978 } 10979 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10980 } 10981 10982 public final void addService(PackageParser.Service s) { 10983 mServices.put(s.getComponentName(), s); 10984 if (DEBUG_SHOW_INFO) { 10985 Log.v(TAG, " " 10986 + (s.info.nonLocalizedLabel != null 10987 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10988 Log.v(TAG, " Class=" + s.info.name); 10989 } 10990 final int NI = s.intents.size(); 10991 int j; 10992 for (j=0; j<NI; j++) { 10993 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10994 if (DEBUG_SHOW_INFO) { 10995 Log.v(TAG, " IntentFilter:"); 10996 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10997 } 10998 if (!intent.debugCheck()) { 10999 Log.w(TAG, "==> For Service " + s.info.name); 11000 } 11001 addFilter(intent); 11002 } 11003 } 11004 11005 public final void removeService(PackageParser.Service s) { 11006 mServices.remove(s.getComponentName()); 11007 if (DEBUG_SHOW_INFO) { 11008 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11009 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11010 Log.v(TAG, " Class=" + s.info.name); 11011 } 11012 final int NI = s.intents.size(); 11013 int j; 11014 for (j=0; j<NI; j++) { 11015 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11016 if (DEBUG_SHOW_INFO) { 11017 Log.v(TAG, " IntentFilter:"); 11018 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11019 } 11020 removeFilter(intent); 11021 } 11022 } 11023 11024 @Override 11025 protected boolean allowFilterResult( 11026 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11027 ServiceInfo filterSi = filter.service.info; 11028 for (int i=dest.size()-1; i>=0; i--) { 11029 ServiceInfo destAi = dest.get(i).serviceInfo; 11030 if (destAi.name == filterSi.name 11031 && destAi.packageName == filterSi.packageName) { 11032 return false; 11033 } 11034 } 11035 return true; 11036 } 11037 11038 @Override 11039 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11040 return new PackageParser.ServiceIntentInfo[size]; 11041 } 11042 11043 @Override 11044 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11045 if (!sUserManager.exists(userId)) return true; 11046 PackageParser.Package p = filter.service.owner; 11047 if (p != null) { 11048 PackageSetting ps = (PackageSetting)p.mExtras; 11049 if (ps != null) { 11050 // System apps are never considered stopped for purposes of 11051 // filtering, because there may be no way for the user to 11052 // actually re-launch them. 11053 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11054 && ps.getStopped(userId); 11055 } 11056 } 11057 return false; 11058 } 11059 11060 @Override 11061 protected boolean isPackageForFilter(String packageName, 11062 PackageParser.ServiceIntentInfo info) { 11063 return packageName.equals(info.service.owner.packageName); 11064 } 11065 11066 @Override 11067 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11068 int match, int userId) { 11069 if (!sUserManager.exists(userId)) return null; 11070 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11071 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11072 return null; 11073 } 11074 final PackageParser.Service service = info.service; 11075 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11076 if (ps == null) { 11077 return null; 11078 } 11079 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11080 ps.readUserState(userId), userId); 11081 if (si == null) { 11082 return null; 11083 } 11084 final ResolveInfo res = new ResolveInfo(); 11085 res.serviceInfo = si; 11086 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11087 res.filter = filter; 11088 } 11089 res.priority = info.getPriority(); 11090 res.preferredOrder = service.owner.mPreferredOrder; 11091 res.match = match; 11092 res.isDefault = info.hasDefault; 11093 res.labelRes = info.labelRes; 11094 res.nonLocalizedLabel = info.nonLocalizedLabel; 11095 res.icon = info.icon; 11096 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11097 return res; 11098 } 11099 11100 @Override 11101 protected void sortResults(List<ResolveInfo> results) { 11102 Collections.sort(results, mResolvePrioritySorter); 11103 } 11104 11105 @Override 11106 protected void dumpFilter(PrintWriter out, String prefix, 11107 PackageParser.ServiceIntentInfo filter) { 11108 out.print(prefix); out.print( 11109 Integer.toHexString(System.identityHashCode(filter.service))); 11110 out.print(' '); 11111 filter.service.printComponentShortName(out); 11112 out.print(" filter "); 11113 out.println(Integer.toHexString(System.identityHashCode(filter))); 11114 } 11115 11116 @Override 11117 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11118 return filter.service; 11119 } 11120 11121 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11122 PackageParser.Service service = (PackageParser.Service)label; 11123 out.print(prefix); out.print( 11124 Integer.toHexString(System.identityHashCode(service))); 11125 out.print(' '); 11126 service.printComponentShortName(out); 11127 if (count > 1) { 11128 out.print(" ("); out.print(count); out.print(" filters)"); 11129 } 11130 out.println(); 11131 } 11132 11133// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11134// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11135// final List<ResolveInfo> retList = Lists.newArrayList(); 11136// while (i.hasNext()) { 11137// final ResolveInfo resolveInfo = (ResolveInfo) i; 11138// if (isEnabledLP(resolveInfo.serviceInfo)) { 11139// retList.add(resolveInfo); 11140// } 11141// } 11142// return retList; 11143// } 11144 11145 // Keys are String (activity class name), values are Activity. 11146 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11147 = new ArrayMap<ComponentName, PackageParser.Service>(); 11148 private int mFlags; 11149 }; 11150 11151 private final class ProviderIntentResolver 11152 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11153 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11154 boolean defaultOnly, int userId) { 11155 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11156 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11157 } 11158 11159 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11160 int userId) { 11161 if (!sUserManager.exists(userId)) 11162 return null; 11163 mFlags = flags; 11164 return super.queryIntent(intent, resolvedType, 11165 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11166 } 11167 11168 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11169 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11170 if (!sUserManager.exists(userId)) 11171 return null; 11172 if (packageProviders == null) { 11173 return null; 11174 } 11175 mFlags = flags; 11176 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11177 final int N = packageProviders.size(); 11178 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11179 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11180 11181 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11182 for (int i = 0; i < N; ++i) { 11183 intentFilters = packageProviders.get(i).intents; 11184 if (intentFilters != null && intentFilters.size() > 0) { 11185 PackageParser.ProviderIntentInfo[] array = 11186 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11187 intentFilters.toArray(array); 11188 listCut.add(array); 11189 } 11190 } 11191 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11192 } 11193 11194 public final void addProvider(PackageParser.Provider p) { 11195 if (mProviders.containsKey(p.getComponentName())) { 11196 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11197 return; 11198 } 11199 11200 mProviders.put(p.getComponentName(), p); 11201 if (DEBUG_SHOW_INFO) { 11202 Log.v(TAG, " " 11203 + (p.info.nonLocalizedLabel != null 11204 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11205 Log.v(TAG, " Class=" + p.info.name); 11206 } 11207 final int NI = p.intents.size(); 11208 int j; 11209 for (j = 0; j < NI; j++) { 11210 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11211 if (DEBUG_SHOW_INFO) { 11212 Log.v(TAG, " IntentFilter:"); 11213 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11214 } 11215 if (!intent.debugCheck()) { 11216 Log.w(TAG, "==> For Provider " + p.info.name); 11217 } 11218 addFilter(intent); 11219 } 11220 } 11221 11222 public final void removeProvider(PackageParser.Provider p) { 11223 mProviders.remove(p.getComponentName()); 11224 if (DEBUG_SHOW_INFO) { 11225 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11226 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11227 Log.v(TAG, " Class=" + p.info.name); 11228 } 11229 final int NI = p.intents.size(); 11230 int j; 11231 for (j = 0; j < NI; j++) { 11232 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11233 if (DEBUG_SHOW_INFO) { 11234 Log.v(TAG, " IntentFilter:"); 11235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11236 } 11237 removeFilter(intent); 11238 } 11239 } 11240 11241 @Override 11242 protected boolean allowFilterResult( 11243 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11244 ProviderInfo filterPi = filter.provider.info; 11245 for (int i = dest.size() - 1; i >= 0; i--) { 11246 ProviderInfo destPi = dest.get(i).providerInfo; 11247 if (destPi.name == filterPi.name 11248 && destPi.packageName == filterPi.packageName) { 11249 return false; 11250 } 11251 } 11252 return true; 11253 } 11254 11255 @Override 11256 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11257 return new PackageParser.ProviderIntentInfo[size]; 11258 } 11259 11260 @Override 11261 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11262 if (!sUserManager.exists(userId)) 11263 return true; 11264 PackageParser.Package p = filter.provider.owner; 11265 if (p != null) { 11266 PackageSetting ps = (PackageSetting) p.mExtras; 11267 if (ps != null) { 11268 // System apps are never considered stopped for purposes of 11269 // filtering, because there may be no way for the user to 11270 // actually re-launch them. 11271 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11272 && ps.getStopped(userId); 11273 } 11274 } 11275 return false; 11276 } 11277 11278 @Override 11279 protected boolean isPackageForFilter(String packageName, 11280 PackageParser.ProviderIntentInfo info) { 11281 return packageName.equals(info.provider.owner.packageName); 11282 } 11283 11284 @Override 11285 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11286 int match, int userId) { 11287 if (!sUserManager.exists(userId)) 11288 return null; 11289 final PackageParser.ProviderIntentInfo info = filter; 11290 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11291 return null; 11292 } 11293 final PackageParser.Provider provider = info.provider; 11294 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11295 if (ps == null) { 11296 return null; 11297 } 11298 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11299 ps.readUserState(userId), userId); 11300 if (pi == null) { 11301 return null; 11302 } 11303 final ResolveInfo res = new ResolveInfo(); 11304 res.providerInfo = pi; 11305 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11306 res.filter = filter; 11307 } 11308 res.priority = info.getPriority(); 11309 res.preferredOrder = provider.owner.mPreferredOrder; 11310 res.match = match; 11311 res.isDefault = info.hasDefault; 11312 res.labelRes = info.labelRes; 11313 res.nonLocalizedLabel = info.nonLocalizedLabel; 11314 res.icon = info.icon; 11315 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11316 return res; 11317 } 11318 11319 @Override 11320 protected void sortResults(List<ResolveInfo> results) { 11321 Collections.sort(results, mResolvePrioritySorter); 11322 } 11323 11324 @Override 11325 protected void dumpFilter(PrintWriter out, String prefix, 11326 PackageParser.ProviderIntentInfo filter) { 11327 out.print(prefix); 11328 out.print( 11329 Integer.toHexString(System.identityHashCode(filter.provider))); 11330 out.print(' '); 11331 filter.provider.printComponentShortName(out); 11332 out.print(" filter "); 11333 out.println(Integer.toHexString(System.identityHashCode(filter))); 11334 } 11335 11336 @Override 11337 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11338 return filter.provider; 11339 } 11340 11341 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11342 PackageParser.Provider provider = (PackageParser.Provider)label; 11343 out.print(prefix); out.print( 11344 Integer.toHexString(System.identityHashCode(provider))); 11345 out.print(' '); 11346 provider.printComponentShortName(out); 11347 if (count > 1) { 11348 out.print(" ("); out.print(count); out.print(" filters)"); 11349 } 11350 out.println(); 11351 } 11352 11353 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11354 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11355 private int mFlags; 11356 } 11357 11358 private static final class EphemeralIntentResolver 11359 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11360 @Override 11361 protected EphemeralResolveIntentInfo[] newArray(int size) { 11362 return new EphemeralResolveIntentInfo[size]; 11363 } 11364 11365 @Override 11366 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11367 return true; 11368 } 11369 11370 @Override 11371 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11372 int userId) { 11373 if (!sUserManager.exists(userId)) { 11374 return null; 11375 } 11376 return info.getEphemeralResolveInfo(); 11377 } 11378 } 11379 11380 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11381 new Comparator<ResolveInfo>() { 11382 public int compare(ResolveInfo r1, ResolveInfo r2) { 11383 int v1 = r1.priority; 11384 int v2 = r2.priority; 11385 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11386 if (v1 != v2) { 11387 return (v1 > v2) ? -1 : 1; 11388 } 11389 v1 = r1.preferredOrder; 11390 v2 = r2.preferredOrder; 11391 if (v1 != v2) { 11392 return (v1 > v2) ? -1 : 1; 11393 } 11394 if (r1.isDefault != r2.isDefault) { 11395 return r1.isDefault ? -1 : 1; 11396 } 11397 v1 = r1.match; 11398 v2 = r2.match; 11399 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11400 if (v1 != v2) { 11401 return (v1 > v2) ? -1 : 1; 11402 } 11403 if (r1.system != r2.system) { 11404 return r1.system ? -1 : 1; 11405 } 11406 if (r1.activityInfo != null) { 11407 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11408 } 11409 if (r1.serviceInfo != null) { 11410 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11411 } 11412 if (r1.providerInfo != null) { 11413 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11414 } 11415 return 0; 11416 } 11417 }; 11418 11419 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11420 new Comparator<ProviderInfo>() { 11421 public int compare(ProviderInfo p1, ProviderInfo p2) { 11422 final int v1 = p1.initOrder; 11423 final int v2 = p2.initOrder; 11424 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11425 } 11426 }; 11427 11428 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11429 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11430 final int[] userIds) { 11431 mHandler.post(new Runnable() { 11432 @Override 11433 public void run() { 11434 try { 11435 final IActivityManager am = ActivityManagerNative.getDefault(); 11436 if (am == null) return; 11437 final int[] resolvedUserIds; 11438 if (userIds == null) { 11439 resolvedUserIds = am.getRunningUserIds(); 11440 } else { 11441 resolvedUserIds = userIds; 11442 } 11443 for (int id : resolvedUserIds) { 11444 final Intent intent = new Intent(action, 11445 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11446 if (extras != null) { 11447 intent.putExtras(extras); 11448 } 11449 if (targetPkg != null) { 11450 intent.setPackage(targetPkg); 11451 } 11452 // Modify the UID when posting to other users 11453 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11454 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11455 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11456 intent.putExtra(Intent.EXTRA_UID, uid); 11457 } 11458 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11459 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11460 if (DEBUG_BROADCASTS) { 11461 RuntimeException here = new RuntimeException("here"); 11462 here.fillInStackTrace(); 11463 Slog.d(TAG, "Sending to user " + id + ": " 11464 + intent.toShortString(false, true, false, false) 11465 + " " + intent.getExtras(), here); 11466 } 11467 am.broadcastIntent(null, intent, null, finishedReceiver, 11468 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11469 null, finishedReceiver != null, false, id); 11470 } 11471 } catch (RemoteException ex) { 11472 } 11473 } 11474 }); 11475 } 11476 11477 /** 11478 * Check if the external storage media is available. This is true if there 11479 * is a mounted external storage medium or if the external storage is 11480 * emulated. 11481 */ 11482 private boolean isExternalMediaAvailable() { 11483 return mMediaMounted || Environment.isExternalStorageEmulated(); 11484 } 11485 11486 @Override 11487 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11488 // writer 11489 synchronized (mPackages) { 11490 if (!isExternalMediaAvailable()) { 11491 // If the external storage is no longer mounted at this point, 11492 // the caller may not have been able to delete all of this 11493 // packages files and can not delete any more. Bail. 11494 return null; 11495 } 11496 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11497 if (lastPackage != null) { 11498 pkgs.remove(lastPackage); 11499 } 11500 if (pkgs.size() > 0) { 11501 return pkgs.get(0); 11502 } 11503 } 11504 return null; 11505 } 11506 11507 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11508 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11509 userId, andCode ? 1 : 0, packageName); 11510 if (mSystemReady) { 11511 msg.sendToTarget(); 11512 } else { 11513 if (mPostSystemReadyMessages == null) { 11514 mPostSystemReadyMessages = new ArrayList<>(); 11515 } 11516 mPostSystemReadyMessages.add(msg); 11517 } 11518 } 11519 11520 void startCleaningPackages() { 11521 // reader 11522 if (!isExternalMediaAvailable()) { 11523 return; 11524 } 11525 synchronized (mPackages) { 11526 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11527 return; 11528 } 11529 } 11530 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11531 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11532 IActivityManager am = ActivityManagerNative.getDefault(); 11533 if (am != null) { 11534 try { 11535 am.startService(null, intent, null, mContext.getOpPackageName(), 11536 UserHandle.USER_SYSTEM); 11537 } catch (RemoteException e) { 11538 } 11539 } 11540 } 11541 11542 @Override 11543 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11544 int installFlags, String installerPackageName, int userId) { 11545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11546 11547 final int callingUid = Binder.getCallingUid(); 11548 enforceCrossUserPermission(callingUid, userId, 11549 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11550 11551 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11552 try { 11553 if (observer != null) { 11554 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11555 } 11556 } catch (RemoteException re) { 11557 } 11558 return; 11559 } 11560 11561 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11562 installFlags |= PackageManager.INSTALL_FROM_ADB; 11563 11564 } else { 11565 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11566 // about installerPackageName. 11567 11568 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11569 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11570 } 11571 11572 UserHandle user; 11573 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11574 user = UserHandle.ALL; 11575 } else { 11576 user = new UserHandle(userId); 11577 } 11578 11579 // Only system components can circumvent runtime permissions when installing. 11580 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11581 && mContext.checkCallingOrSelfPermission(Manifest.permission 11582 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11583 throw new SecurityException("You need the " 11584 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11585 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11586 } 11587 11588 final File originFile = new File(originPath); 11589 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11590 11591 final Message msg = mHandler.obtainMessage(INIT_COPY); 11592 final VerificationInfo verificationInfo = new VerificationInfo( 11593 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11594 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11595 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11596 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11597 null /*certificates*/); 11598 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11599 msg.obj = params; 11600 11601 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11602 System.identityHashCode(msg.obj)); 11603 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11604 System.identityHashCode(msg.obj)); 11605 11606 mHandler.sendMessage(msg); 11607 } 11608 11609 void installStage(String packageName, File stagedDir, String stagedCid, 11610 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11611 String installerPackageName, int installerUid, UserHandle user, 11612 Certificate[][] certificates) { 11613 if (DEBUG_EPHEMERAL) { 11614 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11615 Slog.d(TAG, "Ephemeral install of " + packageName); 11616 } 11617 } 11618 final VerificationInfo verificationInfo = new VerificationInfo( 11619 sessionParams.originatingUri, sessionParams.referrerUri, 11620 sessionParams.originatingUid, installerUid); 11621 11622 final OriginInfo origin; 11623 if (stagedDir != null) { 11624 origin = OriginInfo.fromStagedFile(stagedDir); 11625 } else { 11626 origin = OriginInfo.fromStagedContainer(stagedCid); 11627 } 11628 11629 final Message msg = mHandler.obtainMessage(INIT_COPY); 11630 final InstallParams params = new InstallParams(origin, null, observer, 11631 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11632 verificationInfo, user, sessionParams.abiOverride, 11633 sessionParams.grantedRuntimePermissions, certificates); 11634 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11635 msg.obj = params; 11636 11637 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11638 System.identityHashCode(msg.obj)); 11639 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11640 System.identityHashCode(msg.obj)); 11641 11642 mHandler.sendMessage(msg); 11643 } 11644 11645 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11646 int userId) { 11647 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11648 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11649 } 11650 11651 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11652 int appId, int userId) { 11653 Bundle extras = new Bundle(1); 11654 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11655 11656 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11657 packageName, extras, 0, null, null, new int[] {userId}); 11658 try { 11659 IActivityManager am = ActivityManagerNative.getDefault(); 11660 if (isSystem && am.isUserRunning(userId, 0)) { 11661 // The just-installed/enabled app is bundled on the system, so presumed 11662 // to be able to run automatically without needing an explicit launch. 11663 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11664 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11665 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11666 .setPackage(packageName); 11667 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11668 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11669 } 11670 } catch (RemoteException e) { 11671 // shouldn't happen 11672 Slog.w(TAG, "Unable to bootstrap installed package", e); 11673 } 11674 } 11675 11676 @Override 11677 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11678 int userId) { 11679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11680 PackageSetting pkgSetting; 11681 final int uid = Binder.getCallingUid(); 11682 enforceCrossUserPermission(uid, userId, 11683 true /* requireFullPermission */, true /* checkShell */, 11684 "setApplicationHiddenSetting for user " + userId); 11685 11686 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11687 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11688 return false; 11689 } 11690 11691 long callingId = Binder.clearCallingIdentity(); 11692 try { 11693 boolean sendAdded = false; 11694 boolean sendRemoved = false; 11695 // writer 11696 synchronized (mPackages) { 11697 pkgSetting = mSettings.mPackages.get(packageName); 11698 if (pkgSetting == null) { 11699 return false; 11700 } 11701 // Only allow protected packages to hide themselves. 11702 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11703 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11704 Slog.w(TAG, "Not hiding protected package: " + packageName); 11705 return false; 11706 } 11707 if (pkgSetting.getHidden(userId) != hidden) { 11708 pkgSetting.setHidden(hidden, userId); 11709 mSettings.writePackageRestrictionsLPr(userId); 11710 if (hidden) { 11711 sendRemoved = true; 11712 } else { 11713 sendAdded = true; 11714 } 11715 } 11716 } 11717 if (sendAdded) { 11718 sendPackageAddedForUser(packageName, pkgSetting, userId); 11719 return true; 11720 } 11721 if (sendRemoved) { 11722 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11723 "hiding pkg"); 11724 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11725 return true; 11726 } 11727 } finally { 11728 Binder.restoreCallingIdentity(callingId); 11729 } 11730 return false; 11731 } 11732 11733 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11734 int userId) { 11735 final PackageRemovedInfo info = new PackageRemovedInfo(); 11736 info.removedPackage = packageName; 11737 info.removedUsers = new int[] {userId}; 11738 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11739 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11740 } 11741 11742 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11743 if (pkgList.length > 0) { 11744 Bundle extras = new Bundle(1); 11745 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11746 11747 sendPackageBroadcast( 11748 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11749 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11750 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11751 new int[] {userId}); 11752 } 11753 } 11754 11755 /** 11756 * Returns true if application is not found or there was an error. Otherwise it returns 11757 * the hidden state of the package for the given user. 11758 */ 11759 @Override 11760 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11762 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11763 true /* requireFullPermission */, false /* checkShell */, 11764 "getApplicationHidden for user " + userId); 11765 PackageSetting pkgSetting; 11766 long callingId = Binder.clearCallingIdentity(); 11767 try { 11768 // writer 11769 synchronized (mPackages) { 11770 pkgSetting = mSettings.mPackages.get(packageName); 11771 if (pkgSetting == null) { 11772 return true; 11773 } 11774 return pkgSetting.getHidden(userId); 11775 } 11776 } finally { 11777 Binder.restoreCallingIdentity(callingId); 11778 } 11779 } 11780 11781 /** 11782 * @hide 11783 */ 11784 @Override 11785 public int installExistingPackageAsUser(String packageName, int userId) { 11786 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11787 null); 11788 PackageSetting pkgSetting; 11789 final int uid = Binder.getCallingUid(); 11790 enforceCrossUserPermission(uid, userId, 11791 true /* requireFullPermission */, true /* checkShell */, 11792 "installExistingPackage for user " + userId); 11793 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11794 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11795 } 11796 11797 long callingId = Binder.clearCallingIdentity(); 11798 try { 11799 boolean installed = false; 11800 11801 // writer 11802 synchronized (mPackages) { 11803 pkgSetting = mSettings.mPackages.get(packageName); 11804 if (pkgSetting == null) { 11805 return PackageManager.INSTALL_FAILED_INVALID_URI; 11806 } 11807 if (!pkgSetting.getInstalled(userId)) { 11808 pkgSetting.setInstalled(true, userId); 11809 pkgSetting.setHidden(false, userId); 11810 mSettings.writePackageRestrictionsLPr(userId); 11811 installed = true; 11812 } 11813 } 11814 11815 if (installed) { 11816 if (pkgSetting.pkg != null) { 11817 synchronized (mInstallLock) { 11818 // We don't need to freeze for a brand new install 11819 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11820 } 11821 } 11822 sendPackageAddedForUser(packageName, pkgSetting, userId); 11823 } 11824 } finally { 11825 Binder.restoreCallingIdentity(callingId); 11826 } 11827 11828 return PackageManager.INSTALL_SUCCEEDED; 11829 } 11830 11831 boolean isUserRestricted(int userId, String restrictionKey) { 11832 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11833 if (restrictions.getBoolean(restrictionKey, false)) { 11834 Log.w(TAG, "User is restricted: " + restrictionKey); 11835 return true; 11836 } 11837 return false; 11838 } 11839 11840 @Override 11841 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11842 int userId) { 11843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11844 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11845 true /* requireFullPermission */, true /* checkShell */, 11846 "setPackagesSuspended for user " + userId); 11847 11848 if (ArrayUtils.isEmpty(packageNames)) { 11849 return packageNames; 11850 } 11851 11852 // List of package names for whom the suspended state has changed. 11853 List<String> changedPackages = new ArrayList<>(packageNames.length); 11854 // List of package names for whom the suspended state is not set as requested in this 11855 // method. 11856 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11857 long callingId = Binder.clearCallingIdentity(); 11858 try { 11859 for (int i = 0; i < packageNames.length; i++) { 11860 String packageName = packageNames[i]; 11861 boolean changed = false; 11862 final int appId; 11863 synchronized (mPackages) { 11864 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11865 if (pkgSetting == null) { 11866 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11867 + "\". Skipping suspending/un-suspending."); 11868 unactionedPackages.add(packageName); 11869 continue; 11870 } 11871 appId = pkgSetting.appId; 11872 if (pkgSetting.getSuspended(userId) != suspended) { 11873 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11874 unactionedPackages.add(packageName); 11875 continue; 11876 } 11877 pkgSetting.setSuspended(suspended, userId); 11878 mSettings.writePackageRestrictionsLPr(userId); 11879 changed = true; 11880 changedPackages.add(packageName); 11881 } 11882 } 11883 11884 if (changed && suspended) { 11885 killApplication(packageName, UserHandle.getUid(userId, appId), 11886 "suspending package"); 11887 } 11888 } 11889 } finally { 11890 Binder.restoreCallingIdentity(callingId); 11891 } 11892 11893 if (!changedPackages.isEmpty()) { 11894 sendPackagesSuspendedForUser(changedPackages.toArray( 11895 new String[changedPackages.size()]), userId, suspended); 11896 } 11897 11898 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11899 } 11900 11901 @Override 11902 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11903 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11904 true /* requireFullPermission */, false /* checkShell */, 11905 "isPackageSuspendedForUser for user " + userId); 11906 synchronized (mPackages) { 11907 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11908 if (pkgSetting == null) { 11909 throw new IllegalArgumentException("Unknown target package: " + packageName); 11910 } 11911 return pkgSetting.getSuspended(userId); 11912 } 11913 } 11914 11915 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11916 if (isPackageDeviceAdmin(packageName, userId)) { 11917 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11918 + "\": has an active device admin"); 11919 return false; 11920 } 11921 11922 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11923 if (packageName.equals(activeLauncherPackageName)) { 11924 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11925 + "\": contains the active launcher"); 11926 return false; 11927 } 11928 11929 if (packageName.equals(mRequiredInstallerPackage)) { 11930 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11931 + "\": required for package installation"); 11932 return false; 11933 } 11934 11935 if (packageName.equals(mRequiredVerifierPackage)) { 11936 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11937 + "\": required for package verification"); 11938 return false; 11939 } 11940 11941 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11942 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11943 + "\": is the default dialer"); 11944 return false; 11945 } 11946 11947 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11948 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11949 + "\": protected package"); 11950 return false; 11951 } 11952 11953 return true; 11954 } 11955 11956 private String getActiveLauncherPackageName(int userId) { 11957 Intent intent = new Intent(Intent.ACTION_MAIN); 11958 intent.addCategory(Intent.CATEGORY_HOME); 11959 ResolveInfo resolveInfo = resolveIntent( 11960 intent, 11961 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11962 PackageManager.MATCH_DEFAULT_ONLY, 11963 userId); 11964 11965 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11966 } 11967 11968 private String getDefaultDialerPackageName(int userId) { 11969 synchronized (mPackages) { 11970 return mSettings.getDefaultDialerPackageNameLPw(userId); 11971 } 11972 } 11973 11974 @Override 11975 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11976 mContext.enforceCallingOrSelfPermission( 11977 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11978 "Only package verification agents can verify applications"); 11979 11980 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11981 final PackageVerificationResponse response = new PackageVerificationResponse( 11982 verificationCode, Binder.getCallingUid()); 11983 msg.arg1 = id; 11984 msg.obj = response; 11985 mHandler.sendMessage(msg); 11986 } 11987 11988 @Override 11989 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11990 long millisecondsToDelay) { 11991 mContext.enforceCallingOrSelfPermission( 11992 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11993 "Only package verification agents can extend verification timeouts"); 11994 11995 final PackageVerificationState state = mPendingVerification.get(id); 11996 final PackageVerificationResponse response = new PackageVerificationResponse( 11997 verificationCodeAtTimeout, Binder.getCallingUid()); 11998 11999 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12000 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12001 } 12002 if (millisecondsToDelay < 0) { 12003 millisecondsToDelay = 0; 12004 } 12005 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12006 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12007 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12008 } 12009 12010 if ((state != null) && !state.timeoutExtended()) { 12011 state.extendTimeout(); 12012 12013 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12014 msg.arg1 = id; 12015 msg.obj = response; 12016 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12017 } 12018 } 12019 12020 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12021 int verificationCode, UserHandle user) { 12022 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12023 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12024 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12025 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12026 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12027 12028 mContext.sendBroadcastAsUser(intent, user, 12029 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12030 } 12031 12032 private ComponentName matchComponentForVerifier(String packageName, 12033 List<ResolveInfo> receivers) { 12034 ActivityInfo targetReceiver = null; 12035 12036 final int NR = receivers.size(); 12037 for (int i = 0; i < NR; i++) { 12038 final ResolveInfo info = receivers.get(i); 12039 if (info.activityInfo == null) { 12040 continue; 12041 } 12042 12043 if (packageName.equals(info.activityInfo.packageName)) { 12044 targetReceiver = info.activityInfo; 12045 break; 12046 } 12047 } 12048 12049 if (targetReceiver == null) { 12050 return null; 12051 } 12052 12053 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12054 } 12055 12056 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12057 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12058 if (pkgInfo.verifiers.length == 0) { 12059 return null; 12060 } 12061 12062 final int N = pkgInfo.verifiers.length; 12063 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12064 for (int i = 0; i < N; i++) { 12065 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12066 12067 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12068 receivers); 12069 if (comp == null) { 12070 continue; 12071 } 12072 12073 final int verifierUid = getUidForVerifier(verifierInfo); 12074 if (verifierUid == -1) { 12075 continue; 12076 } 12077 12078 if (DEBUG_VERIFY) { 12079 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12080 + " with the correct signature"); 12081 } 12082 sufficientVerifiers.add(comp); 12083 verificationState.addSufficientVerifier(verifierUid); 12084 } 12085 12086 return sufficientVerifiers; 12087 } 12088 12089 private int getUidForVerifier(VerifierInfo verifierInfo) { 12090 synchronized (mPackages) { 12091 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12092 if (pkg == null) { 12093 return -1; 12094 } else if (pkg.mSignatures.length != 1) { 12095 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12096 + " has more than one signature; ignoring"); 12097 return -1; 12098 } 12099 12100 /* 12101 * If the public key of the package's signature does not match 12102 * our expected public key, then this is a different package and 12103 * we should skip. 12104 */ 12105 12106 final byte[] expectedPublicKey; 12107 try { 12108 final Signature verifierSig = pkg.mSignatures[0]; 12109 final PublicKey publicKey = verifierSig.getPublicKey(); 12110 expectedPublicKey = publicKey.getEncoded(); 12111 } catch (CertificateException e) { 12112 return -1; 12113 } 12114 12115 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12116 12117 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12118 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12119 + " does not have the expected public key; ignoring"); 12120 return -1; 12121 } 12122 12123 return pkg.applicationInfo.uid; 12124 } 12125 } 12126 12127 @Override 12128 public void finishPackageInstall(int token, boolean didLaunch) { 12129 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12130 12131 if (DEBUG_INSTALL) { 12132 Slog.v(TAG, "BM finishing package install for " + token); 12133 } 12134 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12135 12136 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12137 mHandler.sendMessage(msg); 12138 } 12139 12140 /** 12141 * Get the verification agent timeout. 12142 * 12143 * @return verification timeout in milliseconds 12144 */ 12145 private long getVerificationTimeout() { 12146 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12147 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12148 DEFAULT_VERIFICATION_TIMEOUT); 12149 } 12150 12151 /** 12152 * Get the default verification agent response code. 12153 * 12154 * @return default verification response code 12155 */ 12156 private int getDefaultVerificationResponse() { 12157 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12158 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12159 DEFAULT_VERIFICATION_RESPONSE); 12160 } 12161 12162 /** 12163 * Check whether or not package verification has been enabled. 12164 * 12165 * @return true if verification should be performed 12166 */ 12167 private boolean isVerificationEnabled(int userId, int installFlags) { 12168 if (!DEFAULT_VERIFY_ENABLE) { 12169 return false; 12170 } 12171 // Ephemeral apps don't get the full verification treatment 12172 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12173 if (DEBUG_EPHEMERAL) { 12174 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12175 } 12176 return false; 12177 } 12178 12179 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12180 12181 // Check if installing from ADB 12182 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12183 // Do not run verification in a test harness environment 12184 if (ActivityManager.isRunningInTestHarness()) { 12185 return false; 12186 } 12187 if (ensureVerifyAppsEnabled) { 12188 return true; 12189 } 12190 // Check if the developer does not want package verification for ADB installs 12191 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12192 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12193 return false; 12194 } 12195 } 12196 12197 if (ensureVerifyAppsEnabled) { 12198 return true; 12199 } 12200 12201 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12202 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12203 } 12204 12205 @Override 12206 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12207 throws RemoteException { 12208 mContext.enforceCallingOrSelfPermission( 12209 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12210 "Only intentfilter verification agents can verify applications"); 12211 12212 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12213 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12214 Binder.getCallingUid(), verificationCode, failedDomains); 12215 msg.arg1 = id; 12216 msg.obj = response; 12217 mHandler.sendMessage(msg); 12218 } 12219 12220 @Override 12221 public int getIntentVerificationStatus(String packageName, int userId) { 12222 synchronized (mPackages) { 12223 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12224 } 12225 } 12226 12227 @Override 12228 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12229 mContext.enforceCallingOrSelfPermission( 12230 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12231 12232 boolean result = false; 12233 synchronized (mPackages) { 12234 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12235 } 12236 if (result) { 12237 scheduleWritePackageRestrictionsLocked(userId); 12238 } 12239 return result; 12240 } 12241 12242 @Override 12243 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12244 String packageName) { 12245 synchronized (mPackages) { 12246 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12247 } 12248 } 12249 12250 @Override 12251 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12252 if (TextUtils.isEmpty(packageName)) { 12253 return ParceledListSlice.emptyList(); 12254 } 12255 synchronized (mPackages) { 12256 PackageParser.Package pkg = mPackages.get(packageName); 12257 if (pkg == null || pkg.activities == null) { 12258 return ParceledListSlice.emptyList(); 12259 } 12260 final int count = pkg.activities.size(); 12261 ArrayList<IntentFilter> result = new ArrayList<>(); 12262 for (int n=0; n<count; n++) { 12263 PackageParser.Activity activity = pkg.activities.get(n); 12264 if (activity.intents != null && activity.intents.size() > 0) { 12265 result.addAll(activity.intents); 12266 } 12267 } 12268 return new ParceledListSlice<>(result); 12269 } 12270 } 12271 12272 @Override 12273 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12274 mContext.enforceCallingOrSelfPermission( 12275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12276 12277 synchronized (mPackages) { 12278 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12279 if (packageName != null) { 12280 result |= updateIntentVerificationStatus(packageName, 12281 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12282 userId); 12283 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12284 packageName, userId); 12285 } 12286 return result; 12287 } 12288 } 12289 12290 @Override 12291 public String getDefaultBrowserPackageName(int userId) { 12292 synchronized (mPackages) { 12293 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12294 } 12295 } 12296 12297 /** 12298 * Get the "allow unknown sources" setting. 12299 * 12300 * @return the current "allow unknown sources" setting 12301 */ 12302 private int getUnknownSourcesSettings() { 12303 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12304 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12305 -1); 12306 } 12307 12308 @Override 12309 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12310 final int uid = Binder.getCallingUid(); 12311 // writer 12312 synchronized (mPackages) { 12313 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12314 if (targetPackageSetting == null) { 12315 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12316 } 12317 12318 PackageSetting installerPackageSetting; 12319 if (installerPackageName != null) { 12320 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12321 if (installerPackageSetting == null) { 12322 throw new IllegalArgumentException("Unknown installer package: " 12323 + installerPackageName); 12324 } 12325 } else { 12326 installerPackageSetting = null; 12327 } 12328 12329 Signature[] callerSignature; 12330 Object obj = mSettings.getUserIdLPr(uid); 12331 if (obj != null) { 12332 if (obj instanceof SharedUserSetting) { 12333 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12334 } else if (obj instanceof PackageSetting) { 12335 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12336 } else { 12337 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12338 } 12339 } else { 12340 throw new SecurityException("Unknown calling UID: " + uid); 12341 } 12342 12343 // Verify: can't set installerPackageName to a package that is 12344 // not signed with the same cert as the caller. 12345 if (installerPackageSetting != null) { 12346 if (compareSignatures(callerSignature, 12347 installerPackageSetting.signatures.mSignatures) 12348 != PackageManager.SIGNATURE_MATCH) { 12349 throw new SecurityException( 12350 "Caller does not have same cert as new installer package " 12351 + installerPackageName); 12352 } 12353 } 12354 12355 // Verify: if target already has an installer package, it must 12356 // be signed with the same cert as the caller. 12357 if (targetPackageSetting.installerPackageName != null) { 12358 PackageSetting setting = mSettings.mPackages.get( 12359 targetPackageSetting.installerPackageName); 12360 // If the currently set package isn't valid, then it's always 12361 // okay to change it. 12362 if (setting != null) { 12363 if (compareSignatures(callerSignature, 12364 setting.signatures.mSignatures) 12365 != PackageManager.SIGNATURE_MATCH) { 12366 throw new SecurityException( 12367 "Caller does not have same cert as old installer package " 12368 + targetPackageSetting.installerPackageName); 12369 } 12370 } 12371 } 12372 12373 // Okay! 12374 targetPackageSetting.installerPackageName = installerPackageName; 12375 if (installerPackageName != null) { 12376 mSettings.mInstallerPackages.add(installerPackageName); 12377 } 12378 scheduleWriteSettingsLocked(); 12379 } 12380 } 12381 12382 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12383 // Queue up an async operation since the package installation may take a little while. 12384 mHandler.post(new Runnable() { 12385 public void run() { 12386 mHandler.removeCallbacks(this); 12387 // Result object to be returned 12388 PackageInstalledInfo res = new PackageInstalledInfo(); 12389 res.setReturnCode(currentStatus); 12390 res.uid = -1; 12391 res.pkg = null; 12392 res.removedInfo = null; 12393 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12394 args.doPreInstall(res.returnCode); 12395 synchronized (mInstallLock) { 12396 installPackageTracedLI(args, res); 12397 } 12398 args.doPostInstall(res.returnCode, res.uid); 12399 } 12400 12401 // A restore should be performed at this point if (a) the install 12402 // succeeded, (b) the operation is not an update, and (c) the new 12403 // package has not opted out of backup participation. 12404 final boolean update = res.removedInfo != null 12405 && res.removedInfo.removedPackage != null; 12406 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12407 boolean doRestore = !update 12408 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12409 12410 // Set up the post-install work request bookkeeping. This will be used 12411 // and cleaned up by the post-install event handling regardless of whether 12412 // there's a restore pass performed. Token values are >= 1. 12413 int token; 12414 if (mNextInstallToken < 0) mNextInstallToken = 1; 12415 token = mNextInstallToken++; 12416 12417 PostInstallData data = new PostInstallData(args, res); 12418 mRunningInstalls.put(token, data); 12419 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12420 12421 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12422 // Pass responsibility to the Backup Manager. It will perform a 12423 // restore if appropriate, then pass responsibility back to the 12424 // Package Manager to run the post-install observer callbacks 12425 // and broadcasts. 12426 IBackupManager bm = IBackupManager.Stub.asInterface( 12427 ServiceManager.getService(Context.BACKUP_SERVICE)); 12428 if (bm != null) { 12429 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12430 + " to BM for possible restore"); 12431 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12432 try { 12433 // TODO: http://b/22388012 12434 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12435 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12436 } else { 12437 doRestore = false; 12438 } 12439 } catch (RemoteException e) { 12440 // can't happen; the backup manager is local 12441 } catch (Exception e) { 12442 Slog.e(TAG, "Exception trying to enqueue restore", e); 12443 doRestore = false; 12444 } 12445 } else { 12446 Slog.e(TAG, "Backup Manager not found!"); 12447 doRestore = false; 12448 } 12449 } 12450 12451 if (!doRestore) { 12452 // No restore possible, or the Backup Manager was mysteriously not 12453 // available -- just fire the post-install work request directly. 12454 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12455 12456 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12457 12458 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12459 mHandler.sendMessage(msg); 12460 } 12461 } 12462 }); 12463 } 12464 12465 /** 12466 * Callback from PackageSettings whenever an app is first transitioned out of the 12467 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12468 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12469 * here whether the app is the target of an ongoing install, and only send the 12470 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12471 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12472 * handling. 12473 */ 12474 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12475 // Serialize this with the rest of the install-process message chain. In the 12476 // restore-at-install case, this Runnable will necessarily run before the 12477 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12478 // are coherent. In the non-restore case, the app has already completed install 12479 // and been launched through some other means, so it is not in a problematic 12480 // state for observers to see the FIRST_LAUNCH signal. 12481 mHandler.post(new Runnable() { 12482 @Override 12483 public void run() { 12484 for (int i = 0; i < mRunningInstalls.size(); i++) { 12485 final PostInstallData data = mRunningInstalls.valueAt(i); 12486 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12487 // right package; but is it for the right user? 12488 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12489 if (userId == data.res.newUsers[uIndex]) { 12490 if (DEBUG_BACKUP) { 12491 Slog.i(TAG, "Package " + pkgName 12492 + " being restored so deferring FIRST_LAUNCH"); 12493 } 12494 return; 12495 } 12496 } 12497 } 12498 } 12499 // didn't find it, so not being restored 12500 if (DEBUG_BACKUP) { 12501 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12502 } 12503 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12504 } 12505 }); 12506 } 12507 12508 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12509 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12510 installerPkg, null, userIds); 12511 } 12512 12513 private abstract class HandlerParams { 12514 private static final int MAX_RETRIES = 4; 12515 12516 /** 12517 * Number of times startCopy() has been attempted and had a non-fatal 12518 * error. 12519 */ 12520 private int mRetries = 0; 12521 12522 /** User handle for the user requesting the information or installation. */ 12523 private final UserHandle mUser; 12524 String traceMethod; 12525 int traceCookie; 12526 12527 HandlerParams(UserHandle user) { 12528 mUser = user; 12529 } 12530 12531 UserHandle getUser() { 12532 return mUser; 12533 } 12534 12535 HandlerParams setTraceMethod(String traceMethod) { 12536 this.traceMethod = traceMethod; 12537 return this; 12538 } 12539 12540 HandlerParams setTraceCookie(int traceCookie) { 12541 this.traceCookie = traceCookie; 12542 return this; 12543 } 12544 12545 final boolean startCopy() { 12546 boolean res; 12547 try { 12548 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12549 12550 if (++mRetries > MAX_RETRIES) { 12551 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12552 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12553 handleServiceError(); 12554 return false; 12555 } else { 12556 handleStartCopy(); 12557 res = true; 12558 } 12559 } catch (RemoteException e) { 12560 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12561 mHandler.sendEmptyMessage(MCS_RECONNECT); 12562 res = false; 12563 } 12564 handleReturnCode(); 12565 return res; 12566 } 12567 12568 final void serviceError() { 12569 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12570 handleServiceError(); 12571 handleReturnCode(); 12572 } 12573 12574 abstract void handleStartCopy() throws RemoteException; 12575 abstract void handleServiceError(); 12576 abstract void handleReturnCode(); 12577 } 12578 12579 class MeasureParams extends HandlerParams { 12580 private final PackageStats mStats; 12581 private boolean mSuccess; 12582 12583 private final IPackageStatsObserver mObserver; 12584 12585 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12586 super(new UserHandle(stats.userHandle)); 12587 mObserver = observer; 12588 mStats = stats; 12589 } 12590 12591 @Override 12592 public String toString() { 12593 return "MeasureParams{" 12594 + Integer.toHexString(System.identityHashCode(this)) 12595 + " " + mStats.packageName + "}"; 12596 } 12597 12598 @Override 12599 void handleStartCopy() throws RemoteException { 12600 synchronized (mInstallLock) { 12601 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12602 } 12603 12604 if (mSuccess) { 12605 boolean mounted = false; 12606 try { 12607 final String status = Environment.getExternalStorageState(); 12608 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12609 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12610 } catch (Exception e) { 12611 } 12612 12613 if (mounted) { 12614 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12615 12616 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12617 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12618 12619 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12620 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12621 12622 // Always subtract cache size, since it's a subdirectory 12623 mStats.externalDataSize -= mStats.externalCacheSize; 12624 12625 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12626 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12627 12628 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12629 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12630 } 12631 } 12632 } 12633 12634 @Override 12635 void handleReturnCode() { 12636 if (mObserver != null) { 12637 try { 12638 mObserver.onGetStatsCompleted(mStats, mSuccess); 12639 } catch (RemoteException e) { 12640 Slog.i(TAG, "Observer no longer exists."); 12641 } 12642 } 12643 } 12644 12645 @Override 12646 void handleServiceError() { 12647 Slog.e(TAG, "Could not measure application " + mStats.packageName 12648 + " external storage"); 12649 } 12650 } 12651 12652 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12653 throws RemoteException { 12654 long result = 0; 12655 for (File path : paths) { 12656 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12657 } 12658 return result; 12659 } 12660 12661 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12662 for (File path : paths) { 12663 try { 12664 mcs.clearDirectory(path.getAbsolutePath()); 12665 } catch (RemoteException e) { 12666 } 12667 } 12668 } 12669 12670 static class OriginInfo { 12671 /** 12672 * Location where install is coming from, before it has been 12673 * copied/renamed into place. This could be a single monolithic APK 12674 * file, or a cluster directory. This location may be untrusted. 12675 */ 12676 final File file; 12677 final String cid; 12678 12679 /** 12680 * Flag indicating that {@link #file} or {@link #cid} has already been 12681 * staged, meaning downstream users don't need to defensively copy the 12682 * contents. 12683 */ 12684 final boolean staged; 12685 12686 /** 12687 * Flag indicating that {@link #file} or {@link #cid} is an already 12688 * installed app that is being moved. 12689 */ 12690 final boolean existing; 12691 12692 final String resolvedPath; 12693 final File resolvedFile; 12694 12695 static OriginInfo fromNothing() { 12696 return new OriginInfo(null, null, false, false); 12697 } 12698 12699 static OriginInfo fromUntrustedFile(File file) { 12700 return new OriginInfo(file, null, false, false); 12701 } 12702 12703 static OriginInfo fromExistingFile(File file) { 12704 return new OriginInfo(file, null, false, true); 12705 } 12706 12707 static OriginInfo fromStagedFile(File file) { 12708 return new OriginInfo(file, null, true, false); 12709 } 12710 12711 static OriginInfo fromStagedContainer(String cid) { 12712 return new OriginInfo(null, cid, true, false); 12713 } 12714 12715 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12716 this.file = file; 12717 this.cid = cid; 12718 this.staged = staged; 12719 this.existing = existing; 12720 12721 if (cid != null) { 12722 resolvedPath = PackageHelper.getSdDir(cid); 12723 resolvedFile = new File(resolvedPath); 12724 } else if (file != null) { 12725 resolvedPath = file.getAbsolutePath(); 12726 resolvedFile = file; 12727 } else { 12728 resolvedPath = null; 12729 resolvedFile = null; 12730 } 12731 } 12732 } 12733 12734 static class MoveInfo { 12735 final int moveId; 12736 final String fromUuid; 12737 final String toUuid; 12738 final String packageName; 12739 final String dataAppName; 12740 final int appId; 12741 final String seinfo; 12742 final int targetSdkVersion; 12743 12744 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12745 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12746 this.moveId = moveId; 12747 this.fromUuid = fromUuid; 12748 this.toUuid = toUuid; 12749 this.packageName = packageName; 12750 this.dataAppName = dataAppName; 12751 this.appId = appId; 12752 this.seinfo = seinfo; 12753 this.targetSdkVersion = targetSdkVersion; 12754 } 12755 } 12756 12757 static class VerificationInfo { 12758 /** A constant used to indicate that a uid value is not present. */ 12759 public static final int NO_UID = -1; 12760 12761 /** URI referencing where the package was downloaded from. */ 12762 final Uri originatingUri; 12763 12764 /** HTTP referrer URI associated with the originatingURI. */ 12765 final Uri referrer; 12766 12767 /** UID of the application that the install request originated from. */ 12768 final int originatingUid; 12769 12770 /** UID of application requesting the install */ 12771 final int installerUid; 12772 12773 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12774 this.originatingUri = originatingUri; 12775 this.referrer = referrer; 12776 this.originatingUid = originatingUid; 12777 this.installerUid = installerUid; 12778 } 12779 } 12780 12781 class InstallParams extends HandlerParams { 12782 final OriginInfo origin; 12783 final MoveInfo move; 12784 final IPackageInstallObserver2 observer; 12785 int installFlags; 12786 final String installerPackageName; 12787 final String volumeUuid; 12788 private InstallArgs mArgs; 12789 private int mRet; 12790 final String packageAbiOverride; 12791 final String[] grantedRuntimePermissions; 12792 final VerificationInfo verificationInfo; 12793 final Certificate[][] certificates; 12794 12795 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12796 int installFlags, String installerPackageName, String volumeUuid, 12797 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12798 String[] grantedPermissions, Certificate[][] certificates) { 12799 super(user); 12800 this.origin = origin; 12801 this.move = move; 12802 this.observer = observer; 12803 this.installFlags = installFlags; 12804 this.installerPackageName = installerPackageName; 12805 this.volumeUuid = volumeUuid; 12806 this.verificationInfo = verificationInfo; 12807 this.packageAbiOverride = packageAbiOverride; 12808 this.grantedRuntimePermissions = grantedPermissions; 12809 this.certificates = certificates; 12810 } 12811 12812 @Override 12813 public String toString() { 12814 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12815 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12816 } 12817 12818 private int installLocationPolicy(PackageInfoLite pkgLite) { 12819 String packageName = pkgLite.packageName; 12820 int installLocation = pkgLite.installLocation; 12821 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12822 // reader 12823 synchronized (mPackages) { 12824 // Currently installed package which the new package is attempting to replace or 12825 // null if no such package is installed. 12826 PackageParser.Package installedPkg = mPackages.get(packageName); 12827 // Package which currently owns the data which the new package will own if installed. 12828 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12829 // will be null whereas dataOwnerPkg will contain information about the package 12830 // which was uninstalled while keeping its data. 12831 PackageParser.Package dataOwnerPkg = installedPkg; 12832 if (dataOwnerPkg == null) { 12833 PackageSetting ps = mSettings.mPackages.get(packageName); 12834 if (ps != null) { 12835 dataOwnerPkg = ps.pkg; 12836 } 12837 } 12838 12839 if (dataOwnerPkg != null) { 12840 // If installed, the package will get access to data left on the device by its 12841 // predecessor. As a security measure, this is permited only if this is not a 12842 // version downgrade or if the predecessor package is marked as debuggable and 12843 // a downgrade is explicitly requested. 12844 // 12845 // On debuggable platform builds, downgrades are permitted even for 12846 // non-debuggable packages to make testing easier. Debuggable platform builds do 12847 // not offer security guarantees and thus it's OK to disable some security 12848 // mechanisms to make debugging/testing easier on those builds. However, even on 12849 // debuggable builds downgrades of packages are permitted only if requested via 12850 // installFlags. This is because we aim to keep the behavior of debuggable 12851 // platform builds as close as possible to the behavior of non-debuggable 12852 // platform builds. 12853 final boolean downgradeRequested = 12854 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12855 final boolean packageDebuggable = 12856 (dataOwnerPkg.applicationInfo.flags 12857 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12858 final boolean downgradePermitted = 12859 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12860 if (!downgradePermitted) { 12861 try { 12862 checkDowngrade(dataOwnerPkg, pkgLite); 12863 } catch (PackageManagerException e) { 12864 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12865 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12866 } 12867 } 12868 } 12869 12870 if (installedPkg != null) { 12871 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12872 // Check for updated system application. 12873 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12874 if (onSd) { 12875 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12876 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12877 } 12878 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12879 } else { 12880 if (onSd) { 12881 // Install flag overrides everything. 12882 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12883 } 12884 // If current upgrade specifies particular preference 12885 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12886 // Application explicitly specified internal. 12887 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12888 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12889 // App explictly prefers external. Let policy decide 12890 } else { 12891 // Prefer previous location 12892 if (isExternal(installedPkg)) { 12893 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12894 } 12895 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12896 } 12897 } 12898 } else { 12899 // Invalid install. Return error code 12900 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12901 } 12902 } 12903 } 12904 // All the special cases have been taken care of. 12905 // Return result based on recommended install location. 12906 if (onSd) { 12907 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12908 } 12909 return pkgLite.recommendedInstallLocation; 12910 } 12911 12912 /* 12913 * Invoke remote method to get package information and install 12914 * location values. Override install location based on default 12915 * policy if needed and then create install arguments based 12916 * on the install location. 12917 */ 12918 public void handleStartCopy() throws RemoteException { 12919 int ret = PackageManager.INSTALL_SUCCEEDED; 12920 12921 // If we're already staged, we've firmly committed to an install location 12922 if (origin.staged) { 12923 if (origin.file != null) { 12924 installFlags |= PackageManager.INSTALL_INTERNAL; 12925 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12926 } else if (origin.cid != null) { 12927 installFlags |= PackageManager.INSTALL_EXTERNAL; 12928 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12929 } else { 12930 throw new IllegalStateException("Invalid stage location"); 12931 } 12932 } 12933 12934 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12935 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12936 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12937 PackageInfoLite pkgLite = null; 12938 12939 if (onInt && onSd) { 12940 // Check if both bits are set. 12941 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12942 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12943 } else if (onSd && ephemeral) { 12944 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12945 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12946 } else { 12947 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12948 packageAbiOverride); 12949 12950 if (DEBUG_EPHEMERAL && ephemeral) { 12951 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12952 } 12953 12954 /* 12955 * If we have too little free space, try to free cache 12956 * before giving up. 12957 */ 12958 if (!origin.staged && pkgLite.recommendedInstallLocation 12959 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12960 // TODO: focus freeing disk space on the target device 12961 final StorageManager storage = StorageManager.from(mContext); 12962 final long lowThreshold = storage.getStorageLowBytes( 12963 Environment.getDataDirectory()); 12964 12965 final long sizeBytes = mContainerService.calculateInstalledSize( 12966 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12967 12968 try { 12969 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12970 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12971 installFlags, packageAbiOverride); 12972 } catch (InstallerException e) { 12973 Slog.w(TAG, "Failed to free cache", e); 12974 } 12975 12976 /* 12977 * The cache free must have deleted the file we 12978 * downloaded to install. 12979 * 12980 * TODO: fix the "freeCache" call to not delete 12981 * the file we care about. 12982 */ 12983 if (pkgLite.recommendedInstallLocation 12984 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12985 pkgLite.recommendedInstallLocation 12986 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12987 } 12988 } 12989 } 12990 12991 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12992 int loc = pkgLite.recommendedInstallLocation; 12993 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12994 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12995 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12996 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12997 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12998 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12999 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13000 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13001 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13002 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13003 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13004 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13005 } else { 13006 // Override with defaults if needed. 13007 loc = installLocationPolicy(pkgLite); 13008 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13009 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13010 } else if (!onSd && !onInt) { 13011 // Override install location with flags 13012 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13013 // Set the flag to install on external media. 13014 installFlags |= PackageManager.INSTALL_EXTERNAL; 13015 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13016 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13017 if (DEBUG_EPHEMERAL) { 13018 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13019 } 13020 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13021 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13022 |PackageManager.INSTALL_INTERNAL); 13023 } else { 13024 // Make sure the flag for installing on external 13025 // media is unset 13026 installFlags |= PackageManager.INSTALL_INTERNAL; 13027 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13028 } 13029 } 13030 } 13031 } 13032 13033 final InstallArgs args = createInstallArgs(this); 13034 mArgs = args; 13035 13036 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13037 // TODO: http://b/22976637 13038 // Apps installed for "all" users use the device owner to verify the app 13039 UserHandle verifierUser = getUser(); 13040 if (verifierUser == UserHandle.ALL) { 13041 verifierUser = UserHandle.SYSTEM; 13042 } 13043 13044 /* 13045 * Determine if we have any installed package verifiers. If we 13046 * do, then we'll defer to them to verify the packages. 13047 */ 13048 final int requiredUid = mRequiredVerifierPackage == null ? -1 13049 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13050 verifierUser.getIdentifier()); 13051 if (!origin.existing && requiredUid != -1 13052 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13053 final Intent verification = new Intent( 13054 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13055 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13056 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13057 PACKAGE_MIME_TYPE); 13058 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13059 13060 // Query all live verifiers based on current user state 13061 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13062 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13063 13064 if (DEBUG_VERIFY) { 13065 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13066 + verification.toString() + " with " + pkgLite.verifiers.length 13067 + " optional verifiers"); 13068 } 13069 13070 final int verificationId = mPendingVerificationToken++; 13071 13072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13073 13074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13075 installerPackageName); 13076 13077 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13078 installFlags); 13079 13080 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13081 pkgLite.packageName); 13082 13083 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13084 pkgLite.versionCode); 13085 13086 if (verificationInfo != null) { 13087 if (verificationInfo.originatingUri != null) { 13088 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13089 verificationInfo.originatingUri); 13090 } 13091 if (verificationInfo.referrer != null) { 13092 verification.putExtra(Intent.EXTRA_REFERRER, 13093 verificationInfo.referrer); 13094 } 13095 if (verificationInfo.originatingUid >= 0) { 13096 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13097 verificationInfo.originatingUid); 13098 } 13099 if (verificationInfo.installerUid >= 0) { 13100 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13101 verificationInfo.installerUid); 13102 } 13103 } 13104 13105 final PackageVerificationState verificationState = new PackageVerificationState( 13106 requiredUid, args); 13107 13108 mPendingVerification.append(verificationId, verificationState); 13109 13110 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13111 receivers, verificationState); 13112 13113 /* 13114 * If any sufficient verifiers were listed in the package 13115 * manifest, attempt to ask them. 13116 */ 13117 if (sufficientVerifiers != null) { 13118 final int N = sufficientVerifiers.size(); 13119 if (N == 0) { 13120 Slog.i(TAG, "Additional verifiers required, but none installed."); 13121 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13122 } else { 13123 for (int i = 0; i < N; i++) { 13124 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13125 13126 final Intent sufficientIntent = new Intent(verification); 13127 sufficientIntent.setComponent(verifierComponent); 13128 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13129 } 13130 } 13131 } 13132 13133 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13134 mRequiredVerifierPackage, receivers); 13135 if (ret == PackageManager.INSTALL_SUCCEEDED 13136 && mRequiredVerifierPackage != null) { 13137 Trace.asyncTraceBegin( 13138 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13139 /* 13140 * Send the intent to the required verification agent, 13141 * but only start the verification timeout after the 13142 * target BroadcastReceivers have run. 13143 */ 13144 verification.setComponent(requiredVerifierComponent); 13145 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13146 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13147 new BroadcastReceiver() { 13148 @Override 13149 public void onReceive(Context context, Intent intent) { 13150 final Message msg = mHandler 13151 .obtainMessage(CHECK_PENDING_VERIFICATION); 13152 msg.arg1 = verificationId; 13153 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13154 } 13155 }, null, 0, null, null); 13156 13157 /* 13158 * We don't want the copy to proceed until verification 13159 * succeeds, so null out this field. 13160 */ 13161 mArgs = null; 13162 } 13163 } else { 13164 /* 13165 * No package verification is enabled, so immediately start 13166 * the remote call to initiate copy using temporary file. 13167 */ 13168 ret = args.copyApk(mContainerService, true); 13169 } 13170 } 13171 13172 mRet = ret; 13173 } 13174 13175 @Override 13176 void handleReturnCode() { 13177 // If mArgs is null, then MCS couldn't be reached. When it 13178 // reconnects, it will try again to install. At that point, this 13179 // will succeed. 13180 if (mArgs != null) { 13181 processPendingInstall(mArgs, mRet); 13182 } 13183 } 13184 13185 @Override 13186 void handleServiceError() { 13187 mArgs = createInstallArgs(this); 13188 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13189 } 13190 13191 public boolean isForwardLocked() { 13192 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13193 } 13194 } 13195 13196 /** 13197 * Used during creation of InstallArgs 13198 * 13199 * @param installFlags package installation flags 13200 * @return true if should be installed on external storage 13201 */ 13202 private static boolean installOnExternalAsec(int installFlags) { 13203 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13204 return false; 13205 } 13206 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13207 return true; 13208 } 13209 return false; 13210 } 13211 13212 /** 13213 * Used during creation of InstallArgs 13214 * 13215 * @param installFlags package installation flags 13216 * @return true if should be installed as forward locked 13217 */ 13218 private static boolean installForwardLocked(int installFlags) { 13219 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13220 } 13221 13222 private InstallArgs createInstallArgs(InstallParams params) { 13223 if (params.move != null) { 13224 return new MoveInstallArgs(params); 13225 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13226 return new AsecInstallArgs(params); 13227 } else { 13228 return new FileInstallArgs(params); 13229 } 13230 } 13231 13232 /** 13233 * Create args that describe an existing installed package. Typically used 13234 * when cleaning up old installs, or used as a move source. 13235 */ 13236 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13237 String resourcePath, String[] instructionSets) { 13238 final boolean isInAsec; 13239 if (installOnExternalAsec(installFlags)) { 13240 /* Apps on SD card are always in ASEC containers. */ 13241 isInAsec = true; 13242 } else if (installForwardLocked(installFlags) 13243 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13244 /* 13245 * Forward-locked apps are only in ASEC containers if they're the 13246 * new style 13247 */ 13248 isInAsec = true; 13249 } else { 13250 isInAsec = false; 13251 } 13252 13253 if (isInAsec) { 13254 return new AsecInstallArgs(codePath, instructionSets, 13255 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13256 } else { 13257 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13258 } 13259 } 13260 13261 static abstract class InstallArgs { 13262 /** @see InstallParams#origin */ 13263 final OriginInfo origin; 13264 /** @see InstallParams#move */ 13265 final MoveInfo move; 13266 13267 final IPackageInstallObserver2 observer; 13268 // Always refers to PackageManager flags only 13269 final int installFlags; 13270 final String installerPackageName; 13271 final String volumeUuid; 13272 final UserHandle user; 13273 final String abiOverride; 13274 final String[] installGrantPermissions; 13275 /** If non-null, drop an async trace when the install completes */ 13276 final String traceMethod; 13277 final int traceCookie; 13278 final Certificate[][] certificates; 13279 13280 // The list of instruction sets supported by this app. This is currently 13281 // only used during the rmdex() phase to clean up resources. We can get rid of this 13282 // if we move dex files under the common app path. 13283 /* nullable */ String[] instructionSets; 13284 13285 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13286 int installFlags, String installerPackageName, String volumeUuid, 13287 UserHandle user, String[] instructionSets, 13288 String abiOverride, String[] installGrantPermissions, 13289 String traceMethod, int traceCookie, Certificate[][] certificates) { 13290 this.origin = origin; 13291 this.move = move; 13292 this.installFlags = installFlags; 13293 this.observer = observer; 13294 this.installerPackageName = installerPackageName; 13295 this.volumeUuid = volumeUuid; 13296 this.user = user; 13297 this.instructionSets = instructionSets; 13298 this.abiOverride = abiOverride; 13299 this.installGrantPermissions = installGrantPermissions; 13300 this.traceMethod = traceMethod; 13301 this.traceCookie = traceCookie; 13302 this.certificates = certificates; 13303 } 13304 13305 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13306 abstract int doPreInstall(int status); 13307 13308 /** 13309 * Rename package into final resting place. All paths on the given 13310 * scanned package should be updated to reflect the rename. 13311 */ 13312 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13313 abstract int doPostInstall(int status, int uid); 13314 13315 /** @see PackageSettingBase#codePathString */ 13316 abstract String getCodePath(); 13317 /** @see PackageSettingBase#resourcePathString */ 13318 abstract String getResourcePath(); 13319 13320 // Need installer lock especially for dex file removal. 13321 abstract void cleanUpResourcesLI(); 13322 abstract boolean doPostDeleteLI(boolean delete); 13323 13324 /** 13325 * Called before the source arguments are copied. This is used mostly 13326 * for MoveParams when it needs to read the source file to put it in the 13327 * destination. 13328 */ 13329 int doPreCopy() { 13330 return PackageManager.INSTALL_SUCCEEDED; 13331 } 13332 13333 /** 13334 * Called after the source arguments are copied. This is used mostly for 13335 * MoveParams when it needs to read the source file to put it in the 13336 * destination. 13337 */ 13338 int doPostCopy(int uid) { 13339 return PackageManager.INSTALL_SUCCEEDED; 13340 } 13341 13342 protected boolean isFwdLocked() { 13343 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13344 } 13345 13346 protected boolean isExternalAsec() { 13347 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13348 } 13349 13350 protected boolean isEphemeral() { 13351 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13352 } 13353 13354 UserHandle getUser() { 13355 return user; 13356 } 13357 } 13358 13359 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13360 if (!allCodePaths.isEmpty()) { 13361 if (instructionSets == null) { 13362 throw new IllegalStateException("instructionSet == null"); 13363 } 13364 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13365 for (String codePath : allCodePaths) { 13366 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13367 try { 13368 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13369 } catch (InstallerException ignored) { 13370 } 13371 } 13372 } 13373 } 13374 } 13375 13376 /** 13377 * Logic to handle installation of non-ASEC applications, including copying 13378 * and renaming logic. 13379 */ 13380 class FileInstallArgs extends InstallArgs { 13381 private File codeFile; 13382 private File resourceFile; 13383 13384 // Example topology: 13385 // /data/app/com.example/base.apk 13386 // /data/app/com.example/split_foo.apk 13387 // /data/app/com.example/lib/arm/libfoo.so 13388 // /data/app/com.example/lib/arm64/libfoo.so 13389 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13390 13391 /** New install */ 13392 FileInstallArgs(InstallParams params) { 13393 super(params.origin, params.move, params.observer, params.installFlags, 13394 params.installerPackageName, params.volumeUuid, 13395 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13396 params.grantedRuntimePermissions, 13397 params.traceMethod, params.traceCookie, params.certificates); 13398 if (isFwdLocked()) { 13399 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13400 } 13401 } 13402 13403 /** Existing install */ 13404 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13405 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13406 null, null, null, 0, null /*certificates*/); 13407 this.codeFile = (codePath != null) ? new File(codePath) : null; 13408 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13409 } 13410 13411 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13412 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13413 try { 13414 return doCopyApk(imcs, temp); 13415 } finally { 13416 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13417 } 13418 } 13419 13420 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13421 if (origin.staged) { 13422 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13423 codeFile = origin.file; 13424 resourceFile = origin.file; 13425 return PackageManager.INSTALL_SUCCEEDED; 13426 } 13427 13428 try { 13429 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13430 final File tempDir = 13431 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13432 codeFile = tempDir; 13433 resourceFile = tempDir; 13434 } catch (IOException e) { 13435 Slog.w(TAG, "Failed to create copy file: " + e); 13436 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13437 } 13438 13439 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13440 @Override 13441 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13442 if (!FileUtils.isValidExtFilename(name)) { 13443 throw new IllegalArgumentException("Invalid filename: " + name); 13444 } 13445 try { 13446 final File file = new File(codeFile, name); 13447 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13448 O_RDWR | O_CREAT, 0644); 13449 Os.chmod(file.getAbsolutePath(), 0644); 13450 return new ParcelFileDescriptor(fd); 13451 } catch (ErrnoException e) { 13452 throw new RemoteException("Failed to open: " + e.getMessage()); 13453 } 13454 } 13455 }; 13456 13457 int ret = PackageManager.INSTALL_SUCCEEDED; 13458 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13459 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13460 Slog.e(TAG, "Failed to copy package"); 13461 return ret; 13462 } 13463 13464 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13465 NativeLibraryHelper.Handle handle = null; 13466 try { 13467 handle = NativeLibraryHelper.Handle.create(codeFile); 13468 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13469 abiOverride); 13470 } catch (IOException e) { 13471 Slog.e(TAG, "Copying native libraries failed", e); 13472 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13473 } finally { 13474 IoUtils.closeQuietly(handle); 13475 } 13476 13477 return ret; 13478 } 13479 13480 int doPreInstall(int status) { 13481 if (status != PackageManager.INSTALL_SUCCEEDED) { 13482 cleanUp(); 13483 } 13484 return status; 13485 } 13486 13487 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13488 if (status != PackageManager.INSTALL_SUCCEEDED) { 13489 cleanUp(); 13490 return false; 13491 } 13492 13493 final File targetDir = codeFile.getParentFile(); 13494 final File beforeCodeFile = codeFile; 13495 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13496 13497 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13498 try { 13499 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13500 } catch (ErrnoException e) { 13501 Slog.w(TAG, "Failed to rename", e); 13502 return false; 13503 } 13504 13505 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13506 Slog.w(TAG, "Failed to restorecon"); 13507 return false; 13508 } 13509 13510 // Reflect the rename internally 13511 codeFile = afterCodeFile; 13512 resourceFile = afterCodeFile; 13513 13514 // Reflect the rename in scanned details 13515 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13516 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13517 afterCodeFile, pkg.baseCodePath)); 13518 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13519 afterCodeFile, pkg.splitCodePaths)); 13520 13521 // Reflect the rename in app info 13522 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13523 pkg.setApplicationInfoCodePath(pkg.codePath); 13524 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13525 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13526 pkg.setApplicationInfoResourcePath(pkg.codePath); 13527 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13528 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13529 13530 return true; 13531 } 13532 13533 int doPostInstall(int status, int uid) { 13534 if (status != PackageManager.INSTALL_SUCCEEDED) { 13535 cleanUp(); 13536 } 13537 return status; 13538 } 13539 13540 @Override 13541 String getCodePath() { 13542 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13543 } 13544 13545 @Override 13546 String getResourcePath() { 13547 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13548 } 13549 13550 private boolean cleanUp() { 13551 if (codeFile == null || !codeFile.exists()) { 13552 return false; 13553 } 13554 13555 removeCodePathLI(codeFile); 13556 13557 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13558 resourceFile.delete(); 13559 } 13560 13561 return true; 13562 } 13563 13564 void cleanUpResourcesLI() { 13565 // Try enumerating all code paths before deleting 13566 List<String> allCodePaths = Collections.EMPTY_LIST; 13567 if (codeFile != null && codeFile.exists()) { 13568 try { 13569 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13570 allCodePaths = pkg.getAllCodePaths(); 13571 } catch (PackageParserException e) { 13572 // Ignored; we tried our best 13573 } 13574 } 13575 13576 cleanUp(); 13577 removeDexFiles(allCodePaths, instructionSets); 13578 } 13579 13580 boolean doPostDeleteLI(boolean delete) { 13581 // XXX err, shouldn't we respect the delete flag? 13582 cleanUpResourcesLI(); 13583 return true; 13584 } 13585 } 13586 13587 private boolean isAsecExternal(String cid) { 13588 final String asecPath = PackageHelper.getSdFilesystem(cid); 13589 return !asecPath.startsWith(mAsecInternalPath); 13590 } 13591 13592 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13593 PackageManagerException { 13594 if (copyRet < 0) { 13595 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13596 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13597 throw new PackageManagerException(copyRet, message); 13598 } 13599 } 13600 } 13601 13602 /** 13603 * Extract the MountService "container ID" from the full code path of an 13604 * .apk. 13605 */ 13606 static String cidFromCodePath(String fullCodePath) { 13607 int eidx = fullCodePath.lastIndexOf("/"); 13608 String subStr1 = fullCodePath.substring(0, eidx); 13609 int sidx = subStr1.lastIndexOf("/"); 13610 return subStr1.substring(sidx+1, eidx); 13611 } 13612 13613 /** 13614 * Logic to handle installation of ASEC applications, including copying and 13615 * renaming logic. 13616 */ 13617 class AsecInstallArgs extends InstallArgs { 13618 static final String RES_FILE_NAME = "pkg.apk"; 13619 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13620 13621 String cid; 13622 String packagePath; 13623 String resourcePath; 13624 13625 /** New install */ 13626 AsecInstallArgs(InstallParams params) { 13627 super(params.origin, params.move, params.observer, params.installFlags, 13628 params.installerPackageName, params.volumeUuid, 13629 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13630 params.grantedRuntimePermissions, 13631 params.traceMethod, params.traceCookie, params.certificates); 13632 } 13633 13634 /** Existing install */ 13635 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13636 boolean isExternal, boolean isForwardLocked) { 13637 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13638 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13639 instructionSets, null, null, null, 0, null /*certificates*/); 13640 // Hackily pretend we're still looking at a full code path 13641 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13642 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13643 } 13644 13645 // Extract cid from fullCodePath 13646 int eidx = fullCodePath.lastIndexOf("/"); 13647 String subStr1 = fullCodePath.substring(0, eidx); 13648 int sidx = subStr1.lastIndexOf("/"); 13649 cid = subStr1.substring(sidx+1, eidx); 13650 setMountPath(subStr1); 13651 } 13652 13653 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13654 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13655 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13656 instructionSets, null, null, null, 0, null /*certificates*/); 13657 this.cid = cid; 13658 setMountPath(PackageHelper.getSdDir(cid)); 13659 } 13660 13661 void createCopyFile() { 13662 cid = mInstallerService.allocateExternalStageCidLegacy(); 13663 } 13664 13665 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13666 if (origin.staged && origin.cid != null) { 13667 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13668 cid = origin.cid; 13669 setMountPath(PackageHelper.getSdDir(cid)); 13670 return PackageManager.INSTALL_SUCCEEDED; 13671 } 13672 13673 if (temp) { 13674 createCopyFile(); 13675 } else { 13676 /* 13677 * Pre-emptively destroy the container since it's destroyed if 13678 * copying fails due to it existing anyway. 13679 */ 13680 PackageHelper.destroySdDir(cid); 13681 } 13682 13683 final String newMountPath = imcs.copyPackageToContainer( 13684 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13685 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13686 13687 if (newMountPath != null) { 13688 setMountPath(newMountPath); 13689 return PackageManager.INSTALL_SUCCEEDED; 13690 } else { 13691 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13692 } 13693 } 13694 13695 @Override 13696 String getCodePath() { 13697 return packagePath; 13698 } 13699 13700 @Override 13701 String getResourcePath() { 13702 return resourcePath; 13703 } 13704 13705 int doPreInstall(int status) { 13706 if (status != PackageManager.INSTALL_SUCCEEDED) { 13707 // Destroy container 13708 PackageHelper.destroySdDir(cid); 13709 } else { 13710 boolean mounted = PackageHelper.isContainerMounted(cid); 13711 if (!mounted) { 13712 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13713 Process.SYSTEM_UID); 13714 if (newMountPath != null) { 13715 setMountPath(newMountPath); 13716 } else { 13717 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13718 } 13719 } 13720 } 13721 return status; 13722 } 13723 13724 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13725 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13726 String newMountPath = null; 13727 if (PackageHelper.isContainerMounted(cid)) { 13728 // Unmount the container 13729 if (!PackageHelper.unMountSdDir(cid)) { 13730 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13731 return false; 13732 } 13733 } 13734 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13735 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13736 " which might be stale. Will try to clean up."); 13737 // Clean up the stale container and proceed to recreate. 13738 if (!PackageHelper.destroySdDir(newCacheId)) { 13739 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13740 return false; 13741 } 13742 // Successfully cleaned up stale container. Try to rename again. 13743 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13744 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13745 + " inspite of cleaning it up."); 13746 return false; 13747 } 13748 } 13749 if (!PackageHelper.isContainerMounted(newCacheId)) { 13750 Slog.w(TAG, "Mounting container " + newCacheId); 13751 newMountPath = PackageHelper.mountSdDir(newCacheId, 13752 getEncryptKey(), Process.SYSTEM_UID); 13753 } else { 13754 newMountPath = PackageHelper.getSdDir(newCacheId); 13755 } 13756 if (newMountPath == null) { 13757 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13758 return false; 13759 } 13760 Log.i(TAG, "Succesfully renamed " + cid + 13761 " to " + newCacheId + 13762 " at new path: " + newMountPath); 13763 cid = newCacheId; 13764 13765 final File beforeCodeFile = new File(packagePath); 13766 setMountPath(newMountPath); 13767 final File afterCodeFile = new File(packagePath); 13768 13769 // Reflect the rename in scanned details 13770 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13771 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13772 afterCodeFile, pkg.baseCodePath)); 13773 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13774 afterCodeFile, pkg.splitCodePaths)); 13775 13776 // Reflect the rename in app info 13777 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13778 pkg.setApplicationInfoCodePath(pkg.codePath); 13779 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13780 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13781 pkg.setApplicationInfoResourcePath(pkg.codePath); 13782 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13783 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13784 13785 return true; 13786 } 13787 13788 private void setMountPath(String mountPath) { 13789 final File mountFile = new File(mountPath); 13790 13791 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13792 if (monolithicFile.exists()) { 13793 packagePath = monolithicFile.getAbsolutePath(); 13794 if (isFwdLocked()) { 13795 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13796 } else { 13797 resourcePath = packagePath; 13798 } 13799 } else { 13800 packagePath = mountFile.getAbsolutePath(); 13801 resourcePath = packagePath; 13802 } 13803 } 13804 13805 int doPostInstall(int status, int uid) { 13806 if (status != PackageManager.INSTALL_SUCCEEDED) { 13807 cleanUp(); 13808 } else { 13809 final int groupOwner; 13810 final String protectedFile; 13811 if (isFwdLocked()) { 13812 groupOwner = UserHandle.getSharedAppGid(uid); 13813 protectedFile = RES_FILE_NAME; 13814 } else { 13815 groupOwner = -1; 13816 protectedFile = null; 13817 } 13818 13819 if (uid < Process.FIRST_APPLICATION_UID 13820 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13821 Slog.e(TAG, "Failed to finalize " + cid); 13822 PackageHelper.destroySdDir(cid); 13823 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13824 } 13825 13826 boolean mounted = PackageHelper.isContainerMounted(cid); 13827 if (!mounted) { 13828 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13829 } 13830 } 13831 return status; 13832 } 13833 13834 private void cleanUp() { 13835 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13836 13837 // Destroy secure container 13838 PackageHelper.destroySdDir(cid); 13839 } 13840 13841 private List<String> getAllCodePaths() { 13842 final File codeFile = new File(getCodePath()); 13843 if (codeFile != null && codeFile.exists()) { 13844 try { 13845 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13846 return pkg.getAllCodePaths(); 13847 } catch (PackageParserException e) { 13848 // Ignored; we tried our best 13849 } 13850 } 13851 return Collections.EMPTY_LIST; 13852 } 13853 13854 void cleanUpResourcesLI() { 13855 // Enumerate all code paths before deleting 13856 cleanUpResourcesLI(getAllCodePaths()); 13857 } 13858 13859 private void cleanUpResourcesLI(List<String> allCodePaths) { 13860 cleanUp(); 13861 removeDexFiles(allCodePaths, instructionSets); 13862 } 13863 13864 String getPackageName() { 13865 return getAsecPackageName(cid); 13866 } 13867 13868 boolean doPostDeleteLI(boolean delete) { 13869 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13870 final List<String> allCodePaths = getAllCodePaths(); 13871 boolean mounted = PackageHelper.isContainerMounted(cid); 13872 if (mounted) { 13873 // Unmount first 13874 if (PackageHelper.unMountSdDir(cid)) { 13875 mounted = false; 13876 } 13877 } 13878 if (!mounted && delete) { 13879 cleanUpResourcesLI(allCodePaths); 13880 } 13881 return !mounted; 13882 } 13883 13884 @Override 13885 int doPreCopy() { 13886 if (isFwdLocked()) { 13887 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13888 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13889 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13890 } 13891 } 13892 13893 return PackageManager.INSTALL_SUCCEEDED; 13894 } 13895 13896 @Override 13897 int doPostCopy(int uid) { 13898 if (isFwdLocked()) { 13899 if (uid < Process.FIRST_APPLICATION_UID 13900 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13901 RES_FILE_NAME)) { 13902 Slog.e(TAG, "Failed to finalize " + cid); 13903 PackageHelper.destroySdDir(cid); 13904 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13905 } 13906 } 13907 13908 return PackageManager.INSTALL_SUCCEEDED; 13909 } 13910 } 13911 13912 /** 13913 * Logic to handle movement of existing installed applications. 13914 */ 13915 class MoveInstallArgs extends InstallArgs { 13916 private File codeFile; 13917 private File resourceFile; 13918 13919 /** New install */ 13920 MoveInstallArgs(InstallParams params) { 13921 super(params.origin, params.move, params.observer, params.installFlags, 13922 params.installerPackageName, params.volumeUuid, 13923 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13924 params.grantedRuntimePermissions, 13925 params.traceMethod, params.traceCookie, params.certificates); 13926 } 13927 13928 int copyApk(IMediaContainerService imcs, boolean temp) { 13929 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13930 + move.fromUuid + " to " + move.toUuid); 13931 synchronized (mInstaller) { 13932 try { 13933 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13934 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13935 } catch (InstallerException e) { 13936 Slog.w(TAG, "Failed to move app", e); 13937 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13938 } 13939 } 13940 13941 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13942 resourceFile = codeFile; 13943 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13944 13945 return PackageManager.INSTALL_SUCCEEDED; 13946 } 13947 13948 int doPreInstall(int status) { 13949 if (status != PackageManager.INSTALL_SUCCEEDED) { 13950 cleanUp(move.toUuid); 13951 } 13952 return status; 13953 } 13954 13955 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13956 if (status != PackageManager.INSTALL_SUCCEEDED) { 13957 cleanUp(move.toUuid); 13958 return false; 13959 } 13960 13961 // Reflect the move in app info 13962 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13963 pkg.setApplicationInfoCodePath(pkg.codePath); 13964 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13965 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13966 pkg.setApplicationInfoResourcePath(pkg.codePath); 13967 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13968 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13969 13970 return true; 13971 } 13972 13973 int doPostInstall(int status, int uid) { 13974 if (status == PackageManager.INSTALL_SUCCEEDED) { 13975 cleanUp(move.fromUuid); 13976 } else { 13977 cleanUp(move.toUuid); 13978 } 13979 return status; 13980 } 13981 13982 @Override 13983 String getCodePath() { 13984 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13985 } 13986 13987 @Override 13988 String getResourcePath() { 13989 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13990 } 13991 13992 private boolean cleanUp(String volumeUuid) { 13993 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13994 move.dataAppName); 13995 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13996 final int[] userIds = sUserManager.getUserIds(); 13997 synchronized (mInstallLock) { 13998 // Clean up both app data and code 13999 // All package moves are frozen until finished 14000 for (int userId : userIds) { 14001 try { 14002 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14003 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14004 } catch (InstallerException e) { 14005 Slog.w(TAG, String.valueOf(e)); 14006 } 14007 } 14008 removeCodePathLI(codeFile); 14009 } 14010 return true; 14011 } 14012 14013 void cleanUpResourcesLI() { 14014 throw new UnsupportedOperationException(); 14015 } 14016 14017 boolean doPostDeleteLI(boolean delete) { 14018 throw new UnsupportedOperationException(); 14019 } 14020 } 14021 14022 static String getAsecPackageName(String packageCid) { 14023 int idx = packageCid.lastIndexOf("-"); 14024 if (idx == -1) { 14025 return packageCid; 14026 } 14027 return packageCid.substring(0, idx); 14028 } 14029 14030 // Utility method used to create code paths based on package name and available index. 14031 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14032 String idxStr = ""; 14033 int idx = 1; 14034 // Fall back to default value of idx=1 if prefix is not 14035 // part of oldCodePath 14036 if (oldCodePath != null) { 14037 String subStr = oldCodePath; 14038 // Drop the suffix right away 14039 if (suffix != null && subStr.endsWith(suffix)) { 14040 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14041 } 14042 // If oldCodePath already contains prefix find out the 14043 // ending index to either increment or decrement. 14044 int sidx = subStr.lastIndexOf(prefix); 14045 if (sidx != -1) { 14046 subStr = subStr.substring(sidx + prefix.length()); 14047 if (subStr != null) { 14048 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14049 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14050 } 14051 try { 14052 idx = Integer.parseInt(subStr); 14053 if (idx <= 1) { 14054 idx++; 14055 } else { 14056 idx--; 14057 } 14058 } catch(NumberFormatException e) { 14059 } 14060 } 14061 } 14062 } 14063 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14064 return prefix + idxStr; 14065 } 14066 14067 private File getNextCodePath(File targetDir, String packageName) { 14068 int suffix = 1; 14069 File result; 14070 do { 14071 result = new File(targetDir, packageName + "-" + suffix); 14072 suffix++; 14073 } while (result.exists()); 14074 return result; 14075 } 14076 14077 // Utility method that returns the relative package path with respect 14078 // to the installation directory. Like say for /data/data/com.test-1.apk 14079 // string com.test-1 is returned. 14080 static String deriveCodePathName(String codePath) { 14081 if (codePath == null) { 14082 return null; 14083 } 14084 final File codeFile = new File(codePath); 14085 final String name = codeFile.getName(); 14086 if (codeFile.isDirectory()) { 14087 return name; 14088 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14089 final int lastDot = name.lastIndexOf('.'); 14090 return name.substring(0, lastDot); 14091 } else { 14092 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14093 return null; 14094 } 14095 } 14096 14097 static class PackageInstalledInfo { 14098 String name; 14099 int uid; 14100 // The set of users that originally had this package installed. 14101 int[] origUsers; 14102 // The set of users that now have this package installed. 14103 int[] newUsers; 14104 PackageParser.Package pkg; 14105 int returnCode; 14106 String returnMsg; 14107 PackageRemovedInfo removedInfo; 14108 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14109 14110 public void setError(int code, String msg) { 14111 setReturnCode(code); 14112 setReturnMessage(msg); 14113 Slog.w(TAG, msg); 14114 } 14115 14116 public void setError(String msg, PackageParserException e) { 14117 setReturnCode(e.error); 14118 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14119 Slog.w(TAG, msg, e); 14120 } 14121 14122 public void setError(String msg, PackageManagerException e) { 14123 returnCode = e.error; 14124 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14125 Slog.w(TAG, msg, e); 14126 } 14127 14128 public void setReturnCode(int returnCode) { 14129 this.returnCode = returnCode; 14130 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14131 for (int i = 0; i < childCount; i++) { 14132 addedChildPackages.valueAt(i).returnCode = returnCode; 14133 } 14134 } 14135 14136 private void setReturnMessage(String returnMsg) { 14137 this.returnMsg = returnMsg; 14138 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14139 for (int i = 0; i < childCount; i++) { 14140 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14141 } 14142 } 14143 14144 // In some error cases we want to convey more info back to the observer 14145 String origPackage; 14146 String origPermission; 14147 } 14148 14149 /* 14150 * Install a non-existing package. 14151 */ 14152 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14153 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14154 PackageInstalledInfo res) { 14155 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14156 14157 // Remember this for later, in case we need to rollback this install 14158 String pkgName = pkg.packageName; 14159 14160 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14161 14162 synchronized(mPackages) { 14163 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14164 // A package with the same name is already installed, though 14165 // it has been renamed to an older name. The package we 14166 // are trying to install should be installed as an update to 14167 // the existing one, but that has not been requested, so bail. 14168 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14169 + " without first uninstalling package running as " 14170 + mSettings.mRenamedPackages.get(pkgName)); 14171 return; 14172 } 14173 if (mPackages.containsKey(pkgName)) { 14174 // Don't allow installation over an existing package with the same name. 14175 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14176 + " without first uninstalling."); 14177 return; 14178 } 14179 } 14180 14181 try { 14182 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14183 System.currentTimeMillis(), user); 14184 14185 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14186 14187 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14188 prepareAppDataAfterInstallLIF(newPackage); 14189 14190 } else { 14191 // Remove package from internal structures, but keep around any 14192 // data that might have already existed 14193 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14194 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14195 } 14196 } catch (PackageManagerException e) { 14197 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14198 } 14199 14200 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14201 } 14202 14203 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14204 // Can't rotate keys during boot or if sharedUser. 14205 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14206 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14207 return false; 14208 } 14209 // app is using upgradeKeySets; make sure all are valid 14210 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14211 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14212 for (int i = 0; i < upgradeKeySets.length; i++) { 14213 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14214 Slog.wtf(TAG, "Package " 14215 + (oldPs.name != null ? oldPs.name : "<null>") 14216 + " contains upgrade-key-set reference to unknown key-set: " 14217 + upgradeKeySets[i] 14218 + " reverting to signatures check."); 14219 return false; 14220 } 14221 } 14222 return true; 14223 } 14224 14225 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14226 // Upgrade keysets are being used. Determine if new package has a superset of the 14227 // required keys. 14228 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14229 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14230 for (int i = 0; i < upgradeKeySets.length; i++) { 14231 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14232 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14233 return true; 14234 } 14235 } 14236 return false; 14237 } 14238 14239 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14240 try (DigestInputStream digestStream = 14241 new DigestInputStream(new FileInputStream(file), digest)) { 14242 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14243 } 14244 } 14245 14246 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14247 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14248 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14249 14250 final PackageParser.Package oldPackage; 14251 final String pkgName = pkg.packageName; 14252 final int[] allUsers; 14253 final int[] installedUsers; 14254 14255 synchronized(mPackages) { 14256 oldPackage = mPackages.get(pkgName); 14257 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14258 14259 // don't allow upgrade to target a release SDK from a pre-release SDK 14260 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14261 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14262 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14263 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14264 if (oldTargetsPreRelease 14265 && !newTargetsPreRelease 14266 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14267 Slog.w(TAG, "Can't install package targeting released sdk"); 14268 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14269 return; 14270 } 14271 14272 // don't allow an upgrade from full to ephemeral 14273 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14274 if (isEphemeral && !oldIsEphemeral) { 14275 // can't downgrade from full to ephemeral 14276 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14277 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14278 return; 14279 } 14280 14281 // verify signatures are valid 14282 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14283 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14284 if (!checkUpgradeKeySetLP(ps, pkg)) { 14285 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14286 "New package not signed by keys specified by upgrade-keysets: " 14287 + pkgName); 14288 return; 14289 } 14290 } else { 14291 // default to original signature matching 14292 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14293 != PackageManager.SIGNATURE_MATCH) { 14294 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14295 "New package has a different signature: " + pkgName); 14296 return; 14297 } 14298 } 14299 14300 // don't allow a system upgrade unless the upgrade hash matches 14301 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14302 byte[] digestBytes = null; 14303 try { 14304 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14305 updateDigest(digest, new File(pkg.baseCodePath)); 14306 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14307 for (String path : pkg.splitCodePaths) { 14308 updateDigest(digest, new File(path)); 14309 } 14310 } 14311 digestBytes = digest.digest(); 14312 } catch (NoSuchAlgorithmException | IOException e) { 14313 res.setError(INSTALL_FAILED_INVALID_APK, 14314 "Could not compute hash: " + pkgName); 14315 return; 14316 } 14317 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14318 res.setError(INSTALL_FAILED_INVALID_APK, 14319 "New package fails restrict-update check: " + pkgName); 14320 return; 14321 } 14322 // retain upgrade restriction 14323 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14324 } 14325 14326 // Check for shared user id changes 14327 String invalidPackageName = 14328 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14329 if (invalidPackageName != null) { 14330 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14331 "Package " + invalidPackageName + " tried to change user " 14332 + oldPackage.mSharedUserId); 14333 return; 14334 } 14335 14336 // In case of rollback, remember per-user/profile install state 14337 allUsers = sUserManager.getUserIds(); 14338 installedUsers = ps.queryInstalledUsers(allUsers, true); 14339 } 14340 14341 // Update what is removed 14342 res.removedInfo = new PackageRemovedInfo(); 14343 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14344 res.removedInfo.removedPackage = oldPackage.packageName; 14345 res.removedInfo.isUpdate = true; 14346 res.removedInfo.origUsers = installedUsers; 14347 final int childCount = (oldPackage.childPackages != null) 14348 ? oldPackage.childPackages.size() : 0; 14349 for (int i = 0; i < childCount; i++) { 14350 boolean childPackageUpdated = false; 14351 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14352 if (res.addedChildPackages != null) { 14353 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14354 if (childRes != null) { 14355 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14356 childRes.removedInfo.removedPackage = childPkg.packageName; 14357 childRes.removedInfo.isUpdate = true; 14358 childPackageUpdated = true; 14359 } 14360 } 14361 if (!childPackageUpdated) { 14362 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14363 childRemovedRes.removedPackage = childPkg.packageName; 14364 childRemovedRes.isUpdate = false; 14365 childRemovedRes.dataRemoved = true; 14366 synchronized (mPackages) { 14367 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14368 if (childPs != null) { 14369 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14370 } 14371 } 14372 if (res.removedInfo.removedChildPackages == null) { 14373 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14374 } 14375 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14376 } 14377 } 14378 14379 boolean sysPkg = (isSystemApp(oldPackage)); 14380 if (sysPkg) { 14381 // Set the system/privileged flags as needed 14382 final boolean privileged = 14383 (oldPackage.applicationInfo.privateFlags 14384 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14385 final int systemPolicyFlags = policyFlags 14386 | PackageParser.PARSE_IS_SYSTEM 14387 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14388 14389 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14390 user, allUsers, installerPackageName, res); 14391 } else { 14392 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14393 user, allUsers, installerPackageName, res); 14394 } 14395 } 14396 14397 public List<String> getPreviousCodePaths(String packageName) { 14398 final PackageSetting ps = mSettings.mPackages.get(packageName); 14399 final List<String> result = new ArrayList<String>(); 14400 if (ps != null && ps.oldCodePaths != null) { 14401 result.addAll(ps.oldCodePaths); 14402 } 14403 return result; 14404 } 14405 14406 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14407 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14408 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14409 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14410 + deletedPackage); 14411 14412 String pkgName = deletedPackage.packageName; 14413 boolean deletedPkg = true; 14414 boolean addedPkg = false; 14415 boolean updatedSettings = false; 14416 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14417 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14418 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14419 14420 final long origUpdateTime = (pkg.mExtras != null) 14421 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14422 14423 // First delete the existing package while retaining the data directory 14424 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14425 res.removedInfo, true, pkg)) { 14426 // If the existing package wasn't successfully deleted 14427 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14428 deletedPkg = false; 14429 } else { 14430 // Successfully deleted the old package; proceed with replace. 14431 14432 // If deleted package lived in a container, give users a chance to 14433 // relinquish resources before killing. 14434 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14435 if (DEBUG_INSTALL) { 14436 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14437 } 14438 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14439 final ArrayList<String> pkgList = new ArrayList<String>(1); 14440 pkgList.add(deletedPackage.applicationInfo.packageName); 14441 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14442 } 14443 14444 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14445 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14446 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14447 14448 try { 14449 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14450 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14451 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14452 14453 // Update the in-memory copy of the previous code paths. 14454 PackageSetting ps = mSettings.mPackages.get(pkgName); 14455 if (!killApp) { 14456 if (ps.oldCodePaths == null) { 14457 ps.oldCodePaths = new ArraySet<>(); 14458 } 14459 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14460 if (deletedPackage.splitCodePaths != null) { 14461 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14462 } 14463 } else { 14464 ps.oldCodePaths = null; 14465 } 14466 if (ps.childPackageNames != null) { 14467 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14468 final String childPkgName = ps.childPackageNames.get(i); 14469 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14470 childPs.oldCodePaths = ps.oldCodePaths; 14471 } 14472 } 14473 prepareAppDataAfterInstallLIF(newPackage); 14474 addedPkg = true; 14475 } catch (PackageManagerException e) { 14476 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14477 } 14478 } 14479 14480 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14481 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14482 14483 // Revert all internal state mutations and added folders for the failed install 14484 if (addedPkg) { 14485 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14486 res.removedInfo, true, null); 14487 } 14488 14489 // Restore the old package 14490 if (deletedPkg) { 14491 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14492 File restoreFile = new File(deletedPackage.codePath); 14493 // Parse old package 14494 boolean oldExternal = isExternal(deletedPackage); 14495 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14496 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14497 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14498 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14499 try { 14500 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14501 null); 14502 } catch (PackageManagerException e) { 14503 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14504 + e.getMessage()); 14505 return; 14506 } 14507 14508 synchronized (mPackages) { 14509 // Ensure the installer package name up to date 14510 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14511 14512 // Update permissions for restored package 14513 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14514 14515 mSettings.writeLPr(); 14516 } 14517 14518 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14519 } 14520 } else { 14521 synchronized (mPackages) { 14522 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14523 if (ps != null) { 14524 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14525 if (res.removedInfo.removedChildPackages != null) { 14526 final int childCount = res.removedInfo.removedChildPackages.size(); 14527 // Iterate in reverse as we may modify the collection 14528 for (int i = childCount - 1; i >= 0; i--) { 14529 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14530 if (res.addedChildPackages.containsKey(childPackageName)) { 14531 res.removedInfo.removedChildPackages.removeAt(i); 14532 } else { 14533 PackageRemovedInfo childInfo = res.removedInfo 14534 .removedChildPackages.valueAt(i); 14535 childInfo.removedForAllUsers = mPackages.get( 14536 childInfo.removedPackage) == null; 14537 } 14538 } 14539 } 14540 } 14541 } 14542 } 14543 } 14544 14545 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14546 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14547 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14548 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14549 + ", old=" + deletedPackage); 14550 14551 final boolean disabledSystem; 14552 14553 // Remove existing system package 14554 removePackageLI(deletedPackage, true); 14555 14556 synchronized (mPackages) { 14557 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14558 } 14559 if (!disabledSystem) { 14560 // We didn't need to disable the .apk as a current system package, 14561 // which means we are replacing another update that is already 14562 // installed. We need to make sure to delete the older one's .apk. 14563 res.removedInfo.args = createInstallArgsForExisting(0, 14564 deletedPackage.applicationInfo.getCodePath(), 14565 deletedPackage.applicationInfo.getResourcePath(), 14566 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14567 } else { 14568 res.removedInfo.args = null; 14569 } 14570 14571 // Successfully disabled the old package. Now proceed with re-installation 14572 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14573 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14574 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14575 14576 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14577 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14578 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14579 14580 PackageParser.Package newPackage = null; 14581 try { 14582 // Add the package to the internal data structures 14583 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14584 14585 // Set the update and install times 14586 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14587 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14588 System.currentTimeMillis()); 14589 14590 // Update the package dynamic state if succeeded 14591 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14592 // Now that the install succeeded make sure we remove data 14593 // directories for any child package the update removed. 14594 final int deletedChildCount = (deletedPackage.childPackages != null) 14595 ? deletedPackage.childPackages.size() : 0; 14596 final int newChildCount = (newPackage.childPackages != null) 14597 ? newPackage.childPackages.size() : 0; 14598 for (int i = 0; i < deletedChildCount; i++) { 14599 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14600 boolean childPackageDeleted = true; 14601 for (int j = 0; j < newChildCount; j++) { 14602 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14603 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14604 childPackageDeleted = false; 14605 break; 14606 } 14607 } 14608 if (childPackageDeleted) { 14609 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14610 deletedChildPkg.packageName); 14611 if (ps != null && res.removedInfo.removedChildPackages != null) { 14612 PackageRemovedInfo removedChildRes = res.removedInfo 14613 .removedChildPackages.get(deletedChildPkg.packageName); 14614 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14615 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14616 } 14617 } 14618 } 14619 14620 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14621 prepareAppDataAfterInstallLIF(newPackage); 14622 } 14623 } catch (PackageManagerException e) { 14624 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14625 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14626 } 14627 14628 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14629 // Re installation failed. Restore old information 14630 // Remove new pkg information 14631 if (newPackage != null) { 14632 removeInstalledPackageLI(newPackage, true); 14633 } 14634 // Add back the old system package 14635 try { 14636 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14637 } catch (PackageManagerException e) { 14638 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14639 } 14640 14641 synchronized (mPackages) { 14642 if (disabledSystem) { 14643 enableSystemPackageLPw(deletedPackage); 14644 } 14645 14646 // Ensure the installer package name up to date 14647 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14648 14649 // Update permissions for restored package 14650 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14651 14652 mSettings.writeLPr(); 14653 } 14654 14655 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14656 + " after failed upgrade"); 14657 } 14658 } 14659 14660 /** 14661 * Checks whether the parent or any of the child packages have a change shared 14662 * user. For a package to be a valid update the shred users of the parent and 14663 * the children should match. We may later support changing child shared users. 14664 * @param oldPkg The updated package. 14665 * @param newPkg The update package. 14666 * @return The shared user that change between the versions. 14667 */ 14668 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14669 PackageParser.Package newPkg) { 14670 // Check parent shared user 14671 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14672 return newPkg.packageName; 14673 } 14674 // Check child shared users 14675 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14676 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14677 for (int i = 0; i < newChildCount; i++) { 14678 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14679 // If this child was present, did it have the same shared user? 14680 for (int j = 0; j < oldChildCount; j++) { 14681 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14682 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14683 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14684 return newChildPkg.packageName; 14685 } 14686 } 14687 } 14688 return null; 14689 } 14690 14691 private void removeNativeBinariesLI(PackageSetting ps) { 14692 // Remove the lib path for the parent package 14693 if (ps != null) { 14694 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14695 // Remove the lib path for the child packages 14696 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14697 for (int i = 0; i < childCount; i++) { 14698 PackageSetting childPs = null; 14699 synchronized (mPackages) { 14700 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14701 } 14702 if (childPs != null) { 14703 NativeLibraryHelper.removeNativeBinariesLI(childPs 14704 .legacyNativeLibraryPathString); 14705 } 14706 } 14707 } 14708 } 14709 14710 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14711 // Enable the parent package 14712 mSettings.enableSystemPackageLPw(pkg.packageName); 14713 // Enable the child packages 14714 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14715 for (int i = 0; i < childCount; i++) { 14716 PackageParser.Package childPkg = pkg.childPackages.get(i); 14717 mSettings.enableSystemPackageLPw(childPkg.packageName); 14718 } 14719 } 14720 14721 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14722 PackageParser.Package newPkg) { 14723 // Disable the parent package (parent always replaced) 14724 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14725 // Disable the child packages 14726 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14727 for (int i = 0; i < childCount; i++) { 14728 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14729 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14730 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14731 } 14732 return disabled; 14733 } 14734 14735 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14736 String installerPackageName) { 14737 // Enable the parent package 14738 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14739 // Enable the child packages 14740 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14741 for (int i = 0; i < childCount; i++) { 14742 PackageParser.Package childPkg = pkg.childPackages.get(i); 14743 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14744 } 14745 } 14746 14747 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14748 // Collect all used permissions in the UID 14749 ArraySet<String> usedPermissions = new ArraySet<>(); 14750 final int packageCount = su.packages.size(); 14751 for (int i = 0; i < packageCount; i++) { 14752 PackageSetting ps = su.packages.valueAt(i); 14753 if (ps.pkg == null) { 14754 continue; 14755 } 14756 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14757 for (int j = 0; j < requestedPermCount; j++) { 14758 String permission = ps.pkg.requestedPermissions.get(j); 14759 BasePermission bp = mSettings.mPermissions.get(permission); 14760 if (bp != null) { 14761 usedPermissions.add(permission); 14762 } 14763 } 14764 } 14765 14766 PermissionsState permissionsState = su.getPermissionsState(); 14767 // Prune install permissions 14768 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14769 final int installPermCount = installPermStates.size(); 14770 for (int i = installPermCount - 1; i >= 0; i--) { 14771 PermissionState permissionState = installPermStates.get(i); 14772 if (!usedPermissions.contains(permissionState.getName())) { 14773 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14774 if (bp != null) { 14775 permissionsState.revokeInstallPermission(bp); 14776 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14777 PackageManager.MASK_PERMISSION_FLAGS, 0); 14778 } 14779 } 14780 } 14781 14782 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14783 14784 // Prune runtime permissions 14785 for (int userId : allUserIds) { 14786 List<PermissionState> runtimePermStates = permissionsState 14787 .getRuntimePermissionStates(userId); 14788 final int runtimePermCount = runtimePermStates.size(); 14789 for (int i = runtimePermCount - 1; i >= 0; i--) { 14790 PermissionState permissionState = runtimePermStates.get(i); 14791 if (!usedPermissions.contains(permissionState.getName())) { 14792 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14793 if (bp != null) { 14794 permissionsState.revokeRuntimePermission(bp, userId); 14795 permissionsState.updatePermissionFlags(bp, userId, 14796 PackageManager.MASK_PERMISSION_FLAGS, 0); 14797 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14798 runtimePermissionChangedUserIds, userId); 14799 } 14800 } 14801 } 14802 } 14803 14804 return runtimePermissionChangedUserIds; 14805 } 14806 14807 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14808 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14809 // Update the parent package setting 14810 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14811 res, user); 14812 // Update the child packages setting 14813 final int childCount = (newPackage.childPackages != null) 14814 ? newPackage.childPackages.size() : 0; 14815 for (int i = 0; i < childCount; i++) { 14816 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14817 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14818 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14819 childRes.origUsers, childRes, user); 14820 } 14821 } 14822 14823 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14824 String installerPackageName, int[] allUsers, int[] installedForUsers, 14825 PackageInstalledInfo res, UserHandle user) { 14826 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14827 14828 String pkgName = newPackage.packageName; 14829 synchronized (mPackages) { 14830 //write settings. the installStatus will be incomplete at this stage. 14831 //note that the new package setting would have already been 14832 //added to mPackages. It hasn't been persisted yet. 14833 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14834 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14835 mSettings.writeLPr(); 14836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14837 } 14838 14839 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14840 synchronized (mPackages) { 14841 updatePermissionsLPw(newPackage.packageName, newPackage, 14842 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14843 ? UPDATE_PERMISSIONS_ALL : 0)); 14844 // For system-bundled packages, we assume that installing an upgraded version 14845 // of the package implies that the user actually wants to run that new code, 14846 // so we enable the package. 14847 PackageSetting ps = mSettings.mPackages.get(pkgName); 14848 final int userId = user.getIdentifier(); 14849 if (ps != null) { 14850 if (isSystemApp(newPackage)) { 14851 if (DEBUG_INSTALL) { 14852 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14853 } 14854 // Enable system package for requested users 14855 if (res.origUsers != null) { 14856 for (int origUserId : res.origUsers) { 14857 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14858 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14859 origUserId, installerPackageName); 14860 } 14861 } 14862 } 14863 // Also convey the prior install/uninstall state 14864 if (allUsers != null && installedForUsers != null) { 14865 for (int currentUserId : allUsers) { 14866 final boolean installed = ArrayUtils.contains( 14867 installedForUsers, currentUserId); 14868 if (DEBUG_INSTALL) { 14869 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14870 } 14871 ps.setInstalled(installed, currentUserId); 14872 } 14873 // these install state changes will be persisted in the 14874 // upcoming call to mSettings.writeLPr(). 14875 } 14876 } 14877 // It's implied that when a user requests installation, they want the app to be 14878 // installed and enabled. 14879 if (userId != UserHandle.USER_ALL) { 14880 ps.setInstalled(true, userId); 14881 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14882 } 14883 } 14884 res.name = pkgName; 14885 res.uid = newPackage.applicationInfo.uid; 14886 res.pkg = newPackage; 14887 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14888 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14889 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14890 //to update install status 14891 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14892 mSettings.writeLPr(); 14893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14894 } 14895 14896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14897 } 14898 14899 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14900 try { 14901 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14902 installPackageLI(args, res); 14903 } finally { 14904 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14905 } 14906 } 14907 14908 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14909 final int installFlags = args.installFlags; 14910 final String installerPackageName = args.installerPackageName; 14911 final String volumeUuid = args.volumeUuid; 14912 final File tmpPackageFile = new File(args.getCodePath()); 14913 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14914 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14915 || (args.volumeUuid != null)); 14916 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14917 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14918 boolean replace = false; 14919 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14920 if (args.move != null) { 14921 // moving a complete application; perform an initial scan on the new install location 14922 scanFlags |= SCAN_INITIAL; 14923 } 14924 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14925 scanFlags |= SCAN_DONT_KILL_APP; 14926 } 14927 14928 // Result object to be returned 14929 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14930 14931 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14932 14933 // Sanity check 14934 if (ephemeral && (forwardLocked || onExternal)) { 14935 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14936 + " external=" + onExternal); 14937 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14938 return; 14939 } 14940 14941 // Retrieve PackageSettings and parse package 14942 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14943 | PackageParser.PARSE_ENFORCE_CODE 14944 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14945 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14946 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14947 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14948 PackageParser pp = new PackageParser(); 14949 pp.setSeparateProcesses(mSeparateProcesses); 14950 pp.setDisplayMetrics(mMetrics); 14951 14952 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14953 final PackageParser.Package pkg; 14954 try { 14955 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14956 } catch (PackageParserException e) { 14957 res.setError("Failed parse during installPackageLI", e); 14958 return; 14959 } finally { 14960 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14961 } 14962 14963 // If we are installing a clustered package add results for the children 14964 if (pkg.childPackages != null) { 14965 synchronized (mPackages) { 14966 final int childCount = pkg.childPackages.size(); 14967 for (int i = 0; i < childCount; i++) { 14968 PackageParser.Package childPkg = pkg.childPackages.get(i); 14969 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14970 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14971 childRes.pkg = childPkg; 14972 childRes.name = childPkg.packageName; 14973 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14974 if (childPs != null) { 14975 childRes.origUsers = childPs.queryInstalledUsers( 14976 sUserManager.getUserIds(), true); 14977 } 14978 if ((mPackages.containsKey(childPkg.packageName))) { 14979 childRes.removedInfo = new PackageRemovedInfo(); 14980 childRes.removedInfo.removedPackage = childPkg.packageName; 14981 } 14982 if (res.addedChildPackages == null) { 14983 res.addedChildPackages = new ArrayMap<>(); 14984 } 14985 res.addedChildPackages.put(childPkg.packageName, childRes); 14986 } 14987 } 14988 } 14989 14990 // If package doesn't declare API override, mark that we have an install 14991 // time CPU ABI override. 14992 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14993 pkg.cpuAbiOverride = args.abiOverride; 14994 } 14995 14996 String pkgName = res.name = pkg.packageName; 14997 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14998 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14999 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15000 return; 15001 } 15002 } 15003 15004 try { 15005 // either use what we've been given or parse directly from the APK 15006 if (args.certificates != null) { 15007 try { 15008 PackageParser.populateCertificates(pkg, args.certificates); 15009 } catch (PackageParserException e) { 15010 // there was something wrong with the certificates we were given; 15011 // try to pull them from the APK 15012 PackageParser.collectCertificates(pkg, parseFlags); 15013 } 15014 } else { 15015 PackageParser.collectCertificates(pkg, parseFlags); 15016 } 15017 } catch (PackageParserException e) { 15018 res.setError("Failed collect during installPackageLI", e); 15019 return; 15020 } 15021 15022 // Get rid of all references to package scan path via parser. 15023 pp = null; 15024 String oldCodePath = null; 15025 boolean systemApp = false; 15026 synchronized (mPackages) { 15027 // Check if installing already existing package 15028 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15029 String oldName = mSettings.mRenamedPackages.get(pkgName); 15030 if (pkg.mOriginalPackages != null 15031 && pkg.mOriginalPackages.contains(oldName) 15032 && mPackages.containsKey(oldName)) { 15033 // This package is derived from an original package, 15034 // and this device has been updating from that original 15035 // name. We must continue using the original name, so 15036 // rename the new package here. 15037 pkg.setPackageName(oldName); 15038 pkgName = pkg.packageName; 15039 replace = true; 15040 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15041 + oldName + " pkgName=" + pkgName); 15042 } else if (mPackages.containsKey(pkgName)) { 15043 // This package, under its official name, already exists 15044 // on the device; we should replace it. 15045 replace = true; 15046 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15047 } 15048 15049 // Child packages are installed through the parent package 15050 if (pkg.parentPackage != null) { 15051 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15052 "Package " + pkg.packageName + " is child of package " 15053 + pkg.parentPackage.parentPackage + ". Child packages " 15054 + "can be updated only through the parent package."); 15055 return; 15056 } 15057 15058 if (replace) { 15059 // Prevent apps opting out from runtime permissions 15060 PackageParser.Package oldPackage = mPackages.get(pkgName); 15061 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15062 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15063 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15064 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15065 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15066 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15067 + " doesn't support runtime permissions but the old" 15068 + " target SDK " + oldTargetSdk + " does."); 15069 return; 15070 } 15071 15072 // Prevent installing of child packages 15073 if (oldPackage.parentPackage != null) { 15074 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15075 "Package " + pkg.packageName + " is child of package " 15076 + oldPackage.parentPackage + ". Child packages " 15077 + "can be updated only through the parent package."); 15078 return; 15079 } 15080 } 15081 } 15082 15083 PackageSetting ps = mSettings.mPackages.get(pkgName); 15084 if (ps != null) { 15085 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15086 15087 // Quick sanity check that we're signed correctly if updating; 15088 // we'll check this again later when scanning, but we want to 15089 // bail early here before tripping over redefined permissions. 15090 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15091 if (!checkUpgradeKeySetLP(ps, pkg)) { 15092 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15093 + pkg.packageName + " upgrade keys do not match the " 15094 + "previously installed version"); 15095 return; 15096 } 15097 } else { 15098 try { 15099 verifySignaturesLP(ps, pkg); 15100 } catch (PackageManagerException e) { 15101 res.setError(e.error, e.getMessage()); 15102 return; 15103 } 15104 } 15105 15106 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15107 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15108 systemApp = (ps.pkg.applicationInfo.flags & 15109 ApplicationInfo.FLAG_SYSTEM) != 0; 15110 } 15111 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15112 } 15113 15114 // Check whether the newly-scanned package wants to define an already-defined perm 15115 int N = pkg.permissions.size(); 15116 for (int i = N-1; i >= 0; i--) { 15117 PackageParser.Permission perm = pkg.permissions.get(i); 15118 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15119 if (bp != null) { 15120 // If the defining package is signed with our cert, it's okay. This 15121 // also includes the "updating the same package" case, of course. 15122 // "updating same package" could also involve key-rotation. 15123 final boolean sigsOk; 15124 if (bp.sourcePackage.equals(pkg.packageName) 15125 && (bp.packageSetting instanceof PackageSetting) 15126 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15127 scanFlags))) { 15128 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15129 } else { 15130 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15131 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15132 } 15133 if (!sigsOk) { 15134 // If the owning package is the system itself, we log but allow 15135 // install to proceed; we fail the install on all other permission 15136 // redefinitions. 15137 if (!bp.sourcePackage.equals("android")) { 15138 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15139 + pkg.packageName + " attempting to redeclare permission " 15140 + perm.info.name + " already owned by " + bp.sourcePackage); 15141 res.origPermission = perm.info.name; 15142 res.origPackage = bp.sourcePackage; 15143 return; 15144 } else { 15145 Slog.w(TAG, "Package " + pkg.packageName 15146 + " attempting to redeclare system permission " 15147 + perm.info.name + "; ignoring new declaration"); 15148 pkg.permissions.remove(i); 15149 } 15150 } 15151 } 15152 } 15153 } 15154 15155 if (systemApp) { 15156 if (onExternal) { 15157 // Abort update; system app can't be replaced with app on sdcard 15158 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15159 "Cannot install updates to system apps on sdcard"); 15160 return; 15161 } else if (ephemeral) { 15162 // Abort update; system app can't be replaced with an ephemeral app 15163 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15164 "Cannot update a system app with an ephemeral app"); 15165 return; 15166 } 15167 } 15168 15169 if (args.move != null) { 15170 // We did an in-place move, so dex is ready to roll 15171 scanFlags |= SCAN_NO_DEX; 15172 scanFlags |= SCAN_MOVE; 15173 15174 synchronized (mPackages) { 15175 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15176 if (ps == null) { 15177 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15178 "Missing settings for moved package " + pkgName); 15179 } 15180 15181 // We moved the entire application as-is, so bring over the 15182 // previously derived ABI information. 15183 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15184 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15185 } 15186 15187 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15188 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15189 scanFlags |= SCAN_NO_DEX; 15190 15191 try { 15192 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15193 args.abiOverride : pkg.cpuAbiOverride); 15194 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15195 true /* extract libs */); 15196 } catch (PackageManagerException pme) { 15197 Slog.e(TAG, "Error deriving application ABI", pme); 15198 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15199 return; 15200 } 15201 15202 // Shared libraries for the package need to be updated. 15203 synchronized (mPackages) { 15204 try { 15205 updateSharedLibrariesLPw(pkg, null); 15206 } catch (PackageManagerException e) { 15207 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15208 } 15209 } 15210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15211 // Do not run PackageDexOptimizer through the local performDexOpt 15212 // method because `pkg` may not be in `mPackages` yet. 15213 // 15214 // Also, don't fail application installs if the dexopt step fails. 15215 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15216 null /* instructionSets */, false /* checkProfiles */, 15217 getCompilerFilterForReason(REASON_INSTALL)); 15218 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15219 15220 // Notify BackgroundDexOptService that the package has been changed. 15221 // If this is an update of a package which used to fail to compile, 15222 // BDOS will remove it from its blacklist. 15223 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15224 } 15225 15226 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15227 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15228 return; 15229 } 15230 15231 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15232 15233 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15234 "installPackageLI")) { 15235 if (replace) { 15236 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15237 installerPackageName, res); 15238 } else { 15239 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15240 args.user, installerPackageName, volumeUuid, res); 15241 } 15242 } 15243 synchronized (mPackages) { 15244 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15245 if (ps != null) { 15246 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15247 } 15248 15249 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15250 for (int i = 0; i < childCount; i++) { 15251 PackageParser.Package childPkg = pkg.childPackages.get(i); 15252 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15253 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15254 if (childPs != null) { 15255 childRes.newUsers = childPs.queryInstalledUsers( 15256 sUserManager.getUserIds(), true); 15257 } 15258 } 15259 } 15260 } 15261 15262 private void startIntentFilterVerifications(int userId, boolean replacing, 15263 PackageParser.Package pkg) { 15264 if (mIntentFilterVerifierComponent == null) { 15265 Slog.w(TAG, "No IntentFilter verification will not be done as " 15266 + "there is no IntentFilterVerifier available!"); 15267 return; 15268 } 15269 15270 final int verifierUid = getPackageUid( 15271 mIntentFilterVerifierComponent.getPackageName(), 15272 MATCH_DEBUG_TRIAGED_MISSING, 15273 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15274 15275 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15276 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15277 mHandler.sendMessage(msg); 15278 15279 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15280 for (int i = 0; i < childCount; i++) { 15281 PackageParser.Package childPkg = pkg.childPackages.get(i); 15282 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15283 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15284 mHandler.sendMessage(msg); 15285 } 15286 } 15287 15288 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15289 PackageParser.Package pkg) { 15290 int size = pkg.activities.size(); 15291 if (size == 0) { 15292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15293 "No activity, so no need to verify any IntentFilter!"); 15294 return; 15295 } 15296 15297 final boolean hasDomainURLs = hasDomainURLs(pkg); 15298 if (!hasDomainURLs) { 15299 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15300 "No domain URLs, so no need to verify any IntentFilter!"); 15301 return; 15302 } 15303 15304 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15305 + " if any IntentFilter from the " + size 15306 + " Activities needs verification ..."); 15307 15308 int count = 0; 15309 final String packageName = pkg.packageName; 15310 15311 synchronized (mPackages) { 15312 // If this is a new install and we see that we've already run verification for this 15313 // package, we have nothing to do: it means the state was restored from backup. 15314 if (!replacing) { 15315 IntentFilterVerificationInfo ivi = 15316 mSettings.getIntentFilterVerificationLPr(packageName); 15317 if (ivi != null) { 15318 if (DEBUG_DOMAIN_VERIFICATION) { 15319 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15320 + ivi.getStatusString()); 15321 } 15322 return; 15323 } 15324 } 15325 15326 // If any filters need to be verified, then all need to be. 15327 boolean needToVerify = false; 15328 for (PackageParser.Activity a : pkg.activities) { 15329 for (ActivityIntentInfo filter : a.intents) { 15330 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15331 if (DEBUG_DOMAIN_VERIFICATION) { 15332 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15333 } 15334 needToVerify = true; 15335 break; 15336 } 15337 } 15338 } 15339 15340 if (needToVerify) { 15341 final int verificationId = mIntentFilterVerificationToken++; 15342 for (PackageParser.Activity a : pkg.activities) { 15343 for (ActivityIntentInfo filter : a.intents) { 15344 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15345 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15346 "Verification needed for IntentFilter:" + filter.toString()); 15347 mIntentFilterVerifier.addOneIntentFilterVerification( 15348 verifierUid, userId, verificationId, filter, packageName); 15349 count++; 15350 } 15351 } 15352 } 15353 } 15354 } 15355 15356 if (count > 0) { 15357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15358 + " IntentFilter verification" + (count > 1 ? "s" : "") 15359 + " for userId:" + userId); 15360 mIntentFilterVerifier.startVerifications(userId); 15361 } else { 15362 if (DEBUG_DOMAIN_VERIFICATION) { 15363 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15364 } 15365 } 15366 } 15367 15368 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15369 final ComponentName cn = filter.activity.getComponentName(); 15370 final String packageName = cn.getPackageName(); 15371 15372 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15373 packageName); 15374 if (ivi == null) { 15375 return true; 15376 } 15377 int status = ivi.getStatus(); 15378 switch (status) { 15379 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15380 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15381 return true; 15382 15383 default: 15384 // Nothing to do 15385 return false; 15386 } 15387 } 15388 15389 private static boolean isMultiArch(ApplicationInfo info) { 15390 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15391 } 15392 15393 private static boolean isExternal(PackageParser.Package pkg) { 15394 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15395 } 15396 15397 private static boolean isExternal(PackageSetting ps) { 15398 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15399 } 15400 15401 private static boolean isEphemeral(PackageParser.Package pkg) { 15402 return pkg.applicationInfo.isEphemeralApp(); 15403 } 15404 15405 private static boolean isEphemeral(PackageSetting ps) { 15406 return ps.pkg != null && isEphemeral(ps.pkg); 15407 } 15408 15409 private static boolean isSystemApp(PackageParser.Package pkg) { 15410 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15411 } 15412 15413 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15414 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15415 } 15416 15417 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15418 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15419 } 15420 15421 private static boolean isSystemApp(PackageSetting ps) { 15422 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15423 } 15424 15425 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15426 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15427 } 15428 15429 private int packageFlagsToInstallFlags(PackageSetting ps) { 15430 int installFlags = 0; 15431 if (isEphemeral(ps)) { 15432 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15433 } 15434 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15435 // This existing package was an external ASEC install when we have 15436 // the external flag without a UUID 15437 installFlags |= PackageManager.INSTALL_EXTERNAL; 15438 } 15439 if (ps.isForwardLocked()) { 15440 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15441 } 15442 return installFlags; 15443 } 15444 15445 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15446 if (isExternal(pkg)) { 15447 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15448 return StorageManager.UUID_PRIMARY_PHYSICAL; 15449 } else { 15450 return pkg.volumeUuid; 15451 } 15452 } else { 15453 return StorageManager.UUID_PRIVATE_INTERNAL; 15454 } 15455 } 15456 15457 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15458 if (isExternal(pkg)) { 15459 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15460 return mSettings.getExternalVersion(); 15461 } else { 15462 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15463 } 15464 } else { 15465 return mSettings.getInternalVersion(); 15466 } 15467 } 15468 15469 private void deleteTempPackageFiles() { 15470 final FilenameFilter filter = new FilenameFilter() { 15471 public boolean accept(File dir, String name) { 15472 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15473 } 15474 }; 15475 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15476 file.delete(); 15477 } 15478 } 15479 15480 @Override 15481 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15482 int flags) { 15483 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15484 flags); 15485 } 15486 15487 @Override 15488 public void deletePackage(final String packageName, 15489 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15490 mContext.enforceCallingOrSelfPermission( 15491 android.Manifest.permission.DELETE_PACKAGES, null); 15492 Preconditions.checkNotNull(packageName); 15493 Preconditions.checkNotNull(observer); 15494 final int uid = Binder.getCallingUid(); 15495 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15496 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15497 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15498 mContext.enforceCallingOrSelfPermission( 15499 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15500 "deletePackage for user " + userId); 15501 } 15502 15503 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15504 try { 15505 observer.onPackageDeleted(packageName, 15506 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15507 } catch (RemoteException re) { 15508 } 15509 return; 15510 } 15511 15512 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15513 try { 15514 observer.onPackageDeleted(packageName, 15515 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15516 } catch (RemoteException re) { 15517 } 15518 return; 15519 } 15520 15521 if (DEBUG_REMOVE) { 15522 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15523 + " deleteAllUsers: " + deleteAllUsers ); 15524 } 15525 // Queue up an async operation since the package deletion may take a little while. 15526 mHandler.post(new Runnable() { 15527 public void run() { 15528 mHandler.removeCallbacks(this); 15529 int returnCode; 15530 if (!deleteAllUsers) { 15531 returnCode = deletePackageX(packageName, userId, deleteFlags); 15532 } else { 15533 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15534 // If nobody is blocking uninstall, proceed with delete for all users 15535 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15536 returnCode = deletePackageX(packageName, userId, deleteFlags); 15537 } else { 15538 // Otherwise uninstall individually for users with blockUninstalls=false 15539 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15540 for (int userId : users) { 15541 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15542 returnCode = deletePackageX(packageName, userId, userFlags); 15543 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15544 Slog.w(TAG, "Package delete failed for user " + userId 15545 + ", returnCode " + returnCode); 15546 } 15547 } 15548 } 15549 // The app has only been marked uninstalled for certain users. 15550 // We still need to report that delete was blocked 15551 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15552 } 15553 } 15554 try { 15555 observer.onPackageDeleted(packageName, returnCode, null); 15556 } catch (RemoteException e) { 15557 Log.i(TAG, "Observer no longer exists."); 15558 } //end catch 15559 } //end run 15560 }); 15561 } 15562 15563 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15564 int[] result = EMPTY_INT_ARRAY; 15565 for (int userId : userIds) { 15566 if (getBlockUninstallForUser(packageName, userId)) { 15567 result = ArrayUtils.appendInt(result, userId); 15568 } 15569 } 15570 return result; 15571 } 15572 15573 @Override 15574 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15575 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15576 } 15577 15578 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15579 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15580 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15581 try { 15582 if (dpm != null) { 15583 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15584 /* callingUserOnly =*/ false); 15585 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15586 : deviceOwnerComponentName.getPackageName(); 15587 // Does the package contains the device owner? 15588 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15589 // this check is probably not needed, since DO should be registered as a device 15590 // admin on some user too. (Original bug for this: b/17657954) 15591 if (packageName.equals(deviceOwnerPackageName)) { 15592 return true; 15593 } 15594 // Does it contain a device admin for any user? 15595 int[] users; 15596 if (userId == UserHandle.USER_ALL) { 15597 users = sUserManager.getUserIds(); 15598 } else { 15599 users = new int[]{userId}; 15600 } 15601 for (int i = 0; i < users.length; ++i) { 15602 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15603 return true; 15604 } 15605 } 15606 } 15607 } catch (RemoteException e) { 15608 } 15609 return false; 15610 } 15611 15612 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15613 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15614 } 15615 15616 /** 15617 * This method is an internal method that could be get invoked either 15618 * to delete an installed package or to clean up a failed installation. 15619 * After deleting an installed package, a broadcast is sent to notify any 15620 * listeners that the package has been removed. For cleaning up a failed 15621 * installation, the broadcast is not necessary since the package's 15622 * installation wouldn't have sent the initial broadcast either 15623 * The key steps in deleting a package are 15624 * deleting the package information in internal structures like mPackages, 15625 * deleting the packages base directories through installd 15626 * updating mSettings to reflect current status 15627 * persisting settings for later use 15628 * sending a broadcast if necessary 15629 */ 15630 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15631 final PackageRemovedInfo info = new PackageRemovedInfo(); 15632 final boolean res; 15633 15634 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15635 ? UserHandle.USER_ALL : userId; 15636 15637 if (isPackageDeviceAdmin(packageName, removeUser)) { 15638 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15639 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15640 } 15641 15642 PackageSetting uninstalledPs = null; 15643 15644 // for the uninstall-updates case and restricted profiles, remember the per- 15645 // user handle installed state 15646 int[] allUsers; 15647 synchronized (mPackages) { 15648 uninstalledPs = mSettings.mPackages.get(packageName); 15649 if (uninstalledPs == null) { 15650 Slog.w(TAG, "Not removing non-existent package " + packageName); 15651 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15652 } 15653 allUsers = sUserManager.getUserIds(); 15654 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15655 } 15656 15657 final int freezeUser; 15658 if (isUpdatedSystemApp(uninstalledPs) 15659 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15660 // We're downgrading a system app, which will apply to all users, so 15661 // freeze them all during the downgrade 15662 freezeUser = UserHandle.USER_ALL; 15663 } else { 15664 freezeUser = removeUser; 15665 } 15666 15667 synchronized (mInstallLock) { 15668 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15669 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15670 deleteFlags, "deletePackageX")) { 15671 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15672 deleteFlags | REMOVE_CHATTY, info, true, null); 15673 } 15674 synchronized (mPackages) { 15675 if (res) { 15676 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15677 } 15678 } 15679 } 15680 15681 if (res) { 15682 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15683 info.sendPackageRemovedBroadcasts(killApp); 15684 info.sendSystemPackageUpdatedBroadcasts(); 15685 info.sendSystemPackageAppearedBroadcasts(); 15686 } 15687 // Force a gc here. 15688 Runtime.getRuntime().gc(); 15689 // Delete the resources here after sending the broadcast to let 15690 // other processes clean up before deleting resources. 15691 if (info.args != null) { 15692 synchronized (mInstallLock) { 15693 info.args.doPostDeleteLI(true); 15694 } 15695 } 15696 15697 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15698 } 15699 15700 class PackageRemovedInfo { 15701 String removedPackage; 15702 int uid = -1; 15703 int removedAppId = -1; 15704 int[] origUsers; 15705 int[] removedUsers = null; 15706 boolean isRemovedPackageSystemUpdate = false; 15707 boolean isUpdate; 15708 boolean dataRemoved; 15709 boolean removedForAllUsers; 15710 // Clean up resources deleted packages. 15711 InstallArgs args = null; 15712 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15713 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15714 15715 void sendPackageRemovedBroadcasts(boolean killApp) { 15716 sendPackageRemovedBroadcastInternal(killApp); 15717 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15718 for (int i = 0; i < childCount; i++) { 15719 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15720 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15721 } 15722 } 15723 15724 void sendSystemPackageUpdatedBroadcasts() { 15725 if (isRemovedPackageSystemUpdate) { 15726 sendSystemPackageUpdatedBroadcastsInternal(); 15727 final int childCount = (removedChildPackages != null) 15728 ? removedChildPackages.size() : 0; 15729 for (int i = 0; i < childCount; i++) { 15730 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15731 if (childInfo.isRemovedPackageSystemUpdate) { 15732 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15733 } 15734 } 15735 } 15736 } 15737 15738 void sendSystemPackageAppearedBroadcasts() { 15739 final int packageCount = (appearedChildPackages != null) 15740 ? appearedChildPackages.size() : 0; 15741 for (int i = 0; i < packageCount; i++) { 15742 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15743 for (int userId : installedInfo.newUsers) { 15744 sendPackageAddedForUser(installedInfo.name, true, 15745 UserHandle.getAppId(installedInfo.uid), userId); 15746 } 15747 } 15748 } 15749 15750 private void sendSystemPackageUpdatedBroadcastsInternal() { 15751 Bundle extras = new Bundle(2); 15752 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15753 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15754 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15755 extras, 0, null, null, null); 15756 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15757 extras, 0, null, null, null); 15758 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15759 null, 0, removedPackage, null, null); 15760 } 15761 15762 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15763 Bundle extras = new Bundle(2); 15764 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15765 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15766 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15767 if (isUpdate || isRemovedPackageSystemUpdate) { 15768 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15769 } 15770 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15771 if (removedPackage != null) { 15772 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15773 extras, 0, null, null, removedUsers); 15774 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15775 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15776 removedPackage, extras, 0, null, null, removedUsers); 15777 } 15778 } 15779 if (removedAppId >= 0) { 15780 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15781 removedUsers); 15782 } 15783 } 15784 } 15785 15786 /* 15787 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15788 * flag is not set, the data directory is removed as well. 15789 * make sure this flag is set for partially installed apps. If not its meaningless to 15790 * delete a partially installed application. 15791 */ 15792 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15793 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15794 String packageName = ps.name; 15795 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15796 // Retrieve object to delete permissions for shared user later on 15797 final PackageParser.Package deletedPkg; 15798 final PackageSetting deletedPs; 15799 // reader 15800 synchronized (mPackages) { 15801 deletedPkg = mPackages.get(packageName); 15802 deletedPs = mSettings.mPackages.get(packageName); 15803 if (outInfo != null) { 15804 outInfo.removedPackage = packageName; 15805 outInfo.removedUsers = deletedPs != null 15806 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15807 : null; 15808 } 15809 } 15810 15811 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15812 15813 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15814 final PackageParser.Package resolvedPkg; 15815 if (deletedPkg != null) { 15816 resolvedPkg = deletedPkg; 15817 } else { 15818 // We don't have a parsed package when it lives on an ejected 15819 // adopted storage device, so fake something together 15820 resolvedPkg = new PackageParser.Package(ps.name); 15821 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15822 } 15823 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15824 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15825 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15826 if (outInfo != null) { 15827 outInfo.dataRemoved = true; 15828 } 15829 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15830 } 15831 15832 // writer 15833 synchronized (mPackages) { 15834 if (deletedPs != null) { 15835 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15836 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15837 clearDefaultBrowserIfNeeded(packageName); 15838 if (outInfo != null) { 15839 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15840 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15841 } 15842 updatePermissionsLPw(deletedPs.name, null, 0); 15843 if (deletedPs.sharedUser != null) { 15844 // Remove permissions associated with package. Since runtime 15845 // permissions are per user we have to kill the removed package 15846 // or packages running under the shared user of the removed 15847 // package if revoking the permissions requested only by the removed 15848 // package is successful and this causes a change in gids. 15849 for (int userId : UserManagerService.getInstance().getUserIds()) { 15850 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15851 userId); 15852 if (userIdToKill == UserHandle.USER_ALL 15853 || userIdToKill >= UserHandle.USER_SYSTEM) { 15854 // If gids changed for this user, kill all affected packages. 15855 mHandler.post(new Runnable() { 15856 @Override 15857 public void run() { 15858 // This has to happen with no lock held. 15859 killApplication(deletedPs.name, deletedPs.appId, 15860 KILL_APP_REASON_GIDS_CHANGED); 15861 } 15862 }); 15863 break; 15864 } 15865 } 15866 } 15867 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15868 } 15869 // make sure to preserve per-user disabled state if this removal was just 15870 // a downgrade of a system app to the factory package 15871 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15872 if (DEBUG_REMOVE) { 15873 Slog.d(TAG, "Propagating install state across downgrade"); 15874 } 15875 for (int userId : allUserHandles) { 15876 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15877 if (DEBUG_REMOVE) { 15878 Slog.d(TAG, " user " + userId + " => " + installed); 15879 } 15880 ps.setInstalled(installed, userId); 15881 } 15882 } 15883 } 15884 // can downgrade to reader 15885 if (writeSettings) { 15886 // Save settings now 15887 mSettings.writeLPr(); 15888 } 15889 } 15890 if (outInfo != null) { 15891 // A user ID was deleted here. Go through all users and remove it 15892 // from KeyStore. 15893 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15894 } 15895 } 15896 15897 static boolean locationIsPrivileged(File path) { 15898 try { 15899 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15900 .getCanonicalPath(); 15901 return path.getCanonicalPath().startsWith(privilegedAppDir); 15902 } catch (IOException e) { 15903 Slog.e(TAG, "Unable to access code path " + path); 15904 } 15905 return false; 15906 } 15907 15908 /* 15909 * Tries to delete system package. 15910 */ 15911 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15912 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15913 boolean writeSettings) { 15914 if (deletedPs.parentPackageName != null) { 15915 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15916 return false; 15917 } 15918 15919 final boolean applyUserRestrictions 15920 = (allUserHandles != null) && (outInfo.origUsers != null); 15921 final PackageSetting disabledPs; 15922 // Confirm if the system package has been updated 15923 // An updated system app can be deleted. This will also have to restore 15924 // the system pkg from system partition 15925 // reader 15926 synchronized (mPackages) { 15927 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15928 } 15929 15930 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15931 + " disabledPs=" + disabledPs); 15932 15933 if (disabledPs == null) { 15934 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15935 return false; 15936 } else if (DEBUG_REMOVE) { 15937 Slog.d(TAG, "Deleting system pkg from data partition"); 15938 } 15939 15940 if (DEBUG_REMOVE) { 15941 if (applyUserRestrictions) { 15942 Slog.d(TAG, "Remembering install states:"); 15943 for (int userId : allUserHandles) { 15944 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15945 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15946 } 15947 } 15948 } 15949 15950 // Delete the updated package 15951 outInfo.isRemovedPackageSystemUpdate = true; 15952 if (outInfo.removedChildPackages != null) { 15953 final int childCount = (deletedPs.childPackageNames != null) 15954 ? deletedPs.childPackageNames.size() : 0; 15955 for (int i = 0; i < childCount; i++) { 15956 String childPackageName = deletedPs.childPackageNames.get(i); 15957 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15958 .contains(childPackageName)) { 15959 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15960 childPackageName); 15961 if (childInfo != null) { 15962 childInfo.isRemovedPackageSystemUpdate = true; 15963 } 15964 } 15965 } 15966 } 15967 15968 if (disabledPs.versionCode < deletedPs.versionCode) { 15969 // Delete data for downgrades 15970 flags &= ~PackageManager.DELETE_KEEP_DATA; 15971 } else { 15972 // Preserve data by setting flag 15973 flags |= PackageManager.DELETE_KEEP_DATA; 15974 } 15975 15976 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15977 outInfo, writeSettings, disabledPs.pkg); 15978 if (!ret) { 15979 return false; 15980 } 15981 15982 // writer 15983 synchronized (mPackages) { 15984 // Reinstate the old system package 15985 enableSystemPackageLPw(disabledPs.pkg); 15986 // Remove any native libraries from the upgraded package. 15987 removeNativeBinariesLI(deletedPs); 15988 } 15989 15990 // Install the system package 15991 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15992 int parseFlags = mDefParseFlags 15993 | PackageParser.PARSE_MUST_BE_APK 15994 | PackageParser.PARSE_IS_SYSTEM 15995 | PackageParser.PARSE_IS_SYSTEM_DIR; 15996 if (locationIsPrivileged(disabledPs.codePath)) { 15997 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15998 } 15999 16000 final PackageParser.Package newPkg; 16001 try { 16002 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16003 } catch (PackageManagerException e) { 16004 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16005 + e.getMessage()); 16006 return false; 16007 } 16008 16009 prepareAppDataAfterInstallLIF(newPkg); 16010 16011 // writer 16012 synchronized (mPackages) { 16013 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16014 16015 // Propagate the permissions state as we do not want to drop on the floor 16016 // runtime permissions. The update permissions method below will take 16017 // care of removing obsolete permissions and grant install permissions. 16018 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16019 updatePermissionsLPw(newPkg.packageName, newPkg, 16020 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16021 16022 if (applyUserRestrictions) { 16023 if (DEBUG_REMOVE) { 16024 Slog.d(TAG, "Propagating install state across reinstall"); 16025 } 16026 for (int userId : allUserHandles) { 16027 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16028 if (DEBUG_REMOVE) { 16029 Slog.d(TAG, " user " + userId + " => " + installed); 16030 } 16031 ps.setInstalled(installed, userId); 16032 16033 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16034 } 16035 // Regardless of writeSettings we need to ensure that this restriction 16036 // state propagation is persisted 16037 mSettings.writeAllUsersPackageRestrictionsLPr(); 16038 } 16039 // can downgrade to reader here 16040 if (writeSettings) { 16041 mSettings.writeLPr(); 16042 } 16043 } 16044 return true; 16045 } 16046 16047 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16048 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16049 PackageRemovedInfo outInfo, boolean writeSettings, 16050 PackageParser.Package replacingPackage) { 16051 synchronized (mPackages) { 16052 if (outInfo != null) { 16053 outInfo.uid = ps.appId; 16054 } 16055 16056 if (outInfo != null && outInfo.removedChildPackages != null) { 16057 final int childCount = (ps.childPackageNames != null) 16058 ? ps.childPackageNames.size() : 0; 16059 for (int i = 0; i < childCount; i++) { 16060 String childPackageName = ps.childPackageNames.get(i); 16061 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16062 if (childPs == null) { 16063 return false; 16064 } 16065 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16066 childPackageName); 16067 if (childInfo != null) { 16068 childInfo.uid = childPs.appId; 16069 } 16070 } 16071 } 16072 } 16073 16074 // Delete package data from internal structures and also remove data if flag is set 16075 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16076 16077 // Delete the child packages data 16078 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16079 for (int i = 0; i < childCount; i++) { 16080 PackageSetting childPs; 16081 synchronized (mPackages) { 16082 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16083 } 16084 if (childPs != null) { 16085 PackageRemovedInfo childOutInfo = (outInfo != null 16086 && outInfo.removedChildPackages != null) 16087 ? outInfo.removedChildPackages.get(childPs.name) : null; 16088 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16089 && (replacingPackage != null 16090 && !replacingPackage.hasChildPackage(childPs.name)) 16091 ? flags & ~DELETE_KEEP_DATA : flags; 16092 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16093 deleteFlags, writeSettings); 16094 } 16095 } 16096 16097 // Delete application code and resources only for parent packages 16098 if (ps.parentPackageName == null) { 16099 if (deleteCodeAndResources && (outInfo != null)) { 16100 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16101 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16102 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16103 } 16104 } 16105 16106 return true; 16107 } 16108 16109 @Override 16110 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16111 int userId) { 16112 mContext.enforceCallingOrSelfPermission( 16113 android.Manifest.permission.DELETE_PACKAGES, null); 16114 synchronized (mPackages) { 16115 PackageSetting ps = mSettings.mPackages.get(packageName); 16116 if (ps == null) { 16117 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16118 return false; 16119 } 16120 if (!ps.getInstalled(userId)) { 16121 // Can't block uninstall for an app that is not installed or enabled. 16122 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16123 return false; 16124 } 16125 ps.setBlockUninstall(blockUninstall, userId); 16126 mSettings.writePackageRestrictionsLPr(userId); 16127 } 16128 return true; 16129 } 16130 16131 @Override 16132 public boolean getBlockUninstallForUser(String packageName, int userId) { 16133 synchronized (mPackages) { 16134 PackageSetting ps = mSettings.mPackages.get(packageName); 16135 if (ps == null) { 16136 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16137 return false; 16138 } 16139 return ps.getBlockUninstall(userId); 16140 } 16141 } 16142 16143 @Override 16144 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16145 int callingUid = Binder.getCallingUid(); 16146 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16147 throw new SecurityException( 16148 "setRequiredForSystemUser can only be run by the system or root"); 16149 } 16150 synchronized (mPackages) { 16151 PackageSetting ps = mSettings.mPackages.get(packageName); 16152 if (ps == null) { 16153 Log.w(TAG, "Package doesn't exist: " + packageName); 16154 return false; 16155 } 16156 if (systemUserApp) { 16157 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16158 } else { 16159 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16160 } 16161 mSettings.writeLPr(); 16162 } 16163 return true; 16164 } 16165 16166 /* 16167 * This method handles package deletion in general 16168 */ 16169 private boolean deletePackageLIF(String packageName, UserHandle user, 16170 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16171 PackageRemovedInfo outInfo, boolean writeSettings, 16172 PackageParser.Package replacingPackage) { 16173 if (packageName == null) { 16174 Slog.w(TAG, "Attempt to delete null packageName."); 16175 return false; 16176 } 16177 16178 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16179 16180 PackageSetting ps; 16181 16182 synchronized (mPackages) { 16183 ps = mSettings.mPackages.get(packageName); 16184 if (ps == null) { 16185 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16186 return false; 16187 } 16188 16189 if (ps.parentPackageName != null && (!isSystemApp(ps) 16190 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16191 if (DEBUG_REMOVE) { 16192 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16193 + ((user == null) ? UserHandle.USER_ALL : user)); 16194 } 16195 final int removedUserId = (user != null) ? user.getIdentifier() 16196 : UserHandle.USER_ALL; 16197 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16198 return false; 16199 } 16200 markPackageUninstalledForUserLPw(ps, user); 16201 scheduleWritePackageRestrictionsLocked(user); 16202 return true; 16203 } 16204 } 16205 16206 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16207 && user.getIdentifier() != UserHandle.USER_ALL)) { 16208 // The caller is asking that the package only be deleted for a single 16209 // user. To do this, we just mark its uninstalled state and delete 16210 // its data. If this is a system app, we only allow this to happen if 16211 // they have set the special DELETE_SYSTEM_APP which requests different 16212 // semantics than normal for uninstalling system apps. 16213 markPackageUninstalledForUserLPw(ps, user); 16214 16215 if (!isSystemApp(ps)) { 16216 // Do not uninstall the APK if an app should be cached 16217 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16218 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16219 // Other user still have this package installed, so all 16220 // we need to do is clear this user's data and save that 16221 // it is uninstalled. 16222 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16223 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16224 return false; 16225 } 16226 scheduleWritePackageRestrictionsLocked(user); 16227 return true; 16228 } else { 16229 // We need to set it back to 'installed' so the uninstall 16230 // broadcasts will be sent correctly. 16231 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16232 ps.setInstalled(true, user.getIdentifier()); 16233 } 16234 } else { 16235 // This is a system app, so we assume that the 16236 // other users still have this package installed, so all 16237 // we need to do is clear this user's data and save that 16238 // it is uninstalled. 16239 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16240 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16241 return false; 16242 } 16243 scheduleWritePackageRestrictionsLocked(user); 16244 return true; 16245 } 16246 } 16247 16248 // If we are deleting a composite package for all users, keep track 16249 // of result for each child. 16250 if (ps.childPackageNames != null && outInfo != null) { 16251 synchronized (mPackages) { 16252 final int childCount = ps.childPackageNames.size(); 16253 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16254 for (int i = 0; i < childCount; i++) { 16255 String childPackageName = ps.childPackageNames.get(i); 16256 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16257 childInfo.removedPackage = childPackageName; 16258 outInfo.removedChildPackages.put(childPackageName, childInfo); 16259 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16260 if (childPs != null) { 16261 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16262 } 16263 } 16264 } 16265 } 16266 16267 boolean ret = false; 16268 if (isSystemApp(ps)) { 16269 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16270 // When an updated system application is deleted we delete the existing resources 16271 // as well and fall back to existing code in system partition 16272 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16273 } else { 16274 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16275 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16276 outInfo, writeSettings, replacingPackage); 16277 } 16278 16279 // Take a note whether we deleted the package for all users 16280 if (outInfo != null) { 16281 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16282 if (outInfo.removedChildPackages != null) { 16283 synchronized (mPackages) { 16284 final int childCount = outInfo.removedChildPackages.size(); 16285 for (int i = 0; i < childCount; i++) { 16286 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16287 if (childInfo != null) { 16288 childInfo.removedForAllUsers = mPackages.get( 16289 childInfo.removedPackage) == null; 16290 } 16291 } 16292 } 16293 } 16294 // If we uninstalled an update to a system app there may be some 16295 // child packages that appeared as they are declared in the system 16296 // app but were not declared in the update. 16297 if (isSystemApp(ps)) { 16298 synchronized (mPackages) { 16299 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16300 final int childCount = (updatedPs.childPackageNames != null) 16301 ? updatedPs.childPackageNames.size() : 0; 16302 for (int i = 0; i < childCount; i++) { 16303 String childPackageName = updatedPs.childPackageNames.get(i); 16304 if (outInfo.removedChildPackages == null 16305 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16306 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16307 if (childPs == null) { 16308 continue; 16309 } 16310 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16311 installRes.name = childPackageName; 16312 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16313 installRes.pkg = mPackages.get(childPackageName); 16314 installRes.uid = childPs.pkg.applicationInfo.uid; 16315 if (outInfo.appearedChildPackages == null) { 16316 outInfo.appearedChildPackages = new ArrayMap<>(); 16317 } 16318 outInfo.appearedChildPackages.put(childPackageName, installRes); 16319 } 16320 } 16321 } 16322 } 16323 } 16324 16325 return ret; 16326 } 16327 16328 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16329 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16330 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16331 for (int nextUserId : userIds) { 16332 if (DEBUG_REMOVE) { 16333 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16334 } 16335 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16336 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16337 false /*hidden*/, false /*suspended*/, null, null, null, 16338 false /*blockUninstall*/, 16339 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16340 } 16341 } 16342 16343 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16344 PackageRemovedInfo outInfo) { 16345 final PackageParser.Package pkg; 16346 synchronized (mPackages) { 16347 pkg = mPackages.get(ps.name); 16348 } 16349 16350 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16351 : new int[] {userId}; 16352 for (int nextUserId : userIds) { 16353 if (DEBUG_REMOVE) { 16354 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16355 + nextUserId); 16356 } 16357 16358 destroyAppDataLIF(pkg, userId, 16359 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16360 destroyAppProfilesLIF(pkg, userId); 16361 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16362 schedulePackageCleaning(ps.name, nextUserId, false); 16363 synchronized (mPackages) { 16364 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16365 scheduleWritePackageRestrictionsLocked(nextUserId); 16366 } 16367 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16368 } 16369 } 16370 16371 if (outInfo != null) { 16372 outInfo.removedPackage = ps.name; 16373 outInfo.removedAppId = ps.appId; 16374 outInfo.removedUsers = userIds; 16375 } 16376 16377 return true; 16378 } 16379 16380 private final class ClearStorageConnection implements ServiceConnection { 16381 IMediaContainerService mContainerService; 16382 16383 @Override 16384 public void onServiceConnected(ComponentName name, IBinder service) { 16385 synchronized (this) { 16386 mContainerService = IMediaContainerService.Stub.asInterface(service); 16387 notifyAll(); 16388 } 16389 } 16390 16391 @Override 16392 public void onServiceDisconnected(ComponentName name) { 16393 } 16394 } 16395 16396 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16397 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16398 16399 final boolean mounted; 16400 if (Environment.isExternalStorageEmulated()) { 16401 mounted = true; 16402 } else { 16403 final String status = Environment.getExternalStorageState(); 16404 16405 mounted = status.equals(Environment.MEDIA_MOUNTED) 16406 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16407 } 16408 16409 if (!mounted) { 16410 return; 16411 } 16412 16413 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16414 int[] users; 16415 if (userId == UserHandle.USER_ALL) { 16416 users = sUserManager.getUserIds(); 16417 } else { 16418 users = new int[] { userId }; 16419 } 16420 final ClearStorageConnection conn = new ClearStorageConnection(); 16421 if (mContext.bindServiceAsUser( 16422 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16423 try { 16424 for (int curUser : users) { 16425 long timeout = SystemClock.uptimeMillis() + 5000; 16426 synchronized (conn) { 16427 long now; 16428 while (conn.mContainerService == null && 16429 (now = SystemClock.uptimeMillis()) < timeout) { 16430 try { 16431 conn.wait(timeout - now); 16432 } catch (InterruptedException e) { 16433 } 16434 } 16435 } 16436 if (conn.mContainerService == null) { 16437 return; 16438 } 16439 16440 final UserEnvironment userEnv = new UserEnvironment(curUser); 16441 clearDirectory(conn.mContainerService, 16442 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16443 if (allData) { 16444 clearDirectory(conn.mContainerService, 16445 userEnv.buildExternalStorageAppDataDirs(packageName)); 16446 clearDirectory(conn.mContainerService, 16447 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16448 } 16449 } 16450 } finally { 16451 mContext.unbindService(conn); 16452 } 16453 } 16454 } 16455 16456 @Override 16457 public void clearApplicationProfileData(String packageName) { 16458 enforceSystemOrRoot("Only the system can clear all profile data"); 16459 16460 final PackageParser.Package pkg; 16461 synchronized (mPackages) { 16462 pkg = mPackages.get(packageName); 16463 } 16464 16465 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16466 synchronized (mInstallLock) { 16467 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16468 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16469 true /* removeBaseMarker */); 16470 } 16471 } 16472 } 16473 16474 @Override 16475 public void clearApplicationUserData(final String packageName, 16476 final IPackageDataObserver observer, final int userId) { 16477 mContext.enforceCallingOrSelfPermission( 16478 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16479 16480 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16481 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16482 16483 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16484 throw new SecurityException("Cannot clear data for a protected package: " 16485 + packageName); 16486 } 16487 // Queue up an async operation since the package deletion may take a little while. 16488 mHandler.post(new Runnable() { 16489 public void run() { 16490 mHandler.removeCallbacks(this); 16491 final boolean succeeded; 16492 try (PackageFreezer freezer = freezePackage(packageName, 16493 "clearApplicationUserData")) { 16494 synchronized (mInstallLock) { 16495 succeeded = clearApplicationUserDataLIF(packageName, userId); 16496 } 16497 clearExternalStorageDataSync(packageName, userId, true); 16498 } 16499 if (succeeded) { 16500 // invoke DeviceStorageMonitor's update method to clear any notifications 16501 DeviceStorageMonitorInternal dsm = LocalServices 16502 .getService(DeviceStorageMonitorInternal.class); 16503 if (dsm != null) { 16504 dsm.checkMemory(); 16505 } 16506 } 16507 if(observer != null) { 16508 try { 16509 observer.onRemoveCompleted(packageName, succeeded); 16510 } catch (RemoteException e) { 16511 Log.i(TAG, "Observer no longer exists."); 16512 } 16513 } //end if observer 16514 } //end run 16515 }); 16516 } 16517 16518 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16519 if (packageName == null) { 16520 Slog.w(TAG, "Attempt to delete null packageName."); 16521 return false; 16522 } 16523 16524 // Try finding details about the requested package 16525 PackageParser.Package pkg; 16526 synchronized (mPackages) { 16527 pkg = mPackages.get(packageName); 16528 if (pkg == null) { 16529 final PackageSetting ps = mSettings.mPackages.get(packageName); 16530 if (ps != null) { 16531 pkg = ps.pkg; 16532 } 16533 } 16534 16535 if (pkg == null) { 16536 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16537 return false; 16538 } 16539 16540 PackageSetting ps = (PackageSetting) pkg.mExtras; 16541 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16542 } 16543 16544 clearAppDataLIF(pkg, userId, 16545 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16546 16547 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16548 removeKeystoreDataIfNeeded(userId, appId); 16549 16550 UserManagerInternal umInternal = getUserManagerInternal(); 16551 final int flags; 16552 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16553 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16554 } else if (umInternal.isUserRunning(userId)) { 16555 flags = StorageManager.FLAG_STORAGE_DE; 16556 } else { 16557 flags = 0; 16558 } 16559 prepareAppDataContentsLIF(pkg, userId, flags); 16560 16561 return true; 16562 } 16563 16564 /** 16565 * Reverts user permission state changes (permissions and flags) in 16566 * all packages for a given user. 16567 * 16568 * @param userId The device user for which to do a reset. 16569 */ 16570 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16571 final int packageCount = mPackages.size(); 16572 for (int i = 0; i < packageCount; i++) { 16573 PackageParser.Package pkg = mPackages.valueAt(i); 16574 PackageSetting ps = (PackageSetting) pkg.mExtras; 16575 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16576 } 16577 } 16578 16579 private void resetNetworkPolicies(int userId) { 16580 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16581 } 16582 16583 /** 16584 * Reverts user permission state changes (permissions and flags). 16585 * 16586 * @param ps The package for which to reset. 16587 * @param userId The device user for which to do a reset. 16588 */ 16589 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16590 final PackageSetting ps, final int userId) { 16591 if (ps.pkg == null) { 16592 return; 16593 } 16594 16595 // These are flags that can change base on user actions. 16596 final int userSettableMask = FLAG_PERMISSION_USER_SET 16597 | FLAG_PERMISSION_USER_FIXED 16598 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16599 | FLAG_PERMISSION_REVIEW_REQUIRED; 16600 16601 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16602 | FLAG_PERMISSION_POLICY_FIXED; 16603 16604 boolean writeInstallPermissions = false; 16605 boolean writeRuntimePermissions = false; 16606 16607 final int permissionCount = ps.pkg.requestedPermissions.size(); 16608 for (int i = 0; i < permissionCount; i++) { 16609 String permission = ps.pkg.requestedPermissions.get(i); 16610 16611 BasePermission bp = mSettings.mPermissions.get(permission); 16612 if (bp == null) { 16613 continue; 16614 } 16615 16616 // If shared user we just reset the state to which only this app contributed. 16617 if (ps.sharedUser != null) { 16618 boolean used = false; 16619 final int packageCount = ps.sharedUser.packages.size(); 16620 for (int j = 0; j < packageCount; j++) { 16621 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16622 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16623 && pkg.pkg.requestedPermissions.contains(permission)) { 16624 used = true; 16625 break; 16626 } 16627 } 16628 if (used) { 16629 continue; 16630 } 16631 } 16632 16633 PermissionsState permissionsState = ps.getPermissionsState(); 16634 16635 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16636 16637 // Always clear the user settable flags. 16638 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16639 bp.name) != null; 16640 // If permission review is enabled and this is a legacy app, mark the 16641 // permission as requiring a review as this is the initial state. 16642 int flags = 0; 16643 if (Build.PERMISSIONS_REVIEW_REQUIRED 16644 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16645 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16646 } 16647 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16648 if (hasInstallState) { 16649 writeInstallPermissions = true; 16650 } else { 16651 writeRuntimePermissions = true; 16652 } 16653 } 16654 16655 // Below is only runtime permission handling. 16656 if (!bp.isRuntime()) { 16657 continue; 16658 } 16659 16660 // Never clobber system or policy. 16661 if ((oldFlags & policyOrSystemFlags) != 0) { 16662 continue; 16663 } 16664 16665 // If this permission was granted by default, make sure it is. 16666 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16667 if (permissionsState.grantRuntimePermission(bp, userId) 16668 != PERMISSION_OPERATION_FAILURE) { 16669 writeRuntimePermissions = true; 16670 } 16671 // If permission review is enabled the permissions for a legacy apps 16672 // are represented as constantly granted runtime ones, so don't revoke. 16673 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16674 // Otherwise, reset the permission. 16675 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16676 switch (revokeResult) { 16677 case PERMISSION_OPERATION_SUCCESS: 16678 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16679 writeRuntimePermissions = true; 16680 final int appId = ps.appId; 16681 mHandler.post(new Runnable() { 16682 @Override 16683 public void run() { 16684 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16685 } 16686 }); 16687 } break; 16688 } 16689 } 16690 } 16691 16692 // Synchronously write as we are taking permissions away. 16693 if (writeRuntimePermissions) { 16694 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16695 } 16696 16697 // Synchronously write as we are taking permissions away. 16698 if (writeInstallPermissions) { 16699 mSettings.writeLPr(); 16700 } 16701 } 16702 16703 /** 16704 * Remove entries from the keystore daemon. Will only remove it if the 16705 * {@code appId} is valid. 16706 */ 16707 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16708 if (appId < 0) { 16709 return; 16710 } 16711 16712 final KeyStore keyStore = KeyStore.getInstance(); 16713 if (keyStore != null) { 16714 if (userId == UserHandle.USER_ALL) { 16715 for (final int individual : sUserManager.getUserIds()) { 16716 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16717 } 16718 } else { 16719 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16720 } 16721 } else { 16722 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16723 } 16724 } 16725 16726 @Override 16727 public void deleteApplicationCacheFiles(final String packageName, 16728 final IPackageDataObserver observer) { 16729 final int userId = UserHandle.getCallingUserId(); 16730 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16731 } 16732 16733 @Override 16734 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16735 final IPackageDataObserver observer) { 16736 mContext.enforceCallingOrSelfPermission( 16737 android.Manifest.permission.DELETE_CACHE_FILES, null); 16738 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16739 /* requireFullPermission= */ true, /* checkShell= */ false, 16740 "delete application cache files"); 16741 16742 final PackageParser.Package pkg; 16743 synchronized (mPackages) { 16744 pkg = mPackages.get(packageName); 16745 } 16746 16747 // Queue up an async operation since the package deletion may take a little while. 16748 mHandler.post(new Runnable() { 16749 public void run() { 16750 synchronized (mInstallLock) { 16751 final int flags = StorageManager.FLAG_STORAGE_DE 16752 | StorageManager.FLAG_STORAGE_CE; 16753 // We're only clearing cache files, so we don't care if the 16754 // app is unfrozen and still able to run 16755 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16756 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16757 } 16758 clearExternalStorageDataSync(packageName, userId, false); 16759 if (observer != null) { 16760 try { 16761 observer.onRemoveCompleted(packageName, true); 16762 } catch (RemoteException e) { 16763 Log.i(TAG, "Observer no longer exists."); 16764 } 16765 } 16766 } 16767 }); 16768 } 16769 16770 @Override 16771 public void getPackageSizeInfo(final String packageName, int userHandle, 16772 final IPackageStatsObserver observer) { 16773 mContext.enforceCallingOrSelfPermission( 16774 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16775 if (packageName == null) { 16776 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16777 } 16778 16779 PackageStats stats = new PackageStats(packageName, userHandle); 16780 16781 /* 16782 * Queue up an async operation since the package measurement may take a 16783 * little while. 16784 */ 16785 Message msg = mHandler.obtainMessage(INIT_COPY); 16786 msg.obj = new MeasureParams(stats, observer); 16787 mHandler.sendMessage(msg); 16788 } 16789 16790 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16791 final PackageSetting ps; 16792 synchronized (mPackages) { 16793 ps = mSettings.mPackages.get(packageName); 16794 if (ps == null) { 16795 Slog.w(TAG, "Failed to find settings for " + packageName); 16796 return false; 16797 } 16798 } 16799 try { 16800 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16801 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16802 ps.getCeDataInode(userId), ps.codePathString, stats); 16803 } catch (InstallerException e) { 16804 Slog.w(TAG, String.valueOf(e)); 16805 return false; 16806 } 16807 16808 // For now, ignore code size of packages on system partition 16809 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16810 stats.codeSize = 0; 16811 } 16812 16813 return true; 16814 } 16815 16816 private int getUidTargetSdkVersionLockedLPr(int uid) { 16817 Object obj = mSettings.getUserIdLPr(uid); 16818 if (obj instanceof SharedUserSetting) { 16819 final SharedUserSetting sus = (SharedUserSetting) obj; 16820 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16821 final Iterator<PackageSetting> it = sus.packages.iterator(); 16822 while (it.hasNext()) { 16823 final PackageSetting ps = it.next(); 16824 if (ps.pkg != null) { 16825 int v = ps.pkg.applicationInfo.targetSdkVersion; 16826 if (v < vers) vers = v; 16827 } 16828 } 16829 return vers; 16830 } else if (obj instanceof PackageSetting) { 16831 final PackageSetting ps = (PackageSetting) obj; 16832 if (ps.pkg != null) { 16833 return ps.pkg.applicationInfo.targetSdkVersion; 16834 } 16835 } 16836 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16837 } 16838 16839 @Override 16840 public void addPreferredActivity(IntentFilter filter, int match, 16841 ComponentName[] set, ComponentName activity, int userId) { 16842 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16843 "Adding preferred"); 16844 } 16845 16846 private void addPreferredActivityInternal(IntentFilter filter, int match, 16847 ComponentName[] set, ComponentName activity, boolean always, int userId, 16848 String opname) { 16849 // writer 16850 int callingUid = Binder.getCallingUid(); 16851 enforceCrossUserPermission(callingUid, userId, 16852 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16853 if (filter.countActions() == 0) { 16854 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16855 return; 16856 } 16857 synchronized (mPackages) { 16858 if (mContext.checkCallingOrSelfPermission( 16859 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16860 != PackageManager.PERMISSION_GRANTED) { 16861 if (getUidTargetSdkVersionLockedLPr(callingUid) 16862 < Build.VERSION_CODES.FROYO) { 16863 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16864 + callingUid); 16865 return; 16866 } 16867 mContext.enforceCallingOrSelfPermission( 16868 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16869 } 16870 16871 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16872 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16873 + userId + ":"); 16874 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16875 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16876 scheduleWritePackageRestrictionsLocked(userId); 16877 } 16878 } 16879 16880 @Override 16881 public void replacePreferredActivity(IntentFilter filter, int match, 16882 ComponentName[] set, ComponentName activity, int userId) { 16883 if (filter.countActions() != 1) { 16884 throw new IllegalArgumentException( 16885 "replacePreferredActivity expects filter to have only 1 action."); 16886 } 16887 if (filter.countDataAuthorities() != 0 16888 || filter.countDataPaths() != 0 16889 || filter.countDataSchemes() > 1 16890 || filter.countDataTypes() != 0) { 16891 throw new IllegalArgumentException( 16892 "replacePreferredActivity expects filter to have no data authorities, " + 16893 "paths, or types; and at most one scheme."); 16894 } 16895 16896 final int callingUid = Binder.getCallingUid(); 16897 enforceCrossUserPermission(callingUid, userId, 16898 true /* requireFullPermission */, false /* checkShell */, 16899 "replace preferred activity"); 16900 synchronized (mPackages) { 16901 if (mContext.checkCallingOrSelfPermission( 16902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16903 != PackageManager.PERMISSION_GRANTED) { 16904 if (getUidTargetSdkVersionLockedLPr(callingUid) 16905 < Build.VERSION_CODES.FROYO) { 16906 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16907 + Binder.getCallingUid()); 16908 return; 16909 } 16910 mContext.enforceCallingOrSelfPermission( 16911 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16912 } 16913 16914 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16915 if (pir != null) { 16916 // Get all of the existing entries that exactly match this filter. 16917 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16918 if (existing != null && existing.size() == 1) { 16919 PreferredActivity cur = existing.get(0); 16920 if (DEBUG_PREFERRED) { 16921 Slog.i(TAG, "Checking replace of preferred:"); 16922 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16923 if (!cur.mPref.mAlways) { 16924 Slog.i(TAG, " -- CUR; not mAlways!"); 16925 } else { 16926 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16927 Slog.i(TAG, " -- CUR: mSet=" 16928 + Arrays.toString(cur.mPref.mSetComponents)); 16929 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16930 Slog.i(TAG, " -- NEW: mMatch=" 16931 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16932 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16933 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16934 } 16935 } 16936 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16937 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16938 && cur.mPref.sameSet(set)) { 16939 // Setting the preferred activity to what it happens to be already 16940 if (DEBUG_PREFERRED) { 16941 Slog.i(TAG, "Replacing with same preferred activity " 16942 + cur.mPref.mShortComponent + " for user " 16943 + userId + ":"); 16944 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16945 } 16946 return; 16947 } 16948 } 16949 16950 if (existing != null) { 16951 if (DEBUG_PREFERRED) { 16952 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16953 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16954 } 16955 for (int i = 0; i < existing.size(); i++) { 16956 PreferredActivity pa = existing.get(i); 16957 if (DEBUG_PREFERRED) { 16958 Slog.i(TAG, "Removing existing preferred activity " 16959 + pa.mPref.mComponent + ":"); 16960 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16961 } 16962 pir.removeFilter(pa); 16963 } 16964 } 16965 } 16966 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16967 "Replacing preferred"); 16968 } 16969 } 16970 16971 @Override 16972 public void clearPackagePreferredActivities(String packageName) { 16973 final int uid = Binder.getCallingUid(); 16974 // writer 16975 synchronized (mPackages) { 16976 PackageParser.Package pkg = mPackages.get(packageName); 16977 if (pkg == null || pkg.applicationInfo.uid != uid) { 16978 if (mContext.checkCallingOrSelfPermission( 16979 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16980 != PackageManager.PERMISSION_GRANTED) { 16981 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16982 < Build.VERSION_CODES.FROYO) { 16983 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16984 + Binder.getCallingUid()); 16985 return; 16986 } 16987 mContext.enforceCallingOrSelfPermission( 16988 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16989 } 16990 } 16991 16992 int user = UserHandle.getCallingUserId(); 16993 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16994 scheduleWritePackageRestrictionsLocked(user); 16995 } 16996 } 16997 } 16998 16999 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17000 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17001 ArrayList<PreferredActivity> removed = null; 17002 boolean changed = false; 17003 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17004 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17005 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17006 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17007 continue; 17008 } 17009 Iterator<PreferredActivity> it = pir.filterIterator(); 17010 while (it.hasNext()) { 17011 PreferredActivity pa = it.next(); 17012 // Mark entry for removal only if it matches the package name 17013 // and the entry is of type "always". 17014 if (packageName == null || 17015 (pa.mPref.mComponent.getPackageName().equals(packageName) 17016 && pa.mPref.mAlways)) { 17017 if (removed == null) { 17018 removed = new ArrayList<PreferredActivity>(); 17019 } 17020 removed.add(pa); 17021 } 17022 } 17023 if (removed != null) { 17024 for (int j=0; j<removed.size(); j++) { 17025 PreferredActivity pa = removed.get(j); 17026 pir.removeFilter(pa); 17027 } 17028 changed = true; 17029 } 17030 } 17031 return changed; 17032 } 17033 17034 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17035 private void clearIntentFilterVerificationsLPw(int userId) { 17036 final int packageCount = mPackages.size(); 17037 for (int i = 0; i < packageCount; i++) { 17038 PackageParser.Package pkg = mPackages.valueAt(i); 17039 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17040 } 17041 } 17042 17043 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17044 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17045 if (userId == UserHandle.USER_ALL) { 17046 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17047 sUserManager.getUserIds())) { 17048 for (int oneUserId : sUserManager.getUserIds()) { 17049 scheduleWritePackageRestrictionsLocked(oneUserId); 17050 } 17051 } 17052 } else { 17053 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17054 scheduleWritePackageRestrictionsLocked(userId); 17055 } 17056 } 17057 } 17058 17059 void clearDefaultBrowserIfNeeded(String packageName) { 17060 for (int oneUserId : sUserManager.getUserIds()) { 17061 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17062 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17063 if (packageName.equals(defaultBrowserPackageName)) { 17064 setDefaultBrowserPackageName(null, oneUserId); 17065 } 17066 } 17067 } 17068 17069 @Override 17070 public void resetApplicationPreferences(int userId) { 17071 mContext.enforceCallingOrSelfPermission( 17072 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17073 final long identity = Binder.clearCallingIdentity(); 17074 // writer 17075 try { 17076 synchronized (mPackages) { 17077 clearPackagePreferredActivitiesLPw(null, userId); 17078 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17079 // TODO: We have to reset the default SMS and Phone. This requires 17080 // significant refactoring to keep all default apps in the package 17081 // manager (cleaner but more work) or have the services provide 17082 // callbacks to the package manager to request a default app reset. 17083 applyFactoryDefaultBrowserLPw(userId); 17084 clearIntentFilterVerificationsLPw(userId); 17085 primeDomainVerificationsLPw(userId); 17086 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17087 scheduleWritePackageRestrictionsLocked(userId); 17088 } 17089 resetNetworkPolicies(userId); 17090 } finally { 17091 Binder.restoreCallingIdentity(identity); 17092 } 17093 } 17094 17095 @Override 17096 public int getPreferredActivities(List<IntentFilter> outFilters, 17097 List<ComponentName> outActivities, String packageName) { 17098 17099 int num = 0; 17100 final int userId = UserHandle.getCallingUserId(); 17101 // reader 17102 synchronized (mPackages) { 17103 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17104 if (pir != null) { 17105 final Iterator<PreferredActivity> it = pir.filterIterator(); 17106 while (it.hasNext()) { 17107 final PreferredActivity pa = it.next(); 17108 if (packageName == null 17109 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17110 && pa.mPref.mAlways)) { 17111 if (outFilters != null) { 17112 outFilters.add(new IntentFilter(pa)); 17113 } 17114 if (outActivities != null) { 17115 outActivities.add(pa.mPref.mComponent); 17116 } 17117 } 17118 } 17119 } 17120 } 17121 17122 return num; 17123 } 17124 17125 @Override 17126 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17127 int userId) { 17128 int callingUid = Binder.getCallingUid(); 17129 if (callingUid != Process.SYSTEM_UID) { 17130 throw new SecurityException( 17131 "addPersistentPreferredActivity can only be run by the system"); 17132 } 17133 if (filter.countActions() == 0) { 17134 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17135 return; 17136 } 17137 synchronized (mPackages) { 17138 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17139 ":"); 17140 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17141 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17142 new PersistentPreferredActivity(filter, activity)); 17143 scheduleWritePackageRestrictionsLocked(userId); 17144 } 17145 } 17146 17147 @Override 17148 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17149 int callingUid = Binder.getCallingUid(); 17150 if (callingUid != Process.SYSTEM_UID) { 17151 throw new SecurityException( 17152 "clearPackagePersistentPreferredActivities can only be run by the system"); 17153 } 17154 ArrayList<PersistentPreferredActivity> removed = null; 17155 boolean changed = false; 17156 synchronized (mPackages) { 17157 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17158 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17159 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17160 .valueAt(i); 17161 if (userId != thisUserId) { 17162 continue; 17163 } 17164 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17165 while (it.hasNext()) { 17166 PersistentPreferredActivity ppa = it.next(); 17167 // Mark entry for removal only if it matches the package name. 17168 if (ppa.mComponent.getPackageName().equals(packageName)) { 17169 if (removed == null) { 17170 removed = new ArrayList<PersistentPreferredActivity>(); 17171 } 17172 removed.add(ppa); 17173 } 17174 } 17175 if (removed != null) { 17176 for (int j=0; j<removed.size(); j++) { 17177 PersistentPreferredActivity ppa = removed.get(j); 17178 ppir.removeFilter(ppa); 17179 } 17180 changed = true; 17181 } 17182 } 17183 17184 if (changed) { 17185 scheduleWritePackageRestrictionsLocked(userId); 17186 } 17187 } 17188 } 17189 17190 /** 17191 * Common machinery for picking apart a restored XML blob and passing 17192 * it to a caller-supplied functor to be applied to the running system. 17193 */ 17194 private void restoreFromXml(XmlPullParser parser, int userId, 17195 String expectedStartTag, BlobXmlRestorer functor) 17196 throws IOException, XmlPullParserException { 17197 int type; 17198 while ((type = parser.next()) != XmlPullParser.START_TAG 17199 && type != XmlPullParser.END_DOCUMENT) { 17200 } 17201 if (type != XmlPullParser.START_TAG) { 17202 // oops didn't find a start tag?! 17203 if (DEBUG_BACKUP) { 17204 Slog.e(TAG, "Didn't find start tag during restore"); 17205 } 17206 return; 17207 } 17208Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17209 // this is supposed to be TAG_PREFERRED_BACKUP 17210 if (!expectedStartTag.equals(parser.getName())) { 17211 if (DEBUG_BACKUP) { 17212 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17213 } 17214 return; 17215 } 17216 17217 // skip interfering stuff, then we're aligned with the backing implementation 17218 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17219Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17220 functor.apply(parser, userId); 17221 } 17222 17223 private interface BlobXmlRestorer { 17224 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17225 } 17226 17227 /** 17228 * Non-Binder method, support for the backup/restore mechanism: write the 17229 * full set of preferred activities in its canonical XML format. Returns the 17230 * XML output as a byte array, or null if there is none. 17231 */ 17232 @Override 17233 public byte[] getPreferredActivityBackup(int userId) { 17234 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17235 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17236 } 17237 17238 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17239 try { 17240 final XmlSerializer serializer = new FastXmlSerializer(); 17241 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17242 serializer.startDocument(null, true); 17243 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17244 17245 synchronized (mPackages) { 17246 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17247 } 17248 17249 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17250 serializer.endDocument(); 17251 serializer.flush(); 17252 } catch (Exception e) { 17253 if (DEBUG_BACKUP) { 17254 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17255 } 17256 return null; 17257 } 17258 17259 return dataStream.toByteArray(); 17260 } 17261 17262 @Override 17263 public void restorePreferredActivities(byte[] backup, int userId) { 17264 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17265 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17266 } 17267 17268 try { 17269 final XmlPullParser parser = Xml.newPullParser(); 17270 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17271 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17272 new BlobXmlRestorer() { 17273 @Override 17274 public void apply(XmlPullParser parser, int userId) 17275 throws XmlPullParserException, IOException { 17276 synchronized (mPackages) { 17277 mSettings.readPreferredActivitiesLPw(parser, userId); 17278 } 17279 } 17280 } ); 17281 } catch (Exception e) { 17282 if (DEBUG_BACKUP) { 17283 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17284 } 17285 } 17286 } 17287 17288 /** 17289 * Non-Binder method, support for the backup/restore mechanism: write the 17290 * default browser (etc) settings in its canonical XML format. Returns the default 17291 * browser XML representation as a byte array, or null if there is none. 17292 */ 17293 @Override 17294 public byte[] getDefaultAppsBackup(int userId) { 17295 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17296 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17297 } 17298 17299 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17300 try { 17301 final XmlSerializer serializer = new FastXmlSerializer(); 17302 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17303 serializer.startDocument(null, true); 17304 serializer.startTag(null, TAG_DEFAULT_APPS); 17305 17306 synchronized (mPackages) { 17307 mSettings.writeDefaultAppsLPr(serializer, userId); 17308 } 17309 17310 serializer.endTag(null, TAG_DEFAULT_APPS); 17311 serializer.endDocument(); 17312 serializer.flush(); 17313 } catch (Exception e) { 17314 if (DEBUG_BACKUP) { 17315 Slog.e(TAG, "Unable to write default apps for backup", e); 17316 } 17317 return null; 17318 } 17319 17320 return dataStream.toByteArray(); 17321 } 17322 17323 @Override 17324 public void restoreDefaultApps(byte[] backup, int userId) { 17325 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17326 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17327 } 17328 17329 try { 17330 final XmlPullParser parser = Xml.newPullParser(); 17331 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17332 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17333 new BlobXmlRestorer() { 17334 @Override 17335 public void apply(XmlPullParser parser, int userId) 17336 throws XmlPullParserException, IOException { 17337 synchronized (mPackages) { 17338 mSettings.readDefaultAppsLPw(parser, userId); 17339 } 17340 } 17341 } ); 17342 } catch (Exception e) { 17343 if (DEBUG_BACKUP) { 17344 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17345 } 17346 } 17347 } 17348 17349 @Override 17350 public byte[] getIntentFilterVerificationBackup(int userId) { 17351 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17352 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17353 } 17354 17355 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17356 try { 17357 final XmlSerializer serializer = new FastXmlSerializer(); 17358 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17359 serializer.startDocument(null, true); 17360 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17361 17362 synchronized (mPackages) { 17363 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17364 } 17365 17366 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17367 serializer.endDocument(); 17368 serializer.flush(); 17369 } catch (Exception e) { 17370 if (DEBUG_BACKUP) { 17371 Slog.e(TAG, "Unable to write default apps for backup", e); 17372 } 17373 return null; 17374 } 17375 17376 return dataStream.toByteArray(); 17377 } 17378 17379 @Override 17380 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17381 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17382 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17383 } 17384 17385 try { 17386 final XmlPullParser parser = Xml.newPullParser(); 17387 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17388 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17389 new BlobXmlRestorer() { 17390 @Override 17391 public void apply(XmlPullParser parser, int userId) 17392 throws XmlPullParserException, IOException { 17393 synchronized (mPackages) { 17394 mSettings.readAllDomainVerificationsLPr(parser, userId); 17395 mSettings.writeLPr(); 17396 } 17397 } 17398 } ); 17399 } catch (Exception e) { 17400 if (DEBUG_BACKUP) { 17401 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17402 } 17403 } 17404 } 17405 17406 @Override 17407 public byte[] getPermissionGrantBackup(int userId) { 17408 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17409 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17410 } 17411 17412 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17413 try { 17414 final XmlSerializer serializer = new FastXmlSerializer(); 17415 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17416 serializer.startDocument(null, true); 17417 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17418 17419 synchronized (mPackages) { 17420 serializeRuntimePermissionGrantsLPr(serializer, userId); 17421 } 17422 17423 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17424 serializer.endDocument(); 17425 serializer.flush(); 17426 } catch (Exception e) { 17427 if (DEBUG_BACKUP) { 17428 Slog.e(TAG, "Unable to write default apps for backup", e); 17429 } 17430 return null; 17431 } 17432 17433 return dataStream.toByteArray(); 17434 } 17435 17436 @Override 17437 public void restorePermissionGrants(byte[] backup, int userId) { 17438 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17439 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17440 } 17441 17442 try { 17443 final XmlPullParser parser = Xml.newPullParser(); 17444 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17445 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17446 new BlobXmlRestorer() { 17447 @Override 17448 public void apply(XmlPullParser parser, int userId) 17449 throws XmlPullParserException, IOException { 17450 synchronized (mPackages) { 17451 processRestoredPermissionGrantsLPr(parser, userId); 17452 } 17453 } 17454 } ); 17455 } catch (Exception e) { 17456 if (DEBUG_BACKUP) { 17457 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17458 } 17459 } 17460 } 17461 17462 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17463 throws IOException { 17464 serializer.startTag(null, TAG_ALL_GRANTS); 17465 17466 final int N = mSettings.mPackages.size(); 17467 for (int i = 0; i < N; i++) { 17468 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17469 boolean pkgGrantsKnown = false; 17470 17471 PermissionsState packagePerms = ps.getPermissionsState(); 17472 17473 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17474 final int grantFlags = state.getFlags(); 17475 // only look at grants that are not system/policy fixed 17476 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17477 final boolean isGranted = state.isGranted(); 17478 // And only back up the user-twiddled state bits 17479 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17480 final String packageName = mSettings.mPackages.keyAt(i); 17481 if (!pkgGrantsKnown) { 17482 serializer.startTag(null, TAG_GRANT); 17483 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17484 pkgGrantsKnown = true; 17485 } 17486 17487 final boolean userSet = 17488 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17489 final boolean userFixed = 17490 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17491 final boolean revoke = 17492 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17493 17494 serializer.startTag(null, TAG_PERMISSION); 17495 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17496 if (isGranted) { 17497 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17498 } 17499 if (userSet) { 17500 serializer.attribute(null, ATTR_USER_SET, "true"); 17501 } 17502 if (userFixed) { 17503 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17504 } 17505 if (revoke) { 17506 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17507 } 17508 serializer.endTag(null, TAG_PERMISSION); 17509 } 17510 } 17511 } 17512 17513 if (pkgGrantsKnown) { 17514 serializer.endTag(null, TAG_GRANT); 17515 } 17516 } 17517 17518 serializer.endTag(null, TAG_ALL_GRANTS); 17519 } 17520 17521 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17522 throws XmlPullParserException, IOException { 17523 String pkgName = null; 17524 int outerDepth = parser.getDepth(); 17525 int type; 17526 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17527 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17528 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17529 continue; 17530 } 17531 17532 final String tagName = parser.getName(); 17533 if (tagName.equals(TAG_GRANT)) { 17534 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17535 if (DEBUG_BACKUP) { 17536 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17537 } 17538 } else if (tagName.equals(TAG_PERMISSION)) { 17539 17540 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17541 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17542 17543 int newFlagSet = 0; 17544 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17545 newFlagSet |= FLAG_PERMISSION_USER_SET; 17546 } 17547 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17548 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17549 } 17550 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17551 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17552 } 17553 if (DEBUG_BACKUP) { 17554 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17555 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17556 } 17557 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17558 if (ps != null) { 17559 // Already installed so we apply the grant immediately 17560 if (DEBUG_BACKUP) { 17561 Slog.v(TAG, " + already installed; applying"); 17562 } 17563 PermissionsState perms = ps.getPermissionsState(); 17564 BasePermission bp = mSettings.mPermissions.get(permName); 17565 if (bp != null) { 17566 if (isGranted) { 17567 perms.grantRuntimePermission(bp, userId); 17568 } 17569 if (newFlagSet != 0) { 17570 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17571 } 17572 } 17573 } else { 17574 // Need to wait for post-restore install to apply the grant 17575 if (DEBUG_BACKUP) { 17576 Slog.v(TAG, " - not yet installed; saving for later"); 17577 } 17578 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17579 isGranted, newFlagSet, userId); 17580 } 17581 } else { 17582 PackageManagerService.reportSettingsProblem(Log.WARN, 17583 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17584 XmlUtils.skipCurrentTag(parser); 17585 } 17586 } 17587 17588 scheduleWriteSettingsLocked(); 17589 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17590 } 17591 17592 @Override 17593 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17594 int sourceUserId, int targetUserId, int flags) { 17595 mContext.enforceCallingOrSelfPermission( 17596 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17597 int callingUid = Binder.getCallingUid(); 17598 enforceOwnerRights(ownerPackage, callingUid); 17599 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17600 if (intentFilter.countActions() == 0) { 17601 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17602 return; 17603 } 17604 synchronized (mPackages) { 17605 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17606 ownerPackage, targetUserId, flags); 17607 CrossProfileIntentResolver resolver = 17608 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17609 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17610 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17611 if (existing != null) { 17612 int size = existing.size(); 17613 for (int i = 0; i < size; i++) { 17614 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17615 return; 17616 } 17617 } 17618 } 17619 resolver.addFilter(newFilter); 17620 scheduleWritePackageRestrictionsLocked(sourceUserId); 17621 } 17622 } 17623 17624 @Override 17625 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17626 mContext.enforceCallingOrSelfPermission( 17627 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17628 int callingUid = Binder.getCallingUid(); 17629 enforceOwnerRights(ownerPackage, callingUid); 17630 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17631 synchronized (mPackages) { 17632 CrossProfileIntentResolver resolver = 17633 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17634 ArraySet<CrossProfileIntentFilter> set = 17635 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17636 for (CrossProfileIntentFilter filter : set) { 17637 if (filter.getOwnerPackage().equals(ownerPackage)) { 17638 resolver.removeFilter(filter); 17639 } 17640 } 17641 scheduleWritePackageRestrictionsLocked(sourceUserId); 17642 } 17643 } 17644 17645 // Enforcing that callingUid is owning pkg on userId 17646 private void enforceOwnerRights(String pkg, int callingUid) { 17647 // The system owns everything. 17648 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17649 return; 17650 } 17651 int callingUserId = UserHandle.getUserId(callingUid); 17652 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17653 if (pi == null) { 17654 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17655 + callingUserId); 17656 } 17657 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17658 throw new SecurityException("Calling uid " + callingUid 17659 + " does not own package " + pkg); 17660 } 17661 } 17662 17663 @Override 17664 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17665 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17666 } 17667 17668 private Intent getHomeIntent() { 17669 Intent intent = new Intent(Intent.ACTION_MAIN); 17670 intent.addCategory(Intent.CATEGORY_HOME); 17671 return intent; 17672 } 17673 17674 private IntentFilter getHomeFilter() { 17675 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17676 filter.addCategory(Intent.CATEGORY_HOME); 17677 filter.addCategory(Intent.CATEGORY_DEFAULT); 17678 return filter; 17679 } 17680 17681 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17682 int userId) { 17683 Intent intent = getHomeIntent(); 17684 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17685 PackageManager.GET_META_DATA, userId); 17686 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17687 true, false, false, userId); 17688 17689 allHomeCandidates.clear(); 17690 if (list != null) { 17691 for (ResolveInfo ri : list) { 17692 allHomeCandidates.add(ri); 17693 } 17694 } 17695 return (preferred == null || preferred.activityInfo == null) 17696 ? null 17697 : new ComponentName(preferred.activityInfo.packageName, 17698 preferred.activityInfo.name); 17699 } 17700 17701 @Override 17702 public void setHomeActivity(ComponentName comp, int userId) { 17703 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17704 getHomeActivitiesAsUser(homeActivities, userId); 17705 17706 boolean found = false; 17707 17708 final int size = homeActivities.size(); 17709 final ComponentName[] set = new ComponentName[size]; 17710 for (int i = 0; i < size; i++) { 17711 final ResolveInfo candidate = homeActivities.get(i); 17712 final ActivityInfo info = candidate.activityInfo; 17713 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17714 set[i] = activityName; 17715 if (!found && activityName.equals(comp)) { 17716 found = true; 17717 } 17718 } 17719 if (!found) { 17720 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17721 + userId); 17722 } 17723 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17724 set, comp, userId); 17725 } 17726 17727 private @Nullable String getSetupWizardPackageName() { 17728 final Intent intent = new Intent(Intent.ACTION_MAIN); 17729 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17730 17731 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17732 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17733 | MATCH_DISABLED_COMPONENTS, 17734 UserHandle.myUserId()); 17735 if (matches.size() == 1) { 17736 return matches.get(0).getComponentInfo().packageName; 17737 } else { 17738 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17739 + ": matches=" + matches); 17740 return null; 17741 } 17742 } 17743 17744 @Override 17745 public void setApplicationEnabledSetting(String appPackageName, 17746 int newState, int flags, int userId, String callingPackage) { 17747 if (!sUserManager.exists(userId)) return; 17748 if (callingPackage == null) { 17749 callingPackage = Integer.toString(Binder.getCallingUid()); 17750 } 17751 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17752 } 17753 17754 @Override 17755 public void setComponentEnabledSetting(ComponentName componentName, 17756 int newState, int flags, int userId) { 17757 if (!sUserManager.exists(userId)) return; 17758 setEnabledSetting(componentName.getPackageName(), 17759 componentName.getClassName(), newState, flags, userId, null); 17760 } 17761 17762 private void setEnabledSetting(final String packageName, String className, int newState, 17763 final int flags, int userId, String callingPackage) { 17764 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17765 || newState == COMPONENT_ENABLED_STATE_ENABLED 17766 || newState == COMPONENT_ENABLED_STATE_DISABLED 17767 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17768 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17769 throw new IllegalArgumentException("Invalid new component state: " 17770 + newState); 17771 } 17772 PackageSetting pkgSetting; 17773 final int uid = Binder.getCallingUid(); 17774 final int permission; 17775 if (uid == Process.SYSTEM_UID) { 17776 permission = PackageManager.PERMISSION_GRANTED; 17777 } else { 17778 permission = mContext.checkCallingOrSelfPermission( 17779 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17780 } 17781 enforceCrossUserPermission(uid, userId, 17782 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17783 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17784 boolean sendNow = false; 17785 boolean isApp = (className == null); 17786 String componentName = isApp ? packageName : className; 17787 int packageUid = -1; 17788 ArrayList<String> components; 17789 17790 // writer 17791 synchronized (mPackages) { 17792 pkgSetting = mSettings.mPackages.get(packageName); 17793 if (pkgSetting == null) { 17794 if (className == null) { 17795 throw new IllegalArgumentException("Unknown package: " + packageName); 17796 } 17797 throw new IllegalArgumentException( 17798 "Unknown component: " + packageName + "/" + className); 17799 } 17800 } 17801 17802 // Limit who can change which apps 17803 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17804 // Don't allow apps that don't have permission to modify other apps 17805 if (!allowedByPermission) { 17806 throw new SecurityException( 17807 "Permission Denial: attempt to change component state from pid=" 17808 + Binder.getCallingPid() 17809 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17810 } 17811 // Don't allow changing protected packages. 17812 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17813 throw new SecurityException("Cannot disable a protected package: " + packageName); 17814 } 17815 } 17816 17817 synchronized (mPackages) { 17818 if (uid == Process.SHELL_UID) { 17819 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17820 int oldState = pkgSetting.getEnabled(userId); 17821 if (className == null 17822 && 17823 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17824 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17825 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17826 && 17827 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17828 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17829 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17830 // ok 17831 } else { 17832 throw new SecurityException( 17833 "Shell cannot change component state for " + packageName + "/" 17834 + className + " to " + newState); 17835 } 17836 } 17837 if (className == null) { 17838 // We're dealing with an application/package level state change 17839 if (pkgSetting.getEnabled(userId) == newState) { 17840 // Nothing to do 17841 return; 17842 } 17843 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17844 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17845 // Don't care about who enables an app. 17846 callingPackage = null; 17847 } 17848 pkgSetting.setEnabled(newState, userId, callingPackage); 17849 // pkgSetting.pkg.mSetEnabled = newState; 17850 } else { 17851 // We're dealing with a component level state change 17852 // First, verify that this is a valid class name. 17853 PackageParser.Package pkg = pkgSetting.pkg; 17854 if (pkg == null || !pkg.hasComponentClassName(className)) { 17855 if (pkg != null && 17856 pkg.applicationInfo.targetSdkVersion >= 17857 Build.VERSION_CODES.JELLY_BEAN) { 17858 throw new IllegalArgumentException("Component class " + className 17859 + " does not exist in " + packageName); 17860 } else { 17861 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17862 + className + " does not exist in " + packageName); 17863 } 17864 } 17865 switch (newState) { 17866 case COMPONENT_ENABLED_STATE_ENABLED: 17867 if (!pkgSetting.enableComponentLPw(className, userId)) { 17868 return; 17869 } 17870 break; 17871 case COMPONENT_ENABLED_STATE_DISABLED: 17872 if (!pkgSetting.disableComponentLPw(className, userId)) { 17873 return; 17874 } 17875 break; 17876 case COMPONENT_ENABLED_STATE_DEFAULT: 17877 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17878 return; 17879 } 17880 break; 17881 default: 17882 Slog.e(TAG, "Invalid new component state: " + newState); 17883 return; 17884 } 17885 } 17886 scheduleWritePackageRestrictionsLocked(userId); 17887 components = mPendingBroadcasts.get(userId, packageName); 17888 final boolean newPackage = components == null; 17889 if (newPackage) { 17890 components = new ArrayList<String>(); 17891 } 17892 if (!components.contains(componentName)) { 17893 components.add(componentName); 17894 } 17895 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17896 sendNow = true; 17897 // Purge entry from pending broadcast list if another one exists already 17898 // since we are sending one right away. 17899 mPendingBroadcasts.remove(userId, packageName); 17900 } else { 17901 if (newPackage) { 17902 mPendingBroadcasts.put(userId, packageName, components); 17903 } 17904 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17905 // Schedule a message 17906 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17907 } 17908 } 17909 } 17910 17911 long callingId = Binder.clearCallingIdentity(); 17912 try { 17913 if (sendNow) { 17914 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17915 sendPackageChangedBroadcast(packageName, 17916 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17917 } 17918 } finally { 17919 Binder.restoreCallingIdentity(callingId); 17920 } 17921 } 17922 17923 @Override 17924 public void flushPackageRestrictionsAsUser(int userId) { 17925 if (!sUserManager.exists(userId)) { 17926 return; 17927 } 17928 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17929 false /* checkShell */, "flushPackageRestrictions"); 17930 synchronized (mPackages) { 17931 mSettings.writePackageRestrictionsLPr(userId); 17932 mDirtyUsers.remove(userId); 17933 if (mDirtyUsers.isEmpty()) { 17934 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17935 } 17936 } 17937 } 17938 17939 private void sendPackageChangedBroadcast(String packageName, 17940 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17941 if (DEBUG_INSTALL) 17942 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17943 + componentNames); 17944 Bundle extras = new Bundle(4); 17945 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17946 String nameList[] = new String[componentNames.size()]; 17947 componentNames.toArray(nameList); 17948 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17949 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17950 extras.putInt(Intent.EXTRA_UID, packageUid); 17951 // If this is not reporting a change of the overall package, then only send it 17952 // to registered receivers. We don't want to launch a swath of apps for every 17953 // little component state change. 17954 final int flags = !componentNames.contains(packageName) 17955 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17956 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17957 new int[] {UserHandle.getUserId(packageUid)}); 17958 } 17959 17960 @Override 17961 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17962 if (!sUserManager.exists(userId)) return; 17963 final int uid = Binder.getCallingUid(); 17964 final int permission = mContext.checkCallingOrSelfPermission( 17965 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17966 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17967 enforceCrossUserPermission(uid, userId, 17968 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17969 // writer 17970 synchronized (mPackages) { 17971 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17972 allowedByPermission, uid, userId)) { 17973 scheduleWritePackageRestrictionsLocked(userId); 17974 } 17975 } 17976 } 17977 17978 @Override 17979 public String getInstallerPackageName(String packageName) { 17980 // reader 17981 synchronized (mPackages) { 17982 return mSettings.getInstallerPackageNameLPr(packageName); 17983 } 17984 } 17985 17986 public boolean isOrphaned(String packageName) { 17987 // reader 17988 synchronized (mPackages) { 17989 return mSettings.isOrphaned(packageName); 17990 } 17991 } 17992 17993 @Override 17994 public int getApplicationEnabledSetting(String packageName, int userId) { 17995 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17996 int uid = Binder.getCallingUid(); 17997 enforceCrossUserPermission(uid, userId, 17998 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17999 // reader 18000 synchronized (mPackages) { 18001 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18002 } 18003 } 18004 18005 @Override 18006 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18007 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18008 int uid = Binder.getCallingUid(); 18009 enforceCrossUserPermission(uid, userId, 18010 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18011 // reader 18012 synchronized (mPackages) { 18013 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18014 } 18015 } 18016 18017 @Override 18018 public void enterSafeMode() { 18019 enforceSystemOrRoot("Only the system can request entering safe mode"); 18020 18021 if (!mSystemReady) { 18022 mSafeMode = true; 18023 } 18024 } 18025 18026 @Override 18027 public void systemReady() { 18028 mSystemReady = true; 18029 18030 // Read the compatibilty setting when the system is ready. 18031 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18032 mContext.getContentResolver(), 18033 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18034 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18035 if (DEBUG_SETTINGS) { 18036 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18037 } 18038 18039 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18040 18041 synchronized (mPackages) { 18042 // Verify that all of the preferred activity components actually 18043 // exist. It is possible for applications to be updated and at 18044 // that point remove a previously declared activity component that 18045 // had been set as a preferred activity. We try to clean this up 18046 // the next time we encounter that preferred activity, but it is 18047 // possible for the user flow to never be able to return to that 18048 // situation so here we do a sanity check to make sure we haven't 18049 // left any junk around. 18050 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18051 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18052 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18053 removed.clear(); 18054 for (PreferredActivity pa : pir.filterSet()) { 18055 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18056 removed.add(pa); 18057 } 18058 } 18059 if (removed.size() > 0) { 18060 for (int r=0; r<removed.size(); r++) { 18061 PreferredActivity pa = removed.get(r); 18062 Slog.w(TAG, "Removing dangling preferred activity: " 18063 + pa.mPref.mComponent); 18064 pir.removeFilter(pa); 18065 } 18066 mSettings.writePackageRestrictionsLPr( 18067 mSettings.mPreferredActivities.keyAt(i)); 18068 } 18069 } 18070 18071 for (int userId : UserManagerService.getInstance().getUserIds()) { 18072 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18073 grantPermissionsUserIds = ArrayUtils.appendInt( 18074 grantPermissionsUserIds, userId); 18075 } 18076 } 18077 } 18078 sUserManager.systemReady(); 18079 18080 // If we upgraded grant all default permissions before kicking off. 18081 for (int userId : grantPermissionsUserIds) { 18082 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18083 } 18084 18085 // Kick off any messages waiting for system ready 18086 if (mPostSystemReadyMessages != null) { 18087 for (Message msg : mPostSystemReadyMessages) { 18088 msg.sendToTarget(); 18089 } 18090 mPostSystemReadyMessages = null; 18091 } 18092 18093 // Watch for external volumes that come and go over time 18094 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18095 storage.registerListener(mStorageListener); 18096 18097 mInstallerService.systemReady(); 18098 mPackageDexOptimizer.systemReady(); 18099 18100 MountServiceInternal mountServiceInternal = LocalServices.getService( 18101 MountServiceInternal.class); 18102 mountServiceInternal.addExternalStoragePolicy( 18103 new MountServiceInternal.ExternalStorageMountPolicy() { 18104 @Override 18105 public int getMountMode(int uid, String packageName) { 18106 if (Process.isIsolated(uid)) { 18107 return Zygote.MOUNT_EXTERNAL_NONE; 18108 } 18109 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18110 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18111 } 18112 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18113 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18114 } 18115 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18116 return Zygote.MOUNT_EXTERNAL_READ; 18117 } 18118 return Zygote.MOUNT_EXTERNAL_WRITE; 18119 } 18120 18121 @Override 18122 public boolean hasExternalStorage(int uid, String packageName) { 18123 return true; 18124 } 18125 }); 18126 18127 // Now that we're mostly running, clean up stale users and apps 18128 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18129 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18130 } 18131 18132 @Override 18133 public boolean isSafeMode() { 18134 return mSafeMode; 18135 } 18136 18137 @Override 18138 public boolean hasSystemUidErrors() { 18139 return mHasSystemUidErrors; 18140 } 18141 18142 static String arrayToString(int[] array) { 18143 StringBuffer buf = new StringBuffer(128); 18144 buf.append('['); 18145 if (array != null) { 18146 for (int i=0; i<array.length; i++) { 18147 if (i > 0) buf.append(", "); 18148 buf.append(array[i]); 18149 } 18150 } 18151 buf.append(']'); 18152 return buf.toString(); 18153 } 18154 18155 static class DumpState { 18156 public static final int DUMP_LIBS = 1 << 0; 18157 public static final int DUMP_FEATURES = 1 << 1; 18158 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18159 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18160 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18161 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18162 public static final int DUMP_PERMISSIONS = 1 << 6; 18163 public static final int DUMP_PACKAGES = 1 << 7; 18164 public static final int DUMP_SHARED_USERS = 1 << 8; 18165 public static final int DUMP_MESSAGES = 1 << 9; 18166 public static final int DUMP_PROVIDERS = 1 << 10; 18167 public static final int DUMP_VERIFIERS = 1 << 11; 18168 public static final int DUMP_PREFERRED = 1 << 12; 18169 public static final int DUMP_PREFERRED_XML = 1 << 13; 18170 public static final int DUMP_KEYSETS = 1 << 14; 18171 public static final int DUMP_VERSION = 1 << 15; 18172 public static final int DUMP_INSTALLS = 1 << 16; 18173 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18174 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18175 public static final int DUMP_FROZEN = 1 << 19; 18176 public static final int DUMP_DEXOPT = 1 << 20; 18177 18178 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18179 18180 private int mTypes; 18181 18182 private int mOptions; 18183 18184 private boolean mTitlePrinted; 18185 18186 private SharedUserSetting mSharedUser; 18187 18188 public boolean isDumping(int type) { 18189 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18190 return true; 18191 } 18192 18193 return (mTypes & type) != 0; 18194 } 18195 18196 public void setDump(int type) { 18197 mTypes |= type; 18198 } 18199 18200 public boolean isOptionEnabled(int option) { 18201 return (mOptions & option) != 0; 18202 } 18203 18204 public void setOptionEnabled(int option) { 18205 mOptions |= option; 18206 } 18207 18208 public boolean onTitlePrinted() { 18209 final boolean printed = mTitlePrinted; 18210 mTitlePrinted = true; 18211 return printed; 18212 } 18213 18214 public boolean getTitlePrinted() { 18215 return mTitlePrinted; 18216 } 18217 18218 public void setTitlePrinted(boolean enabled) { 18219 mTitlePrinted = enabled; 18220 } 18221 18222 public SharedUserSetting getSharedUser() { 18223 return mSharedUser; 18224 } 18225 18226 public void setSharedUser(SharedUserSetting user) { 18227 mSharedUser = user; 18228 } 18229 } 18230 18231 @Override 18232 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18233 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18234 (new PackageManagerShellCommand(this)).exec( 18235 this, in, out, err, args, resultReceiver); 18236 } 18237 18238 @Override 18239 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18240 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18241 != PackageManager.PERMISSION_GRANTED) { 18242 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18243 + Binder.getCallingPid() 18244 + ", uid=" + Binder.getCallingUid() 18245 + " without permission " 18246 + android.Manifest.permission.DUMP); 18247 return; 18248 } 18249 18250 DumpState dumpState = new DumpState(); 18251 boolean fullPreferred = false; 18252 boolean checkin = false; 18253 18254 String packageName = null; 18255 ArraySet<String> permissionNames = null; 18256 18257 int opti = 0; 18258 while (opti < args.length) { 18259 String opt = args[opti]; 18260 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18261 break; 18262 } 18263 opti++; 18264 18265 if ("-a".equals(opt)) { 18266 // Right now we only know how to print all. 18267 } else if ("-h".equals(opt)) { 18268 pw.println("Package manager dump options:"); 18269 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18270 pw.println(" --checkin: dump for a checkin"); 18271 pw.println(" -f: print details of intent filters"); 18272 pw.println(" -h: print this help"); 18273 pw.println(" cmd may be one of:"); 18274 pw.println(" l[ibraries]: list known shared libraries"); 18275 pw.println(" f[eatures]: list device features"); 18276 pw.println(" k[eysets]: print known keysets"); 18277 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18278 pw.println(" perm[issions]: dump permissions"); 18279 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18280 pw.println(" pref[erred]: print preferred package settings"); 18281 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18282 pw.println(" prov[iders]: dump content providers"); 18283 pw.println(" p[ackages]: dump installed packages"); 18284 pw.println(" s[hared-users]: dump shared user IDs"); 18285 pw.println(" m[essages]: print collected runtime messages"); 18286 pw.println(" v[erifiers]: print package verifier info"); 18287 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18288 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18289 pw.println(" version: print database version info"); 18290 pw.println(" write: write current settings now"); 18291 pw.println(" installs: details about install sessions"); 18292 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18293 pw.println(" dexopt: dump dexopt state"); 18294 pw.println(" <package.name>: info about given package"); 18295 return; 18296 } else if ("--checkin".equals(opt)) { 18297 checkin = true; 18298 } else if ("-f".equals(opt)) { 18299 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18300 } else { 18301 pw.println("Unknown argument: " + opt + "; use -h for help"); 18302 } 18303 } 18304 18305 // Is the caller requesting to dump a particular piece of data? 18306 if (opti < args.length) { 18307 String cmd = args[opti]; 18308 opti++; 18309 // Is this a package name? 18310 if ("android".equals(cmd) || cmd.contains(".")) { 18311 packageName = cmd; 18312 // When dumping a single package, we always dump all of its 18313 // filter information since the amount of data will be reasonable. 18314 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18315 } else if ("check-permission".equals(cmd)) { 18316 if (opti >= args.length) { 18317 pw.println("Error: check-permission missing permission argument"); 18318 return; 18319 } 18320 String perm = args[opti]; 18321 opti++; 18322 if (opti >= args.length) { 18323 pw.println("Error: check-permission missing package argument"); 18324 return; 18325 } 18326 String pkg = args[opti]; 18327 opti++; 18328 int user = UserHandle.getUserId(Binder.getCallingUid()); 18329 if (opti < args.length) { 18330 try { 18331 user = Integer.parseInt(args[opti]); 18332 } catch (NumberFormatException e) { 18333 pw.println("Error: check-permission user argument is not a number: " 18334 + args[opti]); 18335 return; 18336 } 18337 } 18338 pw.println(checkPermission(perm, pkg, user)); 18339 return; 18340 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18341 dumpState.setDump(DumpState.DUMP_LIBS); 18342 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18343 dumpState.setDump(DumpState.DUMP_FEATURES); 18344 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18345 if (opti >= args.length) { 18346 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18347 | DumpState.DUMP_SERVICE_RESOLVERS 18348 | DumpState.DUMP_RECEIVER_RESOLVERS 18349 | DumpState.DUMP_CONTENT_RESOLVERS); 18350 } else { 18351 while (opti < args.length) { 18352 String name = args[opti]; 18353 if ("a".equals(name) || "activity".equals(name)) { 18354 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18355 } else if ("s".equals(name) || "service".equals(name)) { 18356 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18357 } else if ("r".equals(name) || "receiver".equals(name)) { 18358 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18359 } else if ("c".equals(name) || "content".equals(name)) { 18360 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18361 } else { 18362 pw.println("Error: unknown resolver table type: " + name); 18363 return; 18364 } 18365 opti++; 18366 } 18367 } 18368 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18369 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18370 } else if ("permission".equals(cmd)) { 18371 if (opti >= args.length) { 18372 pw.println("Error: permission requires permission name"); 18373 return; 18374 } 18375 permissionNames = new ArraySet<>(); 18376 while (opti < args.length) { 18377 permissionNames.add(args[opti]); 18378 opti++; 18379 } 18380 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18381 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18382 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18383 dumpState.setDump(DumpState.DUMP_PREFERRED); 18384 } else if ("preferred-xml".equals(cmd)) { 18385 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18386 if (opti < args.length && "--full".equals(args[opti])) { 18387 fullPreferred = true; 18388 opti++; 18389 } 18390 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18391 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18392 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18393 dumpState.setDump(DumpState.DUMP_PACKAGES); 18394 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18395 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18396 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18397 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18398 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18399 dumpState.setDump(DumpState.DUMP_MESSAGES); 18400 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18401 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18402 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18403 || "intent-filter-verifiers".equals(cmd)) { 18404 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18405 } else if ("version".equals(cmd)) { 18406 dumpState.setDump(DumpState.DUMP_VERSION); 18407 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18408 dumpState.setDump(DumpState.DUMP_KEYSETS); 18409 } else if ("installs".equals(cmd)) { 18410 dumpState.setDump(DumpState.DUMP_INSTALLS); 18411 } else if ("frozen".equals(cmd)) { 18412 dumpState.setDump(DumpState.DUMP_FROZEN); 18413 } else if ("dexopt".equals(cmd)) { 18414 dumpState.setDump(DumpState.DUMP_DEXOPT); 18415 } else if ("write".equals(cmd)) { 18416 synchronized (mPackages) { 18417 mSettings.writeLPr(); 18418 pw.println("Settings written."); 18419 return; 18420 } 18421 } 18422 } 18423 18424 if (checkin) { 18425 pw.println("vers,1"); 18426 } 18427 18428 // reader 18429 synchronized (mPackages) { 18430 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18431 if (!checkin) { 18432 if (dumpState.onTitlePrinted()) 18433 pw.println(); 18434 pw.println("Database versions:"); 18435 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18436 } 18437 } 18438 18439 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18440 if (!checkin) { 18441 if (dumpState.onTitlePrinted()) 18442 pw.println(); 18443 pw.println("Verifiers:"); 18444 pw.print(" Required: "); 18445 pw.print(mRequiredVerifierPackage); 18446 pw.print(" (uid="); 18447 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18448 UserHandle.USER_SYSTEM)); 18449 pw.println(")"); 18450 } else if (mRequiredVerifierPackage != null) { 18451 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18452 pw.print(","); 18453 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18454 UserHandle.USER_SYSTEM)); 18455 } 18456 } 18457 18458 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18459 packageName == null) { 18460 if (mIntentFilterVerifierComponent != null) { 18461 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18462 if (!checkin) { 18463 if (dumpState.onTitlePrinted()) 18464 pw.println(); 18465 pw.println("Intent Filter Verifier:"); 18466 pw.print(" Using: "); 18467 pw.print(verifierPackageName); 18468 pw.print(" (uid="); 18469 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18470 UserHandle.USER_SYSTEM)); 18471 pw.println(")"); 18472 } else if (verifierPackageName != null) { 18473 pw.print("ifv,"); pw.print(verifierPackageName); 18474 pw.print(","); 18475 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18476 UserHandle.USER_SYSTEM)); 18477 } 18478 } else { 18479 pw.println(); 18480 pw.println("No Intent Filter Verifier available!"); 18481 } 18482 } 18483 18484 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18485 boolean printedHeader = false; 18486 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18487 while (it.hasNext()) { 18488 String name = it.next(); 18489 SharedLibraryEntry ent = mSharedLibraries.get(name); 18490 if (!checkin) { 18491 if (!printedHeader) { 18492 if (dumpState.onTitlePrinted()) 18493 pw.println(); 18494 pw.println("Libraries:"); 18495 printedHeader = true; 18496 } 18497 pw.print(" "); 18498 } else { 18499 pw.print("lib,"); 18500 } 18501 pw.print(name); 18502 if (!checkin) { 18503 pw.print(" -> "); 18504 } 18505 if (ent.path != null) { 18506 if (!checkin) { 18507 pw.print("(jar) "); 18508 pw.print(ent.path); 18509 } else { 18510 pw.print(",jar,"); 18511 pw.print(ent.path); 18512 } 18513 } else { 18514 if (!checkin) { 18515 pw.print("(apk) "); 18516 pw.print(ent.apk); 18517 } else { 18518 pw.print(",apk,"); 18519 pw.print(ent.apk); 18520 } 18521 } 18522 pw.println(); 18523 } 18524 } 18525 18526 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18527 if (dumpState.onTitlePrinted()) 18528 pw.println(); 18529 if (!checkin) { 18530 pw.println("Features:"); 18531 } 18532 18533 for (FeatureInfo feat : mAvailableFeatures.values()) { 18534 if (checkin) { 18535 pw.print("feat,"); 18536 pw.print(feat.name); 18537 pw.print(","); 18538 pw.println(feat.version); 18539 } else { 18540 pw.print(" "); 18541 pw.print(feat.name); 18542 if (feat.version > 0) { 18543 pw.print(" version="); 18544 pw.print(feat.version); 18545 } 18546 pw.println(); 18547 } 18548 } 18549 } 18550 18551 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18552 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18553 : "Activity Resolver Table:", " ", packageName, 18554 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18555 dumpState.setTitlePrinted(true); 18556 } 18557 } 18558 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18559 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18560 : "Receiver Resolver Table:", " ", packageName, 18561 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18562 dumpState.setTitlePrinted(true); 18563 } 18564 } 18565 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18566 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18567 : "Service Resolver Table:", " ", packageName, 18568 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18569 dumpState.setTitlePrinted(true); 18570 } 18571 } 18572 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18573 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18574 : "Provider Resolver Table:", " ", packageName, 18575 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18576 dumpState.setTitlePrinted(true); 18577 } 18578 } 18579 18580 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18581 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18582 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18583 int user = mSettings.mPreferredActivities.keyAt(i); 18584 if (pir.dump(pw, 18585 dumpState.getTitlePrinted() 18586 ? "\nPreferred Activities User " + user + ":" 18587 : "Preferred Activities User " + user + ":", " ", 18588 packageName, true, false)) { 18589 dumpState.setTitlePrinted(true); 18590 } 18591 } 18592 } 18593 18594 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18595 pw.flush(); 18596 FileOutputStream fout = new FileOutputStream(fd); 18597 BufferedOutputStream str = new BufferedOutputStream(fout); 18598 XmlSerializer serializer = new FastXmlSerializer(); 18599 try { 18600 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18601 serializer.startDocument(null, true); 18602 serializer.setFeature( 18603 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18604 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18605 serializer.endDocument(); 18606 serializer.flush(); 18607 } catch (IllegalArgumentException e) { 18608 pw.println("Failed writing: " + e); 18609 } catch (IllegalStateException e) { 18610 pw.println("Failed writing: " + e); 18611 } catch (IOException e) { 18612 pw.println("Failed writing: " + e); 18613 } 18614 } 18615 18616 if (!checkin 18617 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18618 && packageName == null) { 18619 pw.println(); 18620 int count = mSettings.mPackages.size(); 18621 if (count == 0) { 18622 pw.println("No applications!"); 18623 pw.println(); 18624 } else { 18625 final String prefix = " "; 18626 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18627 if (allPackageSettings.size() == 0) { 18628 pw.println("No domain preferred apps!"); 18629 pw.println(); 18630 } else { 18631 pw.println("App verification status:"); 18632 pw.println(); 18633 count = 0; 18634 for (PackageSetting ps : allPackageSettings) { 18635 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18636 if (ivi == null || ivi.getPackageName() == null) continue; 18637 pw.println(prefix + "Package: " + ivi.getPackageName()); 18638 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18639 pw.println(prefix + "Status: " + ivi.getStatusString()); 18640 pw.println(); 18641 count++; 18642 } 18643 if (count == 0) { 18644 pw.println(prefix + "No app verification established."); 18645 pw.println(); 18646 } 18647 for (int userId : sUserManager.getUserIds()) { 18648 pw.println("App linkages for user " + userId + ":"); 18649 pw.println(); 18650 count = 0; 18651 for (PackageSetting ps : allPackageSettings) { 18652 final long status = ps.getDomainVerificationStatusForUser(userId); 18653 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18654 continue; 18655 } 18656 pw.println(prefix + "Package: " + ps.name); 18657 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18658 String statusStr = IntentFilterVerificationInfo. 18659 getStatusStringFromValue(status); 18660 pw.println(prefix + "Status: " + statusStr); 18661 pw.println(); 18662 count++; 18663 } 18664 if (count == 0) { 18665 pw.println(prefix + "No configured app linkages."); 18666 pw.println(); 18667 } 18668 } 18669 } 18670 } 18671 } 18672 18673 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18674 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18675 if (packageName == null && permissionNames == null) { 18676 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18677 if (iperm == 0) { 18678 if (dumpState.onTitlePrinted()) 18679 pw.println(); 18680 pw.println("AppOp Permissions:"); 18681 } 18682 pw.print(" AppOp Permission "); 18683 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18684 pw.println(":"); 18685 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18686 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18687 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18688 } 18689 } 18690 } 18691 } 18692 18693 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18694 boolean printedSomething = false; 18695 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18696 if (packageName != null && !packageName.equals(p.info.packageName)) { 18697 continue; 18698 } 18699 if (!printedSomething) { 18700 if (dumpState.onTitlePrinted()) 18701 pw.println(); 18702 pw.println("Registered ContentProviders:"); 18703 printedSomething = true; 18704 } 18705 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18706 pw.print(" "); pw.println(p.toString()); 18707 } 18708 printedSomething = false; 18709 for (Map.Entry<String, PackageParser.Provider> entry : 18710 mProvidersByAuthority.entrySet()) { 18711 PackageParser.Provider p = entry.getValue(); 18712 if (packageName != null && !packageName.equals(p.info.packageName)) { 18713 continue; 18714 } 18715 if (!printedSomething) { 18716 if (dumpState.onTitlePrinted()) 18717 pw.println(); 18718 pw.println("ContentProvider Authorities:"); 18719 printedSomething = true; 18720 } 18721 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18722 pw.print(" "); pw.println(p.toString()); 18723 if (p.info != null && p.info.applicationInfo != null) { 18724 final String appInfo = p.info.applicationInfo.toString(); 18725 pw.print(" applicationInfo="); pw.println(appInfo); 18726 } 18727 } 18728 } 18729 18730 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18731 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18732 } 18733 18734 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18735 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18736 } 18737 18738 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18739 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18740 } 18741 18742 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18743 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18744 } 18745 18746 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18747 // XXX should handle packageName != null by dumping only install data that 18748 // the given package is involved with. 18749 if (dumpState.onTitlePrinted()) pw.println(); 18750 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18751 } 18752 18753 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18754 // XXX should handle packageName != null by dumping only install data that 18755 // the given package is involved with. 18756 if (dumpState.onTitlePrinted()) pw.println(); 18757 18758 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18759 ipw.println(); 18760 ipw.println("Frozen packages:"); 18761 ipw.increaseIndent(); 18762 if (mFrozenPackages.size() == 0) { 18763 ipw.println("(none)"); 18764 } else { 18765 for (int i = 0; i < mFrozenPackages.size(); i++) { 18766 ipw.println(mFrozenPackages.valueAt(i)); 18767 } 18768 } 18769 ipw.decreaseIndent(); 18770 } 18771 18772 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18773 if (dumpState.onTitlePrinted()) pw.println(); 18774 dumpDexoptStateLPr(pw, packageName); 18775 } 18776 18777 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18778 if (dumpState.onTitlePrinted()) pw.println(); 18779 mSettings.dumpReadMessagesLPr(pw, dumpState); 18780 18781 pw.println(); 18782 pw.println("Package warning messages:"); 18783 BufferedReader in = null; 18784 String line = null; 18785 try { 18786 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18787 while ((line = in.readLine()) != null) { 18788 if (line.contains("ignored: updated version")) continue; 18789 pw.println(line); 18790 } 18791 } catch (IOException ignored) { 18792 } finally { 18793 IoUtils.closeQuietly(in); 18794 } 18795 } 18796 18797 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18798 BufferedReader in = null; 18799 String line = null; 18800 try { 18801 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18802 while ((line = in.readLine()) != null) { 18803 if (line.contains("ignored: updated version")) continue; 18804 pw.print("msg,"); 18805 pw.println(line); 18806 } 18807 } catch (IOException ignored) { 18808 } finally { 18809 IoUtils.closeQuietly(in); 18810 } 18811 } 18812 } 18813 } 18814 18815 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18816 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18817 ipw.println(); 18818 ipw.println("Dexopt state:"); 18819 ipw.increaseIndent(); 18820 Collection<PackageParser.Package> packages = null; 18821 if (packageName != null) { 18822 PackageParser.Package targetPackage = mPackages.get(packageName); 18823 if (targetPackage != null) { 18824 packages = Collections.singletonList(targetPackage); 18825 } else { 18826 ipw.println("Unable to find package: " + packageName); 18827 return; 18828 } 18829 } else { 18830 packages = mPackages.values(); 18831 } 18832 18833 for (PackageParser.Package pkg : packages) { 18834 ipw.println("[" + pkg.packageName + "]"); 18835 ipw.increaseIndent(); 18836 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18837 ipw.decreaseIndent(); 18838 } 18839 } 18840 18841 private String dumpDomainString(String packageName) { 18842 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18843 .getList(); 18844 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18845 18846 ArraySet<String> result = new ArraySet<>(); 18847 if (iviList.size() > 0) { 18848 for (IntentFilterVerificationInfo ivi : iviList) { 18849 for (String host : ivi.getDomains()) { 18850 result.add(host); 18851 } 18852 } 18853 } 18854 if (filters != null && filters.size() > 0) { 18855 for (IntentFilter filter : filters) { 18856 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18857 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18858 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18859 result.addAll(filter.getHostsList()); 18860 } 18861 } 18862 } 18863 18864 StringBuilder sb = new StringBuilder(result.size() * 16); 18865 for (String domain : result) { 18866 if (sb.length() > 0) sb.append(" "); 18867 sb.append(domain); 18868 } 18869 return sb.toString(); 18870 } 18871 18872 // ------- apps on sdcard specific code ------- 18873 static final boolean DEBUG_SD_INSTALL = false; 18874 18875 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18876 18877 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18878 18879 private boolean mMediaMounted = false; 18880 18881 static String getEncryptKey() { 18882 try { 18883 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18884 SD_ENCRYPTION_KEYSTORE_NAME); 18885 if (sdEncKey == null) { 18886 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18887 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18888 if (sdEncKey == null) { 18889 Slog.e(TAG, "Failed to create encryption keys"); 18890 return null; 18891 } 18892 } 18893 return sdEncKey; 18894 } catch (NoSuchAlgorithmException nsae) { 18895 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18896 return null; 18897 } catch (IOException ioe) { 18898 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18899 return null; 18900 } 18901 } 18902 18903 /* 18904 * Update media status on PackageManager. 18905 */ 18906 @Override 18907 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18908 int callingUid = Binder.getCallingUid(); 18909 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18910 throw new SecurityException("Media status can only be updated by the system"); 18911 } 18912 // reader; this apparently protects mMediaMounted, but should probably 18913 // be a different lock in that case. 18914 synchronized (mPackages) { 18915 Log.i(TAG, "Updating external media status from " 18916 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18917 + (mediaStatus ? "mounted" : "unmounted")); 18918 if (DEBUG_SD_INSTALL) 18919 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18920 + ", mMediaMounted=" + mMediaMounted); 18921 if (mediaStatus == mMediaMounted) { 18922 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18923 : 0, -1); 18924 mHandler.sendMessage(msg); 18925 return; 18926 } 18927 mMediaMounted = mediaStatus; 18928 } 18929 // Queue up an async operation since the package installation may take a 18930 // little while. 18931 mHandler.post(new Runnable() { 18932 public void run() { 18933 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18934 } 18935 }); 18936 } 18937 18938 /** 18939 * Called by MountService when the initial ASECs to scan are available. 18940 * Should block until all the ASEC containers are finished being scanned. 18941 */ 18942 public void scanAvailableAsecs() { 18943 updateExternalMediaStatusInner(true, false, false); 18944 } 18945 18946 /* 18947 * Collect information of applications on external media, map them against 18948 * existing containers and update information based on current mount status. 18949 * Please note that we always have to report status if reportStatus has been 18950 * set to true especially when unloading packages. 18951 */ 18952 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18953 boolean externalStorage) { 18954 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18955 int[] uidArr = EmptyArray.INT; 18956 18957 final String[] list = PackageHelper.getSecureContainerList(); 18958 if (ArrayUtils.isEmpty(list)) { 18959 Log.i(TAG, "No secure containers found"); 18960 } else { 18961 // Process list of secure containers and categorize them 18962 // as active or stale based on their package internal state. 18963 18964 // reader 18965 synchronized (mPackages) { 18966 for (String cid : list) { 18967 // Leave stages untouched for now; installer service owns them 18968 if (PackageInstallerService.isStageName(cid)) continue; 18969 18970 if (DEBUG_SD_INSTALL) 18971 Log.i(TAG, "Processing container " + cid); 18972 String pkgName = getAsecPackageName(cid); 18973 if (pkgName == null) { 18974 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18975 continue; 18976 } 18977 if (DEBUG_SD_INSTALL) 18978 Log.i(TAG, "Looking for pkg : " + pkgName); 18979 18980 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18981 if (ps == null) { 18982 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18983 continue; 18984 } 18985 18986 /* 18987 * Skip packages that are not external if we're unmounting 18988 * external storage. 18989 */ 18990 if (externalStorage && !isMounted && !isExternal(ps)) { 18991 continue; 18992 } 18993 18994 final AsecInstallArgs args = new AsecInstallArgs(cid, 18995 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18996 // The package status is changed only if the code path 18997 // matches between settings and the container id. 18998 if (ps.codePathString != null 18999 && ps.codePathString.startsWith(args.getCodePath())) { 19000 if (DEBUG_SD_INSTALL) { 19001 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19002 + " at code path: " + ps.codePathString); 19003 } 19004 19005 // We do have a valid package installed on sdcard 19006 processCids.put(args, ps.codePathString); 19007 final int uid = ps.appId; 19008 if (uid != -1) { 19009 uidArr = ArrayUtils.appendInt(uidArr, uid); 19010 } 19011 } else { 19012 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19013 + ps.codePathString); 19014 } 19015 } 19016 } 19017 19018 Arrays.sort(uidArr); 19019 } 19020 19021 // Process packages with valid entries. 19022 if (isMounted) { 19023 if (DEBUG_SD_INSTALL) 19024 Log.i(TAG, "Loading packages"); 19025 loadMediaPackages(processCids, uidArr, externalStorage); 19026 startCleaningPackages(); 19027 mInstallerService.onSecureContainersAvailable(); 19028 } else { 19029 if (DEBUG_SD_INSTALL) 19030 Log.i(TAG, "Unloading packages"); 19031 unloadMediaPackages(processCids, uidArr, reportStatus); 19032 } 19033 } 19034 19035 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19036 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19037 final int size = infos.size(); 19038 final String[] packageNames = new String[size]; 19039 final int[] packageUids = new int[size]; 19040 for (int i = 0; i < size; i++) { 19041 final ApplicationInfo info = infos.get(i); 19042 packageNames[i] = info.packageName; 19043 packageUids[i] = info.uid; 19044 } 19045 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19046 finishedReceiver); 19047 } 19048 19049 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19050 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19051 sendResourcesChangedBroadcast(mediaStatus, replacing, 19052 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19053 } 19054 19055 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19056 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19057 int size = pkgList.length; 19058 if (size > 0) { 19059 // Send broadcasts here 19060 Bundle extras = new Bundle(); 19061 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19062 if (uidArr != null) { 19063 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19064 } 19065 if (replacing) { 19066 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19067 } 19068 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19069 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19070 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19071 } 19072 } 19073 19074 /* 19075 * Look at potentially valid container ids from processCids If package 19076 * information doesn't match the one on record or package scanning fails, 19077 * the cid is added to list of removeCids. We currently don't delete stale 19078 * containers. 19079 */ 19080 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19081 boolean externalStorage) { 19082 ArrayList<String> pkgList = new ArrayList<String>(); 19083 Set<AsecInstallArgs> keys = processCids.keySet(); 19084 19085 for (AsecInstallArgs args : keys) { 19086 String codePath = processCids.get(args); 19087 if (DEBUG_SD_INSTALL) 19088 Log.i(TAG, "Loading container : " + args.cid); 19089 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19090 try { 19091 // Make sure there are no container errors first. 19092 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19093 Slog.e(TAG, "Failed to mount cid : " + args.cid 19094 + " when installing from sdcard"); 19095 continue; 19096 } 19097 // Check code path here. 19098 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19099 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19100 + " does not match one in settings " + codePath); 19101 continue; 19102 } 19103 // Parse package 19104 int parseFlags = mDefParseFlags; 19105 if (args.isExternalAsec()) { 19106 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19107 } 19108 if (args.isFwdLocked()) { 19109 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19110 } 19111 19112 synchronized (mInstallLock) { 19113 PackageParser.Package pkg = null; 19114 try { 19115 // Sadly we don't know the package name yet to freeze it 19116 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19117 SCAN_IGNORE_FROZEN, 0, null); 19118 } catch (PackageManagerException e) { 19119 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19120 } 19121 // Scan the package 19122 if (pkg != null) { 19123 /* 19124 * TODO why is the lock being held? doPostInstall is 19125 * called in other places without the lock. This needs 19126 * to be straightened out. 19127 */ 19128 // writer 19129 synchronized (mPackages) { 19130 retCode = PackageManager.INSTALL_SUCCEEDED; 19131 pkgList.add(pkg.packageName); 19132 // Post process args 19133 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19134 pkg.applicationInfo.uid); 19135 } 19136 } else { 19137 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19138 } 19139 } 19140 19141 } finally { 19142 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19143 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19144 } 19145 } 19146 } 19147 // writer 19148 synchronized (mPackages) { 19149 // If the platform SDK has changed since the last time we booted, 19150 // we need to re-grant app permission to catch any new ones that 19151 // appear. This is really a hack, and means that apps can in some 19152 // cases get permissions that the user didn't initially explicitly 19153 // allow... it would be nice to have some better way to handle 19154 // this situation. 19155 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19156 : mSettings.getInternalVersion(); 19157 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19158 : StorageManager.UUID_PRIVATE_INTERNAL; 19159 19160 int updateFlags = UPDATE_PERMISSIONS_ALL; 19161 if (ver.sdkVersion != mSdkVersion) { 19162 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19163 + mSdkVersion + "; regranting permissions for external"); 19164 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19165 } 19166 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19167 19168 // Yay, everything is now upgraded 19169 ver.forceCurrent(); 19170 19171 // can downgrade to reader 19172 // Persist settings 19173 mSettings.writeLPr(); 19174 } 19175 // Send a broadcast to let everyone know we are done processing 19176 if (pkgList.size() > 0) { 19177 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19178 } 19179 } 19180 19181 /* 19182 * Utility method to unload a list of specified containers 19183 */ 19184 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19185 // Just unmount all valid containers. 19186 for (AsecInstallArgs arg : cidArgs) { 19187 synchronized (mInstallLock) { 19188 arg.doPostDeleteLI(false); 19189 } 19190 } 19191 } 19192 19193 /* 19194 * Unload packages mounted on external media. This involves deleting package 19195 * data from internal structures, sending broadcasts about disabled packages, 19196 * gc'ing to free up references, unmounting all secure containers 19197 * corresponding to packages on external media, and posting a 19198 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19199 * that we always have to post this message if status has been requested no 19200 * matter what. 19201 */ 19202 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19203 final boolean reportStatus) { 19204 if (DEBUG_SD_INSTALL) 19205 Log.i(TAG, "unloading media packages"); 19206 ArrayList<String> pkgList = new ArrayList<String>(); 19207 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19208 final Set<AsecInstallArgs> keys = processCids.keySet(); 19209 for (AsecInstallArgs args : keys) { 19210 String pkgName = args.getPackageName(); 19211 if (DEBUG_SD_INSTALL) 19212 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19213 // Delete package internally 19214 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19215 synchronized (mInstallLock) { 19216 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19217 final boolean res; 19218 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19219 "unloadMediaPackages")) { 19220 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19221 null); 19222 } 19223 if (res) { 19224 pkgList.add(pkgName); 19225 } else { 19226 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19227 failedList.add(args); 19228 } 19229 } 19230 } 19231 19232 // reader 19233 synchronized (mPackages) { 19234 // We didn't update the settings after removing each package; 19235 // write them now for all packages. 19236 mSettings.writeLPr(); 19237 } 19238 19239 // We have to absolutely send UPDATED_MEDIA_STATUS only 19240 // after confirming that all the receivers processed the ordered 19241 // broadcast when packages get disabled, force a gc to clean things up. 19242 // and unload all the containers. 19243 if (pkgList.size() > 0) { 19244 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19245 new IIntentReceiver.Stub() { 19246 public void performReceive(Intent intent, int resultCode, String data, 19247 Bundle extras, boolean ordered, boolean sticky, 19248 int sendingUser) throws RemoteException { 19249 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19250 reportStatus ? 1 : 0, 1, keys); 19251 mHandler.sendMessage(msg); 19252 } 19253 }); 19254 } else { 19255 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19256 keys); 19257 mHandler.sendMessage(msg); 19258 } 19259 } 19260 19261 private void loadPrivatePackages(final VolumeInfo vol) { 19262 mHandler.post(new Runnable() { 19263 @Override 19264 public void run() { 19265 loadPrivatePackagesInner(vol); 19266 } 19267 }); 19268 } 19269 19270 private void loadPrivatePackagesInner(VolumeInfo vol) { 19271 final String volumeUuid = vol.fsUuid; 19272 if (TextUtils.isEmpty(volumeUuid)) { 19273 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19274 return; 19275 } 19276 19277 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19278 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19279 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19280 19281 final VersionInfo ver; 19282 final List<PackageSetting> packages; 19283 synchronized (mPackages) { 19284 ver = mSettings.findOrCreateVersion(volumeUuid); 19285 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19286 } 19287 19288 for (PackageSetting ps : packages) { 19289 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19290 synchronized (mInstallLock) { 19291 final PackageParser.Package pkg; 19292 try { 19293 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19294 loaded.add(pkg.applicationInfo); 19295 19296 } catch (PackageManagerException e) { 19297 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19298 } 19299 19300 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19301 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19302 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19303 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19304 } 19305 } 19306 } 19307 19308 // Reconcile app data for all started/unlocked users 19309 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19310 final UserManager um = mContext.getSystemService(UserManager.class); 19311 UserManagerInternal umInternal = getUserManagerInternal(); 19312 for (UserInfo user : um.getUsers()) { 19313 final int flags; 19314 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19315 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19316 } else if (umInternal.isUserRunning(user.id)) { 19317 flags = StorageManager.FLAG_STORAGE_DE; 19318 } else { 19319 continue; 19320 } 19321 19322 try { 19323 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19324 synchronized (mInstallLock) { 19325 reconcileAppsDataLI(volumeUuid, user.id, flags); 19326 } 19327 } catch (IllegalStateException e) { 19328 // Device was probably ejected, and we'll process that event momentarily 19329 Slog.w(TAG, "Failed to prepare storage: " + e); 19330 } 19331 } 19332 19333 synchronized (mPackages) { 19334 int updateFlags = UPDATE_PERMISSIONS_ALL; 19335 if (ver.sdkVersion != mSdkVersion) { 19336 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19337 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19338 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19339 } 19340 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19341 19342 // Yay, everything is now upgraded 19343 ver.forceCurrent(); 19344 19345 mSettings.writeLPr(); 19346 } 19347 19348 for (PackageFreezer freezer : freezers) { 19349 freezer.close(); 19350 } 19351 19352 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19353 sendResourcesChangedBroadcast(true, false, loaded, null); 19354 } 19355 19356 private void unloadPrivatePackages(final VolumeInfo vol) { 19357 mHandler.post(new Runnable() { 19358 @Override 19359 public void run() { 19360 unloadPrivatePackagesInner(vol); 19361 } 19362 }); 19363 } 19364 19365 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19366 final String volumeUuid = vol.fsUuid; 19367 if (TextUtils.isEmpty(volumeUuid)) { 19368 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19369 return; 19370 } 19371 19372 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19373 synchronized (mInstallLock) { 19374 synchronized (mPackages) { 19375 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19376 for (PackageSetting ps : packages) { 19377 if (ps.pkg == null) continue; 19378 19379 final ApplicationInfo info = ps.pkg.applicationInfo; 19380 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19381 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19382 19383 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19384 "unloadPrivatePackagesInner")) { 19385 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19386 false, null)) { 19387 unloaded.add(info); 19388 } else { 19389 Slog.w(TAG, "Failed to unload " + ps.codePath); 19390 } 19391 } 19392 19393 // Try very hard to release any references to this package 19394 // so we don't risk the system server being killed due to 19395 // open FDs 19396 AttributeCache.instance().removePackage(ps.name); 19397 } 19398 19399 mSettings.writeLPr(); 19400 } 19401 } 19402 19403 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19404 sendResourcesChangedBroadcast(false, false, unloaded, null); 19405 19406 // Try very hard to release any references to this path so we don't risk 19407 // the system server being killed due to open FDs 19408 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19409 19410 for (int i = 0; i < 3; i++) { 19411 System.gc(); 19412 System.runFinalization(); 19413 } 19414 } 19415 19416 /** 19417 * Prepare storage areas for given user on all mounted devices. 19418 */ 19419 void prepareUserData(int userId, int userSerial, int flags) { 19420 synchronized (mInstallLock) { 19421 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19422 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19423 final String volumeUuid = vol.getFsUuid(); 19424 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19425 } 19426 } 19427 } 19428 19429 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19430 boolean allowRecover) { 19431 // Prepare storage and verify that serial numbers are consistent; if 19432 // there's a mismatch we need to destroy to avoid leaking data 19433 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19434 try { 19435 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19436 19437 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19438 UserManagerService.enforceSerialNumber( 19439 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19440 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19441 UserManagerService.enforceSerialNumber( 19442 Environment.getDataSystemDeDirectory(userId), userSerial); 19443 } 19444 } 19445 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19446 UserManagerService.enforceSerialNumber( 19447 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19448 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19449 UserManagerService.enforceSerialNumber( 19450 Environment.getDataSystemCeDirectory(userId), userSerial); 19451 } 19452 } 19453 19454 synchronized (mInstallLock) { 19455 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19456 } 19457 } catch (Exception e) { 19458 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19459 + " because we failed to prepare: " + e); 19460 destroyUserDataLI(volumeUuid, userId, 19461 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19462 19463 if (allowRecover) { 19464 // Try one last time; if we fail again we're really in trouble 19465 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19466 } 19467 } 19468 } 19469 19470 /** 19471 * Destroy storage areas for given user on all mounted devices. 19472 */ 19473 void destroyUserData(int userId, int flags) { 19474 synchronized (mInstallLock) { 19475 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19476 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19477 final String volumeUuid = vol.getFsUuid(); 19478 destroyUserDataLI(volumeUuid, userId, flags); 19479 } 19480 } 19481 } 19482 19483 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19484 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19485 try { 19486 // Clean up app data, profile data, and media data 19487 mInstaller.destroyUserData(volumeUuid, userId, flags); 19488 19489 // Clean up system data 19490 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19491 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19492 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19493 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19494 } 19495 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19496 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19497 } 19498 } 19499 19500 // Data with special labels is now gone, so finish the job 19501 storage.destroyUserStorage(volumeUuid, userId, flags); 19502 19503 } catch (Exception e) { 19504 logCriticalInfo(Log.WARN, 19505 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19506 } 19507 } 19508 19509 /** 19510 * Examine all users present on given mounted volume, and destroy data 19511 * belonging to users that are no longer valid, or whose user ID has been 19512 * recycled. 19513 */ 19514 private void reconcileUsers(String volumeUuid) { 19515 final List<File> files = new ArrayList<>(); 19516 Collections.addAll(files, FileUtils 19517 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19518 Collections.addAll(files, FileUtils 19519 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19520 Collections.addAll(files, FileUtils 19521 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19522 Collections.addAll(files, FileUtils 19523 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19524 for (File file : files) { 19525 if (!file.isDirectory()) continue; 19526 19527 final int userId; 19528 final UserInfo info; 19529 try { 19530 userId = Integer.parseInt(file.getName()); 19531 info = sUserManager.getUserInfo(userId); 19532 } catch (NumberFormatException e) { 19533 Slog.w(TAG, "Invalid user directory " + file); 19534 continue; 19535 } 19536 19537 boolean destroyUser = false; 19538 if (info == null) { 19539 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19540 + " because no matching user was found"); 19541 destroyUser = true; 19542 } else if (!mOnlyCore) { 19543 try { 19544 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19545 } catch (IOException e) { 19546 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19547 + " because we failed to enforce serial number: " + e); 19548 destroyUser = true; 19549 } 19550 } 19551 19552 if (destroyUser) { 19553 synchronized (mInstallLock) { 19554 destroyUserDataLI(volumeUuid, userId, 19555 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19556 } 19557 } 19558 } 19559 } 19560 19561 private void assertPackageKnown(String volumeUuid, String packageName) 19562 throws PackageManagerException { 19563 synchronized (mPackages) { 19564 final PackageSetting ps = mSettings.mPackages.get(packageName); 19565 if (ps == null) { 19566 throw new PackageManagerException("Package " + packageName + " is unknown"); 19567 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19568 throw new PackageManagerException( 19569 "Package " + packageName + " found on unknown volume " + volumeUuid 19570 + "; expected volume " + ps.volumeUuid); 19571 } 19572 } 19573 } 19574 19575 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19576 throws PackageManagerException { 19577 synchronized (mPackages) { 19578 final PackageSetting ps = mSettings.mPackages.get(packageName); 19579 if (ps == null) { 19580 throw new PackageManagerException("Package " + packageName + " is unknown"); 19581 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19582 throw new PackageManagerException( 19583 "Package " + packageName + " found on unknown volume " + volumeUuid 19584 + "; expected volume " + ps.volumeUuid); 19585 } else if (!ps.getInstalled(userId)) { 19586 throw new PackageManagerException( 19587 "Package " + packageName + " not installed for user " + userId); 19588 } 19589 } 19590 } 19591 19592 /** 19593 * Examine all apps present on given mounted volume, and destroy apps that 19594 * aren't expected, either due to uninstallation or reinstallation on 19595 * another volume. 19596 */ 19597 private void reconcileApps(String volumeUuid) { 19598 final File[] files = FileUtils 19599 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19600 for (File file : files) { 19601 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19602 && !PackageInstallerService.isStageName(file.getName()); 19603 if (!isPackage) { 19604 // Ignore entries which are not packages 19605 continue; 19606 } 19607 19608 try { 19609 final PackageLite pkg = PackageParser.parsePackageLite(file, 19610 PackageParser.PARSE_MUST_BE_APK); 19611 assertPackageKnown(volumeUuid, pkg.packageName); 19612 19613 } catch (PackageParserException | PackageManagerException e) { 19614 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19615 synchronized (mInstallLock) { 19616 removeCodePathLI(file); 19617 } 19618 } 19619 } 19620 } 19621 19622 /** 19623 * Reconcile all app data for the given user. 19624 * <p> 19625 * Verifies that directories exist and that ownership and labeling is 19626 * correct for all installed apps on all mounted volumes. 19627 */ 19628 void reconcileAppsData(int userId, int flags) { 19629 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19630 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19631 final String volumeUuid = vol.getFsUuid(); 19632 synchronized (mInstallLock) { 19633 reconcileAppsDataLI(volumeUuid, userId, flags); 19634 } 19635 } 19636 } 19637 19638 /** 19639 * Reconcile all app data on given mounted volume. 19640 * <p> 19641 * Destroys app data that isn't expected, either due to uninstallation or 19642 * reinstallation on another volume. 19643 * <p> 19644 * Verifies that directories exist and that ownership and labeling is 19645 * correct for all installed apps. 19646 */ 19647 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19648 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19649 + Integer.toHexString(flags)); 19650 19651 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19652 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19653 19654 boolean restoreconNeeded = false; 19655 19656 // First look for stale data that doesn't belong, and check if things 19657 // have changed since we did our last restorecon 19658 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19659 if (StorageManager.isFileEncryptedNativeOrEmulated() 19660 && !StorageManager.isUserKeyUnlocked(userId)) { 19661 throw new RuntimeException( 19662 "Yikes, someone asked us to reconcile CE storage while " + userId 19663 + " was still locked; this would have caused massive data loss!"); 19664 } 19665 19666 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19667 19668 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19669 for (File file : files) { 19670 final String packageName = file.getName(); 19671 try { 19672 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19673 } catch (PackageManagerException e) { 19674 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19675 try { 19676 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19677 StorageManager.FLAG_STORAGE_CE, 0); 19678 } catch (InstallerException e2) { 19679 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19680 } 19681 } 19682 } 19683 } 19684 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19685 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19686 19687 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19688 for (File file : files) { 19689 final String packageName = file.getName(); 19690 try { 19691 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19692 } catch (PackageManagerException e) { 19693 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19694 try { 19695 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19696 StorageManager.FLAG_STORAGE_DE, 0); 19697 } catch (InstallerException e2) { 19698 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19699 } 19700 } 19701 } 19702 } 19703 19704 // Ensure that data directories are ready to roll for all packages 19705 // installed for this volume and user 19706 final List<PackageSetting> packages; 19707 synchronized (mPackages) { 19708 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19709 } 19710 int preparedCount = 0; 19711 for (PackageSetting ps : packages) { 19712 final String packageName = ps.name; 19713 if (ps.pkg == null) { 19714 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19715 // TODO: might be due to legacy ASEC apps; we should circle back 19716 // and reconcile again once they're scanned 19717 continue; 19718 } 19719 19720 if (ps.getInstalled(userId)) { 19721 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19722 19723 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19724 // We may have just shuffled around app data directories, so 19725 // prepare them one more time 19726 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19727 } 19728 19729 preparedCount++; 19730 } 19731 } 19732 19733 if (restoreconNeeded) { 19734 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19735 SELinuxMMAC.setRestoreconDone(ceDir); 19736 } 19737 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19738 SELinuxMMAC.setRestoreconDone(deDir); 19739 } 19740 } 19741 19742 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19743 + " packages; restoreconNeeded was " + restoreconNeeded); 19744 } 19745 19746 /** 19747 * Prepare app data for the given app just after it was installed or 19748 * upgraded. This method carefully only touches users that it's installed 19749 * for, and it forces a restorecon to handle any seinfo changes. 19750 * <p> 19751 * Verifies that directories exist and that ownership and labeling is 19752 * correct for all installed apps. If there is an ownership mismatch, it 19753 * will try recovering system apps by wiping data; third-party app data is 19754 * left intact. 19755 * <p> 19756 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19757 */ 19758 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19759 final PackageSetting ps; 19760 synchronized (mPackages) { 19761 ps = mSettings.mPackages.get(pkg.packageName); 19762 mSettings.writeKernelMappingLPr(ps); 19763 } 19764 19765 final UserManager um = mContext.getSystemService(UserManager.class); 19766 UserManagerInternal umInternal = getUserManagerInternal(); 19767 for (UserInfo user : um.getUsers()) { 19768 final int flags; 19769 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19770 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19771 } else if (umInternal.isUserRunning(user.id)) { 19772 flags = StorageManager.FLAG_STORAGE_DE; 19773 } else { 19774 continue; 19775 } 19776 19777 if (ps.getInstalled(user.id)) { 19778 // Whenever an app changes, force a restorecon of its data 19779 // TODO: when user data is locked, mark that we're still dirty 19780 prepareAppDataLIF(pkg, user.id, flags, true); 19781 } 19782 } 19783 } 19784 19785 /** 19786 * Prepare app data for the given app. 19787 * <p> 19788 * Verifies that directories exist and that ownership and labeling is 19789 * correct for all installed apps. If there is an ownership mismatch, this 19790 * will try recovering system apps by wiping data; third-party app data is 19791 * left intact. 19792 */ 19793 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19794 boolean restoreconNeeded) { 19795 if (pkg == null) { 19796 Slog.wtf(TAG, "Package was null!", new Throwable()); 19797 return; 19798 } 19799 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19800 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19801 for (int i = 0; i < childCount; i++) { 19802 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19803 } 19804 } 19805 19806 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19807 boolean restoreconNeeded) { 19808 if (DEBUG_APP_DATA) { 19809 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19810 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19811 } 19812 19813 final String volumeUuid = pkg.volumeUuid; 19814 final String packageName = pkg.packageName; 19815 final ApplicationInfo app = pkg.applicationInfo; 19816 final int appId = UserHandle.getAppId(app.uid); 19817 19818 Preconditions.checkNotNull(app.seinfo); 19819 19820 try { 19821 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19822 appId, app.seinfo, app.targetSdkVersion); 19823 } catch (InstallerException e) { 19824 if (app.isSystemApp()) { 19825 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19826 + ", but trying to recover: " + e); 19827 destroyAppDataLeafLIF(pkg, userId, flags); 19828 try { 19829 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19830 appId, app.seinfo, app.targetSdkVersion); 19831 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19832 } catch (InstallerException e2) { 19833 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19834 } 19835 } else { 19836 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19837 } 19838 } 19839 19840 if (restoreconNeeded) { 19841 try { 19842 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19843 app.seinfo); 19844 } catch (InstallerException e) { 19845 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19846 } 19847 } 19848 19849 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19850 try { 19851 // CE storage is unlocked right now, so read out the inode and 19852 // remember for use later when it's locked 19853 // TODO: mark this structure as dirty so we persist it! 19854 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19855 StorageManager.FLAG_STORAGE_CE); 19856 synchronized (mPackages) { 19857 final PackageSetting ps = mSettings.mPackages.get(packageName); 19858 if (ps != null) { 19859 ps.setCeDataInode(ceDataInode, userId); 19860 } 19861 } 19862 } catch (InstallerException e) { 19863 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19864 } 19865 } 19866 19867 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19868 } 19869 19870 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19871 if (pkg == null) { 19872 Slog.wtf(TAG, "Package was null!", new Throwable()); 19873 return; 19874 } 19875 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19876 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19877 for (int i = 0; i < childCount; i++) { 19878 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19879 } 19880 } 19881 19882 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19883 final String volumeUuid = pkg.volumeUuid; 19884 final String packageName = pkg.packageName; 19885 final ApplicationInfo app = pkg.applicationInfo; 19886 19887 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19888 // Create a native library symlink only if we have native libraries 19889 // and if the native libraries are 32 bit libraries. We do not provide 19890 // this symlink for 64 bit libraries. 19891 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19892 final String nativeLibPath = app.nativeLibraryDir; 19893 try { 19894 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19895 nativeLibPath, userId); 19896 } catch (InstallerException e) { 19897 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19898 } 19899 } 19900 } 19901 } 19902 19903 /** 19904 * For system apps on non-FBE devices, this method migrates any existing 19905 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19906 * requested by the app. 19907 */ 19908 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19909 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19910 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19911 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19912 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19913 try { 19914 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19915 storageTarget); 19916 } catch (InstallerException e) { 19917 logCriticalInfo(Log.WARN, 19918 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19919 } 19920 return true; 19921 } else { 19922 return false; 19923 } 19924 } 19925 19926 public PackageFreezer freezePackage(String packageName, String killReason) { 19927 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19928 } 19929 19930 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19931 return new PackageFreezer(packageName, userId, killReason); 19932 } 19933 19934 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19935 String killReason) { 19936 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19937 } 19938 19939 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19940 String killReason) { 19941 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19942 return new PackageFreezer(); 19943 } else { 19944 return freezePackage(packageName, userId, killReason); 19945 } 19946 } 19947 19948 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19949 String killReason) { 19950 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19951 } 19952 19953 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19954 String killReason) { 19955 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19956 return new PackageFreezer(); 19957 } else { 19958 return freezePackage(packageName, userId, killReason); 19959 } 19960 } 19961 19962 /** 19963 * Class that freezes and kills the given package upon creation, and 19964 * unfreezes it upon closing. This is typically used when doing surgery on 19965 * app code/data to prevent the app from running while you're working. 19966 */ 19967 private class PackageFreezer implements AutoCloseable { 19968 private final String mPackageName; 19969 private final PackageFreezer[] mChildren; 19970 19971 private final boolean mWeFroze; 19972 19973 private final AtomicBoolean mClosed = new AtomicBoolean(); 19974 private final CloseGuard mCloseGuard = CloseGuard.get(); 19975 19976 /** 19977 * Create and return a stub freezer that doesn't actually do anything, 19978 * typically used when someone requested 19979 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19980 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19981 */ 19982 public PackageFreezer() { 19983 mPackageName = null; 19984 mChildren = null; 19985 mWeFroze = false; 19986 mCloseGuard.open("close"); 19987 } 19988 19989 public PackageFreezer(String packageName, int userId, String killReason) { 19990 synchronized (mPackages) { 19991 mPackageName = packageName; 19992 mWeFroze = mFrozenPackages.add(mPackageName); 19993 19994 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19995 if (ps != null) { 19996 killApplication(ps.name, ps.appId, userId, killReason); 19997 } 19998 19999 final PackageParser.Package p = mPackages.get(packageName); 20000 if (p != null && p.childPackages != null) { 20001 final int N = p.childPackages.size(); 20002 mChildren = new PackageFreezer[N]; 20003 for (int i = 0; i < N; i++) { 20004 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20005 userId, killReason); 20006 } 20007 } else { 20008 mChildren = null; 20009 } 20010 } 20011 mCloseGuard.open("close"); 20012 } 20013 20014 @Override 20015 protected void finalize() throws Throwable { 20016 try { 20017 mCloseGuard.warnIfOpen(); 20018 close(); 20019 } finally { 20020 super.finalize(); 20021 } 20022 } 20023 20024 @Override 20025 public void close() { 20026 mCloseGuard.close(); 20027 if (mClosed.compareAndSet(false, true)) { 20028 synchronized (mPackages) { 20029 if (mWeFroze) { 20030 mFrozenPackages.remove(mPackageName); 20031 } 20032 20033 if (mChildren != null) { 20034 for (PackageFreezer freezer : mChildren) { 20035 freezer.close(); 20036 } 20037 } 20038 } 20039 } 20040 } 20041 } 20042 20043 /** 20044 * Verify that given package is currently frozen. 20045 */ 20046 private void checkPackageFrozen(String packageName) { 20047 synchronized (mPackages) { 20048 if (!mFrozenPackages.contains(packageName)) { 20049 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20050 } 20051 } 20052 } 20053 20054 @Override 20055 public int movePackage(final String packageName, final String volumeUuid) { 20056 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20057 20058 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20059 final int moveId = mNextMoveId.getAndIncrement(); 20060 mHandler.post(new Runnable() { 20061 @Override 20062 public void run() { 20063 try { 20064 movePackageInternal(packageName, volumeUuid, moveId, user); 20065 } catch (PackageManagerException e) { 20066 Slog.w(TAG, "Failed to move " + packageName, e); 20067 mMoveCallbacks.notifyStatusChanged(moveId, 20068 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20069 } 20070 } 20071 }); 20072 return moveId; 20073 } 20074 20075 private void movePackageInternal(final String packageName, final String volumeUuid, 20076 final int moveId, UserHandle user) throws PackageManagerException { 20077 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20078 final PackageManager pm = mContext.getPackageManager(); 20079 20080 final boolean currentAsec; 20081 final String currentVolumeUuid; 20082 final File codeFile; 20083 final String installerPackageName; 20084 final String packageAbiOverride; 20085 final int appId; 20086 final String seinfo; 20087 final String label; 20088 final int targetSdkVersion; 20089 final PackageFreezer freezer; 20090 final int[] installedUserIds; 20091 20092 // reader 20093 synchronized (mPackages) { 20094 final PackageParser.Package pkg = mPackages.get(packageName); 20095 final PackageSetting ps = mSettings.mPackages.get(packageName); 20096 if (pkg == null || ps == null) { 20097 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20098 } 20099 20100 if (pkg.applicationInfo.isSystemApp()) { 20101 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20102 "Cannot move system application"); 20103 } 20104 20105 if (pkg.applicationInfo.isExternalAsec()) { 20106 currentAsec = true; 20107 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20108 } else if (pkg.applicationInfo.isForwardLocked()) { 20109 currentAsec = true; 20110 currentVolumeUuid = "forward_locked"; 20111 } else { 20112 currentAsec = false; 20113 currentVolumeUuid = ps.volumeUuid; 20114 20115 final File probe = new File(pkg.codePath); 20116 final File probeOat = new File(probe, "oat"); 20117 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20118 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20119 "Move only supported for modern cluster style installs"); 20120 } 20121 } 20122 20123 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20124 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20125 "Package already moved to " + volumeUuid); 20126 } 20127 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20128 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20129 "Device admin cannot be moved"); 20130 } 20131 20132 if (mFrozenPackages.contains(packageName)) { 20133 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20134 "Failed to move already frozen package"); 20135 } 20136 20137 codeFile = new File(pkg.codePath); 20138 installerPackageName = ps.installerPackageName; 20139 packageAbiOverride = ps.cpuAbiOverrideString; 20140 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20141 seinfo = pkg.applicationInfo.seinfo; 20142 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20143 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20144 freezer = freezePackage(packageName, "movePackageInternal"); 20145 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20146 } 20147 20148 final Bundle extras = new Bundle(); 20149 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20150 extras.putString(Intent.EXTRA_TITLE, label); 20151 mMoveCallbacks.notifyCreated(moveId, extras); 20152 20153 int installFlags; 20154 final boolean moveCompleteApp; 20155 final File measurePath; 20156 20157 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20158 installFlags = INSTALL_INTERNAL; 20159 moveCompleteApp = !currentAsec; 20160 measurePath = Environment.getDataAppDirectory(volumeUuid); 20161 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20162 installFlags = INSTALL_EXTERNAL; 20163 moveCompleteApp = false; 20164 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20165 } else { 20166 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20167 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20168 || !volume.isMountedWritable()) { 20169 freezer.close(); 20170 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20171 "Move location not mounted private volume"); 20172 } 20173 20174 Preconditions.checkState(!currentAsec); 20175 20176 installFlags = INSTALL_INTERNAL; 20177 moveCompleteApp = true; 20178 measurePath = Environment.getDataAppDirectory(volumeUuid); 20179 } 20180 20181 final PackageStats stats = new PackageStats(null, -1); 20182 synchronized (mInstaller) { 20183 for (int userId : installedUserIds) { 20184 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20185 freezer.close(); 20186 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20187 "Failed to measure package size"); 20188 } 20189 } 20190 } 20191 20192 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20193 + stats.dataSize); 20194 20195 final long startFreeBytes = measurePath.getFreeSpace(); 20196 final long sizeBytes; 20197 if (moveCompleteApp) { 20198 sizeBytes = stats.codeSize + stats.dataSize; 20199 } else { 20200 sizeBytes = stats.codeSize; 20201 } 20202 20203 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20204 freezer.close(); 20205 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20206 "Not enough free space to move"); 20207 } 20208 20209 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20210 20211 final CountDownLatch installedLatch = new CountDownLatch(1); 20212 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20213 @Override 20214 public void onUserActionRequired(Intent intent) throws RemoteException { 20215 throw new IllegalStateException(); 20216 } 20217 20218 @Override 20219 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20220 Bundle extras) throws RemoteException { 20221 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20222 + PackageManager.installStatusToString(returnCode, msg)); 20223 20224 installedLatch.countDown(); 20225 freezer.close(); 20226 20227 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20228 switch (status) { 20229 case PackageInstaller.STATUS_SUCCESS: 20230 mMoveCallbacks.notifyStatusChanged(moveId, 20231 PackageManager.MOVE_SUCCEEDED); 20232 break; 20233 case PackageInstaller.STATUS_FAILURE_STORAGE: 20234 mMoveCallbacks.notifyStatusChanged(moveId, 20235 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20236 break; 20237 default: 20238 mMoveCallbacks.notifyStatusChanged(moveId, 20239 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20240 break; 20241 } 20242 } 20243 }; 20244 20245 final MoveInfo move; 20246 if (moveCompleteApp) { 20247 // Kick off a thread to report progress estimates 20248 new Thread() { 20249 @Override 20250 public void run() { 20251 while (true) { 20252 try { 20253 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20254 break; 20255 } 20256 } catch (InterruptedException ignored) { 20257 } 20258 20259 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20260 final int progress = 10 + (int) MathUtils.constrain( 20261 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20262 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20263 } 20264 } 20265 }.start(); 20266 20267 final String dataAppName = codeFile.getName(); 20268 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20269 dataAppName, appId, seinfo, targetSdkVersion); 20270 } else { 20271 move = null; 20272 } 20273 20274 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20275 20276 final Message msg = mHandler.obtainMessage(INIT_COPY); 20277 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20278 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20279 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20280 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20281 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20282 msg.obj = params; 20283 20284 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20285 System.identityHashCode(msg.obj)); 20286 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20287 System.identityHashCode(msg.obj)); 20288 20289 mHandler.sendMessage(msg); 20290 } 20291 20292 @Override 20293 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20294 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20295 20296 final int realMoveId = mNextMoveId.getAndIncrement(); 20297 final Bundle extras = new Bundle(); 20298 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20299 mMoveCallbacks.notifyCreated(realMoveId, extras); 20300 20301 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20302 @Override 20303 public void onCreated(int moveId, Bundle extras) { 20304 // Ignored 20305 } 20306 20307 @Override 20308 public void onStatusChanged(int moveId, int status, long estMillis) { 20309 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20310 } 20311 }; 20312 20313 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20314 storage.setPrimaryStorageUuid(volumeUuid, callback); 20315 return realMoveId; 20316 } 20317 20318 @Override 20319 public int getMoveStatus(int moveId) { 20320 mContext.enforceCallingOrSelfPermission( 20321 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20322 return mMoveCallbacks.mLastStatus.get(moveId); 20323 } 20324 20325 @Override 20326 public void registerMoveCallback(IPackageMoveObserver callback) { 20327 mContext.enforceCallingOrSelfPermission( 20328 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20329 mMoveCallbacks.register(callback); 20330 } 20331 20332 @Override 20333 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20334 mContext.enforceCallingOrSelfPermission( 20335 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20336 mMoveCallbacks.unregister(callback); 20337 } 20338 20339 @Override 20340 public boolean setInstallLocation(int loc) { 20341 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20342 null); 20343 if (getInstallLocation() == loc) { 20344 return true; 20345 } 20346 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20347 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20348 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20349 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20350 return true; 20351 } 20352 return false; 20353 } 20354 20355 @Override 20356 public int getInstallLocation() { 20357 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20358 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20359 PackageHelper.APP_INSTALL_AUTO); 20360 } 20361 20362 /** Called by UserManagerService */ 20363 void cleanUpUser(UserManagerService userManager, int userHandle) { 20364 synchronized (mPackages) { 20365 mDirtyUsers.remove(userHandle); 20366 mUserNeedsBadging.delete(userHandle); 20367 mSettings.removeUserLPw(userHandle); 20368 mPendingBroadcasts.remove(userHandle); 20369 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20370 removeUnusedPackagesLPw(userManager, userHandle); 20371 } 20372 } 20373 20374 /** 20375 * We're removing userHandle and would like to remove any downloaded packages 20376 * that are no longer in use by any other user. 20377 * @param userHandle the user being removed 20378 */ 20379 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20380 final boolean DEBUG_CLEAN_APKS = false; 20381 int [] users = userManager.getUserIds(); 20382 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20383 while (psit.hasNext()) { 20384 PackageSetting ps = psit.next(); 20385 if (ps.pkg == null) { 20386 continue; 20387 } 20388 final String packageName = ps.pkg.packageName; 20389 // Skip over if system app 20390 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20391 continue; 20392 } 20393 if (DEBUG_CLEAN_APKS) { 20394 Slog.i(TAG, "Checking package " + packageName); 20395 } 20396 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20397 if (keep) { 20398 if (DEBUG_CLEAN_APKS) { 20399 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20400 } 20401 } else { 20402 for (int i = 0; i < users.length; i++) { 20403 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20404 keep = true; 20405 if (DEBUG_CLEAN_APKS) { 20406 Slog.i(TAG, " Keeping package " + packageName + " for user " 20407 + users[i]); 20408 } 20409 break; 20410 } 20411 } 20412 } 20413 if (!keep) { 20414 if (DEBUG_CLEAN_APKS) { 20415 Slog.i(TAG, " Removing package " + packageName); 20416 } 20417 mHandler.post(new Runnable() { 20418 public void run() { 20419 deletePackageX(packageName, userHandle, 0); 20420 } //end run 20421 }); 20422 } 20423 } 20424 } 20425 20426 /** Called by UserManagerService */ 20427 void createNewUser(int userId) { 20428 synchronized (mInstallLock) { 20429 mSettings.createNewUserLI(this, mInstaller, userId); 20430 } 20431 synchronized (mPackages) { 20432 scheduleWritePackageRestrictionsLocked(userId); 20433 scheduleWritePackageListLocked(userId); 20434 applyFactoryDefaultBrowserLPw(userId); 20435 primeDomainVerificationsLPw(userId); 20436 } 20437 } 20438 20439 void onBeforeUserStartUninitialized(final int userId) { 20440 synchronized (mPackages) { 20441 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20442 return; 20443 } 20444 } 20445 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20446 // If permission review for legacy apps is required, we represent 20447 // dagerous permissions for such apps as always granted runtime 20448 // permissions to keep per user flag state whether review is needed. 20449 // Hence, if a new user is added we have to propagate dangerous 20450 // permission grants for these legacy apps. 20451 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20452 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20453 | UPDATE_PERMISSIONS_REPLACE_ALL); 20454 } 20455 } 20456 20457 @Override 20458 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20459 mContext.enforceCallingOrSelfPermission( 20460 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20461 "Only package verification agents can read the verifier device identity"); 20462 20463 synchronized (mPackages) { 20464 return mSettings.getVerifierDeviceIdentityLPw(); 20465 } 20466 } 20467 20468 @Override 20469 public void setPermissionEnforced(String permission, boolean enforced) { 20470 // TODO: Now that we no longer change GID for storage, this should to away. 20471 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20472 "setPermissionEnforced"); 20473 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20474 synchronized (mPackages) { 20475 if (mSettings.mReadExternalStorageEnforced == null 20476 || mSettings.mReadExternalStorageEnforced != enforced) { 20477 mSettings.mReadExternalStorageEnforced = enforced; 20478 mSettings.writeLPr(); 20479 } 20480 } 20481 // kill any non-foreground processes so we restart them and 20482 // grant/revoke the GID. 20483 final IActivityManager am = ActivityManagerNative.getDefault(); 20484 if (am != null) { 20485 final long token = Binder.clearCallingIdentity(); 20486 try { 20487 am.killProcessesBelowForeground("setPermissionEnforcement"); 20488 } catch (RemoteException e) { 20489 } finally { 20490 Binder.restoreCallingIdentity(token); 20491 } 20492 } 20493 } else { 20494 throw new IllegalArgumentException("No selective enforcement for " + permission); 20495 } 20496 } 20497 20498 @Override 20499 @Deprecated 20500 public boolean isPermissionEnforced(String permission) { 20501 return true; 20502 } 20503 20504 @Override 20505 public boolean isStorageLow() { 20506 final long token = Binder.clearCallingIdentity(); 20507 try { 20508 final DeviceStorageMonitorInternal 20509 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20510 if (dsm != null) { 20511 return dsm.isMemoryLow(); 20512 } else { 20513 return false; 20514 } 20515 } finally { 20516 Binder.restoreCallingIdentity(token); 20517 } 20518 } 20519 20520 @Override 20521 public IPackageInstaller getPackageInstaller() { 20522 return mInstallerService; 20523 } 20524 20525 private boolean userNeedsBadging(int userId) { 20526 int index = mUserNeedsBadging.indexOfKey(userId); 20527 if (index < 0) { 20528 final UserInfo userInfo; 20529 final long token = Binder.clearCallingIdentity(); 20530 try { 20531 userInfo = sUserManager.getUserInfo(userId); 20532 } finally { 20533 Binder.restoreCallingIdentity(token); 20534 } 20535 final boolean b; 20536 if (userInfo != null && userInfo.isManagedProfile()) { 20537 b = true; 20538 } else { 20539 b = false; 20540 } 20541 mUserNeedsBadging.put(userId, b); 20542 return b; 20543 } 20544 return mUserNeedsBadging.valueAt(index); 20545 } 20546 20547 @Override 20548 public KeySet getKeySetByAlias(String packageName, String alias) { 20549 if (packageName == null || alias == null) { 20550 return null; 20551 } 20552 synchronized(mPackages) { 20553 final PackageParser.Package pkg = mPackages.get(packageName); 20554 if (pkg == null) { 20555 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20556 throw new IllegalArgumentException("Unknown package: " + packageName); 20557 } 20558 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20559 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20560 } 20561 } 20562 20563 @Override 20564 public KeySet getSigningKeySet(String packageName) { 20565 if (packageName == null) { 20566 return null; 20567 } 20568 synchronized(mPackages) { 20569 final PackageParser.Package pkg = mPackages.get(packageName); 20570 if (pkg == null) { 20571 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20572 throw new IllegalArgumentException("Unknown package: " + packageName); 20573 } 20574 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20575 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20576 throw new SecurityException("May not access signing KeySet of other apps."); 20577 } 20578 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20579 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20580 } 20581 } 20582 20583 @Override 20584 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20585 if (packageName == null || ks == null) { 20586 return false; 20587 } 20588 synchronized(mPackages) { 20589 final PackageParser.Package pkg = mPackages.get(packageName); 20590 if (pkg == null) { 20591 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20592 throw new IllegalArgumentException("Unknown package: " + packageName); 20593 } 20594 IBinder ksh = ks.getToken(); 20595 if (ksh instanceof KeySetHandle) { 20596 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20597 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20598 } 20599 return false; 20600 } 20601 } 20602 20603 @Override 20604 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20605 if (packageName == null || ks == null) { 20606 return false; 20607 } 20608 synchronized(mPackages) { 20609 final PackageParser.Package pkg = mPackages.get(packageName); 20610 if (pkg == null) { 20611 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20612 throw new IllegalArgumentException("Unknown package: " + packageName); 20613 } 20614 IBinder ksh = ks.getToken(); 20615 if (ksh instanceof KeySetHandle) { 20616 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20617 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20618 } 20619 return false; 20620 } 20621 } 20622 20623 private void deletePackageIfUnusedLPr(final String packageName) { 20624 PackageSetting ps = mSettings.mPackages.get(packageName); 20625 if (ps == null) { 20626 return; 20627 } 20628 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20629 // TODO Implement atomic delete if package is unused 20630 // It is currently possible that the package will be deleted even if it is installed 20631 // after this method returns. 20632 mHandler.post(new Runnable() { 20633 public void run() { 20634 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20635 } 20636 }); 20637 } 20638 } 20639 20640 /** 20641 * Check and throw if the given before/after packages would be considered a 20642 * downgrade. 20643 */ 20644 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20645 throws PackageManagerException { 20646 if (after.versionCode < before.mVersionCode) { 20647 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20648 "Update version code " + after.versionCode + " is older than current " 20649 + before.mVersionCode); 20650 } else if (after.versionCode == before.mVersionCode) { 20651 if (after.baseRevisionCode < before.baseRevisionCode) { 20652 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20653 "Update base revision code " + after.baseRevisionCode 20654 + " is older than current " + before.baseRevisionCode); 20655 } 20656 20657 if (!ArrayUtils.isEmpty(after.splitNames)) { 20658 for (int i = 0; i < after.splitNames.length; i++) { 20659 final String splitName = after.splitNames[i]; 20660 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20661 if (j != -1) { 20662 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20663 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20664 "Update split " + splitName + " revision code " 20665 + after.splitRevisionCodes[i] + " is older than current " 20666 + before.splitRevisionCodes[j]); 20667 } 20668 } 20669 } 20670 } 20671 } 20672 } 20673 20674 private static class MoveCallbacks extends Handler { 20675 private static final int MSG_CREATED = 1; 20676 private static final int MSG_STATUS_CHANGED = 2; 20677 20678 private final RemoteCallbackList<IPackageMoveObserver> 20679 mCallbacks = new RemoteCallbackList<>(); 20680 20681 private final SparseIntArray mLastStatus = new SparseIntArray(); 20682 20683 public MoveCallbacks(Looper looper) { 20684 super(looper); 20685 } 20686 20687 public void register(IPackageMoveObserver callback) { 20688 mCallbacks.register(callback); 20689 } 20690 20691 public void unregister(IPackageMoveObserver callback) { 20692 mCallbacks.unregister(callback); 20693 } 20694 20695 @Override 20696 public void handleMessage(Message msg) { 20697 final SomeArgs args = (SomeArgs) msg.obj; 20698 final int n = mCallbacks.beginBroadcast(); 20699 for (int i = 0; i < n; i++) { 20700 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20701 try { 20702 invokeCallback(callback, msg.what, args); 20703 } catch (RemoteException ignored) { 20704 } 20705 } 20706 mCallbacks.finishBroadcast(); 20707 args.recycle(); 20708 } 20709 20710 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20711 throws RemoteException { 20712 switch (what) { 20713 case MSG_CREATED: { 20714 callback.onCreated(args.argi1, (Bundle) args.arg2); 20715 break; 20716 } 20717 case MSG_STATUS_CHANGED: { 20718 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20719 break; 20720 } 20721 } 20722 } 20723 20724 private void notifyCreated(int moveId, Bundle extras) { 20725 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20726 20727 final SomeArgs args = SomeArgs.obtain(); 20728 args.argi1 = moveId; 20729 args.arg2 = extras; 20730 obtainMessage(MSG_CREATED, args).sendToTarget(); 20731 } 20732 20733 private void notifyStatusChanged(int moveId, int status) { 20734 notifyStatusChanged(moveId, status, -1); 20735 } 20736 20737 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20738 Slog.v(TAG, "Move " + moveId + " status " + status); 20739 20740 final SomeArgs args = SomeArgs.obtain(); 20741 args.argi1 = moveId; 20742 args.argi2 = status; 20743 args.arg3 = estMillis; 20744 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20745 20746 synchronized (mLastStatus) { 20747 mLastStatus.put(moveId, status); 20748 } 20749 } 20750 } 20751 20752 private final static class OnPermissionChangeListeners extends Handler { 20753 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20754 20755 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20756 new RemoteCallbackList<>(); 20757 20758 public OnPermissionChangeListeners(Looper looper) { 20759 super(looper); 20760 } 20761 20762 @Override 20763 public void handleMessage(Message msg) { 20764 switch (msg.what) { 20765 case MSG_ON_PERMISSIONS_CHANGED: { 20766 final int uid = msg.arg1; 20767 handleOnPermissionsChanged(uid); 20768 } break; 20769 } 20770 } 20771 20772 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20773 mPermissionListeners.register(listener); 20774 20775 } 20776 20777 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20778 mPermissionListeners.unregister(listener); 20779 } 20780 20781 public void onPermissionsChanged(int uid) { 20782 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20783 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20784 } 20785 } 20786 20787 private void handleOnPermissionsChanged(int uid) { 20788 final int count = mPermissionListeners.beginBroadcast(); 20789 try { 20790 for (int i = 0; i < count; i++) { 20791 IOnPermissionsChangeListener callback = mPermissionListeners 20792 .getBroadcastItem(i); 20793 try { 20794 callback.onPermissionsChanged(uid); 20795 } catch (RemoteException e) { 20796 Log.e(TAG, "Permission listener is dead", e); 20797 } 20798 } 20799 } finally { 20800 mPermissionListeners.finishBroadcast(); 20801 } 20802 } 20803 } 20804 20805 private class PackageManagerInternalImpl extends PackageManagerInternal { 20806 @Override 20807 public void setLocationPackagesProvider(PackagesProvider provider) { 20808 synchronized (mPackages) { 20809 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20810 } 20811 } 20812 20813 @Override 20814 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20815 synchronized (mPackages) { 20816 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20817 } 20818 } 20819 20820 @Override 20821 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20822 synchronized (mPackages) { 20823 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20824 } 20825 } 20826 20827 @Override 20828 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20829 synchronized (mPackages) { 20830 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20831 } 20832 } 20833 20834 @Override 20835 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20836 synchronized (mPackages) { 20837 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20838 } 20839 } 20840 20841 @Override 20842 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20843 synchronized (mPackages) { 20844 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20845 } 20846 } 20847 20848 @Override 20849 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20850 synchronized (mPackages) { 20851 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20852 packageName, userId); 20853 } 20854 } 20855 20856 @Override 20857 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20858 synchronized (mPackages) { 20859 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20860 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20861 packageName, userId); 20862 } 20863 } 20864 20865 @Override 20866 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20867 synchronized (mPackages) { 20868 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20869 packageName, userId); 20870 } 20871 } 20872 20873 @Override 20874 public void setKeepUninstalledPackages(final List<String> packageList) { 20875 Preconditions.checkNotNull(packageList); 20876 List<String> removedFromList = null; 20877 synchronized (mPackages) { 20878 if (mKeepUninstalledPackages != null) { 20879 final int packagesCount = mKeepUninstalledPackages.size(); 20880 for (int i = 0; i < packagesCount; i++) { 20881 String oldPackage = mKeepUninstalledPackages.get(i); 20882 if (packageList != null && packageList.contains(oldPackage)) { 20883 continue; 20884 } 20885 if (removedFromList == null) { 20886 removedFromList = new ArrayList<>(); 20887 } 20888 removedFromList.add(oldPackage); 20889 } 20890 } 20891 mKeepUninstalledPackages = new ArrayList<>(packageList); 20892 if (removedFromList != null) { 20893 final int removedCount = removedFromList.size(); 20894 for (int i = 0; i < removedCount; i++) { 20895 deletePackageIfUnusedLPr(removedFromList.get(i)); 20896 } 20897 } 20898 } 20899 } 20900 20901 @Override 20902 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20903 synchronized (mPackages) { 20904 // If we do not support permission review, done. 20905 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20906 return false; 20907 } 20908 20909 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20910 if (packageSetting == null) { 20911 return false; 20912 } 20913 20914 // Permission review applies only to apps not supporting the new permission model. 20915 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20916 return false; 20917 } 20918 20919 // Legacy apps have the permission and get user consent on launch. 20920 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20921 return permissionsState.isPermissionReviewRequired(userId); 20922 } 20923 } 20924 20925 @Override 20926 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20927 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20928 } 20929 20930 @Override 20931 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20932 int userId) { 20933 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20934 } 20935 20936 @Override 20937 public void setDeviceAndProfileOwnerPackages( 20938 int deviceOwnerUserId, String deviceOwnerPackage, 20939 SparseArray<String> profileOwnerPackages) { 20940 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20941 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20942 } 20943 20944 @Override 20945 public boolean isPackageDataProtected(int userId, String packageName) { 20946 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20947 } 20948 } 20949 20950 @Override 20951 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20952 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20953 synchronized (mPackages) { 20954 final long identity = Binder.clearCallingIdentity(); 20955 try { 20956 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20957 packageNames, userId); 20958 } finally { 20959 Binder.restoreCallingIdentity(identity); 20960 } 20961 } 20962 } 20963 20964 private static void enforceSystemOrPhoneCaller(String tag) { 20965 int callingUid = Binder.getCallingUid(); 20966 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20967 throw new SecurityException( 20968 "Cannot call " + tag + " from UID " + callingUid); 20969 } 20970 } 20971 20972 boolean isHistoricalPackageUsageAvailable() { 20973 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20974 } 20975 20976 /** 20977 * Return a <b>copy</b> of the collection of packages known to the package manager. 20978 * @return A copy of the values of mPackages. 20979 */ 20980 Collection<PackageParser.Package> getPackages() { 20981 synchronized (mPackages) { 20982 return new ArrayList<>(mPackages.values()); 20983 } 20984 } 20985 20986 /** 20987 * Logs process start information (including base APK hash) to the security log. 20988 * @hide 20989 */ 20990 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20991 String apkFile, int pid) { 20992 if (!SecurityLog.isLoggingEnabled()) { 20993 return; 20994 } 20995 Bundle data = new Bundle(); 20996 data.putLong("startTimestamp", System.currentTimeMillis()); 20997 data.putString("processName", processName); 20998 data.putInt("uid", uid); 20999 data.putString("seinfo", seinfo); 21000 data.putString("apkFile", apkFile); 21001 data.putInt("pid", pid); 21002 Message msg = mProcessLoggingHandler.obtainMessage( 21003 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21004 msg.setData(data); 21005 mProcessLoggingHandler.sendMessage(msg); 21006 } 21007} 21008