PackageManagerService.java revision cb8a640cef14c3bc6d4fd2e96c43a87ea4702c27
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_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.ResourcesManager; 107import android.app.admin.IDevicePolicyManager; 108import android.app.admin.SecurityLog; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.ContentResolver; 113import android.content.Context; 114import android.content.IIntentReceiver; 115import android.content.Intent; 116import android.content.IntentFilter; 117import android.content.IntentSender; 118import android.content.IntentSender.SendIntentException; 119import android.content.ServiceConnection; 120import android.content.pm.ActivityInfo; 121import android.content.pm.ApplicationInfo; 122import android.content.pm.AppsQueryHelper; 123import android.content.pm.ComponentInfo; 124import android.content.pm.EphemeralApplicationInfo; 125import android.content.pm.EphemeralResolveInfo; 126import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.PatternMatcher; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.provider.Settings.Global; 201import android.provider.Settings.Secure; 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.DisplayMetrics; 211import android.util.EventLog; 212import android.util.ExceptionUtils; 213import android.util.Log; 214import android.util.LogPrinter; 215import android.util.MathUtils; 216import android.util.Pair; 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.BufferedOutputStream; 270import java.io.BufferedReader; 271import java.io.ByteArrayInputStream; 272import java.io.ByteArrayOutputStream; 273import java.io.File; 274import java.io.FileDescriptor; 275import java.io.FileInputStream; 276import java.io.FileNotFoundException; 277import java.io.FileOutputStream; 278import java.io.FileReader; 279import java.io.FilenameFilter; 280import java.io.IOException; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307 308/** 309 * Keep track of all those APKs everywhere. 310 * <p> 311 * Internally there are two important locks: 312 * <ul> 313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 314 * and other related state. It is a fine-grained lock that should only be held 315 * momentarily, as it's one of the most contended locks in the system. 316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 317 * operations typically involve heavy lifting of application data on disk. Since 318 * {@code installd} is single-threaded, and it's operations can often be slow, 319 * this lock should never be acquired while already holding {@link #mPackages}. 320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 321 * holding {@link #mInstallLock}. 322 * </ul> 323 * Many internal methods rely on the caller to hold the appropriate locks, and 324 * this contract is expressed through method name suffixes: 325 * <ul> 326 * <li>fooLI(): the caller must hold {@link #mInstallLock} 327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 328 * being modified must be frozen 329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 331 * </ul> 332 * <p> 333 * Because this class is very central to the platform's security; please run all 334 * CTS and unit tests whenever making modifications: 335 * 336 * <pre> 337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 339 * </pre> 340 */ 341public class PackageManagerService extends IPackageManager.Stub { 342 static final String TAG = "PackageManager"; 343 static final boolean DEBUG_SETTINGS = false; 344 static final boolean DEBUG_PREFERRED = false; 345 static final boolean DEBUG_UPGRADE = false; 346 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 347 private static final boolean DEBUG_BACKUP = false; 348 private static final boolean DEBUG_INSTALL = false; 349 private static final boolean DEBUG_REMOVE = false; 350 private static final boolean DEBUG_BROADCASTS = false; 351 private static final boolean DEBUG_SHOW_INFO = false; 352 private static final boolean DEBUG_PACKAGE_INFO = false; 353 private static final boolean DEBUG_INTENT_MATCHING = false; 354 private static final boolean DEBUG_PACKAGE_SCANNING = false; 355 private static final boolean DEBUG_VERIFY = false; 356 private static final boolean DEBUG_FILTERS = false; 357 358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 360 // user, but by default initialize to this. 361 static final boolean DEBUG_DEXOPT = false; 362 363 private static final boolean DEBUG_ABI_SELECTION = false; 364 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 365 private static final boolean DEBUG_TRIAGED_MISSING = false; 366 private static final boolean DEBUG_APP_DATA = false; 367 368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 369 370 private static final boolean DISABLE_EPHEMERAL_APPS = false; 371 private static final boolean HIDE_EPHEMERAL_APIS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String PACKAGE_SCHEME = "package"; 464 465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 466 /** 467 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 468 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 469 * VENDOR_OVERLAY_DIR. 470 */ 471 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 472 473 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 474 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 475 476 /** Permission grant: not grant the permission. */ 477 private static final int GRANT_DENIED = 1; 478 479 /** Permission grant: grant the permission as an install permission. */ 480 private static final int GRANT_INSTALL = 2; 481 482 /** Permission grant: grant the permission as a runtime one. */ 483 private static final int GRANT_RUNTIME = 3; 484 485 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 486 private static final int GRANT_UPGRADE = 4; 487 488 /** Canonical intent used to identify what counts as a "web browser" app */ 489 private static final Intent sBrowserIntent; 490 static { 491 sBrowserIntent = new Intent(); 492 sBrowserIntent.setAction(Intent.ACTION_VIEW); 493 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 494 sBrowserIntent.setData(Uri.parse("http:")); 495 } 496 497 /** 498 * The set of all protected actions [i.e. those actions for which a high priority 499 * intent filter is disallowed]. 500 */ 501 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 502 static { 503 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 504 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 505 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 506 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 507 } 508 509 // Compilation reasons. 510 public static final int REASON_FIRST_BOOT = 0; 511 public static final int REASON_BOOT = 1; 512 public static final int REASON_INSTALL = 2; 513 public static final int REASON_BACKGROUND_DEXOPT = 3; 514 public static final int REASON_AB_OTA = 4; 515 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 516 public static final int REASON_SHARED_APK = 6; 517 public static final int REASON_FORCED_DEXOPT = 7; 518 public static final int REASON_CORE_APP = 8; 519 520 public static final int REASON_LAST = REASON_CORE_APP; 521 522 /** Special library name that skips shared libraries check during compilation. */ 523 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 524 525 final ServiceThread mHandlerThread; 526 527 final PackageHandler mHandler; 528 529 private final ProcessLoggingHandler mProcessLoggingHandler; 530 531 /** 532 * Messages for {@link #mHandler} that need to wait for system ready before 533 * being dispatched. 534 */ 535 private ArrayList<Message> mPostSystemReadyMessages; 536 537 final int mSdkVersion = Build.VERSION.SDK_INT; 538 539 final Context mContext; 540 final boolean mFactoryTest; 541 final boolean mOnlyCore; 542 final DisplayMetrics mMetrics; 543 final int mDefParseFlags; 544 final String[] mSeparateProcesses; 545 final boolean mIsUpgrade; 546 final boolean mIsPreNUpgrade; 547 final boolean mIsPreNMR1Upgrade; 548 549 @GuardedBy("mPackages") 550 private boolean mDexOptDialogShown; 551 552 /** The location for ASEC container files on internal storage. */ 553 final String mAsecInternalPath; 554 555 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 556 // LOCK HELD. Can be called with mInstallLock held. 557 @GuardedBy("mInstallLock") 558 final Installer mInstaller; 559 560 /** Directory where installed third-party apps stored */ 561 final File mAppInstallDir; 562 final File mEphemeralInstallDir; 563 564 /** 565 * Directory to which applications installed internally have their 566 * 32 bit native libraries copied. 567 */ 568 private File mAppLib32InstallDir; 569 570 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 571 // apps. 572 final File mDrmAppPrivateInstallDir; 573 574 // ---------------------------------------------------------------- 575 576 // Lock for state used when installing and doing other long running 577 // operations. Methods that must be called with this lock held have 578 // the suffix "LI". 579 final Object mInstallLock = new Object(); 580 581 // ---------------------------------------------------------------- 582 583 // Keys are String (package name), values are Package. This also serves 584 // as the lock for the global state. Methods that must be called with 585 // this lock held have the prefix "LP". 586 @GuardedBy("mPackages") 587 final ArrayMap<String, PackageParser.Package> mPackages = 588 new ArrayMap<String, PackageParser.Package>(); 589 590 final ArrayMap<String, Set<String>> mKnownCodebase = 591 new ArrayMap<String, Set<String>>(); 592 593 // Tracks available target package names -> overlay package paths. 594 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 595 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 596 597 /** 598 * Tracks new system packages [received in an OTA] that we expect to 599 * find updated user-installed versions. Keys are package name, values 600 * are package location. 601 */ 602 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 603 /** 604 * Tracks high priority intent filters for protected actions. During boot, certain 605 * filter actions are protected and should never be allowed to have a high priority 606 * intent filter for them. However, there is one, and only one exception -- the 607 * setup wizard. It must be able to define a high priority intent filter for these 608 * actions to ensure there are no escapes from the wizard. We need to delay processing 609 * of these during boot as we need to look at all of the system packages in order 610 * to know which component is the setup wizard. 611 */ 612 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 613 /** 614 * Whether or not processing protected filters should be deferred. 615 */ 616 private boolean mDeferProtectedFilters = true; 617 618 /** 619 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 620 */ 621 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 622 /** 623 * Whether or not system app permissions should be promoted from install to runtime. 624 */ 625 boolean mPromoteSystemApps; 626 627 @GuardedBy("mPackages") 628 final Settings mSettings; 629 630 /** 631 * Set of package names that are currently "frozen", which means active 632 * surgery is being done on the code/data for that package. The platform 633 * will refuse to launch frozen packages to avoid race conditions. 634 * 635 * @see PackageFreezer 636 */ 637 @GuardedBy("mPackages") 638 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 639 640 final ProtectedPackages mProtectedPackages; 641 642 boolean mFirstBoot; 643 644 // System configuration read by SystemConfig. 645 final int[] mGlobalGids; 646 final SparseArray<ArraySet<String>> mSystemPermissions; 647 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 648 649 // If mac_permissions.xml was found for seinfo labeling. 650 boolean mFoundPolicyFile; 651 652 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 653 654 public static final class SharedLibraryEntry { 655 public final String path; 656 public final String apk; 657 658 SharedLibraryEntry(String _path, String _apk) { 659 path = _path; 660 apk = _apk; 661 } 662 } 663 664 // Currently known shared libraries. 665 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 666 new ArrayMap<String, SharedLibraryEntry>(); 667 668 // All available activities, for your resolving pleasure. 669 final ActivityIntentResolver mActivities = 670 new ActivityIntentResolver(); 671 672 // All available receivers, for your resolving pleasure. 673 final ActivityIntentResolver mReceivers = 674 new ActivityIntentResolver(); 675 676 // All available services, for your resolving pleasure. 677 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 678 679 // All available providers, for your resolving pleasure. 680 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 681 682 // Mapping from provider base names (first directory in content URI codePath) 683 // to the provider information. 684 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 685 new ArrayMap<String, PackageParser.Provider>(); 686 687 // Mapping from instrumentation class names to info about them. 688 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 689 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 690 691 // Mapping from permission names to info about them. 692 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 693 new ArrayMap<String, PackageParser.PermissionGroup>(); 694 695 // Packages whose data we have transfered into another package, thus 696 // should no longer exist. 697 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 698 699 // Broadcast actions that are only available to the system. 700 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 701 702 /** List of packages waiting for verification. */ 703 final SparseArray<PackageVerificationState> mPendingVerification 704 = new SparseArray<PackageVerificationState>(); 705 706 /** Set of packages associated with each app op permission. */ 707 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 708 709 final PackageInstallerService mInstallerService; 710 711 private final PackageDexOptimizer mPackageDexOptimizer; 712 713 private AtomicInteger mNextMoveId = new AtomicInteger(); 714 private final MoveCallbacks mMoveCallbacks; 715 716 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 717 718 // Cache of users who need badging. 719 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 720 721 /** Token for keys in mPendingVerification. */ 722 private int mPendingVerificationToken = 0; 723 724 volatile boolean mSystemReady; 725 volatile boolean mSafeMode; 726 volatile boolean mHasSystemUidErrors; 727 728 ApplicationInfo mAndroidApplication; 729 final ActivityInfo mResolveActivity = new ActivityInfo(); 730 final ResolveInfo mResolveInfo = new ResolveInfo(); 731 ComponentName mResolveComponentName; 732 PackageParser.Package mPlatformPackage; 733 ComponentName mCustomResolverComponentName; 734 735 boolean mResolverReplaced = false; 736 737 private final @Nullable ComponentName mIntentFilterVerifierComponent; 738 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 739 740 private int mIntentFilterVerificationToken = 0; 741 742 /** Component that knows whether or not an ephemeral application exists */ 743 final ComponentName mEphemeralResolverComponent; 744 /** The service connection to the ephemeral resolver */ 745 final EphemeralResolverConnection mEphemeralResolverConnection; 746 747 /** Component used to install ephemeral applications */ 748 final ComponentName mEphemeralInstallerComponent; 749 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 750 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 751 752 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 753 = new SparseArray<IntentFilterVerificationState>(); 754 755 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 756 757 // List of packages names to keep cached, even if they are uninstalled for all users 758 private List<String> mKeepUninstalledPackages; 759 760 private UserManagerInternal mUserManagerInternal; 761 762 private static class IFVerificationParams { 763 PackageParser.Package pkg; 764 boolean replacing; 765 int userId; 766 int verifierUid; 767 768 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 769 int _userId, int _verifierUid) { 770 pkg = _pkg; 771 replacing = _replacing; 772 userId = _userId; 773 replacing = _replacing; 774 verifierUid = _verifierUid; 775 } 776 } 777 778 private interface IntentFilterVerifier<T extends IntentFilter> { 779 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 780 T filter, String packageName); 781 void startVerifications(int userId); 782 void receiveVerificationResponse(int verificationId); 783 } 784 785 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 786 private Context mContext; 787 private ComponentName mIntentFilterVerifierComponent; 788 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 789 790 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 791 mContext = context; 792 mIntentFilterVerifierComponent = verifierComponent; 793 } 794 795 private String getDefaultScheme() { 796 return IntentFilter.SCHEME_HTTPS; 797 } 798 799 @Override 800 public void startVerifications(int userId) { 801 // Launch verifications requests 802 int count = mCurrentIntentFilterVerifications.size(); 803 for (int n=0; n<count; n++) { 804 int verificationId = mCurrentIntentFilterVerifications.get(n); 805 final IntentFilterVerificationState ivs = 806 mIntentFilterVerificationStates.get(verificationId); 807 808 String packageName = ivs.getPackageName(); 809 810 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 811 final int filterCount = filters.size(); 812 ArraySet<String> domainsSet = new ArraySet<>(); 813 for (int m=0; m<filterCount; m++) { 814 PackageParser.ActivityIntentInfo filter = filters.get(m); 815 domainsSet.addAll(filter.getHostsList()); 816 } 817 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 818 synchronized (mPackages) { 819 if (mSettings.createIntentFilterVerificationIfNeededLPw( 820 packageName, domainsList) != null) { 821 scheduleWriteSettingsLocked(); 822 } 823 } 824 sendVerificationRequest(userId, verificationId, ivs); 825 } 826 mCurrentIntentFilterVerifications.clear(); 827 } 828 829 private void sendVerificationRequest(int userId, int verificationId, 830 IntentFilterVerificationState ivs) { 831 832 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 833 verificationIntent.putExtra( 834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 835 verificationId); 836 verificationIntent.putExtra( 837 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 838 getDefaultScheme()); 839 verificationIntent.putExtra( 840 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 841 ivs.getHostsString()); 842 verificationIntent.putExtra( 843 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 844 ivs.getPackageName()); 845 verificationIntent.setComponent(mIntentFilterVerifierComponent); 846 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 847 848 UserHandle user = new UserHandle(userId); 849 mContext.sendBroadcastAsUser(verificationIntent, user); 850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 851 "Sending IntentFilter verification broadcast"); 852 } 853 854 public void receiveVerificationResponse(int verificationId) { 855 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 856 857 final boolean verified = ivs.isVerified(); 858 859 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 860 final int count = filters.size(); 861 if (DEBUG_DOMAIN_VERIFICATION) { 862 Slog.i(TAG, "Received verification response " + verificationId 863 + " for " + count + " filters, verified=" + verified); 864 } 865 for (int n=0; n<count; n++) { 866 PackageParser.ActivityIntentInfo filter = filters.get(n); 867 filter.setVerified(verified); 868 869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 870 + " verified with result:" + verified + " and hosts:" 871 + ivs.getHostsString()); 872 } 873 874 mIntentFilterVerificationStates.remove(verificationId); 875 876 final String packageName = ivs.getPackageName(); 877 IntentFilterVerificationInfo ivi = null; 878 879 synchronized (mPackages) { 880 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 881 } 882 if (ivi == null) { 883 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 884 + verificationId + " packageName:" + packageName); 885 return; 886 } 887 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 888 "Updating IntentFilterVerificationInfo for package " + packageName 889 +" verificationId:" + verificationId); 890 891 synchronized (mPackages) { 892 if (verified) { 893 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 894 } else { 895 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 896 } 897 scheduleWriteSettingsLocked(); 898 899 final int userId = ivs.getUserId(); 900 if (userId != UserHandle.USER_ALL) { 901 final int userStatus = 902 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 903 904 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 905 boolean needUpdate = false; 906 907 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 908 // already been set by the User thru the Disambiguation dialog 909 switch (userStatus) { 910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 911 if (verified) { 912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 913 } else { 914 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 915 } 916 needUpdate = true; 917 break; 918 919 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 920 if (verified) { 921 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 922 needUpdate = true; 923 } 924 break; 925 926 default: 927 // Nothing to do 928 } 929 930 if (needUpdate) { 931 mSettings.updateIntentFilterVerificationStatusLPw( 932 packageName, updatedStatus, userId); 933 scheduleWritePackageRestrictionsLocked(userId); 934 } 935 } 936 } 937 } 938 939 @Override 940 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 941 ActivityIntentInfo filter, String packageName) { 942 if (!hasValidDomains(filter)) { 943 return false; 944 } 945 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 946 if (ivs == null) { 947 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 948 packageName); 949 } 950 if (DEBUG_DOMAIN_VERIFICATION) { 951 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 952 } 953 ivs.addFilter(filter); 954 return true; 955 } 956 957 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 958 int userId, int verificationId, String packageName) { 959 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 960 verifierUid, userId, packageName); 961 ivs.setPendingState(); 962 synchronized (mPackages) { 963 mIntentFilterVerificationStates.append(verificationId, ivs); 964 mCurrentIntentFilterVerifications.add(verificationId); 965 } 966 return ivs; 967 } 968 } 969 970 private static boolean hasValidDomains(ActivityIntentInfo filter) { 971 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 972 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 973 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 974 } 975 976 // Set of pending broadcasts for aggregating enable/disable of components. 977 static class PendingPackageBroadcasts { 978 // for each user id, a map of <package name -> components within that package> 979 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 980 981 public PendingPackageBroadcasts() { 982 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 983 } 984 985 public ArrayList<String> get(int userId, String packageName) { 986 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 987 return packages.get(packageName); 988 } 989 990 public void put(int userId, String packageName, ArrayList<String> components) { 991 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 992 packages.put(packageName, components); 993 } 994 995 public void remove(int userId, String packageName) { 996 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 997 if (packages != null) { 998 packages.remove(packageName); 999 } 1000 } 1001 1002 public void remove(int userId) { 1003 mUidMap.remove(userId); 1004 } 1005 1006 public int userIdCount() { 1007 return mUidMap.size(); 1008 } 1009 1010 public int userIdAt(int n) { 1011 return mUidMap.keyAt(n); 1012 } 1013 1014 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1015 return mUidMap.get(userId); 1016 } 1017 1018 public int size() { 1019 // total number of pending broadcast entries across all userIds 1020 int num = 0; 1021 for (int i = 0; i< mUidMap.size(); i++) { 1022 num += mUidMap.valueAt(i).size(); 1023 } 1024 return num; 1025 } 1026 1027 public void clear() { 1028 mUidMap.clear(); 1029 } 1030 1031 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1032 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1033 if (map == null) { 1034 map = new ArrayMap<String, ArrayList<String>>(); 1035 mUidMap.put(userId, map); 1036 } 1037 return map; 1038 } 1039 } 1040 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1041 1042 // Service Connection to remote media container service to copy 1043 // package uri's from external media onto secure containers 1044 // or internal storage. 1045 private IMediaContainerService mContainerService = null; 1046 1047 static final int SEND_PENDING_BROADCAST = 1; 1048 static final int MCS_BOUND = 3; 1049 static final int END_COPY = 4; 1050 static final int INIT_COPY = 5; 1051 static final int MCS_UNBIND = 6; 1052 static final int START_CLEANING_PACKAGE = 7; 1053 static final int FIND_INSTALL_LOC = 8; 1054 static final int POST_INSTALL = 9; 1055 static final int MCS_RECONNECT = 10; 1056 static final int MCS_GIVE_UP = 11; 1057 static final int UPDATED_MEDIA_STATUS = 12; 1058 static final int WRITE_SETTINGS = 13; 1059 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1060 static final int PACKAGE_VERIFIED = 15; 1061 static final int CHECK_PENDING_VERIFICATION = 16; 1062 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1063 static final int INTENT_FILTER_VERIFIED = 18; 1064 static final int WRITE_PACKAGE_LIST = 19; 1065 1066 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1067 1068 // Delay time in millisecs 1069 static final int BROADCAST_DELAY = 10 * 1000; 1070 1071 static UserManagerService sUserManager; 1072 1073 // Stores a list of users whose package restrictions file needs to be updated 1074 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1075 1076 final private DefaultContainerConnection mDefContainerConn = 1077 new DefaultContainerConnection(); 1078 class DefaultContainerConnection implements ServiceConnection { 1079 public void onServiceConnected(ComponentName name, IBinder service) { 1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1081 IMediaContainerService imcs = 1082 IMediaContainerService.Stub.asInterface(service); 1083 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1084 } 1085 1086 public void onServiceDisconnected(ComponentName name) { 1087 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1088 } 1089 } 1090 1091 // Recordkeeping of restore-after-install operations that are currently in flight 1092 // between the Package Manager and the Backup Manager 1093 static class PostInstallData { 1094 public InstallArgs args; 1095 public PackageInstalledInfo res; 1096 1097 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1098 args = _a; 1099 res = _r; 1100 } 1101 } 1102 1103 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1104 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1105 1106 // XML tags for backup/restore of various bits of state 1107 private static final String TAG_PREFERRED_BACKUP = "pa"; 1108 private static final String TAG_DEFAULT_APPS = "da"; 1109 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1110 1111 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1112 private static final String TAG_ALL_GRANTS = "rt-grants"; 1113 private static final String TAG_GRANT = "grant"; 1114 private static final String ATTR_PACKAGE_NAME = "pkg"; 1115 1116 private static final String TAG_PERMISSION = "perm"; 1117 private static final String ATTR_PERMISSION_NAME = "name"; 1118 private static final String ATTR_IS_GRANTED = "g"; 1119 private static final String ATTR_USER_SET = "set"; 1120 private static final String ATTR_USER_FIXED = "fixed"; 1121 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1122 1123 // System/policy permission grants are not backed up 1124 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1125 FLAG_PERMISSION_POLICY_FIXED 1126 | FLAG_PERMISSION_SYSTEM_FIXED 1127 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1128 1129 // And we back up these user-adjusted states 1130 private static final int USER_RUNTIME_GRANT_MASK = 1131 FLAG_PERMISSION_USER_SET 1132 | FLAG_PERMISSION_USER_FIXED 1133 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1134 1135 final @Nullable String mRequiredVerifierPackage; 1136 final @NonNull String mRequiredInstallerPackage; 1137 final @NonNull String mRequiredUninstallerPackage; 1138 final @Nullable String mSetupWizardPackage; 1139 final @Nullable String mStorageManagerPackage; 1140 final @NonNull String mServicesSystemSharedLibraryPackageName; 1141 final @NonNull String mSharedSystemSharedLibraryPackageName; 1142 1143 final boolean mPermissionReviewRequired; 1144 1145 private final PackageUsage mPackageUsage = new PackageUsage(); 1146 private final CompilerStats mCompilerStats = new CompilerStats(); 1147 1148 class PackageHandler extends Handler { 1149 private boolean mBound = false; 1150 final ArrayList<HandlerParams> mPendingInstalls = 1151 new ArrayList<HandlerParams>(); 1152 1153 private boolean connectToService() { 1154 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1155 " DefaultContainerService"); 1156 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1157 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1158 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1159 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1160 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1161 mBound = true; 1162 return true; 1163 } 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1165 return false; 1166 } 1167 1168 private void disconnectService() { 1169 mContainerService = null; 1170 mBound = false; 1171 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1172 mContext.unbindService(mDefContainerConn); 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 } 1175 1176 PackageHandler(Looper looper) { 1177 super(looper); 1178 } 1179 1180 public void handleMessage(Message msg) { 1181 try { 1182 doHandleMessage(msg); 1183 } finally { 1184 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1185 } 1186 } 1187 1188 void doHandleMessage(Message msg) { 1189 switch (msg.what) { 1190 case INIT_COPY: { 1191 HandlerParams params = (HandlerParams) msg.obj; 1192 int idx = mPendingInstalls.size(); 1193 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1194 // If a bind was already initiated we dont really 1195 // need to do anything. The pending install 1196 // will be processed later on. 1197 if (!mBound) { 1198 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1199 System.identityHashCode(mHandler)); 1200 // If this is the only one pending we might 1201 // have to bind to the service again. 1202 if (!connectToService()) { 1203 Slog.e(TAG, "Failed to bind to media container service"); 1204 params.serviceError(); 1205 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1206 System.identityHashCode(mHandler)); 1207 if (params.traceMethod != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1209 params.traceCookie); 1210 } 1211 return; 1212 } else { 1213 // Once we bind to the service, the first 1214 // pending request will be processed. 1215 mPendingInstalls.add(idx, params); 1216 } 1217 } else { 1218 mPendingInstalls.add(idx, params); 1219 // Already bound to the service. Just make 1220 // sure we trigger off processing the first request. 1221 if (idx == 0) { 1222 mHandler.sendEmptyMessage(MCS_BOUND); 1223 } 1224 } 1225 break; 1226 } 1227 case MCS_BOUND: { 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1229 if (msg.obj != null) { 1230 mContainerService = (IMediaContainerService) msg.obj; 1231 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1232 System.identityHashCode(mHandler)); 1233 } 1234 if (mContainerService == null) { 1235 if (!mBound) { 1236 // Something seriously wrong since we are not bound and we are not 1237 // waiting for connection. Bail out. 1238 Slog.e(TAG, "Cannot bind to media container service"); 1239 for (HandlerParams params : mPendingInstalls) { 1240 // Indicate service bind error 1241 params.serviceError(); 1242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1243 System.identityHashCode(params)); 1244 if (params.traceMethod != null) { 1245 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1246 params.traceMethod, params.traceCookie); 1247 } 1248 return; 1249 } 1250 mPendingInstalls.clear(); 1251 } else { 1252 Slog.w(TAG, "Waiting to connect to media container service"); 1253 } 1254 } else if (mPendingInstalls.size() > 0) { 1255 HandlerParams params = mPendingInstalls.get(0); 1256 if (params != null) { 1257 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1258 System.identityHashCode(params)); 1259 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1260 if (params.startCopy()) { 1261 // We are done... look for more work or to 1262 // go idle. 1263 if (DEBUG_SD_INSTALL) Log.i(TAG, 1264 "Checking for more work or unbind..."); 1265 // Delete pending install 1266 if (mPendingInstalls.size() > 0) { 1267 mPendingInstalls.remove(0); 1268 } 1269 if (mPendingInstalls.size() == 0) { 1270 if (mBound) { 1271 if (DEBUG_SD_INSTALL) Log.i(TAG, 1272 "Posting delayed MCS_UNBIND"); 1273 removeMessages(MCS_UNBIND); 1274 Message ubmsg = obtainMessage(MCS_UNBIND); 1275 // Unbind after a little delay, to avoid 1276 // continual thrashing. 1277 sendMessageDelayed(ubmsg, 10000); 1278 } 1279 } else { 1280 // There are more pending requests in queue. 1281 // Just post MCS_BOUND message to trigger processing 1282 // of next pending install. 1283 if (DEBUG_SD_INSTALL) Log.i(TAG, 1284 "Posting MCS_BOUND for next work"); 1285 mHandler.sendEmptyMessage(MCS_BOUND); 1286 } 1287 } 1288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1289 } 1290 } else { 1291 // Should never happen ideally. 1292 Slog.w(TAG, "Empty queue"); 1293 } 1294 break; 1295 } 1296 case MCS_RECONNECT: { 1297 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1298 if (mPendingInstalls.size() > 0) { 1299 if (mBound) { 1300 disconnectService(); 1301 } 1302 if (!connectToService()) { 1303 Slog.e(TAG, "Failed to bind to media container service"); 1304 for (HandlerParams params : mPendingInstalls) { 1305 // Indicate service bind error 1306 params.serviceError(); 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1308 System.identityHashCode(params)); 1309 } 1310 mPendingInstalls.clear(); 1311 } 1312 } 1313 break; 1314 } 1315 case MCS_UNBIND: { 1316 // If there is no actual work left, then time to unbind. 1317 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1318 1319 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1320 if (mBound) { 1321 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1322 1323 disconnectService(); 1324 } 1325 } else if (mPendingInstalls.size() > 0) { 1326 // There are more pending requests in queue. 1327 // Just post MCS_BOUND message to trigger processing 1328 // of next pending install. 1329 mHandler.sendEmptyMessage(MCS_BOUND); 1330 } 1331 1332 break; 1333 } 1334 case MCS_GIVE_UP: { 1335 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1336 HandlerParams params = mPendingInstalls.remove(0); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 break; 1340 } 1341 case SEND_PENDING_BROADCAST: { 1342 String packages[]; 1343 ArrayList<String> components[]; 1344 int size = 0; 1345 int uids[]; 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1347 synchronized (mPackages) { 1348 if (mPendingBroadcasts == null) { 1349 return; 1350 } 1351 size = mPendingBroadcasts.size(); 1352 if (size <= 0) { 1353 // Nothing to be done. Just return 1354 return; 1355 } 1356 packages = new String[size]; 1357 components = new ArrayList[size]; 1358 uids = new int[size]; 1359 int i = 0; // filling out the above arrays 1360 1361 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1362 int packageUserId = mPendingBroadcasts.userIdAt(n); 1363 Iterator<Map.Entry<String, ArrayList<String>>> it 1364 = mPendingBroadcasts.packagesForUserId(packageUserId) 1365 .entrySet().iterator(); 1366 while (it.hasNext() && i < size) { 1367 Map.Entry<String, ArrayList<String>> ent = it.next(); 1368 packages[i] = ent.getKey(); 1369 components[i] = ent.getValue(); 1370 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1371 uids[i] = (ps != null) 1372 ? UserHandle.getUid(packageUserId, ps.appId) 1373 : -1; 1374 i++; 1375 } 1376 } 1377 size = i; 1378 mPendingBroadcasts.clear(); 1379 } 1380 // Send broadcasts 1381 for (int i = 0; i < size; i++) { 1382 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1383 } 1384 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1385 break; 1386 } 1387 case START_CLEANING_PACKAGE: { 1388 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1389 final String packageName = (String)msg.obj; 1390 final int userId = msg.arg1; 1391 final boolean andCode = msg.arg2 != 0; 1392 synchronized (mPackages) { 1393 if (userId == UserHandle.USER_ALL) { 1394 int[] users = sUserManager.getUserIds(); 1395 for (int user : users) { 1396 mSettings.addPackageToCleanLPw( 1397 new PackageCleanItem(user, packageName, andCode)); 1398 } 1399 } else { 1400 mSettings.addPackageToCleanLPw( 1401 new PackageCleanItem(userId, packageName, andCode)); 1402 } 1403 } 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1405 startCleaningPackages(); 1406 } break; 1407 case POST_INSTALL: { 1408 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1409 1410 PostInstallData data = mRunningInstalls.get(msg.arg1); 1411 final boolean didRestore = (msg.arg2 != 0); 1412 mRunningInstalls.delete(msg.arg1); 1413 1414 if (data != null) { 1415 InstallArgs args = data.args; 1416 PackageInstalledInfo parentRes = data.res; 1417 1418 final boolean grantPermissions = (args.installFlags 1419 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1420 final boolean killApp = (args.installFlags 1421 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1422 final String[] grantedPermissions = args.installGrantPermissions; 1423 1424 // Handle the parent package 1425 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1426 grantedPermissions, didRestore, args.installerPackageName, 1427 args.observer); 1428 1429 // Handle the child packages 1430 final int childCount = (parentRes.addedChildPackages != null) 1431 ? parentRes.addedChildPackages.size() : 0; 1432 for (int i = 0; i < childCount; i++) { 1433 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1434 handlePackagePostInstall(childRes, grantPermissions, killApp, 1435 grantedPermissions, false, args.installerPackageName, 1436 args.observer); 1437 } 1438 1439 // Log tracing if needed 1440 if (args.traceMethod != null) { 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1442 args.traceCookie); 1443 } 1444 } else { 1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1446 } 1447 1448 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case WRITE_PACKAGE_LIST: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 synchronized (mPackages) { 1499 removeMessages(WRITE_PACKAGE_LIST); 1500 mSettings.writePackageListLPr(msg.arg1); 1501 } 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1503 } break; 1504 case CHECK_PENDING_VERIFICATION: { 1505 final int verificationId = msg.arg1; 1506 final PackageVerificationState state = mPendingVerification.get(verificationId); 1507 1508 if ((state != null) && !state.timeoutExtended()) { 1509 final InstallArgs args = state.getInstallArgs(); 1510 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1511 1512 Slog.i(TAG, "Verification timed out for " + originUri); 1513 mPendingVerification.remove(verificationId); 1514 1515 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1516 1517 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1518 Slog.i(TAG, "Continuing with installation of " + originUri); 1519 state.setVerifierResponse(Binder.getCallingUid(), 1520 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1521 broadcastPackageVerified(verificationId, originUri, 1522 PackageManager.VERIFICATION_ALLOW, 1523 state.getInstallArgs().getUser()); 1524 try { 1525 ret = args.copyApk(mContainerService, true); 1526 } catch (RemoteException e) { 1527 Slog.e(TAG, "Could not contact the ContainerService"); 1528 } 1529 } else { 1530 broadcastPackageVerified(verificationId, originUri, 1531 PackageManager.VERIFICATION_REJECT, 1532 state.getInstallArgs().getUser()); 1533 } 1534 1535 Trace.asyncTraceEnd( 1536 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1537 1538 processPendingInstall(args, ret); 1539 mHandler.sendEmptyMessage(MCS_UNBIND); 1540 } 1541 break; 1542 } 1543 case PACKAGE_VERIFIED: { 1544 final int verificationId = msg.arg1; 1545 1546 final PackageVerificationState state = mPendingVerification.get(verificationId); 1547 if (state == null) { 1548 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1549 break; 1550 } 1551 1552 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1553 1554 state.setVerifierResponse(response.callerUid, response.code); 1555 1556 if (state.isVerificationComplete()) { 1557 mPendingVerification.remove(verificationId); 1558 1559 final InstallArgs args = state.getInstallArgs(); 1560 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1561 1562 int ret; 1563 if (state.isInstallAllowed()) { 1564 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1565 broadcastPackageVerified(verificationId, originUri, 1566 response.code, state.getInstallArgs().getUser()); 1567 try { 1568 ret = args.copyApk(mContainerService, true); 1569 } catch (RemoteException e) { 1570 Slog.e(TAG, "Could not contact the ContainerService"); 1571 } 1572 } else { 1573 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1574 } 1575 1576 Trace.asyncTraceEnd( 1577 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1578 1579 processPendingInstall(args, ret); 1580 mHandler.sendEmptyMessage(MCS_UNBIND); 1581 } 1582 1583 break; 1584 } 1585 case START_INTENT_FILTER_VERIFICATIONS: { 1586 IFVerificationParams params = (IFVerificationParams) msg.obj; 1587 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1588 params.replacing, params.pkg); 1589 break; 1590 } 1591 case INTENT_FILTER_VERIFIED: { 1592 final int verificationId = msg.arg1; 1593 1594 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1595 verificationId); 1596 if (state == null) { 1597 Slog.w(TAG, "Invalid IntentFilter verification token " 1598 + verificationId + " received"); 1599 break; 1600 } 1601 1602 final int userId = state.getUserId(); 1603 1604 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1605 "Processing IntentFilter verification with token:" 1606 + verificationId + " and userId:" + userId); 1607 1608 final IntentFilterVerificationResponse response = 1609 (IntentFilterVerificationResponse) msg.obj; 1610 1611 state.setVerifierResponse(response.callerUid, response.code); 1612 1613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1614 "IntentFilter verification with token:" + verificationId 1615 + " and userId:" + userId 1616 + " is settings verifier response with response code:" 1617 + response.code); 1618 1619 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1621 + response.getFailedDomainsString()); 1622 } 1623 1624 if (state.isVerificationComplete()) { 1625 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1626 } else { 1627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1628 "IntentFilter verification with token:" + verificationId 1629 + " was not said to be complete"); 1630 } 1631 1632 break; 1633 } 1634 } 1635 } 1636 } 1637 1638 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1639 boolean killApp, String[] grantedPermissions, 1640 boolean launchedForRestore, String installerPackage, 1641 IPackageInstallObserver2 installObserver) { 1642 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1643 // Send the removed broadcasts 1644 if (res.removedInfo != null) { 1645 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1646 } 1647 1648 // Now that we successfully installed the package, grant runtime 1649 // permissions if requested before broadcasting the install. Also 1650 // for legacy apps in permission review mode we clear the permission 1651 // review flag which is used to emulate runtime permissions for 1652 // legacy apps. 1653 if (grantPermissions) { 1654 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1655 } 1656 1657 final boolean update = res.removedInfo != null 1658 && res.removedInfo.removedPackage != null; 1659 1660 // If this is the first time we have child packages for a disabled privileged 1661 // app that had no children, we grant requested runtime permissions to the new 1662 // children if the parent on the system image had them already granted. 1663 if (res.pkg.parentPackage != null) { 1664 synchronized (mPackages) { 1665 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1666 } 1667 } 1668 1669 synchronized (mPackages) { 1670 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1671 } 1672 1673 final String packageName = res.pkg.applicationInfo.packageName; 1674 Bundle extras = new Bundle(1); 1675 extras.putInt(Intent.EXTRA_UID, res.uid); 1676 1677 // Determine the set of users who are adding this package for 1678 // the first time vs. those who are seeing an update. 1679 int[] firstUsers = EMPTY_INT_ARRAY; 1680 int[] updateUsers = EMPTY_INT_ARRAY; 1681 if (res.origUsers == null || res.origUsers.length == 0) { 1682 firstUsers = res.newUsers; 1683 } else { 1684 for (int newUser : res.newUsers) { 1685 boolean isNew = true; 1686 for (int origUser : res.origUsers) { 1687 if (origUser == newUser) { 1688 isNew = false; 1689 break; 1690 } 1691 } 1692 if (isNew) { 1693 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1694 } else { 1695 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1696 } 1697 } 1698 } 1699 1700 // Send installed broadcasts if the install/update is not ephemeral 1701 if (!isEphemeral(res.pkg)) { 1702 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1703 1704 // Send added for users that see the package for the first time 1705 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1706 extras, 0 /*flags*/, null /*targetPackage*/, 1707 null /*finishedReceiver*/, firstUsers); 1708 1709 // Send added for users that don't see the package for the first time 1710 if (update) { 1711 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1712 } 1713 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1714 extras, 0 /*flags*/, null /*targetPackage*/, 1715 null /*finishedReceiver*/, updateUsers); 1716 1717 // Send replaced for users that don't see the package for the first time 1718 if (update) { 1719 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1720 packageName, extras, 0 /*flags*/, 1721 null /*targetPackage*/, null /*finishedReceiver*/, 1722 updateUsers); 1723 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1724 null /*package*/, null /*extras*/, 0 /*flags*/, 1725 packageName /*targetPackage*/, 1726 null /*finishedReceiver*/, updateUsers); 1727 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1728 // First-install and we did a restore, so we're responsible for the 1729 // first-launch broadcast. 1730 if (DEBUG_BACKUP) { 1731 Slog.i(TAG, "Post-restore of " + packageName 1732 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1733 } 1734 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1735 } 1736 1737 // Send broadcast package appeared if forward locked/external for all users 1738 // treat asec-hosted packages like removable media on upgrade 1739 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1740 if (DEBUG_INSTALL) { 1741 Slog.i(TAG, "upgrading pkg " + res.pkg 1742 + " is ASEC-hosted -> AVAILABLE"); 1743 } 1744 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1745 ArrayList<String> pkgList = new ArrayList<>(1); 1746 pkgList.add(packageName); 1747 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1748 } 1749 } 1750 1751 // Work that needs to happen on first install within each user 1752 if (firstUsers != null && firstUsers.length > 0) { 1753 synchronized (mPackages) { 1754 for (int userId : firstUsers) { 1755 // If this app is a browser and it's newly-installed for some 1756 // users, clear any default-browser state in those users. The 1757 // app's nature doesn't depend on the user, so we can just check 1758 // its browser nature in any user and generalize. 1759 if (packageIsBrowser(packageName, userId)) { 1760 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1761 } 1762 1763 // We may also need to apply pending (restored) runtime 1764 // permission grants within these users. 1765 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1766 } 1767 } 1768 } 1769 1770 // Log current value of "unknown sources" setting 1771 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1772 getUnknownSourcesSettings()); 1773 1774 // Force a gc to clear up things 1775 Runtime.getRuntime().gc(); 1776 1777 // Remove the replaced package's older resources safely now 1778 // We delete after a gc for applications on sdcard. 1779 if (res.removedInfo != null && res.removedInfo.args != null) { 1780 synchronized (mInstallLock) { 1781 res.removedInfo.args.doPostDeleteLI(true); 1782 } 1783 } 1784 } 1785 1786 // If someone is watching installs - notify them 1787 if (installObserver != null) { 1788 try { 1789 Bundle extras = extrasForInstallResult(res); 1790 installObserver.onPackageInstalled(res.name, res.returnCode, 1791 res.returnMsg, extras); 1792 } catch (RemoteException e) { 1793 Slog.i(TAG, "Observer no longer exists."); 1794 } 1795 } 1796 } 1797 1798 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1799 PackageParser.Package pkg) { 1800 if (pkg.parentPackage == null) { 1801 return; 1802 } 1803 if (pkg.requestedPermissions == null) { 1804 return; 1805 } 1806 final PackageSetting disabledSysParentPs = mSettings 1807 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1808 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1809 || !disabledSysParentPs.isPrivileged() 1810 || (disabledSysParentPs.childPackageNames != null 1811 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1812 return; 1813 } 1814 final int[] allUserIds = sUserManager.getUserIds(); 1815 final int permCount = pkg.requestedPermissions.size(); 1816 for (int i = 0; i < permCount; i++) { 1817 String permission = pkg.requestedPermissions.get(i); 1818 BasePermission bp = mSettings.mPermissions.get(permission); 1819 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1820 continue; 1821 } 1822 for (int userId : allUserIds) { 1823 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1824 permission, userId)) { 1825 grantRuntimePermission(pkg.packageName, permission, userId); 1826 } 1827 } 1828 } 1829 } 1830 1831 private StorageEventListener mStorageListener = new StorageEventListener() { 1832 @Override 1833 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1834 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1835 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1836 final String volumeUuid = vol.getFsUuid(); 1837 1838 // Clean up any users or apps that were removed or recreated 1839 // while this volume was missing 1840 reconcileUsers(volumeUuid); 1841 reconcileApps(volumeUuid); 1842 1843 // Clean up any install sessions that expired or were 1844 // cancelled while this volume was missing 1845 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1846 1847 loadPrivatePackages(vol); 1848 1849 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1850 unloadPrivatePackages(vol); 1851 } 1852 } 1853 1854 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1855 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1856 updateExternalMediaStatus(true, false); 1857 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1858 updateExternalMediaStatus(false, false); 1859 } 1860 } 1861 } 1862 1863 @Override 1864 public void onVolumeForgotten(String fsUuid) { 1865 if (TextUtils.isEmpty(fsUuid)) { 1866 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1867 return; 1868 } 1869 1870 // Remove any apps installed on the forgotten volume 1871 synchronized (mPackages) { 1872 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1873 for (PackageSetting ps : packages) { 1874 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1875 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1876 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1877 } 1878 1879 mSettings.onVolumeForgotten(fsUuid); 1880 mSettings.writeLPr(); 1881 } 1882 } 1883 }; 1884 1885 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1886 String[] grantedPermissions) { 1887 for (int userId : userIds) { 1888 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1889 } 1890 } 1891 1892 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1893 String[] grantedPermissions) { 1894 SettingBase sb = (SettingBase) pkg.mExtras; 1895 if (sb == null) { 1896 return; 1897 } 1898 1899 PermissionsState permissionsState = sb.getPermissionsState(); 1900 1901 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1902 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1903 1904 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 1905 >= Build.VERSION_CODES.M; 1906 1907 for (String permission : pkg.requestedPermissions) { 1908 final BasePermission bp; 1909 synchronized (mPackages) { 1910 bp = mSettings.mPermissions.get(permission); 1911 } 1912 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1913 && (grantedPermissions == null 1914 || ArrayUtils.contains(grantedPermissions, permission))) { 1915 final int flags = permissionsState.getPermissionFlags(permission, userId); 1916 if (supportsRuntimePermissions) { 1917 // Installer cannot change immutable permissions. 1918 if ((flags & immutableFlags) == 0) { 1919 grantRuntimePermission(pkg.packageName, permission, userId); 1920 } 1921 } else if (mPermissionReviewRequired) { 1922 // In permission review mode we clear the review flag when we 1923 // are asked to install the app with all permissions granted. 1924 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 1925 updatePermissionFlags(permission, pkg.packageName, 1926 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0 /*value*/, userId); 1927 } 1928 } 1929 } 1930 } 1931 } 1932 1933 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1934 Bundle extras = null; 1935 switch (res.returnCode) { 1936 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1937 extras = new Bundle(); 1938 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1939 res.origPermission); 1940 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1941 res.origPackage); 1942 break; 1943 } 1944 case PackageManager.INSTALL_SUCCEEDED: { 1945 extras = new Bundle(); 1946 extras.putBoolean(Intent.EXTRA_REPLACING, 1947 res.removedInfo != null && res.removedInfo.removedPackage != null); 1948 break; 1949 } 1950 } 1951 return extras; 1952 } 1953 1954 void scheduleWriteSettingsLocked() { 1955 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1956 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1957 } 1958 } 1959 1960 void scheduleWritePackageListLocked(int userId) { 1961 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1962 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1963 msg.arg1 = userId; 1964 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1965 } 1966 } 1967 1968 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1969 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1970 scheduleWritePackageRestrictionsLocked(userId); 1971 } 1972 1973 void scheduleWritePackageRestrictionsLocked(int userId) { 1974 final int[] userIds = (userId == UserHandle.USER_ALL) 1975 ? sUserManager.getUserIds() : new int[]{userId}; 1976 for (int nextUserId : userIds) { 1977 if (!sUserManager.exists(nextUserId)) return; 1978 mDirtyUsers.add(nextUserId); 1979 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1980 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1981 } 1982 } 1983 } 1984 1985 public static PackageManagerService main(Context context, Installer installer, 1986 boolean factoryTest, boolean onlyCore) { 1987 // Self-check for initial settings. 1988 PackageManagerServiceCompilerMapping.checkProperties(); 1989 1990 PackageManagerService m = new PackageManagerService(context, installer, 1991 factoryTest, onlyCore); 1992 m.enableSystemUserPackages(); 1993 ServiceManager.addService("package", m); 1994 return m; 1995 } 1996 1997 private void enableSystemUserPackages() { 1998 if (!UserManager.isSplitSystemUser()) { 1999 return; 2000 } 2001 // For system user, enable apps based on the following conditions: 2002 // - app is whitelisted or belong to one of these groups: 2003 // -- system app which has no launcher icons 2004 // -- system app which has INTERACT_ACROSS_USERS permission 2005 // -- system IME app 2006 // - app is not in the blacklist 2007 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2008 Set<String> enableApps = new ArraySet<>(); 2009 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2010 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2011 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2012 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2013 enableApps.addAll(wlApps); 2014 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2015 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2016 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2017 enableApps.removeAll(blApps); 2018 Log.i(TAG, "Applications installed for system user: " + enableApps); 2019 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2020 UserHandle.SYSTEM); 2021 final int allAppsSize = allAps.size(); 2022 synchronized (mPackages) { 2023 for (int i = 0; i < allAppsSize; i++) { 2024 String pName = allAps.get(i); 2025 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2026 // Should not happen, but we shouldn't be failing if it does 2027 if (pkgSetting == null) { 2028 continue; 2029 } 2030 boolean install = enableApps.contains(pName); 2031 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2032 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2033 + " for system user"); 2034 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2035 } 2036 } 2037 } 2038 } 2039 2040 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2041 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2042 Context.DISPLAY_SERVICE); 2043 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2044 } 2045 2046 /** 2047 * Requests that files preopted on a secondary system partition be copied to the data partition 2048 * if possible. Note that the actual copying of the files is accomplished by init for security 2049 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2050 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2051 */ 2052 private static void requestCopyPreoptedFiles() { 2053 final int WAIT_TIME_MS = 100; 2054 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2055 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2056 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2057 // We will wait for up to 100 seconds. 2058 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2059 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2060 try { 2061 Thread.sleep(WAIT_TIME_MS); 2062 } catch (InterruptedException e) { 2063 // Do nothing 2064 } 2065 if (SystemClock.uptimeMillis() > timeEnd) { 2066 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2067 Slog.wtf(TAG, "cppreopt did not finish!"); 2068 break; 2069 } 2070 } 2071 } 2072 } 2073 2074 public PackageManagerService(Context context, Installer installer, 2075 boolean factoryTest, boolean onlyCore) { 2076 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2077 SystemClock.uptimeMillis()); 2078 2079 if (mSdkVersion <= 0) { 2080 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2081 } 2082 2083 mContext = context; 2084 2085 mPermissionReviewRequired = context.getResources().getBoolean( 2086 R.bool.config_permissionReviewRequired); 2087 2088 mFactoryTest = factoryTest; 2089 mOnlyCore = onlyCore; 2090 mMetrics = new DisplayMetrics(); 2091 mSettings = new Settings(mPackages); 2092 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2094 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2095 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2096 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2097 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2098 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2099 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2100 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2101 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2102 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2103 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2104 2105 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2106 if (separateProcesses != null && separateProcesses.length() > 0) { 2107 if ("*".equals(separateProcesses)) { 2108 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2109 mSeparateProcesses = null; 2110 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2111 } else { 2112 mDefParseFlags = 0; 2113 mSeparateProcesses = separateProcesses.split(","); 2114 Slog.w(TAG, "Running with debug.separate_processes: " 2115 + separateProcesses); 2116 } 2117 } else { 2118 mDefParseFlags = 0; 2119 mSeparateProcesses = null; 2120 } 2121 2122 mInstaller = installer; 2123 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2124 "*dexopt*"); 2125 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2126 2127 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2128 FgThread.get().getLooper()); 2129 2130 getDefaultDisplayMetrics(context, mMetrics); 2131 2132 SystemConfig systemConfig = SystemConfig.getInstance(); 2133 mGlobalGids = systemConfig.getGlobalGids(); 2134 mSystemPermissions = systemConfig.getSystemPermissions(); 2135 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2136 2137 mProtectedPackages = new ProtectedPackages(mContext); 2138 2139 synchronized (mInstallLock) { 2140 // writer 2141 synchronized (mPackages) { 2142 mHandlerThread = new ServiceThread(TAG, 2143 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2144 mHandlerThread.start(); 2145 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2146 mProcessLoggingHandler = new ProcessLoggingHandler(); 2147 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2148 2149 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2150 2151 File dataDir = Environment.getDataDirectory(); 2152 mAppInstallDir = new File(dataDir, "app"); 2153 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2154 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2155 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2156 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2157 2158 sUserManager = new UserManagerService(context, this, mPackages); 2159 2160 // Propagate permission configuration in to package manager. 2161 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2162 = systemConfig.getPermissions(); 2163 for (int i=0; i<permConfig.size(); i++) { 2164 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2165 BasePermission bp = mSettings.mPermissions.get(perm.name); 2166 if (bp == null) { 2167 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2168 mSettings.mPermissions.put(perm.name, bp); 2169 } 2170 if (perm.gids != null) { 2171 bp.setGids(perm.gids, perm.perUser); 2172 } 2173 } 2174 2175 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2176 for (int i=0; i<libConfig.size(); i++) { 2177 mSharedLibraries.put(libConfig.keyAt(i), 2178 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2179 } 2180 2181 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2182 2183 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2184 2185 // Clean up orphaned packages for which the code path doesn't exist 2186 // and they are an update to a system app - caused by bug/32321269 2187 final int packageSettingCount = mSettings.mPackages.size(); 2188 for (int i = packageSettingCount - 1; i >= 0; i--) { 2189 PackageSetting ps = mSettings.mPackages.valueAt(i); 2190 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2191 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2192 mSettings.mPackages.removeAt(i); 2193 mSettings.enableSystemPackageLPw(ps.name); 2194 } 2195 } 2196 2197 if (mFirstBoot) { 2198 requestCopyPreoptedFiles(); 2199 } 2200 2201 String customResolverActivity = Resources.getSystem().getString( 2202 R.string.config_customResolverActivity); 2203 if (TextUtils.isEmpty(customResolverActivity)) { 2204 customResolverActivity = null; 2205 } else { 2206 mCustomResolverComponentName = ComponentName.unflattenFromString( 2207 customResolverActivity); 2208 } 2209 2210 long startTime = SystemClock.uptimeMillis(); 2211 2212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2213 startTime); 2214 2215 // Set flag to monitor and not change apk file paths when 2216 // scanning install directories. 2217 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2218 2219 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2220 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2221 2222 if (bootClassPath == null) { 2223 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2224 } 2225 2226 if (systemServerClassPath == null) { 2227 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2228 } 2229 2230 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2231 final String[] dexCodeInstructionSets = 2232 getDexCodeInstructionSets( 2233 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2234 2235 /** 2236 * Ensure all external libraries have had dexopt run on them. 2237 */ 2238 if (mSharedLibraries.size() > 0) { 2239 // NOTE: For now, we're compiling these system "shared libraries" 2240 // (and framework jars) into all available architectures. It's possible 2241 // to compile them only when we come across an app that uses them (there's 2242 // already logic for that in scanPackageLI) but that adds some complexity. 2243 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2244 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2245 final String lib = libEntry.path; 2246 if (lib == null) { 2247 continue; 2248 } 2249 2250 try { 2251 // Shared libraries do not have profiles so we perform a full 2252 // AOT compilation (if needed). 2253 int dexoptNeeded = DexFile.getDexOptNeeded( 2254 lib, dexCodeInstructionSet, 2255 getCompilerFilterForReason(REASON_SHARED_APK), 2256 false /* newProfile */); 2257 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2258 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2259 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2260 getCompilerFilterForReason(REASON_SHARED_APK), 2261 StorageManager.UUID_PRIVATE_INTERNAL, 2262 SKIP_SHARED_LIBRARY_CHECK); 2263 } 2264 } catch (FileNotFoundException e) { 2265 Slog.w(TAG, "Library not found: " + lib); 2266 } catch (IOException | InstallerException e) { 2267 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2268 + e.getMessage()); 2269 } 2270 } 2271 } 2272 } 2273 2274 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2275 2276 final VersionInfo ver = mSettings.getInternalVersion(); 2277 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2278 2279 // when upgrading from pre-M, promote system app permissions from install to runtime 2280 mPromoteSystemApps = 2281 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2282 2283 // When upgrading from pre-N, we need to handle package extraction like first boot, 2284 // as there is no profiling data available. 2285 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2286 2287 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2288 2289 // save off the names of pre-existing system packages prior to scanning; we don't 2290 // want to automatically grant runtime permissions for new system apps 2291 if (mPromoteSystemApps) { 2292 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2293 while (pkgSettingIter.hasNext()) { 2294 PackageSetting ps = pkgSettingIter.next(); 2295 if (isSystemApp(ps)) { 2296 mExistingSystemPackages.add(ps.name); 2297 } 2298 } 2299 } 2300 2301 // Collect vendor overlay packages. (Do this before scanning any apps.) 2302 // For security and version matching reason, only consider 2303 // overlay packages if they reside in the right directory. 2304 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2305 if (!overlayThemeDir.isEmpty()) { 2306 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2307 | PackageParser.PARSE_IS_SYSTEM 2308 | PackageParser.PARSE_IS_SYSTEM_DIR 2309 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2310 } 2311 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2312 | PackageParser.PARSE_IS_SYSTEM 2313 | PackageParser.PARSE_IS_SYSTEM_DIR 2314 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2315 2316 // Find base frameworks (resource packages without code). 2317 scanDirTracedLI(frameworkDir, mDefParseFlags 2318 | PackageParser.PARSE_IS_SYSTEM 2319 | PackageParser.PARSE_IS_SYSTEM_DIR 2320 | PackageParser.PARSE_IS_PRIVILEGED, 2321 scanFlags | SCAN_NO_DEX, 0); 2322 2323 // Collected privileged system packages. 2324 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2325 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2326 | PackageParser.PARSE_IS_SYSTEM 2327 | PackageParser.PARSE_IS_SYSTEM_DIR 2328 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2329 2330 // Collect ordinary system packages. 2331 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2332 scanDirTracedLI(systemAppDir, mDefParseFlags 2333 | PackageParser.PARSE_IS_SYSTEM 2334 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2335 2336 // Collect all vendor packages. 2337 File vendorAppDir = new File("/vendor/app"); 2338 try { 2339 vendorAppDir = vendorAppDir.getCanonicalFile(); 2340 } catch (IOException e) { 2341 // failed to look up canonical path, continue with original one 2342 } 2343 scanDirTracedLI(vendorAppDir, mDefParseFlags 2344 | PackageParser.PARSE_IS_SYSTEM 2345 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2346 2347 // Collect all OEM packages. 2348 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2349 scanDirTracedLI(oemAppDir, mDefParseFlags 2350 | PackageParser.PARSE_IS_SYSTEM 2351 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2352 2353 // Prune any system packages that no longer exist. 2354 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2355 if (!mOnlyCore) { 2356 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2357 while (psit.hasNext()) { 2358 PackageSetting ps = psit.next(); 2359 2360 /* 2361 * If this is not a system app, it can't be a 2362 * disable system app. 2363 */ 2364 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2365 continue; 2366 } 2367 2368 /* 2369 * If the package is scanned, it's not erased. 2370 */ 2371 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2372 if (scannedPkg != null) { 2373 /* 2374 * If the system app is both scanned and in the 2375 * disabled packages list, then it must have been 2376 * added via OTA. Remove it from the currently 2377 * scanned package so the previously user-installed 2378 * application can be scanned. 2379 */ 2380 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2381 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2382 + ps.name + "; removing system app. Last known codePath=" 2383 + ps.codePathString + ", installStatus=" + ps.installStatus 2384 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2385 + scannedPkg.mVersionCode); 2386 removePackageLI(scannedPkg, true); 2387 mExpectingBetter.put(ps.name, ps.codePath); 2388 } 2389 2390 continue; 2391 } 2392 2393 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2394 psit.remove(); 2395 logCriticalInfo(Log.WARN, "System package " + ps.name 2396 + " no longer exists; it's data will be wiped"); 2397 // Actual deletion of code and data will be handled by later 2398 // reconciliation step 2399 } else { 2400 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2401 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2402 possiblyDeletedUpdatedSystemApps.add(ps.name); 2403 } 2404 } 2405 } 2406 } 2407 2408 //look for any incomplete package installations 2409 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2410 for (int i = 0; i < deletePkgsList.size(); i++) { 2411 // Actual deletion of code and data will be handled by later 2412 // reconciliation step 2413 final String packageName = deletePkgsList.get(i).name; 2414 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2415 synchronized (mPackages) { 2416 mSettings.removePackageLPw(packageName); 2417 } 2418 } 2419 2420 //delete tmp files 2421 deleteTempPackageFiles(); 2422 2423 // Remove any shared userIDs that have no associated packages 2424 mSettings.pruneSharedUsersLPw(); 2425 2426 if (!mOnlyCore) { 2427 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2428 SystemClock.uptimeMillis()); 2429 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2430 2431 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2432 | PackageParser.PARSE_FORWARD_LOCK, 2433 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2434 2435 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2436 | PackageParser.PARSE_IS_EPHEMERAL, 2437 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2438 2439 /** 2440 * Remove disable package settings for any updated system 2441 * apps that were removed via an OTA. If they're not a 2442 * previously-updated app, remove them completely. 2443 * Otherwise, just revoke their system-level permissions. 2444 */ 2445 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2446 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2447 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2448 2449 String msg; 2450 if (deletedPkg == null) { 2451 msg = "Updated system package " + deletedAppName 2452 + " no longer exists; it's data will be wiped"; 2453 // Actual deletion of code and data will be handled by later 2454 // reconciliation step 2455 } else { 2456 msg = "Updated system app + " + deletedAppName 2457 + " no longer present; removing system privileges for " 2458 + deletedAppName; 2459 2460 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2461 2462 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2463 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2464 } 2465 logCriticalInfo(Log.WARN, msg); 2466 } 2467 2468 /** 2469 * Make sure all system apps that we expected to appear on 2470 * the userdata partition actually showed up. If they never 2471 * appeared, crawl back and revive the system version. 2472 */ 2473 for (int i = 0; i < mExpectingBetter.size(); i++) { 2474 final String packageName = mExpectingBetter.keyAt(i); 2475 if (!mPackages.containsKey(packageName)) { 2476 final File scanFile = mExpectingBetter.valueAt(i); 2477 2478 logCriticalInfo(Log.WARN, "Expected better " + packageName 2479 + " but never showed up; reverting to system"); 2480 2481 int reparseFlags = mDefParseFlags; 2482 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2483 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2484 | PackageParser.PARSE_IS_SYSTEM_DIR 2485 | PackageParser.PARSE_IS_PRIVILEGED; 2486 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2487 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR; 2489 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2490 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2491 | PackageParser.PARSE_IS_SYSTEM_DIR; 2492 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2493 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2494 | PackageParser.PARSE_IS_SYSTEM_DIR; 2495 } else { 2496 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2497 continue; 2498 } 2499 2500 mSettings.enableSystemPackageLPw(packageName); 2501 2502 try { 2503 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2504 } catch (PackageManagerException e) { 2505 Slog.e(TAG, "Failed to parse original system package: " 2506 + e.getMessage()); 2507 } 2508 } 2509 } 2510 } 2511 mExpectingBetter.clear(); 2512 2513 // Resolve the storage manager. 2514 mStorageManagerPackage = getStorageManagerPackageName(); 2515 2516 // Resolve protected action filters. Only the setup wizard is allowed to 2517 // have a high priority filter for these actions. 2518 mSetupWizardPackage = getSetupWizardPackageName(); 2519 if (mProtectedFilters.size() > 0) { 2520 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2521 Slog.i(TAG, "No setup wizard;" 2522 + " All protected intents capped to priority 0"); 2523 } 2524 for (ActivityIntentInfo filter : mProtectedFilters) { 2525 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2526 if (DEBUG_FILTERS) { 2527 Slog.i(TAG, "Found setup wizard;" 2528 + " allow priority " + filter.getPriority() + ";" 2529 + " package: " + filter.activity.info.packageName 2530 + " activity: " + filter.activity.className 2531 + " priority: " + filter.getPriority()); 2532 } 2533 // skip setup wizard; allow it to keep the high priority filter 2534 continue; 2535 } 2536 Slog.w(TAG, "Protected action; cap priority to 0;" 2537 + " package: " + filter.activity.info.packageName 2538 + " activity: " + filter.activity.className 2539 + " origPrio: " + filter.getPriority()); 2540 filter.setPriority(0); 2541 } 2542 } 2543 mDeferProtectedFilters = false; 2544 mProtectedFilters.clear(); 2545 2546 // Now that we know all of the shared libraries, update all clients to have 2547 // the correct library paths. 2548 updateAllSharedLibrariesLPw(); 2549 2550 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2551 // NOTE: We ignore potential failures here during a system scan (like 2552 // the rest of the commands above) because there's precious little we 2553 // can do about it. A settings error is reported, though. 2554 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2555 false /* boot complete */); 2556 } 2557 2558 // Now that we know all the packages we are keeping, 2559 // read and update their last usage times. 2560 mPackageUsage.read(mPackages); 2561 mCompilerStats.read(); 2562 2563 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2564 SystemClock.uptimeMillis()); 2565 Slog.i(TAG, "Time to scan packages: " 2566 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2567 + " seconds"); 2568 2569 // If the platform SDK has changed since the last time we booted, 2570 // we need to re-grant app permission to catch any new ones that 2571 // appear. This is really a hack, and means that apps can in some 2572 // cases get permissions that the user didn't initially explicitly 2573 // allow... it would be nice to have some better way to handle 2574 // this situation. 2575 int updateFlags = UPDATE_PERMISSIONS_ALL; 2576 if (ver.sdkVersion != mSdkVersion) { 2577 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2578 + mSdkVersion + "; regranting permissions for internal storage"); 2579 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2580 } 2581 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2582 ver.sdkVersion = mSdkVersion; 2583 2584 // If this is the first boot or an update from pre-M, and it is a normal 2585 // boot, then we need to initialize the default preferred apps across 2586 // all defined users. 2587 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2588 for (UserInfo user : sUserManager.getUsers(true)) { 2589 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2590 applyFactoryDefaultBrowserLPw(user.id); 2591 primeDomainVerificationsLPw(user.id); 2592 } 2593 } 2594 2595 // Prepare storage for system user really early during boot, 2596 // since core system apps like SettingsProvider and SystemUI 2597 // can't wait for user to start 2598 final int storageFlags; 2599 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2600 storageFlags = StorageManager.FLAG_STORAGE_DE; 2601 } else { 2602 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2603 } 2604 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2605 storageFlags); 2606 2607 // If this is first boot after an OTA, and a normal boot, then 2608 // we need to clear code cache directories. 2609 // Note that we do *not* clear the application profiles. These remain valid 2610 // across OTAs and are used to drive profile verification (post OTA) and 2611 // profile compilation (without waiting to collect a fresh set of profiles). 2612 if (mIsUpgrade && !onlyCore) { 2613 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2614 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2615 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2616 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2617 // No apps are running this early, so no need to freeze 2618 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2619 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2620 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2621 } 2622 } 2623 ver.fingerprint = Build.FINGERPRINT; 2624 } 2625 2626 checkDefaultBrowser(); 2627 2628 // clear only after permissions and other defaults have been updated 2629 mExistingSystemPackages.clear(); 2630 mPromoteSystemApps = false; 2631 2632 // All the changes are done during package scanning. 2633 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2634 2635 // can downgrade to reader 2636 mSettings.writeLPr(); 2637 2638 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2639 // early on (before the package manager declares itself as early) because other 2640 // components in the system server might ask for package contexts for these apps. 2641 // 2642 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2643 // (i.e, that the data partition is unavailable). 2644 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2645 long start = System.nanoTime(); 2646 List<PackageParser.Package> coreApps = new ArrayList<>(); 2647 for (PackageParser.Package pkg : mPackages.values()) { 2648 if (pkg.coreApp) { 2649 coreApps.add(pkg); 2650 } 2651 } 2652 2653 int[] stats = performDexOptUpgrade(coreApps, false, 2654 getCompilerFilterForReason(REASON_CORE_APP)); 2655 2656 final int elapsedTimeSeconds = 2657 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2658 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2659 2660 if (DEBUG_DEXOPT) { 2661 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2662 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2663 } 2664 2665 2666 // TODO: Should we log these stats to tron too ? 2667 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2668 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2669 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2670 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2671 } 2672 2673 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2674 SystemClock.uptimeMillis()); 2675 2676 if (!mOnlyCore) { 2677 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2678 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2679 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2680 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2681 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2682 mIntentFilterVerifierComponent); 2683 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2684 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2685 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2686 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2687 } else { 2688 mRequiredVerifierPackage = null; 2689 mRequiredInstallerPackage = null; 2690 mRequiredUninstallerPackage = null; 2691 mIntentFilterVerifierComponent = null; 2692 mIntentFilterVerifier = null; 2693 mServicesSystemSharedLibraryPackageName = null; 2694 mSharedSystemSharedLibraryPackageName = null; 2695 } 2696 2697 mInstallerService = new PackageInstallerService(context, this); 2698 2699 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2700 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2701 // both the installer and resolver must be present to enable ephemeral 2702 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2703 if (DEBUG_EPHEMERAL) { 2704 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2705 + " installer:" + ephemeralInstallerComponent); 2706 } 2707 mEphemeralResolverComponent = ephemeralResolverComponent; 2708 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2709 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2710 mEphemeralResolverConnection = 2711 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2712 } else { 2713 if (DEBUG_EPHEMERAL) { 2714 final String missingComponent = 2715 (ephemeralResolverComponent == null) 2716 ? (ephemeralInstallerComponent == null) 2717 ? "resolver and installer" 2718 : "resolver" 2719 : "installer"; 2720 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2721 } 2722 mEphemeralResolverComponent = null; 2723 mEphemeralInstallerComponent = null; 2724 mEphemeralResolverConnection = null; 2725 } 2726 2727 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2728 } // synchronized (mPackages) 2729 } // synchronized (mInstallLock) 2730 2731 // Now after opening every single application zip, make sure they 2732 // are all flushed. Not really needed, but keeps things nice and 2733 // tidy. 2734 Runtime.getRuntime().gc(); 2735 2736 // The initial scanning above does many calls into installd while 2737 // holding the mPackages lock, but we're mostly interested in yelling 2738 // once we have a booted system. 2739 mInstaller.setWarnIfHeld(mPackages); 2740 2741 // Expose private service for system components to use. 2742 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2743 } 2744 2745 @Override 2746 public boolean isFirstBoot() { 2747 return mFirstBoot; 2748 } 2749 2750 @Override 2751 public boolean isOnlyCoreApps() { 2752 return mOnlyCore; 2753 } 2754 2755 @Override 2756 public boolean isUpgrade() { 2757 return mIsUpgrade; 2758 } 2759 2760 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2761 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2762 2763 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2764 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2765 UserHandle.USER_SYSTEM); 2766 if (matches.size() == 1) { 2767 return matches.get(0).getComponentInfo().packageName; 2768 } else if (matches.size() == 0) { 2769 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2770 return null; 2771 } 2772 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2773 } 2774 2775 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2776 synchronized (mPackages) { 2777 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2778 if (libraryEntry == null) { 2779 throw new IllegalStateException("Missing required shared library:" + libraryName); 2780 } 2781 return libraryEntry.apk; 2782 } 2783 } 2784 2785 private @NonNull String getRequiredInstallerLPr() { 2786 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2787 intent.addCategory(Intent.CATEGORY_DEFAULT); 2788 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2789 2790 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2791 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2792 UserHandle.USER_SYSTEM); 2793 if (matches.size() == 1) { 2794 ResolveInfo resolveInfo = matches.get(0); 2795 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2796 throw new RuntimeException("The installer must be a privileged app"); 2797 } 2798 return matches.get(0).getComponentInfo().packageName; 2799 } else { 2800 throw new RuntimeException("There must be exactly one installer; found " + matches); 2801 } 2802 } 2803 2804 private @NonNull String getRequiredUninstallerLPr() { 2805 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2806 intent.addCategory(Intent.CATEGORY_DEFAULT); 2807 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2808 2809 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2810 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2811 UserHandle.USER_SYSTEM); 2812 if (resolveInfo == null || 2813 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2814 throw new RuntimeException("There must be exactly one uninstaller; found " 2815 + resolveInfo); 2816 } 2817 return resolveInfo.getComponentInfo().packageName; 2818 } 2819 2820 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2821 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2822 2823 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2824 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2825 UserHandle.USER_SYSTEM); 2826 ResolveInfo best = null; 2827 final int N = matches.size(); 2828 for (int i = 0; i < N; i++) { 2829 final ResolveInfo cur = matches.get(i); 2830 final String packageName = cur.getComponentInfo().packageName; 2831 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2832 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2833 continue; 2834 } 2835 2836 if (best == null || cur.priority > best.priority) { 2837 best = cur; 2838 } 2839 } 2840 2841 if (best != null) { 2842 return best.getComponentInfo().getComponentName(); 2843 } else { 2844 throw new RuntimeException("There must be at least one intent filter verifier"); 2845 } 2846 } 2847 2848 private @Nullable ComponentName getEphemeralResolverLPr() { 2849 final String[] packageArray = 2850 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2851 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2852 if (DEBUG_EPHEMERAL) { 2853 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2854 } 2855 return null; 2856 } 2857 2858 final int resolveFlags = 2859 MATCH_DIRECT_BOOT_AWARE 2860 | MATCH_DIRECT_BOOT_UNAWARE 2861 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2862 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2863 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2864 resolveFlags, UserHandle.USER_SYSTEM); 2865 2866 final int N = resolvers.size(); 2867 if (N == 0) { 2868 if (DEBUG_EPHEMERAL) { 2869 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2870 } 2871 return null; 2872 } 2873 2874 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2875 for (int i = 0; i < N; i++) { 2876 final ResolveInfo info = resolvers.get(i); 2877 2878 if (info.serviceInfo == null) { 2879 continue; 2880 } 2881 2882 final String packageName = info.serviceInfo.packageName; 2883 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2884 if (DEBUG_EPHEMERAL) { 2885 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2886 + " pkg: " + packageName + ", info:" + info); 2887 } 2888 continue; 2889 } 2890 2891 if (DEBUG_EPHEMERAL) { 2892 Slog.v(TAG, "Ephemeral resolver found;" 2893 + " pkg: " + packageName + ", info:" + info); 2894 } 2895 return new ComponentName(packageName, info.serviceInfo.name); 2896 } 2897 if (DEBUG_EPHEMERAL) { 2898 Slog.v(TAG, "Ephemeral resolver NOT found"); 2899 } 2900 return null; 2901 } 2902 2903 private @Nullable ComponentName getEphemeralInstallerLPr() { 2904 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2905 intent.addCategory(Intent.CATEGORY_DEFAULT); 2906 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2907 2908 final int resolveFlags = 2909 MATCH_DIRECT_BOOT_AWARE 2910 | MATCH_DIRECT_BOOT_UNAWARE 2911 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2912 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2913 resolveFlags, UserHandle.USER_SYSTEM); 2914 if (matches.size() == 0) { 2915 return null; 2916 } else if (matches.size() == 1) { 2917 return matches.get(0).getComponentInfo().getComponentName(); 2918 } else { 2919 throw new RuntimeException( 2920 "There must be at most one ephemeral installer; found " + matches); 2921 } 2922 } 2923 2924 private void primeDomainVerificationsLPw(int userId) { 2925 if (DEBUG_DOMAIN_VERIFICATION) { 2926 Slog.d(TAG, "Priming domain verifications in user " + userId); 2927 } 2928 2929 SystemConfig systemConfig = SystemConfig.getInstance(); 2930 ArraySet<String> packages = systemConfig.getLinkedApps(); 2931 ArraySet<String> domains = new ArraySet<String>(); 2932 2933 for (String packageName : packages) { 2934 PackageParser.Package pkg = mPackages.get(packageName); 2935 if (pkg != null) { 2936 if (!pkg.isSystemApp()) { 2937 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2938 continue; 2939 } 2940 2941 domains.clear(); 2942 for (PackageParser.Activity a : pkg.activities) { 2943 for (ActivityIntentInfo filter : a.intents) { 2944 if (hasValidDomains(filter)) { 2945 domains.addAll(filter.getHostsList()); 2946 } 2947 } 2948 } 2949 2950 if (domains.size() > 0) { 2951 if (DEBUG_DOMAIN_VERIFICATION) { 2952 Slog.v(TAG, " + " + packageName); 2953 } 2954 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2955 // state w.r.t. the formal app-linkage "no verification attempted" state; 2956 // and then 'always' in the per-user state actually used for intent resolution. 2957 final IntentFilterVerificationInfo ivi; 2958 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2959 new ArrayList<String>(domains)); 2960 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2961 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2962 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2963 } else { 2964 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2965 + "' does not handle web links"); 2966 } 2967 } else { 2968 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2969 } 2970 } 2971 2972 scheduleWritePackageRestrictionsLocked(userId); 2973 scheduleWriteSettingsLocked(); 2974 } 2975 2976 private void applyFactoryDefaultBrowserLPw(int userId) { 2977 // The default browser app's package name is stored in a string resource, 2978 // with a product-specific overlay used for vendor customization. 2979 String browserPkg = mContext.getResources().getString( 2980 com.android.internal.R.string.default_browser); 2981 if (!TextUtils.isEmpty(browserPkg)) { 2982 // non-empty string => required to be a known package 2983 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2984 if (ps == null) { 2985 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2986 browserPkg = null; 2987 } else { 2988 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2989 } 2990 } 2991 2992 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2993 // default. If there's more than one, just leave everything alone. 2994 if (browserPkg == null) { 2995 calculateDefaultBrowserLPw(userId); 2996 } 2997 } 2998 2999 private void calculateDefaultBrowserLPw(int userId) { 3000 List<String> allBrowsers = resolveAllBrowserApps(userId); 3001 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3002 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3003 } 3004 3005 private List<String> resolveAllBrowserApps(int userId) { 3006 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3007 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3008 PackageManager.MATCH_ALL, userId); 3009 3010 final int count = list.size(); 3011 List<String> result = new ArrayList<String>(count); 3012 for (int i=0; i<count; i++) { 3013 ResolveInfo info = list.get(i); 3014 if (info.activityInfo == null 3015 || !info.handleAllWebDataURI 3016 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3017 || result.contains(info.activityInfo.packageName)) { 3018 continue; 3019 } 3020 result.add(info.activityInfo.packageName); 3021 } 3022 3023 return result; 3024 } 3025 3026 private boolean packageIsBrowser(String packageName, int userId) { 3027 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3028 PackageManager.MATCH_ALL, userId); 3029 final int N = list.size(); 3030 for (int i = 0; i < N; i++) { 3031 ResolveInfo info = list.get(i); 3032 if (packageName.equals(info.activityInfo.packageName)) { 3033 return true; 3034 } 3035 } 3036 return false; 3037 } 3038 3039 private void checkDefaultBrowser() { 3040 final int myUserId = UserHandle.myUserId(); 3041 final String packageName = getDefaultBrowserPackageName(myUserId); 3042 if (packageName != null) { 3043 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3044 if (info == null) { 3045 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3046 synchronized (mPackages) { 3047 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3048 } 3049 } 3050 } 3051 } 3052 3053 @Override 3054 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3055 throws RemoteException { 3056 try { 3057 return super.onTransact(code, data, reply, flags); 3058 } catch (RuntimeException e) { 3059 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3060 Slog.wtf(TAG, "Package Manager Crash", e); 3061 } 3062 throw e; 3063 } 3064 } 3065 3066 static int[] appendInts(int[] cur, int[] add) { 3067 if (add == null) return cur; 3068 if (cur == null) return add; 3069 final int N = add.length; 3070 for (int i=0; i<N; i++) { 3071 cur = appendInt(cur, add[i]); 3072 } 3073 return cur; 3074 } 3075 3076 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3077 if (!sUserManager.exists(userId)) return null; 3078 if (ps == null) { 3079 return null; 3080 } 3081 final PackageParser.Package p = ps.pkg; 3082 if (p == null) { 3083 return null; 3084 } 3085 3086 final PermissionsState permissionsState = ps.getPermissionsState(); 3087 3088 // Compute GIDs only if requested 3089 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3090 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3091 // Compute granted permissions only if package has requested permissions 3092 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3093 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3094 final PackageUserState state = ps.readUserState(userId); 3095 3096 return PackageParser.generatePackageInfo(p, gids, flags, 3097 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3098 } 3099 3100 @Override 3101 public void checkPackageStartable(String packageName, int userId) { 3102 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3103 3104 synchronized (mPackages) { 3105 final PackageSetting ps = mSettings.mPackages.get(packageName); 3106 if (ps == null) { 3107 throw new SecurityException("Package " + packageName + " was not found!"); 3108 } 3109 3110 if (!ps.getInstalled(userId)) { 3111 throw new SecurityException( 3112 "Package " + packageName + " was not installed for user " + userId + "!"); 3113 } 3114 3115 if (mSafeMode && !ps.isSystem()) { 3116 throw new SecurityException("Package " + packageName + " not a system app!"); 3117 } 3118 3119 if (mFrozenPackages.contains(packageName)) { 3120 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3121 } 3122 3123 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3124 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3125 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3126 } 3127 } 3128 } 3129 3130 @Override 3131 public boolean isPackageAvailable(String packageName, int userId) { 3132 if (!sUserManager.exists(userId)) return false; 3133 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3134 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3135 synchronized (mPackages) { 3136 PackageParser.Package p = mPackages.get(packageName); 3137 if (p != null) { 3138 final PackageSetting ps = (PackageSetting) p.mExtras; 3139 if (ps != null) { 3140 final PackageUserState state = ps.readUserState(userId); 3141 if (state != null) { 3142 return PackageParser.isAvailable(state); 3143 } 3144 } 3145 } 3146 } 3147 return false; 3148 } 3149 3150 @Override 3151 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3152 if (!sUserManager.exists(userId)) return null; 3153 flags = updateFlagsForPackage(flags, userId, packageName); 3154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3155 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3156 3157 // reader 3158 synchronized (mPackages) { 3159 // Normalize package name to hanlde renamed packages 3160 packageName = normalizePackageNameLPr(packageName); 3161 3162 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3163 PackageParser.Package p = null; 3164 if (matchFactoryOnly) { 3165 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3166 if (ps != null) { 3167 return generatePackageInfo(ps, flags, userId); 3168 } 3169 } 3170 if (p == null) { 3171 p = mPackages.get(packageName); 3172 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3173 return null; 3174 } 3175 } 3176 if (DEBUG_PACKAGE_INFO) 3177 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3178 if (p != null) { 3179 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3180 } 3181 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3182 final PackageSetting ps = mSettings.mPackages.get(packageName); 3183 return generatePackageInfo(ps, flags, userId); 3184 } 3185 } 3186 return null; 3187 } 3188 3189 @Override 3190 public String[] currentToCanonicalPackageNames(String[] names) { 3191 String[] out = new String[names.length]; 3192 // reader 3193 synchronized (mPackages) { 3194 for (int i=names.length-1; i>=0; i--) { 3195 PackageSetting ps = mSettings.mPackages.get(names[i]); 3196 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3197 } 3198 } 3199 return out; 3200 } 3201 3202 @Override 3203 public String[] canonicalToCurrentPackageNames(String[] names) { 3204 String[] out = new String[names.length]; 3205 // reader 3206 synchronized (mPackages) { 3207 for (int i=names.length-1; i>=0; i--) { 3208 String cur = mSettings.mRenamedPackages.get(names[i]); 3209 out[i] = cur != null ? cur : names[i]; 3210 } 3211 } 3212 return out; 3213 } 3214 3215 @Override 3216 public int getPackageUid(String packageName, int flags, int userId) { 3217 if (!sUserManager.exists(userId)) return -1; 3218 flags = updateFlagsForPackage(flags, userId, packageName); 3219 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3220 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3221 3222 // reader 3223 synchronized (mPackages) { 3224 final PackageParser.Package p = mPackages.get(packageName); 3225 if (p != null && p.isMatch(flags)) { 3226 return UserHandle.getUid(userId, p.applicationInfo.uid); 3227 } 3228 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3229 final PackageSetting ps = mSettings.mPackages.get(packageName); 3230 if (ps != null && ps.isMatch(flags)) { 3231 return UserHandle.getUid(userId, ps.appId); 3232 } 3233 } 3234 } 3235 3236 return -1; 3237 } 3238 3239 @Override 3240 public int[] getPackageGids(String packageName, int flags, int userId) { 3241 if (!sUserManager.exists(userId)) return null; 3242 flags = updateFlagsForPackage(flags, userId, packageName); 3243 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3244 false /* requireFullPermission */, false /* checkShell */, 3245 "getPackageGids"); 3246 3247 // reader 3248 synchronized (mPackages) { 3249 final PackageParser.Package p = mPackages.get(packageName); 3250 if (p != null && p.isMatch(flags)) { 3251 PackageSetting ps = (PackageSetting) p.mExtras; 3252 return ps.getPermissionsState().computeGids(userId); 3253 } 3254 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3255 final PackageSetting ps = mSettings.mPackages.get(packageName); 3256 if (ps != null && ps.isMatch(flags)) { 3257 return ps.getPermissionsState().computeGids(userId); 3258 } 3259 } 3260 } 3261 3262 return null; 3263 } 3264 3265 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3266 if (bp.perm != null) { 3267 return PackageParser.generatePermissionInfo(bp.perm, flags); 3268 } 3269 PermissionInfo pi = new PermissionInfo(); 3270 pi.name = bp.name; 3271 pi.packageName = bp.sourcePackage; 3272 pi.nonLocalizedLabel = bp.name; 3273 pi.protectionLevel = bp.protectionLevel; 3274 return pi; 3275 } 3276 3277 @Override 3278 public PermissionInfo getPermissionInfo(String name, int flags) { 3279 // reader 3280 synchronized (mPackages) { 3281 final BasePermission p = mSettings.mPermissions.get(name); 3282 if (p != null) { 3283 return generatePermissionInfo(p, flags); 3284 } 3285 return null; 3286 } 3287 } 3288 3289 @Override 3290 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3291 int flags) { 3292 // reader 3293 synchronized (mPackages) { 3294 if (group != null && !mPermissionGroups.containsKey(group)) { 3295 // This is thrown as NameNotFoundException 3296 return null; 3297 } 3298 3299 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3300 for (BasePermission p : mSettings.mPermissions.values()) { 3301 if (group == null) { 3302 if (p.perm == null || p.perm.info.group == null) { 3303 out.add(generatePermissionInfo(p, flags)); 3304 } 3305 } else { 3306 if (p.perm != null && group.equals(p.perm.info.group)) { 3307 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3308 } 3309 } 3310 } 3311 return new ParceledListSlice<>(out); 3312 } 3313 } 3314 3315 @Override 3316 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3317 // reader 3318 synchronized (mPackages) { 3319 return PackageParser.generatePermissionGroupInfo( 3320 mPermissionGroups.get(name), flags); 3321 } 3322 } 3323 3324 @Override 3325 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3326 // reader 3327 synchronized (mPackages) { 3328 final int N = mPermissionGroups.size(); 3329 ArrayList<PermissionGroupInfo> out 3330 = new ArrayList<PermissionGroupInfo>(N); 3331 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3332 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3333 } 3334 return new ParceledListSlice<>(out); 3335 } 3336 } 3337 3338 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3339 int userId) { 3340 if (!sUserManager.exists(userId)) return null; 3341 PackageSetting ps = mSettings.mPackages.get(packageName); 3342 if (ps != null) { 3343 if (ps.pkg == null) { 3344 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3345 if (pInfo != null) { 3346 return pInfo.applicationInfo; 3347 } 3348 return null; 3349 } 3350 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3351 ps.readUserState(userId), userId); 3352 } 3353 return null; 3354 } 3355 3356 @Override 3357 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3358 if (!sUserManager.exists(userId)) return null; 3359 flags = updateFlagsForApplication(flags, userId, packageName); 3360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3361 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3362 3363 // writer 3364 synchronized (mPackages) { 3365 // Normalize package name to hanlde renamed packages 3366 packageName = normalizePackageNameLPr(packageName); 3367 3368 PackageParser.Package p = mPackages.get(packageName); 3369 if (DEBUG_PACKAGE_INFO) Log.v( 3370 TAG, "getApplicationInfo " + packageName 3371 + ": " + p); 3372 if (p != null) { 3373 PackageSetting ps = mSettings.mPackages.get(packageName); 3374 if (ps == null) return null; 3375 // Note: isEnabledLP() does not apply here - always return info 3376 return PackageParser.generateApplicationInfo( 3377 p, flags, ps.readUserState(userId), userId); 3378 } 3379 if ("android".equals(packageName)||"system".equals(packageName)) { 3380 return mAndroidApplication; 3381 } 3382 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3383 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3384 } 3385 } 3386 return null; 3387 } 3388 3389 private String normalizePackageNameLPr(String packageName) { 3390 String normalizedPackageName = mSettings.mRenamedPackages.get(packageName); 3391 return normalizedPackageName != null ? normalizedPackageName : packageName; 3392 } 3393 3394 @Override 3395 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3396 final IPackageDataObserver observer) { 3397 mContext.enforceCallingOrSelfPermission( 3398 android.Manifest.permission.CLEAR_APP_CACHE, null); 3399 // Queue up an async operation since clearing cache may take a little while. 3400 mHandler.post(new Runnable() { 3401 public void run() { 3402 mHandler.removeCallbacks(this); 3403 boolean success = true; 3404 synchronized (mInstallLock) { 3405 try { 3406 mInstaller.freeCache(volumeUuid, freeStorageSize); 3407 } catch (InstallerException e) { 3408 Slog.w(TAG, "Couldn't clear application caches: " + e); 3409 success = false; 3410 } 3411 } 3412 if (observer != null) { 3413 try { 3414 observer.onRemoveCompleted(null, success); 3415 } catch (RemoteException e) { 3416 Slog.w(TAG, "RemoveException when invoking call back"); 3417 } 3418 } 3419 } 3420 }); 3421 } 3422 3423 @Override 3424 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3425 final IntentSender pi) { 3426 mContext.enforceCallingOrSelfPermission( 3427 android.Manifest.permission.CLEAR_APP_CACHE, null); 3428 // Queue up an async operation since clearing cache may take a little while. 3429 mHandler.post(new Runnable() { 3430 public void run() { 3431 mHandler.removeCallbacks(this); 3432 boolean success = true; 3433 synchronized (mInstallLock) { 3434 try { 3435 mInstaller.freeCache(volumeUuid, freeStorageSize); 3436 } catch (InstallerException e) { 3437 Slog.w(TAG, "Couldn't clear application caches: " + e); 3438 success = false; 3439 } 3440 } 3441 if(pi != null) { 3442 try { 3443 // Callback via pending intent 3444 int code = success ? 1 : 0; 3445 pi.sendIntent(null, code, null, 3446 null, null); 3447 } catch (SendIntentException e1) { 3448 Slog.i(TAG, "Failed to send pending intent"); 3449 } 3450 } 3451 } 3452 }); 3453 } 3454 3455 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3456 synchronized (mInstallLock) { 3457 try { 3458 mInstaller.freeCache(volumeUuid, freeStorageSize); 3459 } catch (InstallerException e) { 3460 throw new IOException("Failed to free enough space", e); 3461 } 3462 } 3463 } 3464 3465 /** 3466 * Update given flags based on encryption status of current user. 3467 */ 3468 private int updateFlags(int flags, int userId) { 3469 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3470 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3471 // Caller expressed an explicit opinion about what encryption 3472 // aware/unaware components they want to see, so fall through and 3473 // give them what they want 3474 } else { 3475 // Caller expressed no opinion, so match based on user state 3476 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3477 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3478 } else { 3479 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3480 } 3481 } 3482 return flags; 3483 } 3484 3485 private UserManagerInternal getUserManagerInternal() { 3486 if (mUserManagerInternal == null) { 3487 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3488 } 3489 return mUserManagerInternal; 3490 } 3491 3492 /** 3493 * Update given flags when being used to request {@link PackageInfo}. 3494 */ 3495 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3496 boolean triaged = true; 3497 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3498 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3499 // Caller is asking for component details, so they'd better be 3500 // asking for specific encryption matching behavior, or be triaged 3501 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3502 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3503 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3504 triaged = false; 3505 } 3506 } 3507 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3508 | PackageManager.MATCH_SYSTEM_ONLY 3509 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3510 triaged = false; 3511 } 3512 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3513 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3514 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3515 } 3516 return updateFlags(flags, userId); 3517 } 3518 3519 /** 3520 * Update given flags when being used to request {@link ApplicationInfo}. 3521 */ 3522 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3523 return updateFlagsForPackage(flags, userId, cookie); 3524 } 3525 3526 /** 3527 * Update given flags when being used to request {@link ComponentInfo}. 3528 */ 3529 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3530 if (cookie instanceof Intent) { 3531 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3532 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3533 } 3534 } 3535 3536 boolean triaged = true; 3537 // Caller is asking for component details, so they'd better be 3538 // asking for specific encryption matching behavior, or be triaged 3539 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3540 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3541 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3542 triaged = false; 3543 } 3544 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3545 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3546 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3547 } 3548 3549 return updateFlags(flags, userId); 3550 } 3551 3552 /** 3553 * Update given flags when being used to request {@link ResolveInfo}. 3554 */ 3555 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3556 // Safe mode means we shouldn't match any third-party components 3557 if (mSafeMode) { 3558 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3559 } 3560 3561 return updateFlagsForComponent(flags, userId, cookie); 3562 } 3563 3564 @Override 3565 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3566 if (!sUserManager.exists(userId)) return null; 3567 flags = updateFlagsForComponent(flags, userId, component); 3568 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3569 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3570 synchronized (mPackages) { 3571 PackageParser.Activity a = mActivities.mActivities.get(component); 3572 3573 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3574 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3575 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3576 if (ps == null) return null; 3577 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3578 userId); 3579 } 3580 if (mResolveComponentName.equals(component)) { 3581 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3582 new PackageUserState(), userId); 3583 } 3584 } 3585 return null; 3586 } 3587 3588 @Override 3589 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3590 String resolvedType) { 3591 synchronized (mPackages) { 3592 if (component.equals(mResolveComponentName)) { 3593 // The resolver supports EVERYTHING! 3594 return true; 3595 } 3596 PackageParser.Activity a = mActivities.mActivities.get(component); 3597 if (a == null) { 3598 return false; 3599 } 3600 for (int i=0; i<a.intents.size(); i++) { 3601 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3602 intent.getData(), intent.getCategories(), TAG) >= 0) { 3603 return true; 3604 } 3605 } 3606 return false; 3607 } 3608 } 3609 3610 @Override 3611 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3612 if (!sUserManager.exists(userId)) return null; 3613 flags = updateFlagsForComponent(flags, userId, component); 3614 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3615 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3616 synchronized (mPackages) { 3617 PackageParser.Activity a = mReceivers.mActivities.get(component); 3618 if (DEBUG_PACKAGE_INFO) Log.v( 3619 TAG, "getReceiverInfo " + component + ": " + a); 3620 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3621 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3622 if (ps == null) return null; 3623 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3624 userId); 3625 } 3626 } 3627 return null; 3628 } 3629 3630 @Override 3631 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3632 if (!sUserManager.exists(userId)) return null; 3633 flags = updateFlagsForComponent(flags, userId, component); 3634 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3635 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3636 synchronized (mPackages) { 3637 PackageParser.Service s = mServices.mServices.get(component); 3638 if (DEBUG_PACKAGE_INFO) Log.v( 3639 TAG, "getServiceInfo " + component + ": " + s); 3640 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3641 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3642 if (ps == null) return null; 3643 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3644 userId); 3645 } 3646 } 3647 return null; 3648 } 3649 3650 @Override 3651 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3652 if (!sUserManager.exists(userId)) return null; 3653 flags = updateFlagsForComponent(flags, userId, component); 3654 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3655 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3656 synchronized (mPackages) { 3657 PackageParser.Provider p = mProviders.mProviders.get(component); 3658 if (DEBUG_PACKAGE_INFO) Log.v( 3659 TAG, "getProviderInfo " + component + ": " + p); 3660 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3661 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3662 if (ps == null) return null; 3663 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3664 userId); 3665 } 3666 } 3667 return null; 3668 } 3669 3670 @Override 3671 public String[] getSystemSharedLibraryNames() { 3672 Set<String> libSet; 3673 synchronized (mPackages) { 3674 libSet = mSharedLibraries.keySet(); 3675 int size = libSet.size(); 3676 if (size > 0) { 3677 String[] libs = new String[size]; 3678 libSet.toArray(libs); 3679 return libs; 3680 } 3681 } 3682 return null; 3683 } 3684 3685 @Override 3686 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3687 synchronized (mPackages) { 3688 return mServicesSystemSharedLibraryPackageName; 3689 } 3690 } 3691 3692 @Override 3693 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3694 synchronized (mPackages) { 3695 return mSharedSystemSharedLibraryPackageName; 3696 } 3697 } 3698 3699 @Override 3700 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3701 synchronized (mPackages) { 3702 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3703 3704 final FeatureInfo fi = new FeatureInfo(); 3705 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3706 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3707 res.add(fi); 3708 3709 return new ParceledListSlice<>(res); 3710 } 3711 } 3712 3713 @Override 3714 public boolean hasSystemFeature(String name, int version) { 3715 synchronized (mPackages) { 3716 final FeatureInfo feat = mAvailableFeatures.get(name); 3717 if (feat == null) { 3718 return false; 3719 } else { 3720 return feat.version >= version; 3721 } 3722 } 3723 } 3724 3725 @Override 3726 public int checkPermission(String permName, String pkgName, int userId) { 3727 if (!sUserManager.exists(userId)) { 3728 return PackageManager.PERMISSION_DENIED; 3729 } 3730 3731 synchronized (mPackages) { 3732 final PackageParser.Package p = mPackages.get(pkgName); 3733 if (p != null && p.mExtras != null) { 3734 final PackageSetting ps = (PackageSetting) p.mExtras; 3735 final PermissionsState permissionsState = ps.getPermissionsState(); 3736 if (permissionsState.hasPermission(permName, userId)) { 3737 return PackageManager.PERMISSION_GRANTED; 3738 } 3739 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3740 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3741 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3742 return PackageManager.PERMISSION_GRANTED; 3743 } 3744 } 3745 } 3746 3747 return PackageManager.PERMISSION_DENIED; 3748 } 3749 3750 @Override 3751 public int checkUidPermission(String permName, int uid) { 3752 final int userId = UserHandle.getUserId(uid); 3753 3754 if (!sUserManager.exists(userId)) { 3755 return PackageManager.PERMISSION_DENIED; 3756 } 3757 3758 synchronized (mPackages) { 3759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3760 if (obj != null) { 3761 final SettingBase ps = (SettingBase) obj; 3762 final PermissionsState permissionsState = ps.getPermissionsState(); 3763 if (permissionsState.hasPermission(permName, userId)) { 3764 return PackageManager.PERMISSION_GRANTED; 3765 } 3766 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3767 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3768 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3769 return PackageManager.PERMISSION_GRANTED; 3770 } 3771 } else { 3772 ArraySet<String> perms = mSystemPermissions.get(uid); 3773 if (perms != null) { 3774 if (perms.contains(permName)) { 3775 return PackageManager.PERMISSION_GRANTED; 3776 } 3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3778 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 } 3782 } 3783 } 3784 3785 return PackageManager.PERMISSION_DENIED; 3786 } 3787 3788 @Override 3789 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3790 if (UserHandle.getCallingUserId() != userId) { 3791 mContext.enforceCallingPermission( 3792 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3793 "isPermissionRevokedByPolicy for user " + userId); 3794 } 3795 3796 if (checkPermission(permission, packageName, userId) 3797 == PackageManager.PERMISSION_GRANTED) { 3798 return false; 3799 } 3800 3801 final long identity = Binder.clearCallingIdentity(); 3802 try { 3803 final int flags = getPermissionFlags(permission, packageName, userId); 3804 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3805 } finally { 3806 Binder.restoreCallingIdentity(identity); 3807 } 3808 } 3809 3810 @Override 3811 public String getPermissionControllerPackageName() { 3812 synchronized (mPackages) { 3813 return mRequiredInstallerPackage; 3814 } 3815 } 3816 3817 /** 3818 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3819 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3820 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3821 * @param message the message to log on security exception 3822 */ 3823 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3824 boolean checkShell, String message) { 3825 if (userId < 0) { 3826 throw new IllegalArgumentException("Invalid userId " + userId); 3827 } 3828 if (checkShell) { 3829 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3830 } 3831 if (userId == UserHandle.getUserId(callingUid)) return; 3832 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3833 if (requireFullPermission) { 3834 mContext.enforceCallingOrSelfPermission( 3835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3836 } else { 3837 try { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3840 } catch (SecurityException se) { 3841 mContext.enforceCallingOrSelfPermission( 3842 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3843 } 3844 } 3845 } 3846 } 3847 3848 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3849 if (callingUid == Process.SHELL_UID) { 3850 if (userHandle >= 0 3851 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3852 throw new SecurityException("Shell does not have permission to access user " 3853 + userHandle); 3854 } else if (userHandle < 0) { 3855 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3856 + Debug.getCallers(3)); 3857 } 3858 } 3859 } 3860 3861 private BasePermission findPermissionTreeLP(String permName) { 3862 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3863 if (permName.startsWith(bp.name) && 3864 permName.length() > bp.name.length() && 3865 permName.charAt(bp.name.length()) == '.') { 3866 return bp; 3867 } 3868 } 3869 return null; 3870 } 3871 3872 private BasePermission checkPermissionTreeLP(String permName) { 3873 if (permName != null) { 3874 BasePermission bp = findPermissionTreeLP(permName); 3875 if (bp != null) { 3876 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3877 return bp; 3878 } 3879 throw new SecurityException("Calling uid " 3880 + Binder.getCallingUid() 3881 + " is not allowed to add to permission tree " 3882 + bp.name + " owned by uid " + bp.uid); 3883 } 3884 } 3885 throw new SecurityException("No permission tree found for " + permName); 3886 } 3887 3888 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3889 if (s1 == null) { 3890 return s2 == null; 3891 } 3892 if (s2 == null) { 3893 return false; 3894 } 3895 if (s1.getClass() != s2.getClass()) { 3896 return false; 3897 } 3898 return s1.equals(s2); 3899 } 3900 3901 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3902 if (pi1.icon != pi2.icon) return false; 3903 if (pi1.logo != pi2.logo) return false; 3904 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3905 if (!compareStrings(pi1.name, pi2.name)) return false; 3906 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3907 // We'll take care of setting this one. 3908 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3909 // These are not currently stored in settings. 3910 //if (!compareStrings(pi1.group, pi2.group)) return false; 3911 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3912 //if (pi1.labelRes != pi2.labelRes) return false; 3913 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3914 return true; 3915 } 3916 3917 int permissionInfoFootprint(PermissionInfo info) { 3918 int size = info.name.length(); 3919 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3920 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3921 return size; 3922 } 3923 3924 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3925 int size = 0; 3926 for (BasePermission perm : mSettings.mPermissions.values()) { 3927 if (perm.uid == tree.uid) { 3928 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3929 } 3930 } 3931 return size; 3932 } 3933 3934 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3935 // We calculate the max size of permissions defined by this uid and throw 3936 // if that plus the size of 'info' would exceed our stated maximum. 3937 if (tree.uid != Process.SYSTEM_UID) { 3938 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3939 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3940 throw new SecurityException("Permission tree size cap exceeded"); 3941 } 3942 } 3943 } 3944 3945 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3946 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3947 throw new SecurityException("Label must be specified in permission"); 3948 } 3949 BasePermission tree = checkPermissionTreeLP(info.name); 3950 BasePermission bp = mSettings.mPermissions.get(info.name); 3951 boolean added = bp == null; 3952 boolean changed = true; 3953 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3954 if (added) { 3955 enforcePermissionCapLocked(info, tree); 3956 bp = new BasePermission(info.name, tree.sourcePackage, 3957 BasePermission.TYPE_DYNAMIC); 3958 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3959 throw new SecurityException( 3960 "Not allowed to modify non-dynamic permission " 3961 + info.name); 3962 } else { 3963 if ((bp.perm == null) || (tree.perm == null)) { 3964 Slog.w(TAG, "Base or tree permission is null: " + bp.perm + ", " + tree.perm); 3965 return false; 3966 } 3967 if (bp.protectionLevel == fixedLevel 3968 && bp.perm.owner.equals(tree.perm.owner) 3969 && bp.uid == tree.uid 3970 && comparePermissionInfos(bp.perm.info, info)) { 3971 changed = false; 3972 } 3973 } 3974 bp.protectionLevel = fixedLevel; 3975 info = new PermissionInfo(info); 3976 info.protectionLevel = fixedLevel; 3977 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3978 bp.perm.info.packageName = tree.perm.info.packageName; 3979 bp.uid = tree.uid; 3980 if (added) { 3981 mSettings.mPermissions.put(info.name, bp); 3982 } 3983 if (changed) { 3984 if (!async) { 3985 mSettings.writeLPr(); 3986 } else { 3987 scheduleWriteSettingsLocked(); 3988 } 3989 } 3990 return added; 3991 } 3992 3993 @Override 3994 public boolean addPermission(PermissionInfo info) { 3995 synchronized (mPackages) { 3996 return addPermissionLocked(info, false); 3997 } 3998 } 3999 4000 @Override 4001 public boolean addPermissionAsync(PermissionInfo info) { 4002 synchronized (mPackages) { 4003 return addPermissionLocked(info, true); 4004 } 4005 } 4006 4007 @Override 4008 public void removePermission(String name) { 4009 synchronized (mPackages) { 4010 checkPermissionTreeLP(name); 4011 BasePermission bp = mSettings.mPermissions.get(name); 4012 if (bp != null) { 4013 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4014 throw new SecurityException( 4015 "Not allowed to modify non-dynamic permission " 4016 + name); 4017 } 4018 mSettings.mPermissions.remove(name); 4019 mSettings.writeLPr(); 4020 } 4021 } 4022 } 4023 4024 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4025 BasePermission bp) { 4026 int index = pkg.requestedPermissions.indexOf(bp.name); 4027 if (index == -1) { 4028 throw new SecurityException("Package " + pkg.packageName 4029 + " has not requested permission " + bp.name); 4030 } 4031 if (!bp.isRuntime() && !bp.isDevelopment()) { 4032 throw new SecurityException("Permission " + bp.name 4033 + " is not a changeable permission type"); 4034 } 4035 } 4036 4037 @Override 4038 public void grantRuntimePermission(String packageName, String name, final int userId) { 4039 if (!sUserManager.exists(userId)) { 4040 Log.e(TAG, "No such user:" + userId); 4041 return; 4042 } 4043 4044 mContext.enforceCallingOrSelfPermission( 4045 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4046 "grantRuntimePermission"); 4047 4048 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4049 true /* requireFullPermission */, true /* checkShell */, 4050 "grantRuntimePermission"); 4051 4052 final int uid; 4053 final SettingBase sb; 4054 4055 synchronized (mPackages) { 4056 final PackageParser.Package pkg = mPackages.get(packageName); 4057 if (pkg == null) { 4058 throw new IllegalArgumentException("Unknown package: " + packageName); 4059 } 4060 4061 final BasePermission bp = mSettings.mPermissions.get(name); 4062 if (bp == null) { 4063 throw new IllegalArgumentException("Unknown permission: " + name); 4064 } 4065 4066 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4067 4068 // If a permission review is required for legacy apps we represent 4069 // their permissions as always granted runtime ones since we need 4070 // to keep the review required permission flag per user while an 4071 // install permission's state is shared across all users. 4072 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4073 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4074 && bp.isRuntime()) { 4075 return; 4076 } 4077 4078 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4079 sb = (SettingBase) pkg.mExtras; 4080 if (sb == null) { 4081 throw new IllegalArgumentException("Unknown package: " + packageName); 4082 } 4083 4084 final PermissionsState permissionsState = sb.getPermissionsState(); 4085 4086 final int flags = permissionsState.getPermissionFlags(name, userId); 4087 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4088 throw new SecurityException("Cannot grant system fixed permission " 4089 + name + " for package " + packageName); 4090 } 4091 4092 if (bp.isDevelopment()) { 4093 // Development permissions must be handled specially, since they are not 4094 // normal runtime permissions. For now they apply to all users. 4095 if (permissionsState.grantInstallPermission(bp) != 4096 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4097 scheduleWriteSettingsLocked(); 4098 } 4099 return; 4100 } 4101 4102 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4103 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4104 return; 4105 } 4106 4107 final int result = permissionsState.grantRuntimePermission(bp, userId); 4108 switch (result) { 4109 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4110 return; 4111 } 4112 4113 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4114 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4115 mHandler.post(new Runnable() { 4116 @Override 4117 public void run() { 4118 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4119 } 4120 }); 4121 } 4122 break; 4123 } 4124 4125 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4126 4127 // Not critical if that is lost - app has to request again. 4128 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4129 } 4130 4131 // Only need to do this if user is initialized. Otherwise it's a new user 4132 // and there are no processes running as the user yet and there's no need 4133 // to make an expensive call to remount processes for the changed permissions. 4134 if (READ_EXTERNAL_STORAGE.equals(name) 4135 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4136 final long token = Binder.clearCallingIdentity(); 4137 try { 4138 if (sUserManager.isInitialized(userId)) { 4139 MountServiceInternal mountServiceInternal = LocalServices.getService( 4140 MountServiceInternal.class); 4141 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4142 } 4143 } finally { 4144 Binder.restoreCallingIdentity(token); 4145 } 4146 } 4147 } 4148 4149 @Override 4150 public void revokeRuntimePermission(String packageName, String name, int userId) { 4151 if (!sUserManager.exists(userId)) { 4152 Log.e(TAG, "No such user:" + userId); 4153 return; 4154 } 4155 4156 mContext.enforceCallingOrSelfPermission( 4157 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4158 "revokeRuntimePermission"); 4159 4160 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4161 true /* requireFullPermission */, true /* checkShell */, 4162 "revokeRuntimePermission"); 4163 4164 final int appId; 4165 4166 synchronized (mPackages) { 4167 final PackageParser.Package pkg = mPackages.get(packageName); 4168 if (pkg == null) { 4169 throw new IllegalArgumentException("Unknown package: " + packageName); 4170 } 4171 4172 final BasePermission bp = mSettings.mPermissions.get(name); 4173 if (bp == null) { 4174 throw new IllegalArgumentException("Unknown permission: " + name); 4175 } 4176 4177 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4178 4179 // If a permission review is required for legacy apps we represent 4180 // their permissions as always granted runtime ones since we need 4181 // to keep the review required permission flag per user while an 4182 // install permission's state is shared across all users. 4183 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4184 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4185 && bp.isRuntime()) { 4186 return; 4187 } 4188 4189 SettingBase sb = (SettingBase) pkg.mExtras; 4190 if (sb == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final PermissionsState permissionsState = sb.getPermissionsState(); 4195 4196 final int flags = permissionsState.getPermissionFlags(name, userId); 4197 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4198 throw new SecurityException("Cannot revoke system fixed permission " 4199 + name + " for package " + packageName); 4200 } 4201 4202 if (bp.isDevelopment()) { 4203 // Development permissions must be handled specially, since they are not 4204 // normal runtime permissions. For now they apply to all users. 4205 if (permissionsState.revokeInstallPermission(bp) != 4206 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4207 scheduleWriteSettingsLocked(); 4208 } 4209 return; 4210 } 4211 4212 if (permissionsState.revokeRuntimePermission(bp, userId) == 4213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4214 return; 4215 } 4216 4217 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4218 4219 // Critical, after this call app should never have the permission. 4220 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4221 4222 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4223 } 4224 4225 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4226 } 4227 4228 @Override 4229 public void resetRuntimePermissions() { 4230 mContext.enforceCallingOrSelfPermission( 4231 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4232 "revokeRuntimePermission"); 4233 4234 int callingUid = Binder.getCallingUid(); 4235 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4236 mContext.enforceCallingOrSelfPermission( 4237 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4238 "resetRuntimePermissions"); 4239 } 4240 4241 synchronized (mPackages) { 4242 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4243 for (int userId : UserManagerService.getInstance().getUserIds()) { 4244 final int packageCount = mPackages.size(); 4245 for (int i = 0; i < packageCount; i++) { 4246 PackageParser.Package pkg = mPackages.valueAt(i); 4247 if (!(pkg.mExtras instanceof PackageSetting)) { 4248 continue; 4249 } 4250 PackageSetting ps = (PackageSetting) pkg.mExtras; 4251 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4252 } 4253 } 4254 } 4255 } 4256 4257 @Override 4258 public int getPermissionFlags(String name, String packageName, int userId) { 4259 if (!sUserManager.exists(userId)) { 4260 return 0; 4261 } 4262 4263 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4264 4265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4266 true /* requireFullPermission */, false /* checkShell */, 4267 "getPermissionFlags"); 4268 4269 synchronized (mPackages) { 4270 final PackageParser.Package pkg = mPackages.get(packageName); 4271 if (pkg == null) { 4272 return 0; 4273 } 4274 4275 final BasePermission bp = mSettings.mPermissions.get(name); 4276 if (bp == null) { 4277 return 0; 4278 } 4279 4280 SettingBase sb = (SettingBase) pkg.mExtras; 4281 if (sb == null) { 4282 return 0; 4283 } 4284 4285 PermissionsState permissionsState = sb.getPermissionsState(); 4286 return permissionsState.getPermissionFlags(name, userId); 4287 } 4288 } 4289 4290 @Override 4291 public void updatePermissionFlags(String name, String packageName, int flagMask, 4292 int flagValues, int userId) { 4293 if (!sUserManager.exists(userId)) { 4294 return; 4295 } 4296 4297 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4298 4299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4300 true /* requireFullPermission */, true /* checkShell */, 4301 "updatePermissionFlags"); 4302 4303 // Only the system can change these flags and nothing else. 4304 if (getCallingUid() != Process.SYSTEM_UID) { 4305 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4306 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4307 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4308 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4309 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4310 } 4311 4312 synchronized (mPackages) { 4313 final PackageParser.Package pkg = mPackages.get(packageName); 4314 if (pkg == null) { 4315 throw new IllegalArgumentException("Unknown package: " + packageName); 4316 } 4317 4318 final BasePermission bp = mSettings.mPermissions.get(name); 4319 if (bp == null) { 4320 throw new IllegalArgumentException("Unknown permission: " + name); 4321 } 4322 4323 SettingBase sb = (SettingBase) pkg.mExtras; 4324 if (sb == null) { 4325 throw new IllegalArgumentException("Unknown package: " + packageName); 4326 } 4327 4328 PermissionsState permissionsState = sb.getPermissionsState(); 4329 4330 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4331 4332 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4333 // Install and runtime permissions are stored in different places, 4334 // so figure out what permission changed and persist the change. 4335 if (permissionsState.getInstallPermissionState(name) != null) { 4336 scheduleWriteSettingsLocked(); 4337 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4338 || hadState) { 4339 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4340 } 4341 } 4342 } 4343 } 4344 4345 /** 4346 * Update the permission flags for all packages and runtime permissions of a user in order 4347 * to allow device or profile owner to remove POLICY_FIXED. 4348 */ 4349 @Override 4350 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4351 if (!sUserManager.exists(userId)) { 4352 return; 4353 } 4354 4355 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4356 4357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4358 true /* requireFullPermission */, true /* checkShell */, 4359 "updatePermissionFlagsForAllApps"); 4360 4361 // Only the system can change system fixed flags. 4362 if (getCallingUid() != Process.SYSTEM_UID) { 4363 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4364 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4365 } 4366 4367 synchronized (mPackages) { 4368 boolean changed = false; 4369 final int packageCount = mPackages.size(); 4370 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4371 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4372 SettingBase sb = (SettingBase) pkg.mExtras; 4373 if (sb == null) { 4374 continue; 4375 } 4376 PermissionsState permissionsState = sb.getPermissionsState(); 4377 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4378 userId, flagMask, flagValues); 4379 } 4380 if (changed) { 4381 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4382 } 4383 } 4384 } 4385 4386 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4387 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4388 != PackageManager.PERMISSION_GRANTED 4389 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4390 != PackageManager.PERMISSION_GRANTED) { 4391 throw new SecurityException(message + " requires " 4392 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4393 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4394 } 4395 } 4396 4397 @Override 4398 public boolean shouldShowRequestPermissionRationale(String permissionName, 4399 String packageName, int userId) { 4400 if (UserHandle.getCallingUserId() != userId) { 4401 mContext.enforceCallingPermission( 4402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4403 "canShowRequestPermissionRationale for user " + userId); 4404 } 4405 4406 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4407 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4408 return false; 4409 } 4410 4411 if (checkPermission(permissionName, packageName, userId) 4412 == PackageManager.PERMISSION_GRANTED) { 4413 return false; 4414 } 4415 4416 final int flags; 4417 4418 final long identity = Binder.clearCallingIdentity(); 4419 try { 4420 flags = getPermissionFlags(permissionName, 4421 packageName, userId); 4422 } finally { 4423 Binder.restoreCallingIdentity(identity); 4424 } 4425 4426 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4427 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4428 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4429 4430 if ((flags & fixedFlags) != 0) { 4431 return false; 4432 } 4433 4434 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4435 } 4436 4437 @Override 4438 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4439 mContext.enforceCallingOrSelfPermission( 4440 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4441 "addOnPermissionsChangeListener"); 4442 4443 synchronized (mPackages) { 4444 mOnPermissionChangeListeners.addListenerLocked(listener); 4445 } 4446 } 4447 4448 @Override 4449 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4450 synchronized (mPackages) { 4451 mOnPermissionChangeListeners.removeListenerLocked(listener); 4452 } 4453 } 4454 4455 @Override 4456 public boolean isProtectedBroadcast(String actionName) { 4457 synchronized (mPackages) { 4458 if (mProtectedBroadcasts.contains(actionName)) { 4459 return true; 4460 } else if (actionName != null) { 4461 // TODO: remove these terrible hacks 4462 if (actionName.startsWith("android.net.netmon.lingerExpired") 4463 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4464 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4465 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4466 return true; 4467 } 4468 } 4469 } 4470 return false; 4471 } 4472 4473 @Override 4474 public int checkSignatures(String pkg1, String pkg2) { 4475 synchronized (mPackages) { 4476 final PackageParser.Package p1 = mPackages.get(pkg1); 4477 final PackageParser.Package p2 = mPackages.get(pkg2); 4478 if (p1 == null || p1.mExtras == null 4479 || p2 == null || p2.mExtras == null) { 4480 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4481 } 4482 return compareSignatures(p1.mSignatures, p2.mSignatures); 4483 } 4484 } 4485 4486 @Override 4487 public int checkUidSignatures(int uid1, int uid2) { 4488 // Map to base uids. 4489 uid1 = UserHandle.getAppId(uid1); 4490 uid2 = UserHandle.getAppId(uid2); 4491 // reader 4492 synchronized (mPackages) { 4493 Signature[] s1; 4494 Signature[] s2; 4495 Object obj = mSettings.getUserIdLPr(uid1); 4496 if (obj != null) { 4497 if (obj instanceof SharedUserSetting) { 4498 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4499 } else if (obj instanceof PackageSetting) { 4500 s1 = ((PackageSetting)obj).signatures.mSignatures; 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 } else { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 obj = mSettings.getUserIdLPr(uid2); 4508 if (obj != null) { 4509 if (obj instanceof SharedUserSetting) { 4510 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4511 } else if (obj instanceof PackageSetting) { 4512 s2 = ((PackageSetting)obj).signatures.mSignatures; 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 } else { 4517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4518 } 4519 return compareSignatures(s1, s2); 4520 } 4521 } 4522 4523 /** 4524 * This method should typically only be used when granting or revoking 4525 * permissions, since the app may immediately restart after this call. 4526 * <p> 4527 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4528 * guard your work against the app being relaunched. 4529 */ 4530 private void killUid(int appId, int userId, String reason) { 4531 final long identity = Binder.clearCallingIdentity(); 4532 try { 4533 IActivityManager am = ActivityManagerNative.getDefault(); 4534 if (am != null) { 4535 try { 4536 am.killUid(appId, userId, reason); 4537 } catch (RemoteException e) { 4538 /* ignore - same process */ 4539 } 4540 } 4541 } finally { 4542 Binder.restoreCallingIdentity(identity); 4543 } 4544 } 4545 4546 /** 4547 * Compares two sets of signatures. Returns: 4548 * <br /> 4549 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4550 * <br /> 4551 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4552 * <br /> 4553 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4558 */ 4559 static int compareSignatures(Signature[] s1, Signature[] s2) { 4560 if (s1 == null) { 4561 return s2 == null 4562 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4563 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4564 } 4565 4566 if (s2 == null) { 4567 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4568 } 4569 4570 if (s1.length != s2.length) { 4571 return PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 // Since both signature sets are of size 1, we can compare without HashSets. 4575 if (s1.length == 1) { 4576 return s1[0].equals(s2[0]) ? 4577 PackageManager.SIGNATURE_MATCH : 4578 PackageManager.SIGNATURE_NO_MATCH; 4579 } 4580 4581 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4582 for (Signature sig : s1) { 4583 set1.add(sig); 4584 } 4585 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4586 for (Signature sig : s2) { 4587 set2.add(sig); 4588 } 4589 // Make sure s2 contains all signatures in s1. 4590 if (set1.equals(set2)) { 4591 return PackageManager.SIGNATURE_MATCH; 4592 } 4593 return PackageManager.SIGNATURE_NO_MATCH; 4594 } 4595 4596 /** 4597 * If the database version for this type of package (internal storage or 4598 * external storage) is less than the version where package signatures 4599 * were updated, return true. 4600 */ 4601 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4602 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4603 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4604 } 4605 4606 /** 4607 * Used for backward compatibility to make sure any packages with 4608 * certificate chains get upgraded to the new style. {@code existingSigs} 4609 * will be in the old format (since they were stored on disk from before the 4610 * system upgrade) and {@code scannedSigs} will be in the newer format. 4611 */ 4612 private int compareSignaturesCompat(PackageSignatures existingSigs, 4613 PackageParser.Package scannedPkg) { 4614 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4615 return PackageManager.SIGNATURE_NO_MATCH; 4616 } 4617 4618 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4619 for (Signature sig : existingSigs.mSignatures) { 4620 existingSet.add(sig); 4621 } 4622 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4623 for (Signature sig : scannedPkg.mSignatures) { 4624 try { 4625 Signature[] chainSignatures = sig.getChainSignatures(); 4626 for (Signature chainSig : chainSignatures) { 4627 scannedCompatSet.add(chainSig); 4628 } 4629 } catch (CertificateEncodingException e) { 4630 scannedCompatSet.add(sig); 4631 } 4632 } 4633 /* 4634 * Make sure the expanded scanned set contains all signatures in the 4635 * existing one. 4636 */ 4637 if (scannedCompatSet.equals(existingSet)) { 4638 // Migrate the old signatures to the new scheme. 4639 existingSigs.assignSignatures(scannedPkg.mSignatures); 4640 // The new KeySets will be re-added later in the scanning process. 4641 synchronized (mPackages) { 4642 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4643 } 4644 return PackageManager.SIGNATURE_MATCH; 4645 } 4646 return PackageManager.SIGNATURE_NO_MATCH; 4647 } 4648 4649 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4650 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4651 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4652 } 4653 4654 private int compareSignaturesRecover(PackageSignatures existingSigs, 4655 PackageParser.Package scannedPkg) { 4656 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4657 return PackageManager.SIGNATURE_NO_MATCH; 4658 } 4659 4660 String msg = null; 4661 try { 4662 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4663 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4664 + scannedPkg.packageName); 4665 return PackageManager.SIGNATURE_MATCH; 4666 } 4667 } catch (CertificateException e) { 4668 msg = e.getMessage(); 4669 } 4670 4671 logCriticalInfo(Log.INFO, 4672 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4673 return PackageManager.SIGNATURE_NO_MATCH; 4674 } 4675 4676 @Override 4677 public List<String> getAllPackages() { 4678 synchronized (mPackages) { 4679 return new ArrayList<String>(mPackages.keySet()); 4680 } 4681 } 4682 4683 @Override 4684 public String[] getPackagesForUid(int uid) { 4685 uid = UserHandle.getAppId(uid); 4686 // reader 4687 synchronized (mPackages) { 4688 Object obj = mSettings.getUserIdLPr(uid); 4689 if (obj instanceof SharedUserSetting) { 4690 final SharedUserSetting sus = (SharedUserSetting) obj; 4691 final int N = sus.packages.size(); 4692 final String[] res = new String[N]; 4693 for (int i = 0; i < N; i++) { 4694 res[i] = sus.packages.valueAt(i).name; 4695 } 4696 return res; 4697 } else if (obj instanceof PackageSetting) { 4698 final PackageSetting ps = (PackageSetting) obj; 4699 return new String[] { ps.name }; 4700 } 4701 } 4702 return null; 4703 } 4704 4705 @Override 4706 public String getNameForUid(int uid) { 4707 // reader 4708 synchronized (mPackages) { 4709 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4710 if (obj instanceof SharedUserSetting) { 4711 final SharedUserSetting sus = (SharedUserSetting) obj; 4712 return sus.name + ":" + sus.userId; 4713 } else if (obj instanceof PackageSetting) { 4714 final PackageSetting ps = (PackageSetting) obj; 4715 return ps.name; 4716 } 4717 } 4718 return null; 4719 } 4720 4721 @Override 4722 public int getUidForSharedUser(String sharedUserName) { 4723 if(sharedUserName == null) { 4724 return -1; 4725 } 4726 // reader 4727 synchronized (mPackages) { 4728 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4729 if (suid == null) { 4730 return -1; 4731 } 4732 return suid.userId; 4733 } 4734 } 4735 4736 @Override 4737 public int getFlagsForUid(int uid) { 4738 synchronized (mPackages) { 4739 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4740 if (obj instanceof SharedUserSetting) { 4741 final SharedUserSetting sus = (SharedUserSetting) obj; 4742 return sus.pkgFlags; 4743 } else if (obj instanceof PackageSetting) { 4744 final PackageSetting ps = (PackageSetting) obj; 4745 return ps.pkgFlags; 4746 } 4747 } 4748 return 0; 4749 } 4750 4751 @Override 4752 public int getPrivateFlagsForUid(int uid) { 4753 synchronized (mPackages) { 4754 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4755 if (obj instanceof SharedUserSetting) { 4756 final SharedUserSetting sus = (SharedUserSetting) obj; 4757 return sus.pkgPrivateFlags; 4758 } else if (obj instanceof PackageSetting) { 4759 final PackageSetting ps = (PackageSetting) obj; 4760 return ps.pkgPrivateFlags; 4761 } 4762 } 4763 return 0; 4764 } 4765 4766 @Override 4767 public boolean isUidPrivileged(int uid) { 4768 uid = UserHandle.getAppId(uid); 4769 // reader 4770 synchronized (mPackages) { 4771 Object obj = mSettings.getUserIdLPr(uid); 4772 if (obj instanceof SharedUserSetting) { 4773 final SharedUserSetting sus = (SharedUserSetting) obj; 4774 final Iterator<PackageSetting> it = sus.packages.iterator(); 4775 while (it.hasNext()) { 4776 if (it.next().isPrivileged()) { 4777 return true; 4778 } 4779 } 4780 } else if (obj instanceof PackageSetting) { 4781 final PackageSetting ps = (PackageSetting) obj; 4782 return ps.isPrivileged(); 4783 } 4784 } 4785 return false; 4786 } 4787 4788 @Override 4789 public String[] getAppOpPermissionPackages(String permissionName) { 4790 synchronized (mPackages) { 4791 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4792 if (pkgs == null) { 4793 return null; 4794 } 4795 return pkgs.toArray(new String[pkgs.size()]); 4796 } 4797 } 4798 4799 @Override 4800 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4801 int flags, int userId) { 4802 try { 4803 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4804 4805 if (!sUserManager.exists(userId)) return null; 4806 flags = updateFlagsForResolve(flags, userId, intent); 4807 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4808 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4809 4810 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4811 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4812 flags, userId); 4813 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4814 4815 final ResolveInfo bestChoice = 4816 chooseBestActivity(intent, resolvedType, flags, query, userId); 4817 return bestChoice; 4818 } finally { 4819 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4820 } 4821 } 4822 4823 @Override 4824 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4825 IntentFilter filter, int match, ComponentName activity) { 4826 final int userId = UserHandle.getCallingUserId(); 4827 if (DEBUG_PREFERRED) { 4828 Log.v(TAG, "setLastChosenActivity intent=" + intent 4829 + " resolvedType=" + resolvedType 4830 + " flags=" + flags 4831 + " filter=" + filter 4832 + " match=" + match 4833 + " activity=" + activity); 4834 filter.dump(new PrintStreamPrinter(System.out), " "); 4835 } 4836 intent.setComponent(null); 4837 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4838 userId); 4839 // Find any earlier preferred or last chosen entries and nuke them 4840 findPreferredActivity(intent, resolvedType, 4841 flags, query, 0, false, true, false, userId); 4842 // Add the new activity as the last chosen for this filter 4843 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4844 "Setting last chosen"); 4845 } 4846 4847 @Override 4848 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4849 final int userId = UserHandle.getCallingUserId(); 4850 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4851 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4852 userId); 4853 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4854 false, false, false, userId); 4855 } 4856 4857 private boolean isEphemeralDisabled() { 4858 // ephemeral apps have been disabled across the board 4859 if (DISABLE_EPHEMERAL_APPS) { 4860 return true; 4861 } 4862 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4863 if (!mSystemReady) { 4864 return true; 4865 } 4866 // we can't get a content resolver until the system is ready; these checks must happen last 4867 final ContentResolver resolver = mContext.getContentResolver(); 4868 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4869 return true; 4870 } 4871 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4872 } 4873 4874 private boolean isEphemeralAllowed( 4875 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4876 boolean skipPackageCheck) { 4877 // Short circuit and return early if possible. 4878 if (isEphemeralDisabled()) { 4879 return false; 4880 } 4881 final int callingUser = UserHandle.getCallingUserId(); 4882 if (callingUser != UserHandle.USER_SYSTEM) { 4883 return false; 4884 } 4885 if (mEphemeralResolverConnection == null) { 4886 return false; 4887 } 4888 if (intent.getComponent() != null) { 4889 return false; 4890 } 4891 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4892 return false; 4893 } 4894 if (!skipPackageCheck && intent.getPackage() != null) { 4895 return false; 4896 } 4897 final boolean isWebUri = hasWebURI(intent); 4898 if (!isWebUri || intent.getData().getHost() == null) { 4899 return false; 4900 } 4901 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4902 synchronized (mPackages) { 4903 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4904 for (int n = 0; n < count; n++) { 4905 ResolveInfo info = resolvedActivities.get(n); 4906 String packageName = info.activityInfo.packageName; 4907 PackageSetting ps = mSettings.mPackages.get(packageName); 4908 if (ps != null) { 4909 // Try to get the status from User settings first 4910 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4911 int status = (int) (packedStatus >> 32); 4912 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4913 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4914 if (DEBUG_EPHEMERAL) { 4915 Slog.v(TAG, "DENY ephemeral apps;" 4916 + " pkg: " + packageName + ", status: " + status); 4917 } 4918 return false; 4919 } 4920 } 4921 } 4922 } 4923 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4924 return true; 4925 } 4926 4927 private static EphemeralResolveInfo getEphemeralResolveInfo( 4928 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4929 String resolvedType, int userId, String packageName) { 4930 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4931 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4932 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4933 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4934 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4935 ephemeralPrefixCount); 4936 final int[] shaPrefix = digest.getDigestPrefix(); 4937 final byte[][] digestBytes = digest.getDigestBytes(); 4938 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4939 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4940 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4941 // No hash prefix match; there are no ephemeral apps for this domain. 4942 return null; 4943 } 4944 4945 // Go in reverse order so we match the narrowest scope first. 4946 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4947 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4948 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4949 continue; 4950 } 4951 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4952 // No filters; this should never happen. 4953 if (filters.isEmpty()) { 4954 continue; 4955 } 4956 if (packageName != null 4957 && !packageName.equals(ephemeralApplication.getPackageName())) { 4958 continue; 4959 } 4960 // We have a domain match; resolve the filters to see if anything matches. 4961 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4962 for (int j = filters.size() - 1; j >= 0; --j) { 4963 final EphemeralResolveIntentInfo intentInfo = 4964 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4965 ephemeralResolver.addFilter(intentInfo); 4966 } 4967 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4968 intent, resolvedType, false /*defaultOnly*/, userId); 4969 if (!matchedResolveInfoList.isEmpty()) { 4970 return matchedResolveInfoList.get(0); 4971 } 4972 } 4973 } 4974 // Hash or filter mis-match; no ephemeral apps for this domain. 4975 return null; 4976 } 4977 4978 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4979 int flags, List<ResolveInfo> query, int userId) { 4980 if (query != null) { 4981 final int N = query.size(); 4982 if (N == 1) { 4983 return query.get(0); 4984 } else if (N > 1) { 4985 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4986 // If there is more than one activity with the same priority, 4987 // then let the user decide between them. 4988 ResolveInfo r0 = query.get(0); 4989 ResolveInfo r1 = query.get(1); 4990 if (DEBUG_INTENT_MATCHING || debug) { 4991 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4992 + r1.activityInfo.name + "=" + r1.priority); 4993 } 4994 // If the first activity has a higher priority, or a different 4995 // default, then it is always desirable to pick it. 4996 if (r0.priority != r1.priority 4997 || r0.preferredOrder != r1.preferredOrder 4998 || r0.isDefault != r1.isDefault) { 4999 return query.get(0); 5000 } 5001 // If we have saved a preference for a preferred activity for 5002 // this Intent, use that. 5003 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5004 flags, query, r0.priority, true, false, debug, userId); 5005 if (ri != null) { 5006 return ri; 5007 } 5008 ri = new ResolveInfo(mResolveInfo); 5009 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5010 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5011 // If all of the options come from the same package, show the application's 5012 // label and icon instead of the generic resolver's. 5013 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5014 // and then throw away the ResolveInfo itself, meaning that the caller loses 5015 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5016 // a fallback for this case; we only set the target package's resources on 5017 // the ResolveInfo, not the ActivityInfo. 5018 final String intentPackage = intent.getPackage(); 5019 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5020 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5021 ri.resolvePackageName = intentPackage; 5022 if (userNeedsBadging(userId)) { 5023 ri.noResourceId = true; 5024 } else { 5025 ri.icon = appi.icon; 5026 } 5027 ri.iconResourceId = appi.icon; 5028 ri.labelRes = appi.labelRes; 5029 } 5030 ri.activityInfo.applicationInfo = new ApplicationInfo( 5031 ri.activityInfo.applicationInfo); 5032 if (userId != 0) { 5033 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5034 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5035 } 5036 // Make sure that the resolver is displayable in car mode 5037 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5038 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5039 return ri; 5040 } 5041 } 5042 return null; 5043 } 5044 5045 /** 5046 * Return true if the given list is not empty and all of its contents have 5047 * an activityInfo with the given package name. 5048 */ 5049 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5050 if (ArrayUtils.isEmpty(list)) { 5051 return false; 5052 } 5053 for (int i = 0, N = list.size(); i < N; i++) { 5054 final ResolveInfo ri = list.get(i); 5055 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5056 if (ai == null || !packageName.equals(ai.packageName)) { 5057 return false; 5058 } 5059 } 5060 return true; 5061 } 5062 5063 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5064 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5065 final int N = query.size(); 5066 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5067 .get(userId); 5068 // Get the list of persistent preferred activities that handle the intent 5069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5070 List<PersistentPreferredActivity> pprefs = ppir != null 5071 ? ppir.queryIntent(intent, resolvedType, 5072 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5073 : null; 5074 if (pprefs != null && pprefs.size() > 0) { 5075 final int M = pprefs.size(); 5076 for (int i=0; i<M; i++) { 5077 final PersistentPreferredActivity ppa = pprefs.get(i); 5078 if (DEBUG_PREFERRED || debug) { 5079 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5080 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5081 + "\n component=" + ppa.mComponent); 5082 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5083 } 5084 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5085 flags | MATCH_DISABLED_COMPONENTS, userId); 5086 if (DEBUG_PREFERRED || debug) { 5087 Slog.v(TAG, "Found persistent preferred activity:"); 5088 if (ai != null) { 5089 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5090 } else { 5091 Slog.v(TAG, " null"); 5092 } 5093 } 5094 if (ai == null) { 5095 // This previously registered persistent preferred activity 5096 // component is no longer known. Ignore it and do NOT remove it. 5097 continue; 5098 } 5099 for (int j=0; j<N; j++) { 5100 final ResolveInfo ri = query.get(j); 5101 if (!ri.activityInfo.applicationInfo.packageName 5102 .equals(ai.applicationInfo.packageName)) { 5103 continue; 5104 } 5105 if (!ri.activityInfo.name.equals(ai.name)) { 5106 continue; 5107 } 5108 // Found a persistent preference that can handle the intent. 5109 if (DEBUG_PREFERRED || debug) { 5110 Slog.v(TAG, "Returning persistent preferred activity: " + 5111 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5112 } 5113 return ri; 5114 } 5115 } 5116 } 5117 return null; 5118 } 5119 5120 // TODO: handle preferred activities missing while user has amnesia 5121 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5122 List<ResolveInfo> query, int priority, boolean always, 5123 boolean removeMatches, boolean debug, int userId) { 5124 if (!sUserManager.exists(userId)) return null; 5125 flags = updateFlagsForResolve(flags, userId, intent); 5126 // writer 5127 synchronized (mPackages) { 5128 if (intent.getSelector() != null) { 5129 intent = intent.getSelector(); 5130 } 5131 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5132 5133 // Try to find a matching persistent preferred activity. 5134 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5135 debug, userId); 5136 5137 // If a persistent preferred activity matched, use it. 5138 if (pri != null) { 5139 return pri; 5140 } 5141 5142 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5143 // Get the list of preferred activities that handle the intent 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5145 List<PreferredActivity> prefs = pir != null 5146 ? pir.queryIntent(intent, resolvedType, 5147 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5148 : null; 5149 if (prefs != null && prefs.size() > 0) { 5150 boolean changed = false; 5151 try { 5152 // First figure out how good the original match set is. 5153 // We will only allow preferred activities that came 5154 // from the same match quality. 5155 int match = 0; 5156 5157 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5158 5159 final int N = query.size(); 5160 for (int j=0; j<N; j++) { 5161 final ResolveInfo ri = query.get(j); 5162 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5163 + ": 0x" + Integer.toHexString(match)); 5164 if (ri.match > match) { 5165 match = ri.match; 5166 } 5167 } 5168 5169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5170 + Integer.toHexString(match)); 5171 5172 match &= IntentFilter.MATCH_CATEGORY_MASK; 5173 final int M = prefs.size(); 5174 for (int i=0; i<M; i++) { 5175 final PreferredActivity pa = prefs.get(i); 5176 if (DEBUG_PREFERRED || debug) { 5177 Slog.v(TAG, "Checking PreferredActivity ds=" 5178 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5179 + "\n component=" + pa.mPref.mComponent); 5180 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5181 } 5182 if (pa.mPref.mMatch != match) { 5183 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5184 + Integer.toHexString(pa.mPref.mMatch)); 5185 continue; 5186 } 5187 // If it's not an "always" type preferred activity and that's what we're 5188 // looking for, skip it. 5189 if (always && !pa.mPref.mAlways) { 5190 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5191 continue; 5192 } 5193 final ActivityInfo ai = getActivityInfo( 5194 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5195 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5196 userId); 5197 if (DEBUG_PREFERRED || debug) { 5198 Slog.v(TAG, "Found preferred activity:"); 5199 if (ai != null) { 5200 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5201 } else { 5202 Slog.v(TAG, " null"); 5203 } 5204 } 5205 if (ai == null) { 5206 // This previously registered preferred activity 5207 // component is no longer known. Most likely an update 5208 // to the app was installed and in the new version this 5209 // component no longer exists. Clean it up by removing 5210 // it from the preferred activities list, and skip it. 5211 Slog.w(TAG, "Removing dangling preferred activity: " 5212 + pa.mPref.mComponent); 5213 pir.removeFilter(pa); 5214 changed = true; 5215 continue; 5216 } 5217 for (int j=0; j<N; j++) { 5218 final ResolveInfo ri = query.get(j); 5219 if (!ri.activityInfo.applicationInfo.packageName 5220 .equals(ai.applicationInfo.packageName)) { 5221 continue; 5222 } 5223 if (!ri.activityInfo.name.equals(ai.name)) { 5224 continue; 5225 } 5226 5227 if (removeMatches) { 5228 pir.removeFilter(pa); 5229 changed = true; 5230 if (DEBUG_PREFERRED) { 5231 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5232 } 5233 break; 5234 } 5235 5236 // Okay we found a previously set preferred or last chosen app. 5237 // If the result set is different from when this 5238 // was created, we need to clear it and re-ask the 5239 // user their preference, if we're looking for an "always" type entry. 5240 if (always && !pa.mPref.sameSet(query)) { 5241 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5242 + intent + " type " + resolvedType); 5243 if (DEBUG_PREFERRED) { 5244 Slog.v(TAG, "Removing preferred activity since set changed " 5245 + pa.mPref.mComponent); 5246 } 5247 pir.removeFilter(pa); 5248 // Re-add the filter as a "last chosen" entry (!always) 5249 PreferredActivity lastChosen = new PreferredActivity( 5250 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5251 pir.addFilter(lastChosen); 5252 changed = true; 5253 return null; 5254 } 5255 5256 // Yay! Either the set matched or we're looking for the last chosen 5257 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5258 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5259 return ri; 5260 } 5261 } 5262 } finally { 5263 if (changed) { 5264 if (DEBUG_PREFERRED) { 5265 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5266 } 5267 scheduleWritePackageRestrictionsLocked(userId); 5268 } 5269 } 5270 } 5271 } 5272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5273 return null; 5274 } 5275 5276 /* 5277 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5278 */ 5279 @Override 5280 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5281 int targetUserId) { 5282 mContext.enforceCallingOrSelfPermission( 5283 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5284 List<CrossProfileIntentFilter> matches = 5285 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5286 if (matches != null) { 5287 int size = matches.size(); 5288 for (int i = 0; i < size; i++) { 5289 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5290 } 5291 } 5292 if (hasWebURI(intent)) { 5293 // cross-profile app linking works only towards the parent. 5294 final UserInfo parent = getProfileParent(sourceUserId); 5295 synchronized(mPackages) { 5296 int flags = updateFlagsForResolve(0, parent.id, intent); 5297 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5298 intent, resolvedType, flags, sourceUserId, parent.id); 5299 return xpDomainInfo != null; 5300 } 5301 } 5302 return false; 5303 } 5304 5305 private UserInfo getProfileParent(int userId) { 5306 final long identity = Binder.clearCallingIdentity(); 5307 try { 5308 return sUserManager.getProfileParent(userId); 5309 } finally { 5310 Binder.restoreCallingIdentity(identity); 5311 } 5312 } 5313 5314 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5315 String resolvedType, int userId) { 5316 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5317 if (resolver != null) { 5318 return resolver.queryIntent(intent, resolvedType, false, userId); 5319 } 5320 return null; 5321 } 5322 5323 @Override 5324 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5325 String resolvedType, int flags, int userId) { 5326 try { 5327 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5328 5329 return new ParceledListSlice<>( 5330 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5331 } finally { 5332 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5333 } 5334 } 5335 5336 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5337 String resolvedType, int flags, int userId) { 5338 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5339 flags = updateFlagsForResolve(flags, userId, intent); 5340 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5341 false /* requireFullPermission */, false /* checkShell */, 5342 "query intent activities"); 5343 ComponentName comp = intent.getComponent(); 5344 if (comp == null) { 5345 if (intent.getSelector() != null) { 5346 intent = intent.getSelector(); 5347 comp = intent.getComponent(); 5348 } 5349 } 5350 5351 if (comp != null) { 5352 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5353 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5354 if (ai != null) { 5355 final ResolveInfo ri = new ResolveInfo(); 5356 ri.activityInfo = ai; 5357 list.add(ri); 5358 } 5359 return list; 5360 } 5361 5362 // reader 5363 boolean sortResult = false; 5364 boolean addEphemeral = false; 5365 boolean matchEphemeralPackage = false; 5366 List<ResolveInfo> result; 5367 final String pkgName = intent.getPackage(); 5368 synchronized (mPackages) { 5369 if (pkgName == null) { 5370 List<CrossProfileIntentFilter> matchingFilters = 5371 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5372 // Check for results that need to skip the current profile. 5373 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5374 resolvedType, flags, userId); 5375 if (xpResolveInfo != null) { 5376 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5377 xpResult.add(xpResolveInfo); 5378 return filterIfNotSystemUser(xpResult, userId); 5379 } 5380 5381 // Check for results in the current profile. 5382 result = filterIfNotSystemUser(mActivities.queryIntent( 5383 intent, resolvedType, flags, userId), userId); 5384 addEphemeral = 5385 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5386 5387 // Check for cross profile results. 5388 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5389 xpResolveInfo = queryCrossProfileIntents( 5390 matchingFilters, intent, resolvedType, flags, userId, 5391 hasNonNegativePriorityResult); 5392 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5393 boolean isVisibleToUser = filterIfNotSystemUser( 5394 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5395 if (isVisibleToUser) { 5396 result.add(xpResolveInfo); 5397 sortResult = true; 5398 } 5399 } 5400 if (hasWebURI(intent)) { 5401 CrossProfileDomainInfo xpDomainInfo = null; 5402 final UserInfo parent = getProfileParent(userId); 5403 if (parent != null) { 5404 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5405 flags, userId, parent.id); 5406 } 5407 if (xpDomainInfo != null) { 5408 if (xpResolveInfo != null) { 5409 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5410 // in the result. 5411 result.remove(xpResolveInfo); 5412 } 5413 if (result.size() == 0 && !addEphemeral) { 5414 result.add(xpDomainInfo.resolveInfo); 5415 return result; 5416 } 5417 } 5418 if (result.size() > 1 || addEphemeral) { 5419 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5420 intent, flags, result, xpDomainInfo, userId); 5421 sortResult = true; 5422 } 5423 } 5424 } else { 5425 final PackageParser.Package pkg = mPackages.get(pkgName); 5426 if (pkg != null) { 5427 result = filterIfNotSystemUser( 5428 mActivities.queryIntentForPackage( 5429 intent, resolvedType, flags, pkg.activities, userId), 5430 userId); 5431 } else { 5432 // the caller wants to resolve for a particular package; however, there 5433 // were no installed results, so, try to find an ephemeral result 5434 addEphemeral = isEphemeralAllowed( 5435 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5436 matchEphemeralPackage = true; 5437 result = new ArrayList<ResolveInfo>(); 5438 } 5439 } 5440 } 5441 if (addEphemeral) { 5442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5443 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5444 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5445 matchEphemeralPackage ? pkgName : null); 5446 if (ai != null) { 5447 if (DEBUG_EPHEMERAL) { 5448 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5449 } 5450 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5451 ephemeralInstaller.ephemeralResolveInfo = ai; 5452 // make sure this resolver is the default 5453 ephemeralInstaller.isDefault = true; 5454 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5455 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5456 // add a non-generic filter 5457 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5458 ephemeralInstaller.filter.addDataPath( 5459 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5460 result.add(ephemeralInstaller); 5461 } 5462 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5463 } 5464 if (sortResult) { 5465 Collections.sort(result, mResolvePrioritySorter); 5466 } 5467 return result; 5468 } 5469 5470 private static class CrossProfileDomainInfo { 5471 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5472 ResolveInfo resolveInfo; 5473 /* Best domain verification status of the activities found in the other profile */ 5474 int bestDomainVerificationStatus; 5475 } 5476 5477 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5478 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5479 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5480 sourceUserId)) { 5481 return null; 5482 } 5483 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5484 resolvedType, flags, parentUserId); 5485 5486 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5487 return null; 5488 } 5489 CrossProfileDomainInfo result = null; 5490 int size = resultTargetUser.size(); 5491 for (int i = 0; i < size; i++) { 5492 ResolveInfo riTargetUser = resultTargetUser.get(i); 5493 // Intent filter verification is only for filters that specify a host. So don't return 5494 // those that handle all web uris. 5495 if (riTargetUser.handleAllWebDataURI) { 5496 continue; 5497 } 5498 String packageName = riTargetUser.activityInfo.packageName; 5499 PackageSetting ps = mSettings.mPackages.get(packageName); 5500 if (ps == null) { 5501 continue; 5502 } 5503 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5504 int status = (int)(verificationState >> 32); 5505 if (result == null) { 5506 result = new CrossProfileDomainInfo(); 5507 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5508 sourceUserId, parentUserId); 5509 result.bestDomainVerificationStatus = status; 5510 } else { 5511 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5512 result.bestDomainVerificationStatus); 5513 } 5514 } 5515 // Don't consider matches with status NEVER across profiles. 5516 if (result != null && result.bestDomainVerificationStatus 5517 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5518 return null; 5519 } 5520 return result; 5521 } 5522 5523 /** 5524 * Verification statuses are ordered from the worse to the best, except for 5525 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5526 */ 5527 private int bestDomainVerificationStatus(int status1, int status2) { 5528 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5529 return status2; 5530 } 5531 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5532 return status1; 5533 } 5534 return (int) MathUtils.max(status1, status2); 5535 } 5536 5537 private boolean isUserEnabled(int userId) { 5538 long callingId = Binder.clearCallingIdentity(); 5539 try { 5540 UserInfo userInfo = sUserManager.getUserInfo(userId); 5541 return userInfo != null && userInfo.isEnabled(); 5542 } finally { 5543 Binder.restoreCallingIdentity(callingId); 5544 } 5545 } 5546 5547 /** 5548 * Filter out activities with systemUserOnly flag set, when current user is not System. 5549 * 5550 * @return filtered list 5551 */ 5552 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5553 if (userId == UserHandle.USER_SYSTEM) { 5554 return resolveInfos; 5555 } 5556 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5557 ResolveInfo info = resolveInfos.get(i); 5558 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5559 resolveInfos.remove(i); 5560 } 5561 } 5562 return resolveInfos; 5563 } 5564 5565 /** 5566 * @param resolveInfos list of resolve infos in descending priority order 5567 * @return if the list contains a resolve info with non-negative priority 5568 */ 5569 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5570 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5571 } 5572 5573 private static boolean hasWebURI(Intent intent) { 5574 if (intent.getData() == null) { 5575 return false; 5576 } 5577 final String scheme = intent.getScheme(); 5578 if (TextUtils.isEmpty(scheme)) { 5579 return false; 5580 } 5581 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5582 } 5583 5584 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5585 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5586 int userId) { 5587 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5588 5589 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5590 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5591 candidates.size()); 5592 } 5593 5594 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5595 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5596 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5597 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5598 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5599 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5600 5601 synchronized (mPackages) { 5602 final int count = candidates.size(); 5603 // First, try to use linked apps. Partition the candidates into four lists: 5604 // one for the final results, one for the "do not use ever", one for "undefined status" 5605 // and finally one for "browser app type". 5606 for (int n=0; n<count; n++) { 5607 ResolveInfo info = candidates.get(n); 5608 String packageName = info.activityInfo.packageName; 5609 PackageSetting ps = mSettings.mPackages.get(packageName); 5610 if (ps != null) { 5611 // Add to the special match all list (Browser use case) 5612 if (info.handleAllWebDataURI) { 5613 matchAllList.add(info); 5614 continue; 5615 } 5616 // Try to get the status from User settings first 5617 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5618 int status = (int)(packedStatus >> 32); 5619 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5620 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5621 if (DEBUG_DOMAIN_VERIFICATION) { 5622 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5623 + " : linkgen=" + linkGeneration); 5624 } 5625 // Use link-enabled generation as preferredOrder, i.e. 5626 // prefer newly-enabled over earlier-enabled. 5627 info.preferredOrder = linkGeneration; 5628 alwaysList.add(info); 5629 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5630 if (DEBUG_DOMAIN_VERIFICATION) { 5631 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5632 } 5633 neverList.add(info); 5634 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5635 if (DEBUG_DOMAIN_VERIFICATION) { 5636 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5637 } 5638 alwaysAskList.add(info); 5639 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5640 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5641 if (DEBUG_DOMAIN_VERIFICATION) { 5642 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5643 } 5644 undefinedList.add(info); 5645 } 5646 } 5647 } 5648 5649 // We'll want to include browser possibilities in a few cases 5650 boolean includeBrowser = false; 5651 5652 // First try to add the "always" resolution(s) for the current user, if any 5653 if (alwaysList.size() > 0) { 5654 result.addAll(alwaysList); 5655 } else { 5656 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5657 result.addAll(undefinedList); 5658 // Maybe add one for the other profile. 5659 if (xpDomainInfo != null && ( 5660 xpDomainInfo.bestDomainVerificationStatus 5661 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5662 result.add(xpDomainInfo.resolveInfo); 5663 } 5664 includeBrowser = true; 5665 } 5666 5667 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5668 // If there were 'always' entries their preferred order has been set, so we also 5669 // back that off to make the alternatives equivalent 5670 if (alwaysAskList.size() > 0) { 5671 for (ResolveInfo i : result) { 5672 i.preferredOrder = 0; 5673 } 5674 result.addAll(alwaysAskList); 5675 includeBrowser = true; 5676 } 5677 5678 if (includeBrowser) { 5679 // Also add browsers (all of them or only the default one) 5680 if (DEBUG_DOMAIN_VERIFICATION) { 5681 Slog.v(TAG, " ...including browsers in candidate set"); 5682 } 5683 if ((matchFlags & MATCH_ALL) != 0) { 5684 result.addAll(matchAllList); 5685 } else { 5686 // Browser/generic handling case. If there's a default browser, go straight 5687 // to that (but only if there is no other higher-priority match). 5688 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5689 int maxMatchPrio = 0; 5690 ResolveInfo defaultBrowserMatch = null; 5691 final int numCandidates = matchAllList.size(); 5692 for (int n = 0; n < numCandidates; n++) { 5693 ResolveInfo info = matchAllList.get(n); 5694 // track the highest overall match priority... 5695 if (info.priority > maxMatchPrio) { 5696 maxMatchPrio = info.priority; 5697 } 5698 // ...and the highest-priority default browser match 5699 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5700 if (defaultBrowserMatch == null 5701 || (defaultBrowserMatch.priority < info.priority)) { 5702 if (debug) { 5703 Slog.v(TAG, "Considering default browser match " + info); 5704 } 5705 defaultBrowserMatch = info; 5706 } 5707 } 5708 } 5709 if (defaultBrowserMatch != null 5710 && defaultBrowserMatch.priority >= maxMatchPrio 5711 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5712 { 5713 if (debug) { 5714 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5715 } 5716 result.add(defaultBrowserMatch); 5717 } else { 5718 result.addAll(matchAllList); 5719 } 5720 } 5721 5722 // If there is nothing selected, add all candidates and remove the ones that the user 5723 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5724 if (result.size() == 0) { 5725 result.addAll(candidates); 5726 result.removeAll(neverList); 5727 } 5728 } 5729 } 5730 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5731 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5732 result.size()); 5733 for (ResolveInfo info : result) { 5734 Slog.v(TAG, " + " + info.activityInfo); 5735 } 5736 } 5737 return result; 5738 } 5739 5740 // Returns a packed value as a long: 5741 // 5742 // high 'int'-sized word: link status: undefined/ask/never/always. 5743 // low 'int'-sized word: relative priority among 'always' results. 5744 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5745 long result = ps.getDomainVerificationStatusForUser(userId); 5746 // if none available, get the master status 5747 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5748 if (ps.getIntentFilterVerificationInfo() != null) { 5749 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5750 } 5751 } 5752 return result; 5753 } 5754 5755 private ResolveInfo querySkipCurrentProfileIntents( 5756 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5757 int flags, int sourceUserId) { 5758 if (matchingFilters != null) { 5759 int size = matchingFilters.size(); 5760 for (int i = 0; i < size; i ++) { 5761 CrossProfileIntentFilter filter = matchingFilters.get(i); 5762 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5763 // Checking if there are activities in the target user that can handle the 5764 // intent. 5765 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5766 resolvedType, flags, sourceUserId); 5767 if (resolveInfo != null) { 5768 return resolveInfo; 5769 } 5770 } 5771 } 5772 } 5773 return null; 5774 } 5775 5776 // Return matching ResolveInfo in target user if any. 5777 private ResolveInfo queryCrossProfileIntents( 5778 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5779 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5780 if (matchingFilters != null) { 5781 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5782 // match the same intent. For performance reasons, it is better not to 5783 // run queryIntent twice for the same userId 5784 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5785 int size = matchingFilters.size(); 5786 for (int i = 0; i < size; i++) { 5787 CrossProfileIntentFilter filter = matchingFilters.get(i); 5788 int targetUserId = filter.getTargetUserId(); 5789 boolean skipCurrentProfile = 5790 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5791 boolean skipCurrentProfileIfNoMatchFound = 5792 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5793 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5794 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5795 // Checking if there are activities in the target user that can handle the 5796 // intent. 5797 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5798 resolvedType, flags, sourceUserId); 5799 if (resolveInfo != null) return resolveInfo; 5800 alreadyTriedUserIds.put(targetUserId, true); 5801 } 5802 } 5803 } 5804 return null; 5805 } 5806 5807 /** 5808 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5809 * will forward the intent to the filter's target user. 5810 * Otherwise, returns null. 5811 */ 5812 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5813 String resolvedType, int flags, int sourceUserId) { 5814 int targetUserId = filter.getTargetUserId(); 5815 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5816 resolvedType, flags, targetUserId); 5817 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5818 // If all the matches in the target profile are suspended, return null. 5819 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5820 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5821 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5822 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5823 targetUserId); 5824 } 5825 } 5826 } 5827 return null; 5828 } 5829 5830 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5831 int sourceUserId, int targetUserId) { 5832 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5833 long ident = Binder.clearCallingIdentity(); 5834 boolean targetIsProfile; 5835 try { 5836 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5837 } finally { 5838 Binder.restoreCallingIdentity(ident); 5839 } 5840 String className; 5841 if (targetIsProfile) { 5842 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5843 } else { 5844 className = FORWARD_INTENT_TO_PARENT; 5845 } 5846 ComponentName forwardingActivityComponentName = new ComponentName( 5847 mAndroidApplication.packageName, className); 5848 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5849 sourceUserId); 5850 if (!targetIsProfile) { 5851 forwardingActivityInfo.showUserIcon = targetUserId; 5852 forwardingResolveInfo.noResourceId = true; 5853 } 5854 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5855 forwardingResolveInfo.priority = 0; 5856 forwardingResolveInfo.preferredOrder = 0; 5857 forwardingResolveInfo.match = 0; 5858 forwardingResolveInfo.isDefault = true; 5859 forwardingResolveInfo.filter = filter; 5860 forwardingResolveInfo.targetUserId = targetUserId; 5861 return forwardingResolveInfo; 5862 } 5863 5864 @Override 5865 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5866 Intent[] specifics, String[] specificTypes, Intent intent, 5867 String resolvedType, int flags, int userId) { 5868 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5869 specificTypes, intent, resolvedType, flags, userId)); 5870 } 5871 5872 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5873 Intent[] specifics, String[] specificTypes, Intent intent, 5874 String resolvedType, int flags, int userId) { 5875 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5876 flags = updateFlagsForResolve(flags, userId, intent); 5877 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5878 false /* requireFullPermission */, false /* checkShell */, 5879 "query intent activity options"); 5880 final String resultsAction = intent.getAction(); 5881 5882 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5883 | PackageManager.GET_RESOLVED_FILTER, userId); 5884 5885 if (DEBUG_INTENT_MATCHING) { 5886 Log.v(TAG, "Query " + intent + ": " + results); 5887 } 5888 5889 int specificsPos = 0; 5890 int N; 5891 5892 // todo: note that the algorithm used here is O(N^2). This 5893 // isn't a problem in our current environment, but if we start running 5894 // into situations where we have more than 5 or 10 matches then this 5895 // should probably be changed to something smarter... 5896 5897 // First we go through and resolve each of the specific items 5898 // that were supplied, taking care of removing any corresponding 5899 // duplicate items in the generic resolve list. 5900 if (specifics != null) { 5901 for (int i=0; i<specifics.length; i++) { 5902 final Intent sintent = specifics[i]; 5903 if (sintent == null) { 5904 continue; 5905 } 5906 5907 if (DEBUG_INTENT_MATCHING) { 5908 Log.v(TAG, "Specific #" + i + ": " + sintent); 5909 } 5910 5911 String action = sintent.getAction(); 5912 if (resultsAction != null && resultsAction.equals(action)) { 5913 // If this action was explicitly requested, then don't 5914 // remove things that have it. 5915 action = null; 5916 } 5917 5918 ResolveInfo ri = null; 5919 ActivityInfo ai = null; 5920 5921 ComponentName comp = sintent.getComponent(); 5922 if (comp == null) { 5923 ri = resolveIntent( 5924 sintent, 5925 specificTypes != null ? specificTypes[i] : null, 5926 flags, userId); 5927 if (ri == null) { 5928 continue; 5929 } 5930 if (ri == mResolveInfo) { 5931 // ACK! Must do something better with this. 5932 } 5933 ai = ri.activityInfo; 5934 comp = new ComponentName(ai.applicationInfo.packageName, 5935 ai.name); 5936 } else { 5937 ai = getActivityInfo(comp, flags, userId); 5938 if (ai == null) { 5939 continue; 5940 } 5941 } 5942 5943 // Look for any generic query activities that are duplicates 5944 // of this specific one, and remove them from the results. 5945 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5946 N = results.size(); 5947 int j; 5948 for (j=specificsPos; j<N; j++) { 5949 ResolveInfo sri = results.get(j); 5950 if ((sri.activityInfo.name.equals(comp.getClassName()) 5951 && sri.activityInfo.applicationInfo.packageName.equals( 5952 comp.getPackageName())) 5953 || (action != null && sri.filter.matchAction(action))) { 5954 results.remove(j); 5955 if (DEBUG_INTENT_MATCHING) Log.v( 5956 TAG, "Removing duplicate item from " + j 5957 + " due to specific " + specificsPos); 5958 if (ri == null) { 5959 ri = sri; 5960 } 5961 j--; 5962 N--; 5963 } 5964 } 5965 5966 // Add this specific item to its proper place. 5967 if (ri == null) { 5968 ri = new ResolveInfo(); 5969 ri.activityInfo = ai; 5970 } 5971 results.add(specificsPos, ri); 5972 ri.specificIndex = i; 5973 specificsPos++; 5974 } 5975 } 5976 5977 // Now we go through the remaining generic results and remove any 5978 // duplicate actions that are found here. 5979 N = results.size(); 5980 for (int i=specificsPos; i<N-1; i++) { 5981 final ResolveInfo rii = results.get(i); 5982 if (rii.filter == null) { 5983 continue; 5984 } 5985 5986 // Iterate over all of the actions of this result's intent 5987 // filter... typically this should be just one. 5988 final Iterator<String> it = rii.filter.actionsIterator(); 5989 if (it == null) { 5990 continue; 5991 } 5992 while (it.hasNext()) { 5993 final String action = it.next(); 5994 if (resultsAction != null && resultsAction.equals(action)) { 5995 // If this action was explicitly requested, then don't 5996 // remove things that have it. 5997 continue; 5998 } 5999 for (int j=i+1; j<N; j++) { 6000 final ResolveInfo rij = results.get(j); 6001 if (rij.filter != null && rij.filter.hasAction(action)) { 6002 results.remove(j); 6003 if (DEBUG_INTENT_MATCHING) Log.v( 6004 TAG, "Removing duplicate item from " + j 6005 + " due to action " + action + " at " + i); 6006 j--; 6007 N--; 6008 } 6009 } 6010 } 6011 6012 // If the caller didn't request filter information, drop it now 6013 // so we don't have to marshall/unmarshall it. 6014 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6015 rii.filter = null; 6016 } 6017 } 6018 6019 // Filter out the caller activity if so requested. 6020 if (caller != null) { 6021 N = results.size(); 6022 for (int i=0; i<N; i++) { 6023 ActivityInfo ainfo = results.get(i).activityInfo; 6024 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6025 && caller.getClassName().equals(ainfo.name)) { 6026 results.remove(i); 6027 break; 6028 } 6029 } 6030 } 6031 6032 // If the caller didn't request filter information, 6033 // drop them now so we don't have to 6034 // marshall/unmarshall it. 6035 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6036 N = results.size(); 6037 for (int i=0; i<N; i++) { 6038 results.get(i).filter = null; 6039 } 6040 } 6041 6042 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6043 return results; 6044 } 6045 6046 @Override 6047 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6048 String resolvedType, int flags, int userId) { 6049 return new ParceledListSlice<>( 6050 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6051 } 6052 6053 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6054 String resolvedType, int flags, int userId) { 6055 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6056 flags = updateFlagsForResolve(flags, userId, intent); 6057 ComponentName comp = intent.getComponent(); 6058 if (comp == null) { 6059 if (intent.getSelector() != null) { 6060 intent = intent.getSelector(); 6061 comp = intent.getComponent(); 6062 } 6063 } 6064 if (comp != null) { 6065 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6066 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6067 if (ai != null) { 6068 ResolveInfo ri = new ResolveInfo(); 6069 ri.activityInfo = ai; 6070 list.add(ri); 6071 } 6072 return list; 6073 } 6074 6075 // reader 6076 synchronized (mPackages) { 6077 String pkgName = intent.getPackage(); 6078 if (pkgName == null) { 6079 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6080 } 6081 final PackageParser.Package pkg = mPackages.get(pkgName); 6082 if (pkg != null) { 6083 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6084 userId); 6085 } 6086 return Collections.emptyList(); 6087 } 6088 } 6089 6090 @Override 6091 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6092 if (!sUserManager.exists(userId)) return null; 6093 flags = updateFlagsForResolve(flags, userId, intent); 6094 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6095 if (query != null) { 6096 if (query.size() >= 1) { 6097 // If there is more than one service with the same priority, 6098 // just arbitrarily pick the first one. 6099 return query.get(0); 6100 } 6101 } 6102 return null; 6103 } 6104 6105 @Override 6106 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6107 String resolvedType, int flags, int userId) { 6108 return new ParceledListSlice<>( 6109 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6110 } 6111 6112 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6113 String resolvedType, int flags, int userId) { 6114 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6115 flags = updateFlagsForResolve(flags, userId, intent); 6116 ComponentName comp = intent.getComponent(); 6117 if (comp == null) { 6118 if (intent.getSelector() != null) { 6119 intent = intent.getSelector(); 6120 comp = intent.getComponent(); 6121 } 6122 } 6123 if (comp != null) { 6124 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6125 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6126 if (si != null) { 6127 final ResolveInfo ri = new ResolveInfo(); 6128 ri.serviceInfo = si; 6129 list.add(ri); 6130 } 6131 return list; 6132 } 6133 6134 // reader 6135 synchronized (mPackages) { 6136 String pkgName = intent.getPackage(); 6137 if (pkgName == null) { 6138 return mServices.queryIntent(intent, resolvedType, flags, userId); 6139 } 6140 final PackageParser.Package pkg = mPackages.get(pkgName); 6141 if (pkg != null) { 6142 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6143 userId); 6144 } 6145 return Collections.emptyList(); 6146 } 6147 } 6148 6149 @Override 6150 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6151 String resolvedType, int flags, int userId) { 6152 return new ParceledListSlice<>( 6153 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6154 } 6155 6156 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6157 Intent intent, String resolvedType, int flags, int userId) { 6158 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6159 flags = updateFlagsForResolve(flags, userId, intent); 6160 ComponentName comp = intent.getComponent(); 6161 if (comp == null) { 6162 if (intent.getSelector() != null) { 6163 intent = intent.getSelector(); 6164 comp = intent.getComponent(); 6165 } 6166 } 6167 if (comp != null) { 6168 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6169 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6170 if (pi != null) { 6171 final ResolveInfo ri = new ResolveInfo(); 6172 ri.providerInfo = pi; 6173 list.add(ri); 6174 } 6175 return list; 6176 } 6177 6178 // reader 6179 synchronized (mPackages) { 6180 String pkgName = intent.getPackage(); 6181 if (pkgName == null) { 6182 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6183 } 6184 final PackageParser.Package pkg = mPackages.get(pkgName); 6185 if (pkg != null) { 6186 return mProviders.queryIntentForPackage( 6187 intent, resolvedType, flags, pkg.providers, userId); 6188 } 6189 return Collections.emptyList(); 6190 } 6191 } 6192 6193 @Override 6194 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6195 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6196 flags = updateFlagsForPackage(flags, userId, null); 6197 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6198 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6199 true /* requireFullPermission */, false /* checkShell */, 6200 "get installed packages"); 6201 6202 // writer 6203 synchronized (mPackages) { 6204 ArrayList<PackageInfo> list; 6205 if (listUninstalled) { 6206 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6207 for (PackageSetting ps : mSettings.mPackages.values()) { 6208 final PackageInfo pi; 6209 if (ps.pkg != null) { 6210 pi = generatePackageInfo(ps, flags, userId); 6211 } else { 6212 pi = generatePackageInfo(ps, flags, userId); 6213 } 6214 if (pi != null) { 6215 list.add(pi); 6216 } 6217 } 6218 } else { 6219 list = new ArrayList<PackageInfo>(mPackages.size()); 6220 for (PackageParser.Package p : mPackages.values()) { 6221 final PackageInfo pi = 6222 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6223 if (pi != null) { 6224 list.add(pi); 6225 } 6226 } 6227 } 6228 6229 return new ParceledListSlice<PackageInfo>(list); 6230 } 6231 } 6232 6233 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6234 String[] permissions, boolean[] tmp, int flags, int userId) { 6235 int numMatch = 0; 6236 final PermissionsState permissionsState = ps.getPermissionsState(); 6237 for (int i=0; i<permissions.length; i++) { 6238 final String permission = permissions[i]; 6239 if (permissionsState.hasPermission(permission, userId)) { 6240 tmp[i] = true; 6241 numMatch++; 6242 } else { 6243 tmp[i] = false; 6244 } 6245 } 6246 if (numMatch == 0) { 6247 return; 6248 } 6249 final PackageInfo pi; 6250 if (ps.pkg != null) { 6251 pi = generatePackageInfo(ps, flags, userId); 6252 } else { 6253 pi = generatePackageInfo(ps, flags, userId); 6254 } 6255 // The above might return null in cases of uninstalled apps or install-state 6256 // skew across users/profiles. 6257 if (pi != null) { 6258 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6259 if (numMatch == permissions.length) { 6260 pi.requestedPermissions = permissions; 6261 } else { 6262 pi.requestedPermissions = new String[numMatch]; 6263 numMatch = 0; 6264 for (int i=0; i<permissions.length; i++) { 6265 if (tmp[i]) { 6266 pi.requestedPermissions[numMatch] = permissions[i]; 6267 numMatch++; 6268 } 6269 } 6270 } 6271 } 6272 list.add(pi); 6273 } 6274 } 6275 6276 @Override 6277 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6278 String[] permissions, int flags, int userId) { 6279 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6280 flags = updateFlagsForPackage(flags, userId, permissions); 6281 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6282 6283 // writer 6284 synchronized (mPackages) { 6285 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6286 boolean[] tmpBools = new boolean[permissions.length]; 6287 if (listUninstalled) { 6288 for (PackageSetting ps : mSettings.mPackages.values()) { 6289 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6290 } 6291 } else { 6292 for (PackageParser.Package pkg : mPackages.values()) { 6293 PackageSetting ps = (PackageSetting)pkg.mExtras; 6294 if (ps != null) { 6295 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6296 userId); 6297 } 6298 } 6299 } 6300 6301 return new ParceledListSlice<PackageInfo>(list); 6302 } 6303 } 6304 6305 @Override 6306 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6307 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6308 flags = updateFlagsForApplication(flags, userId, null); 6309 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6310 6311 // writer 6312 synchronized (mPackages) { 6313 ArrayList<ApplicationInfo> list; 6314 if (listUninstalled) { 6315 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6316 for (PackageSetting ps : mSettings.mPackages.values()) { 6317 ApplicationInfo ai; 6318 if (ps.pkg != null) { 6319 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6320 ps.readUserState(userId), userId); 6321 } else { 6322 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6323 } 6324 if (ai != null) { 6325 list.add(ai); 6326 } 6327 } 6328 } else { 6329 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6330 for (PackageParser.Package p : mPackages.values()) { 6331 if (p.mExtras != null) { 6332 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6333 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6334 if (ai != null) { 6335 list.add(ai); 6336 } 6337 } 6338 } 6339 } 6340 6341 return new ParceledListSlice<ApplicationInfo>(list); 6342 } 6343 } 6344 6345 @Override 6346 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6347 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6348 return null; 6349 } 6350 6351 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6352 "getEphemeralApplications"); 6353 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6354 true /* requireFullPermission */, false /* checkShell */, 6355 "getEphemeralApplications"); 6356 synchronized (mPackages) { 6357 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6358 .getEphemeralApplicationsLPw(userId); 6359 if (ephemeralApps != null) { 6360 return new ParceledListSlice<>(ephemeralApps); 6361 } 6362 } 6363 return null; 6364 } 6365 6366 @Override 6367 public boolean isEphemeralApplication(String packageName, int userId) { 6368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6369 true /* requireFullPermission */, false /* checkShell */, 6370 "isEphemeral"); 6371 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6372 return false; 6373 } 6374 6375 if (!isCallerSameApp(packageName)) { 6376 return false; 6377 } 6378 synchronized (mPackages) { 6379 PackageParser.Package pkg = mPackages.get(packageName); 6380 if (pkg != null) { 6381 return pkg.applicationInfo.isEphemeralApp(); 6382 } 6383 } 6384 return false; 6385 } 6386 6387 @Override 6388 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6389 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6390 return null; 6391 } 6392 6393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6394 true /* requireFullPermission */, false /* checkShell */, 6395 "getCookie"); 6396 if (!isCallerSameApp(packageName)) { 6397 return null; 6398 } 6399 synchronized (mPackages) { 6400 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6401 packageName, userId); 6402 } 6403 } 6404 6405 @Override 6406 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6407 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6408 return true; 6409 } 6410 6411 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6412 true /* requireFullPermission */, true /* checkShell */, 6413 "setCookie"); 6414 if (!isCallerSameApp(packageName)) { 6415 return false; 6416 } 6417 synchronized (mPackages) { 6418 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6419 packageName, cookie, userId); 6420 } 6421 } 6422 6423 @Override 6424 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6425 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6426 return null; 6427 } 6428 6429 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6430 "getEphemeralApplicationIcon"); 6431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6432 true /* requireFullPermission */, false /* checkShell */, 6433 "getEphemeralApplicationIcon"); 6434 synchronized (mPackages) { 6435 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6436 packageName, userId); 6437 } 6438 } 6439 6440 private boolean isCallerSameApp(String packageName) { 6441 PackageParser.Package pkg = mPackages.get(packageName); 6442 return pkg != null 6443 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6444 } 6445 6446 @Override 6447 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6448 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6449 } 6450 6451 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6452 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6453 6454 // reader 6455 synchronized (mPackages) { 6456 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6457 final int userId = UserHandle.getCallingUserId(); 6458 while (i.hasNext()) { 6459 final PackageParser.Package p = i.next(); 6460 if (p.applicationInfo == null) continue; 6461 6462 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6463 && !p.applicationInfo.isDirectBootAware(); 6464 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6465 && p.applicationInfo.isDirectBootAware(); 6466 6467 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6468 && (!mSafeMode || isSystemApp(p)) 6469 && (matchesUnaware || matchesAware)) { 6470 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6471 if (ps != null) { 6472 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6473 ps.readUserState(userId), userId); 6474 if (ai != null) { 6475 finalList.add(ai); 6476 } 6477 } 6478 } 6479 } 6480 } 6481 6482 return finalList; 6483 } 6484 6485 @Override 6486 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6487 if (!sUserManager.exists(userId)) return null; 6488 flags = updateFlagsForComponent(flags, userId, name); 6489 // reader 6490 synchronized (mPackages) { 6491 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6492 PackageSetting ps = provider != null 6493 ? mSettings.mPackages.get(provider.owner.packageName) 6494 : null; 6495 return ps != null 6496 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6497 ? PackageParser.generateProviderInfo(provider, flags, 6498 ps.readUserState(userId), userId) 6499 : null; 6500 } 6501 } 6502 6503 /** 6504 * @deprecated 6505 */ 6506 @Deprecated 6507 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6508 // reader 6509 synchronized (mPackages) { 6510 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6511 .entrySet().iterator(); 6512 final int userId = UserHandle.getCallingUserId(); 6513 while (i.hasNext()) { 6514 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6515 PackageParser.Provider p = entry.getValue(); 6516 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6517 6518 if (ps != null && p.syncable 6519 && (!mSafeMode || (p.info.applicationInfo.flags 6520 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6521 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6522 ps.readUserState(userId), userId); 6523 if (info != null) { 6524 outNames.add(entry.getKey()); 6525 outInfo.add(info); 6526 } 6527 } 6528 } 6529 } 6530 } 6531 6532 @Override 6533 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6534 int uid, int flags) { 6535 final int userId = processName != null ? UserHandle.getUserId(uid) 6536 : UserHandle.getCallingUserId(); 6537 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6538 flags = updateFlagsForComponent(flags, userId, processName); 6539 6540 ArrayList<ProviderInfo> finalList = null; 6541 // reader 6542 synchronized (mPackages) { 6543 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6544 while (i.hasNext()) { 6545 final PackageParser.Provider p = i.next(); 6546 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6547 if (ps != null && p.info.authority != null 6548 && (processName == null 6549 || (p.info.processName.equals(processName) 6550 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6551 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6552 if (finalList == null) { 6553 finalList = new ArrayList<ProviderInfo>(3); 6554 } 6555 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6556 ps.readUserState(userId), userId); 6557 if (info != null) { 6558 finalList.add(info); 6559 } 6560 } 6561 } 6562 } 6563 6564 if (finalList != null) { 6565 Collections.sort(finalList, mProviderInitOrderSorter); 6566 return new ParceledListSlice<ProviderInfo>(finalList); 6567 } 6568 6569 return ParceledListSlice.emptyList(); 6570 } 6571 6572 @Override 6573 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6574 // reader 6575 synchronized (mPackages) { 6576 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6577 return PackageParser.generateInstrumentationInfo(i, flags); 6578 } 6579 } 6580 6581 @Override 6582 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6583 String targetPackage, int flags) { 6584 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6585 } 6586 6587 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6588 int flags) { 6589 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6590 6591 // reader 6592 synchronized (mPackages) { 6593 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6594 while (i.hasNext()) { 6595 final PackageParser.Instrumentation p = i.next(); 6596 if (targetPackage == null 6597 || targetPackage.equals(p.info.targetPackage)) { 6598 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6599 flags); 6600 if (ii != null) { 6601 finalList.add(ii); 6602 } 6603 } 6604 } 6605 } 6606 6607 return finalList; 6608 } 6609 6610 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6611 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6612 if (overlays == null) { 6613 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6614 return; 6615 } 6616 for (PackageParser.Package opkg : overlays.values()) { 6617 // Not much to do if idmap fails: we already logged the error 6618 // and we certainly don't want to abort installation of pkg simply 6619 // because an overlay didn't fit properly. For these reasons, 6620 // ignore the return value of createIdmapForPackagePairLI. 6621 createIdmapForPackagePairLI(pkg, opkg); 6622 } 6623 } 6624 6625 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6626 PackageParser.Package opkg) { 6627 if (!opkg.mTrustedOverlay) { 6628 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6629 opkg.baseCodePath + ": overlay not trusted"); 6630 return false; 6631 } 6632 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6633 if (overlaySet == null) { 6634 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6635 opkg.baseCodePath + " but target package has no known overlays"); 6636 return false; 6637 } 6638 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6639 // TODO: generate idmap for split APKs 6640 try { 6641 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6642 } catch (InstallerException e) { 6643 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6644 + opkg.baseCodePath); 6645 return false; 6646 } 6647 PackageParser.Package[] overlayArray = 6648 overlaySet.values().toArray(new PackageParser.Package[0]); 6649 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6650 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6651 return p1.mOverlayPriority - p2.mOverlayPriority; 6652 } 6653 }; 6654 Arrays.sort(overlayArray, cmp); 6655 6656 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6657 int i = 0; 6658 for (PackageParser.Package p : overlayArray) { 6659 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6660 } 6661 return true; 6662 } 6663 6664 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6665 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6666 try { 6667 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6668 } finally { 6669 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6670 } 6671 } 6672 6673 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6674 final File[] files = dir.listFiles(); 6675 if (ArrayUtils.isEmpty(files)) { 6676 Log.d(TAG, "No files in app dir " + dir); 6677 return; 6678 } 6679 6680 if (DEBUG_PACKAGE_SCANNING) { 6681 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6682 + " flags=0x" + Integer.toHexString(parseFlags)); 6683 } 6684 6685 for (File file : files) { 6686 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6687 && !PackageInstallerService.isStageName(file.getName()); 6688 if (!isPackage) { 6689 // Ignore entries which are not packages 6690 continue; 6691 } 6692 try { 6693 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6694 scanFlags, currentTime, null); 6695 } catch (PackageManagerException e) { 6696 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6697 6698 // Delete invalid userdata apps 6699 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6700 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6701 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6702 removeCodePathLI(file); 6703 } 6704 } 6705 } 6706 } 6707 6708 private static File getSettingsProblemFile() { 6709 File dataDir = Environment.getDataDirectory(); 6710 File systemDir = new File(dataDir, "system"); 6711 File fname = new File(systemDir, "uiderrors.txt"); 6712 return fname; 6713 } 6714 6715 static void reportSettingsProblem(int priority, String msg) { 6716 logCriticalInfo(priority, msg); 6717 } 6718 6719 static void logCriticalInfo(int priority, String msg) { 6720 Slog.println(priority, TAG, msg); 6721 EventLogTags.writePmCriticalInfo(msg); 6722 try { 6723 File fname = getSettingsProblemFile(); 6724 FileOutputStream out = new FileOutputStream(fname, true); 6725 PrintWriter pw = new FastPrintWriter(out); 6726 SimpleDateFormat formatter = new SimpleDateFormat(); 6727 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6728 pw.println(dateString + ": " + msg); 6729 pw.close(); 6730 FileUtils.setPermissions( 6731 fname.toString(), 6732 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6733 -1, -1); 6734 } catch (java.io.IOException e) { 6735 } 6736 } 6737 6738 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6739 if (srcFile.isDirectory()) { 6740 final File baseFile = new File(pkg.baseCodePath); 6741 long maxModifiedTime = baseFile.lastModified(); 6742 if (pkg.splitCodePaths != null) { 6743 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6744 final File splitFile = new File(pkg.splitCodePaths[i]); 6745 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6746 } 6747 } 6748 return maxModifiedTime; 6749 } 6750 return srcFile.lastModified(); 6751 } 6752 6753 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6754 final int policyFlags) throws PackageManagerException { 6755 // When upgrading from pre-N MR1, verify the package time stamp using the package 6756 // directory and not the APK file. 6757 final long lastModifiedTime = mIsPreNMR1Upgrade 6758 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6759 if (ps != null 6760 && ps.codePath.equals(srcFile) 6761 && ps.timeStamp == lastModifiedTime 6762 && !isCompatSignatureUpdateNeeded(pkg) 6763 && !isRecoverSignatureUpdateNeeded(pkg)) { 6764 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6765 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6766 ArraySet<PublicKey> signingKs; 6767 synchronized (mPackages) { 6768 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6769 } 6770 if (ps.signatures.mSignatures != null 6771 && ps.signatures.mSignatures.length != 0 6772 && signingKs != null) { 6773 // Optimization: reuse the existing cached certificates 6774 // if the package appears to be unchanged. 6775 pkg.mSignatures = ps.signatures.mSignatures; 6776 pkg.mSigningKeys = signingKs; 6777 return; 6778 } 6779 6780 Slog.w(TAG, "PackageSetting for " + ps.name 6781 + " is missing signatures. Collecting certs again to recover them."); 6782 } else { 6783 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6784 } 6785 6786 try { 6787 PackageParser.collectCertificates(pkg, policyFlags); 6788 } catch (PackageParserException e) { 6789 throw PackageManagerException.from(e); 6790 } 6791 } 6792 6793 /** 6794 * Traces a package scan. 6795 * @see #scanPackageLI(File, int, int, long, UserHandle) 6796 */ 6797 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6798 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6800 try { 6801 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6802 } finally { 6803 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6804 } 6805 } 6806 6807 /** 6808 * Scans a package and returns the newly parsed package. 6809 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6810 */ 6811 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6812 long currentTime, UserHandle user) throws PackageManagerException { 6813 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6814 PackageParser pp = new PackageParser(); 6815 pp.setSeparateProcesses(mSeparateProcesses); 6816 pp.setOnlyCoreApps(mOnlyCore); 6817 pp.setDisplayMetrics(mMetrics); 6818 6819 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6820 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6821 } 6822 6823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6824 final PackageParser.Package pkg; 6825 try { 6826 pkg = pp.parsePackage(scanFile, parseFlags); 6827 } catch (PackageParserException e) { 6828 throw PackageManagerException.from(e); 6829 } finally { 6830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6831 } 6832 6833 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6834 } 6835 6836 /** 6837 * Scans a package and returns the newly parsed package. 6838 * @throws PackageManagerException on a parse error. 6839 */ 6840 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6841 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6842 throws PackageManagerException { 6843 // If the package has children and this is the first dive in the function 6844 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6845 // packages (parent and children) would be successfully scanned before the 6846 // actual scan since scanning mutates internal state and we want to atomically 6847 // install the package and its children. 6848 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6849 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6850 scanFlags |= SCAN_CHECK_ONLY; 6851 } 6852 } else { 6853 scanFlags &= ~SCAN_CHECK_ONLY; 6854 } 6855 6856 // Scan the parent 6857 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6858 scanFlags, currentTime, user); 6859 6860 // Scan the children 6861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6862 for (int i = 0; i < childCount; i++) { 6863 PackageParser.Package childPackage = pkg.childPackages.get(i); 6864 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6865 currentTime, user); 6866 } 6867 6868 6869 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6870 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6871 } 6872 6873 return scannedPkg; 6874 } 6875 6876 /** 6877 * Scans a package and returns the newly parsed package. 6878 * @throws PackageManagerException on a parse error. 6879 */ 6880 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6881 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6882 throws PackageManagerException { 6883 PackageSetting ps = null; 6884 PackageSetting updatedPkg; 6885 // reader 6886 synchronized (mPackages) { 6887 // Look to see if we already know about this package. 6888 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6889 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6890 // This package has been renamed to its original name. Let's 6891 // use that. 6892 ps = mSettings.peekPackageLPr(oldName); 6893 } 6894 // If there was no original package, see one for the real package name. 6895 if (ps == null) { 6896 ps = mSettings.peekPackageLPr(pkg.packageName); 6897 } 6898 // Check to see if this package could be hiding/updating a system 6899 // package. Must look for it either under the original or real 6900 // package name depending on our state. 6901 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6902 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6903 6904 // If this is a package we don't know about on the system partition, we 6905 // may need to remove disabled child packages on the system partition 6906 // or may need to not add child packages if the parent apk is updated 6907 // on the data partition and no longer defines this child package. 6908 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6909 // If this is a parent package for an updated system app and this system 6910 // app got an OTA update which no longer defines some of the child packages 6911 // we have to prune them from the disabled system packages. 6912 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6913 if (disabledPs != null) { 6914 final int scannedChildCount = (pkg.childPackages != null) 6915 ? pkg.childPackages.size() : 0; 6916 final int disabledChildCount = disabledPs.childPackageNames != null 6917 ? disabledPs.childPackageNames.size() : 0; 6918 for (int i = 0; i < disabledChildCount; i++) { 6919 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6920 boolean disabledPackageAvailable = false; 6921 for (int j = 0; j < scannedChildCount; j++) { 6922 PackageParser.Package childPkg = pkg.childPackages.get(j); 6923 if (childPkg.packageName.equals(disabledChildPackageName)) { 6924 disabledPackageAvailable = true; 6925 break; 6926 } 6927 } 6928 if (!disabledPackageAvailable) { 6929 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6930 } 6931 } 6932 } 6933 } 6934 } 6935 6936 boolean updatedPkgBetter = false; 6937 // First check if this is a system package that may involve an update 6938 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6939 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6940 // it needs to drop FLAG_PRIVILEGED. 6941 if (locationIsPrivileged(scanFile)) { 6942 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6943 } else { 6944 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6945 } 6946 6947 if (ps != null && !ps.codePath.equals(scanFile)) { 6948 // The path has changed from what was last scanned... check the 6949 // version of the new path against what we have stored to determine 6950 // what to do. 6951 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6952 if (pkg.mVersionCode <= ps.versionCode) { 6953 // The system package has been updated and the code path does not match 6954 // Ignore entry. Skip it. 6955 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6956 + " ignored: updated version " + ps.versionCode 6957 + " better than this " + pkg.mVersionCode); 6958 if (!updatedPkg.codePath.equals(scanFile)) { 6959 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6960 + ps.name + " changing from " + updatedPkg.codePathString 6961 + " to " + scanFile); 6962 updatedPkg.codePath = scanFile; 6963 updatedPkg.codePathString = scanFile.toString(); 6964 updatedPkg.resourcePath = scanFile; 6965 updatedPkg.resourcePathString = scanFile.toString(); 6966 } 6967 updatedPkg.pkg = pkg; 6968 updatedPkg.versionCode = pkg.mVersionCode; 6969 6970 // Update the disabled system child packages to point to the package too. 6971 final int childCount = updatedPkg.childPackageNames != null 6972 ? updatedPkg.childPackageNames.size() : 0; 6973 for (int i = 0; i < childCount; i++) { 6974 String childPackageName = updatedPkg.childPackageNames.get(i); 6975 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6976 childPackageName); 6977 if (updatedChildPkg != null) { 6978 updatedChildPkg.pkg = pkg; 6979 updatedChildPkg.versionCode = pkg.mVersionCode; 6980 } 6981 } 6982 6983 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6984 + scanFile + " ignored: updated version " + ps.versionCode 6985 + " better than this " + pkg.mVersionCode); 6986 } else { 6987 // The current app on the system partition is better than 6988 // what we have updated to on the data partition; switch 6989 // back to the system partition version. 6990 // At this point, its safely assumed that package installation for 6991 // apps in system partition will go through. If not there won't be a working 6992 // version of the app 6993 // writer 6994 synchronized (mPackages) { 6995 // Just remove the loaded entries from package lists. 6996 mPackages.remove(ps.name); 6997 } 6998 6999 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7000 + " reverting from " + ps.codePathString 7001 + ": new version " + pkg.mVersionCode 7002 + " better than installed " + ps.versionCode); 7003 7004 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7005 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7006 synchronized (mInstallLock) { 7007 args.cleanUpResourcesLI(); 7008 } 7009 synchronized (mPackages) { 7010 mSettings.enableSystemPackageLPw(ps.name); 7011 } 7012 updatedPkgBetter = true; 7013 } 7014 } 7015 } 7016 7017 if (updatedPkg != null) { 7018 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7019 // initially 7020 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7021 7022 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7023 // flag set initially 7024 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7025 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7026 } 7027 } 7028 7029 // Verify certificates against what was last scanned 7030 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7031 7032 /* 7033 * A new system app appeared, but we already had a non-system one of the 7034 * same name installed earlier. 7035 */ 7036 boolean shouldHideSystemApp = false; 7037 if (updatedPkg == null && ps != null 7038 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7039 /* 7040 * Check to make sure the signatures match first. If they don't, 7041 * wipe the installed application and its data. 7042 */ 7043 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7044 != PackageManager.SIGNATURE_MATCH) { 7045 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7046 + " signatures don't match existing userdata copy; removing"); 7047 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7048 "scanPackageInternalLI")) { 7049 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7050 } 7051 ps = null; 7052 } else { 7053 /* 7054 * If the newly-added system app is an older version than the 7055 * already installed version, hide it. It will be scanned later 7056 * and re-added like an update. 7057 */ 7058 if (pkg.mVersionCode <= ps.versionCode) { 7059 shouldHideSystemApp = true; 7060 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7061 + " but new version " + pkg.mVersionCode + " better than installed " 7062 + ps.versionCode + "; hiding system"); 7063 } else { 7064 /* 7065 * The newly found system app is a newer version that the 7066 * one previously installed. Simply remove the 7067 * already-installed application and replace it with our own 7068 * while keeping the application data. 7069 */ 7070 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7071 + " reverting from " + ps.codePathString + ": new version " 7072 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7073 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7074 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7075 synchronized (mInstallLock) { 7076 args.cleanUpResourcesLI(); 7077 } 7078 } 7079 } 7080 } 7081 7082 // The apk is forward locked (not public) if its code and resources 7083 // are kept in different files. (except for app in either system or 7084 // vendor path). 7085 // TODO grab this value from PackageSettings 7086 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7087 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7088 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7089 } 7090 } 7091 7092 // TODO: extend to support forward-locked splits 7093 String resourcePath = null; 7094 String baseResourcePath = null; 7095 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7096 if (ps != null && ps.resourcePathString != null) { 7097 resourcePath = ps.resourcePathString; 7098 baseResourcePath = ps.resourcePathString; 7099 } else { 7100 // Should not happen at all. Just log an error. 7101 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7102 } 7103 } else { 7104 resourcePath = pkg.codePath; 7105 baseResourcePath = pkg.baseCodePath; 7106 } 7107 7108 // Set application objects path explicitly. 7109 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7110 pkg.setApplicationInfoCodePath(pkg.codePath); 7111 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7112 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7113 pkg.setApplicationInfoResourcePath(resourcePath); 7114 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7115 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7116 7117 // Note that we invoke the following method only if we are about to unpack an application 7118 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7119 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7120 7121 /* 7122 * If the system app should be overridden by a previously installed 7123 * data, hide the system app now and let the /data/app scan pick it up 7124 * again. 7125 */ 7126 if (shouldHideSystemApp) { 7127 synchronized (mPackages) { 7128 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7129 } 7130 } 7131 7132 return scannedPkg; 7133 } 7134 7135 private static String fixProcessName(String defProcessName, 7136 String processName, int uid) { 7137 if (processName == null) { 7138 return defProcessName; 7139 } 7140 return processName; 7141 } 7142 7143 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7144 throws PackageManagerException { 7145 if (pkgSetting.signatures.mSignatures != null) { 7146 // Already existing package. Make sure signatures match 7147 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7148 == PackageManager.SIGNATURE_MATCH; 7149 if (!match) { 7150 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7151 == PackageManager.SIGNATURE_MATCH; 7152 } 7153 if (!match) { 7154 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7155 == PackageManager.SIGNATURE_MATCH; 7156 } 7157 if (!match) { 7158 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7159 + pkg.packageName + " signatures do not match the " 7160 + "previously installed version; ignoring!"); 7161 } 7162 } 7163 7164 // Check for shared user signatures 7165 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7166 // Already existing package. Make sure signatures match 7167 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7168 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7169 if (!match) { 7170 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7171 == PackageManager.SIGNATURE_MATCH; 7172 } 7173 if (!match) { 7174 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7175 == PackageManager.SIGNATURE_MATCH; 7176 } 7177 if (!match) { 7178 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7179 "Package " + pkg.packageName 7180 + " has no signatures that match those in shared user " 7181 + pkgSetting.sharedUser.name + "; ignoring!"); 7182 } 7183 } 7184 } 7185 7186 /** 7187 * Enforces that only the system UID or root's UID can call a method exposed 7188 * via Binder. 7189 * 7190 * @param message used as message if SecurityException is thrown 7191 * @throws SecurityException if the caller is not system or root 7192 */ 7193 private static final void enforceSystemOrRoot(String message) { 7194 final int uid = Binder.getCallingUid(); 7195 if (uid != Process.SYSTEM_UID && uid != 0) { 7196 throw new SecurityException(message); 7197 } 7198 } 7199 7200 @Override 7201 public void performFstrimIfNeeded() { 7202 enforceSystemOrRoot("Only the system can request fstrim"); 7203 7204 // Before everything else, see whether we need to fstrim. 7205 try { 7206 IMountService ms = PackageHelper.getMountService(); 7207 if (ms != null) { 7208 boolean doTrim = false; 7209 final long interval = android.provider.Settings.Global.getLong( 7210 mContext.getContentResolver(), 7211 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7212 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7213 if (interval > 0) { 7214 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7215 if (timeSinceLast > interval) { 7216 doTrim = true; 7217 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7218 + "; running immediately"); 7219 } 7220 } 7221 if (doTrim) { 7222 final boolean dexOptDialogShown; 7223 synchronized (mPackages) { 7224 dexOptDialogShown = mDexOptDialogShown; 7225 } 7226 if (!isFirstBoot() && dexOptDialogShown) { 7227 try { 7228 ActivityManagerNative.getDefault().showBootMessage( 7229 mContext.getResources().getString( 7230 R.string.android_upgrading_fstrim), true); 7231 } catch (RemoteException e) { 7232 } 7233 } 7234 ms.runMaintenance(); 7235 } 7236 } else { 7237 Slog.e(TAG, "Mount service unavailable!"); 7238 } 7239 } catch (RemoteException e) { 7240 // Can't happen; MountService is local 7241 } 7242 } 7243 7244 @Override 7245 public void updatePackagesIfNeeded() { 7246 enforceSystemOrRoot("Only the system can request package update"); 7247 7248 // We need to re-extract after an OTA. 7249 boolean causeUpgrade = isUpgrade(); 7250 7251 // First boot or factory reset. 7252 // Note: we also handle devices that are upgrading to N right now as if it is their 7253 // first boot, as they do not have profile data. 7254 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7255 7256 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7257 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7258 7259 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7260 return; 7261 } 7262 7263 List<PackageParser.Package> pkgs; 7264 synchronized (mPackages) { 7265 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7266 } 7267 7268 final long startTime = System.nanoTime(); 7269 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7270 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7271 7272 final int elapsedTimeSeconds = 7273 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7274 7275 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7276 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7277 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7278 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7279 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7280 } 7281 7282 /** 7283 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7284 * containing statistics about the invocation. The array consists of three elements, 7285 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7286 * and {@code numberOfPackagesFailed}. 7287 */ 7288 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7289 String compilerFilter) { 7290 7291 int numberOfPackagesVisited = 0; 7292 int numberOfPackagesOptimized = 0; 7293 int numberOfPackagesSkipped = 0; 7294 int numberOfPackagesFailed = 0; 7295 final int numberOfPackagesToDexopt = pkgs.size(); 7296 7297 for (PackageParser.Package pkg : pkgs) { 7298 numberOfPackagesVisited++; 7299 7300 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7301 if (DEBUG_DEXOPT) { 7302 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7303 } 7304 numberOfPackagesSkipped++; 7305 continue; 7306 } 7307 7308 if (DEBUG_DEXOPT) { 7309 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7310 numberOfPackagesToDexopt + ": " + pkg.packageName); 7311 } 7312 7313 if (showDialog) { 7314 try { 7315 ActivityManagerNative.getDefault().showBootMessage( 7316 mContext.getResources().getString(R.string.android_upgrading_apk, 7317 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7318 } catch (RemoteException e) { 7319 } 7320 synchronized (mPackages) { 7321 mDexOptDialogShown = true; 7322 } 7323 } 7324 7325 // If the OTA updates a system app which was previously preopted to a non-preopted state 7326 // the app might end up being verified at runtime. That's because by default the apps 7327 // are verify-profile but for preopted apps there's no profile. 7328 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7329 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7330 // filter (by default interpret-only). 7331 // Note that at this stage unused apps are already filtered. 7332 if (isSystemApp(pkg) && 7333 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7334 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7335 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7336 } 7337 7338 // checkProfiles is false to avoid merging profiles during boot which 7339 // might interfere with background compilation (b/28612421). 7340 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7341 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7342 // trade-off worth doing to save boot time work. 7343 int dexOptStatus = performDexOptTraced(pkg.packageName, 7344 false /* checkProfiles */, 7345 compilerFilter, 7346 false /* force */); 7347 switch (dexOptStatus) { 7348 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7349 numberOfPackagesOptimized++; 7350 break; 7351 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7352 numberOfPackagesSkipped++; 7353 break; 7354 case PackageDexOptimizer.DEX_OPT_FAILED: 7355 numberOfPackagesFailed++; 7356 break; 7357 default: 7358 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7359 break; 7360 } 7361 } 7362 7363 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7364 numberOfPackagesFailed }; 7365 } 7366 7367 @Override 7368 public void notifyPackageUse(String packageName, int reason) { 7369 synchronized (mPackages) { 7370 PackageParser.Package p = mPackages.get(packageName); 7371 if (p == null) { 7372 return; 7373 } 7374 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7375 } 7376 } 7377 7378 // TODO: this is not used nor needed. Delete it. 7379 @Override 7380 public boolean performDexOptIfNeeded(String packageName) { 7381 int dexOptStatus = performDexOptTraced(packageName, 7382 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7383 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7384 } 7385 7386 @Override 7387 public boolean performDexOpt(String packageName, 7388 boolean checkProfiles, int compileReason, boolean force) { 7389 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7390 getCompilerFilterForReason(compileReason), force); 7391 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7392 } 7393 7394 @Override 7395 public boolean performDexOptMode(String packageName, 7396 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7397 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7398 targetCompilerFilter, force); 7399 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7400 } 7401 7402 private int performDexOptTraced(String packageName, 7403 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7404 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7405 try { 7406 return performDexOptInternal(packageName, checkProfiles, 7407 targetCompilerFilter, force); 7408 } finally { 7409 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7410 } 7411 } 7412 7413 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7414 // if the package can now be considered up to date for the given filter. 7415 private int performDexOptInternal(String packageName, 7416 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7417 PackageParser.Package p; 7418 synchronized (mPackages) { 7419 p = mPackages.get(packageName); 7420 if (p == null) { 7421 // Package could not be found. Report failure. 7422 return PackageDexOptimizer.DEX_OPT_FAILED; 7423 } 7424 mPackageUsage.maybeWriteAsync(mPackages); 7425 mCompilerStats.maybeWriteAsync(); 7426 } 7427 long callingId = Binder.clearCallingIdentity(); 7428 try { 7429 synchronized (mInstallLock) { 7430 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7431 targetCompilerFilter, force); 7432 } 7433 } finally { 7434 Binder.restoreCallingIdentity(callingId); 7435 } 7436 } 7437 7438 public ArraySet<String> getOptimizablePackages() { 7439 ArraySet<String> pkgs = new ArraySet<String>(); 7440 synchronized (mPackages) { 7441 for (PackageParser.Package p : mPackages.values()) { 7442 if (PackageDexOptimizer.canOptimizePackage(p)) { 7443 pkgs.add(p.packageName); 7444 } 7445 } 7446 } 7447 return pkgs; 7448 } 7449 7450 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7451 boolean checkProfiles, String targetCompilerFilter, 7452 boolean force) { 7453 // Select the dex optimizer based on the force parameter. 7454 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7455 // allocate an object here. 7456 PackageDexOptimizer pdo = force 7457 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7458 : mPackageDexOptimizer; 7459 7460 // Optimize all dependencies first. Note: we ignore the return value and march on 7461 // on errors. 7462 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7463 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7464 if (!deps.isEmpty()) { 7465 for (PackageParser.Package depPackage : deps) { 7466 // TODO: Analyze and investigate if we (should) profile libraries. 7467 // Currently this will do a full compilation of the library by default. 7468 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7469 false /* checkProfiles */, 7470 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7471 getOrCreateCompilerPackageStats(depPackage)); 7472 } 7473 } 7474 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7475 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7476 } 7477 7478 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7479 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7480 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7481 Set<String> collectedNames = new HashSet<>(); 7482 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7483 7484 retValue.remove(p); 7485 7486 return retValue; 7487 } else { 7488 return Collections.emptyList(); 7489 } 7490 } 7491 7492 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7493 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7494 if (!collectedNames.contains(p.packageName)) { 7495 collectedNames.add(p.packageName); 7496 collected.add(p); 7497 7498 if (p.usesLibraries != null) { 7499 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7500 } 7501 if (p.usesOptionalLibraries != null) { 7502 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7503 collectedNames); 7504 } 7505 } 7506 } 7507 7508 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7509 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7510 for (String libName : libs) { 7511 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7512 if (libPkg != null) { 7513 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7514 } 7515 } 7516 } 7517 7518 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7519 synchronized (mPackages) { 7520 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7521 if (lib != null && lib.apk != null) { 7522 return mPackages.get(lib.apk); 7523 } 7524 } 7525 return null; 7526 } 7527 7528 public void shutdown() { 7529 mPackageUsage.writeNow(mPackages); 7530 mCompilerStats.writeNow(); 7531 } 7532 7533 @Override 7534 public void dumpProfiles(String packageName) { 7535 PackageParser.Package pkg; 7536 synchronized (mPackages) { 7537 pkg = mPackages.get(packageName); 7538 if (pkg == null) { 7539 throw new IllegalArgumentException("Unknown package: " + packageName); 7540 } 7541 } 7542 /* Only the shell, root, or the app user should be able to dump profiles. */ 7543 int callingUid = Binder.getCallingUid(); 7544 if (callingUid != Process.SHELL_UID && 7545 callingUid != Process.ROOT_UID && 7546 callingUid != pkg.applicationInfo.uid) { 7547 throw new SecurityException("dumpProfiles"); 7548 } 7549 7550 synchronized (mInstallLock) { 7551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7552 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7553 try { 7554 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7555 String gid = Integer.toString(sharedGid); 7556 String codePaths = TextUtils.join(";", allCodePaths); 7557 mInstaller.dumpProfiles(gid, packageName, codePaths); 7558 } catch (InstallerException e) { 7559 Slog.w(TAG, "Failed to dump profiles", e); 7560 } 7561 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7562 } 7563 } 7564 7565 @Override 7566 public void forceDexOpt(String packageName) { 7567 enforceSystemOrRoot("forceDexOpt"); 7568 7569 PackageParser.Package pkg; 7570 synchronized (mPackages) { 7571 pkg = mPackages.get(packageName); 7572 if (pkg == null) { 7573 throw new IllegalArgumentException("Unknown package: " + packageName); 7574 } 7575 } 7576 7577 synchronized (mInstallLock) { 7578 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7579 7580 // Whoever is calling forceDexOpt wants a fully compiled package. 7581 // Don't use profiles since that may cause compilation to be skipped. 7582 final int res = performDexOptInternalWithDependenciesLI(pkg, 7583 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7584 true /* force */); 7585 7586 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7587 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7588 throw new IllegalStateException("Failed to dexopt: " + res); 7589 } 7590 } 7591 } 7592 7593 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7594 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7595 Slog.w(TAG, "Unable to update from " + oldPkg.name 7596 + " to " + newPkg.packageName 7597 + ": old package not in system partition"); 7598 return false; 7599 } else if (mPackages.get(oldPkg.name) != null) { 7600 Slog.w(TAG, "Unable to update from " + oldPkg.name 7601 + " to " + newPkg.packageName 7602 + ": old package still exists"); 7603 return false; 7604 } 7605 return true; 7606 } 7607 7608 void removeCodePathLI(File codePath) { 7609 if (codePath.isDirectory()) { 7610 try { 7611 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7612 } catch (InstallerException e) { 7613 Slog.w(TAG, "Failed to remove code path", e); 7614 } 7615 } else { 7616 codePath.delete(); 7617 } 7618 } 7619 7620 private int[] resolveUserIds(int userId) { 7621 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7622 } 7623 7624 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7625 if (pkg == null) { 7626 Slog.wtf(TAG, "Package was null!", new Throwable()); 7627 return; 7628 } 7629 clearAppDataLeafLIF(pkg, userId, flags); 7630 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7631 for (int i = 0; i < childCount; i++) { 7632 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7633 } 7634 } 7635 7636 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7637 final PackageSetting ps; 7638 synchronized (mPackages) { 7639 ps = mSettings.mPackages.get(pkg.packageName); 7640 } 7641 for (int realUserId : resolveUserIds(userId)) { 7642 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7643 try { 7644 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7645 ceDataInode); 7646 } catch (InstallerException e) { 7647 Slog.w(TAG, String.valueOf(e)); 7648 } 7649 } 7650 } 7651 7652 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7653 if (pkg == null) { 7654 Slog.wtf(TAG, "Package was null!", new Throwable()); 7655 return; 7656 } 7657 destroyAppDataLeafLIF(pkg, userId, flags); 7658 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7659 for (int i = 0; i < childCount; i++) { 7660 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7661 } 7662 } 7663 7664 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7665 final PackageSetting ps; 7666 synchronized (mPackages) { 7667 ps = mSettings.mPackages.get(pkg.packageName); 7668 } 7669 for (int realUserId : resolveUserIds(userId)) { 7670 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7671 try { 7672 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7673 ceDataInode); 7674 } catch (InstallerException e) { 7675 Slog.w(TAG, String.valueOf(e)); 7676 } 7677 } 7678 } 7679 7680 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7681 if (pkg == null) { 7682 Slog.wtf(TAG, "Package was null!", new Throwable()); 7683 return; 7684 } 7685 destroyAppProfilesLeafLIF(pkg); 7686 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7687 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7688 for (int i = 0; i < childCount; i++) { 7689 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7690 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7691 true /* removeBaseMarker */); 7692 } 7693 } 7694 7695 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7696 boolean removeBaseMarker) { 7697 if (pkg.isForwardLocked()) { 7698 return; 7699 } 7700 7701 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7702 try { 7703 path = PackageManagerServiceUtils.realpath(new File(path)); 7704 } catch (IOException e) { 7705 // TODO: Should we return early here ? 7706 Slog.w(TAG, "Failed to get canonical path", e); 7707 continue; 7708 } 7709 7710 final String useMarker = path.replace('/', '@'); 7711 for (int realUserId : resolveUserIds(userId)) { 7712 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7713 if (removeBaseMarker) { 7714 File foreignUseMark = new File(profileDir, useMarker); 7715 if (foreignUseMark.exists()) { 7716 if (!foreignUseMark.delete()) { 7717 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7718 + pkg.packageName); 7719 } 7720 } 7721 } 7722 7723 File[] markers = profileDir.listFiles(); 7724 if (markers != null) { 7725 final String searchString = "@" + pkg.packageName + "@"; 7726 // We also delete all markers that contain the package name we're 7727 // uninstalling. These are associated with secondary dex-files belonging 7728 // to the package. Reconstructing the path of these dex files is messy 7729 // in general. 7730 for (File marker : markers) { 7731 if (marker.getName().indexOf(searchString) > 0) { 7732 if (!marker.delete()) { 7733 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7734 + pkg.packageName); 7735 } 7736 } 7737 } 7738 } 7739 } 7740 } 7741 } 7742 7743 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7744 try { 7745 mInstaller.destroyAppProfiles(pkg.packageName); 7746 } catch (InstallerException e) { 7747 Slog.w(TAG, String.valueOf(e)); 7748 } 7749 } 7750 7751 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7752 if (pkg == null) { 7753 Slog.wtf(TAG, "Package was null!", new Throwable()); 7754 return; 7755 } 7756 clearAppProfilesLeafLIF(pkg); 7757 // We don't remove the base foreign use marker when clearing profiles because 7758 // we will rename it when the app is updated. Unlike the actual profile contents, 7759 // the foreign use marker is good across installs. 7760 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7761 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7762 for (int i = 0; i < childCount; i++) { 7763 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7764 } 7765 } 7766 7767 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7768 try { 7769 mInstaller.clearAppProfiles(pkg.packageName); 7770 } catch (InstallerException e) { 7771 Slog.w(TAG, String.valueOf(e)); 7772 } 7773 } 7774 7775 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7776 long lastUpdateTime) { 7777 // Set parent install/update time 7778 PackageSetting ps = (PackageSetting) pkg.mExtras; 7779 if (ps != null) { 7780 ps.firstInstallTime = firstInstallTime; 7781 ps.lastUpdateTime = lastUpdateTime; 7782 } 7783 // Set children install/update time 7784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7785 for (int i = 0; i < childCount; i++) { 7786 PackageParser.Package childPkg = pkg.childPackages.get(i); 7787 ps = (PackageSetting) childPkg.mExtras; 7788 if (ps != null) { 7789 ps.firstInstallTime = firstInstallTime; 7790 ps.lastUpdateTime = lastUpdateTime; 7791 } 7792 } 7793 } 7794 7795 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7796 PackageParser.Package changingLib) { 7797 if (file.path != null) { 7798 usesLibraryFiles.add(file.path); 7799 return; 7800 } 7801 PackageParser.Package p = mPackages.get(file.apk); 7802 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7803 // If we are doing this while in the middle of updating a library apk, 7804 // then we need to make sure to use that new apk for determining the 7805 // dependencies here. (We haven't yet finished committing the new apk 7806 // to the package manager state.) 7807 if (p == null || p.packageName.equals(changingLib.packageName)) { 7808 p = changingLib; 7809 } 7810 } 7811 if (p != null) { 7812 usesLibraryFiles.addAll(p.getAllCodePaths()); 7813 } 7814 } 7815 7816 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7817 PackageParser.Package changingLib) throws PackageManagerException { 7818 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7819 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7820 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7821 for (int i=0; i<N; i++) { 7822 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7823 if (file == null) { 7824 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7825 "Package " + pkg.packageName + " requires unavailable shared library " 7826 + pkg.usesLibraries.get(i) + "; failing!"); 7827 } 7828 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7829 } 7830 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7831 for (int i=0; i<N; i++) { 7832 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7833 if (file == null) { 7834 Slog.w(TAG, "Package " + pkg.packageName 7835 + " desires unavailable shared library " 7836 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7837 } else { 7838 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7839 } 7840 } 7841 N = usesLibraryFiles.size(); 7842 if (N > 0) { 7843 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7844 } else { 7845 pkg.usesLibraryFiles = null; 7846 } 7847 } 7848 } 7849 7850 private static boolean hasString(List<String> list, List<String> which) { 7851 if (list == null) { 7852 return false; 7853 } 7854 for (int i=list.size()-1; i>=0; i--) { 7855 for (int j=which.size()-1; j>=0; j--) { 7856 if (which.get(j).equals(list.get(i))) { 7857 return true; 7858 } 7859 } 7860 } 7861 return false; 7862 } 7863 7864 private void updateAllSharedLibrariesLPw() { 7865 for (PackageParser.Package pkg : mPackages.values()) { 7866 try { 7867 updateSharedLibrariesLPw(pkg, null); 7868 } catch (PackageManagerException e) { 7869 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7870 } 7871 } 7872 } 7873 7874 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7875 PackageParser.Package changingPkg) { 7876 ArrayList<PackageParser.Package> res = null; 7877 for (PackageParser.Package pkg : mPackages.values()) { 7878 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7879 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7880 if (res == null) { 7881 res = new ArrayList<PackageParser.Package>(); 7882 } 7883 res.add(pkg); 7884 try { 7885 updateSharedLibrariesLPw(pkg, changingPkg); 7886 } catch (PackageManagerException e) { 7887 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7888 } 7889 } 7890 } 7891 return res; 7892 } 7893 7894 /** 7895 * Derive the value of the {@code cpuAbiOverride} based on the provided 7896 * value and an optional stored value from the package settings. 7897 */ 7898 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7899 String cpuAbiOverride = null; 7900 7901 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7902 cpuAbiOverride = null; 7903 } else if (abiOverride != null) { 7904 cpuAbiOverride = abiOverride; 7905 } else if (settings != null) { 7906 cpuAbiOverride = settings.cpuAbiOverrideString; 7907 } 7908 7909 return cpuAbiOverride; 7910 } 7911 7912 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7913 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7914 throws PackageManagerException { 7915 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7916 // If the package has children and this is the first dive in the function 7917 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7918 // whether all packages (parent and children) would be successfully scanned 7919 // before the actual scan since scanning mutates internal state and we want 7920 // to atomically install the package and its children. 7921 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7922 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7923 scanFlags |= SCAN_CHECK_ONLY; 7924 } 7925 } else { 7926 scanFlags &= ~SCAN_CHECK_ONLY; 7927 } 7928 7929 final PackageParser.Package scannedPkg; 7930 try { 7931 // Scan the parent 7932 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7933 // Scan the children 7934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7935 for (int i = 0; i < childCount; i++) { 7936 PackageParser.Package childPkg = pkg.childPackages.get(i); 7937 scanPackageLI(childPkg, policyFlags, 7938 scanFlags, currentTime, user); 7939 } 7940 } finally { 7941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7942 } 7943 7944 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7945 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7946 } 7947 7948 return scannedPkg; 7949 } 7950 7951 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7952 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7953 boolean success = false; 7954 try { 7955 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7956 currentTime, user); 7957 success = true; 7958 return res; 7959 } finally { 7960 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7961 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7962 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7963 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7964 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7965 } 7966 } 7967 } 7968 7969 /** 7970 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7971 */ 7972 private static boolean apkHasCode(String fileName) { 7973 StrictJarFile jarFile = null; 7974 try { 7975 jarFile = new StrictJarFile(fileName, 7976 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7977 return jarFile.findEntry("classes.dex") != null; 7978 } catch (IOException ignore) { 7979 } finally { 7980 try { 7981 if (jarFile != null) { 7982 jarFile.close(); 7983 } 7984 } catch (IOException ignore) {} 7985 } 7986 return false; 7987 } 7988 7989 /** 7990 * Enforces code policy for the package. This ensures that if an APK has 7991 * declared hasCode="true" in its manifest that the APK actually contains 7992 * code. 7993 * 7994 * @throws PackageManagerException If bytecode could not be found when it should exist 7995 */ 7996 private static void enforceCodePolicy(PackageParser.Package pkg) 7997 throws PackageManagerException { 7998 final boolean shouldHaveCode = 7999 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8000 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8001 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8002 "Package " + pkg.baseCodePath + " code is missing"); 8003 } 8004 8005 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8006 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8007 final boolean splitShouldHaveCode = 8008 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8009 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8010 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8011 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8012 } 8013 } 8014 } 8015 } 8016 8017 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8018 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8019 throws PackageManagerException { 8020 final File scanFile = new File(pkg.codePath); 8021 if (pkg.applicationInfo.getCodePath() == null || 8022 pkg.applicationInfo.getResourcePath() == null) { 8023 // Bail out. The resource and code paths haven't been set. 8024 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8025 "Code and resource paths haven't been set correctly"); 8026 } 8027 8028 // Apply policy 8029 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8030 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8031 if (pkg.applicationInfo.isDirectBootAware()) { 8032 // we're direct boot aware; set for all components 8033 for (PackageParser.Service s : pkg.services) { 8034 s.info.encryptionAware = s.info.directBootAware = true; 8035 } 8036 for (PackageParser.Provider p : pkg.providers) { 8037 p.info.encryptionAware = p.info.directBootAware = true; 8038 } 8039 for (PackageParser.Activity a : pkg.activities) { 8040 a.info.encryptionAware = a.info.directBootAware = true; 8041 } 8042 for (PackageParser.Activity r : pkg.receivers) { 8043 r.info.encryptionAware = r.info.directBootAware = true; 8044 } 8045 } 8046 } else { 8047 // Only allow system apps to be flagged as core apps. 8048 pkg.coreApp = false; 8049 // clear flags not applicable to regular apps 8050 pkg.applicationInfo.privateFlags &= 8051 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8052 pkg.applicationInfo.privateFlags &= 8053 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8054 } 8055 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8056 8057 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8058 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8059 } 8060 8061 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8062 enforceCodePolicy(pkg); 8063 } 8064 8065 if (mCustomResolverComponentName != null && 8066 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8067 setUpCustomResolverActivity(pkg); 8068 } 8069 8070 if (pkg.packageName.equals("android")) { 8071 synchronized (mPackages) { 8072 if (mAndroidApplication != null) { 8073 Slog.w(TAG, "*************************************************"); 8074 Slog.w(TAG, "Core android package being redefined. Skipping."); 8075 Slog.w(TAG, " file=" + scanFile); 8076 Slog.w(TAG, "*************************************************"); 8077 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8078 "Core android package being redefined. Skipping."); 8079 } 8080 8081 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8082 // Set up information for our fall-back user intent resolution activity. 8083 mPlatformPackage = pkg; 8084 pkg.mVersionCode = mSdkVersion; 8085 mAndroidApplication = pkg.applicationInfo; 8086 8087 if (!mResolverReplaced) { 8088 mResolveActivity.applicationInfo = mAndroidApplication; 8089 mResolveActivity.name = ResolverActivity.class.getName(); 8090 mResolveActivity.packageName = mAndroidApplication.packageName; 8091 mResolveActivity.processName = "system:ui"; 8092 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8093 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8094 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8095 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8096 mResolveActivity.exported = true; 8097 mResolveActivity.enabled = true; 8098 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8099 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8100 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8101 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8102 | ActivityInfo.CONFIG_ORIENTATION 8103 | ActivityInfo.CONFIG_KEYBOARD 8104 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8105 mResolveInfo.activityInfo = mResolveActivity; 8106 mResolveInfo.priority = 0; 8107 mResolveInfo.preferredOrder = 0; 8108 mResolveInfo.match = 0; 8109 mResolveComponentName = new ComponentName( 8110 mAndroidApplication.packageName, mResolveActivity.name); 8111 } 8112 } 8113 } 8114 } 8115 8116 if (DEBUG_PACKAGE_SCANNING) { 8117 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8118 Log.d(TAG, "Scanning package " + pkg.packageName); 8119 } 8120 8121 synchronized (mPackages) { 8122 if (mPackages.containsKey(pkg.packageName) 8123 || mSharedLibraries.containsKey(pkg.packageName)) { 8124 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8125 "Application package " + pkg.packageName 8126 + " already installed. Skipping duplicate."); 8127 } 8128 8129 // If we're only installing presumed-existing packages, require that the 8130 // scanned APK is both already known and at the path previously established 8131 // for it. Previously unknown packages we pick up normally, but if we have an 8132 // a priori expectation about this package's install presence, enforce it. 8133 // With a singular exception for new system packages. When an OTA contains 8134 // a new system package, we allow the codepath to change from a system location 8135 // to the user-installed location. If we don't allow this change, any newer, 8136 // user-installed version of the application will be ignored. 8137 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8138 if (mExpectingBetter.containsKey(pkg.packageName)) { 8139 logCriticalInfo(Log.WARN, 8140 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8141 } else { 8142 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8143 if (known != null) { 8144 if (DEBUG_PACKAGE_SCANNING) { 8145 Log.d(TAG, "Examining " + pkg.codePath 8146 + " and requiring known paths " + known.codePathString 8147 + " & " + known.resourcePathString); 8148 } 8149 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8150 || !pkg.applicationInfo.getResourcePath().equals( 8151 known.resourcePathString)) { 8152 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8153 "Application package " + pkg.packageName 8154 + " found at " + pkg.applicationInfo.getCodePath() 8155 + " but expected at " + known.codePathString 8156 + "; ignoring."); 8157 } 8158 } 8159 } 8160 } 8161 } 8162 8163 // Initialize package source and resource directories 8164 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8165 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8166 8167 SharedUserSetting suid = null; 8168 PackageSetting pkgSetting = null; 8169 8170 if (!isSystemApp(pkg)) { 8171 // Only system apps can use these features. 8172 pkg.mOriginalPackages = null; 8173 pkg.mRealPackage = null; 8174 pkg.mAdoptPermissions = null; 8175 } 8176 8177 // Getting the package setting may have a side-effect, so if we 8178 // are only checking if scan would succeed, stash a copy of the 8179 // old setting to restore at the end. 8180 PackageSetting nonMutatedPs = null; 8181 8182 // writer 8183 synchronized (mPackages) { 8184 if (pkg.mSharedUserId != null) { 8185 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8186 if (suid == null) { 8187 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8188 "Creating application package " + pkg.packageName 8189 + " for shared user failed"); 8190 } 8191 if (DEBUG_PACKAGE_SCANNING) { 8192 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8193 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8194 + "): packages=" + suid.packages); 8195 } 8196 } 8197 8198 // Check if we are renaming from an original package name. 8199 PackageSetting origPackage = null; 8200 String realName = null; 8201 if (pkg.mOriginalPackages != null) { 8202 // This package may need to be renamed to a previously 8203 // installed name. Let's check on that... 8204 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8205 if (pkg.mOriginalPackages.contains(renamed)) { 8206 // This package had originally been installed as the 8207 // original name, and we have already taken care of 8208 // transitioning to the new one. Just update the new 8209 // one to continue using the old name. 8210 realName = pkg.mRealPackage; 8211 if (!pkg.packageName.equals(renamed)) { 8212 // Callers into this function may have already taken 8213 // care of renaming the package; only do it here if 8214 // it is not already done. 8215 pkg.setPackageName(renamed); 8216 } 8217 8218 } else { 8219 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8220 if ((origPackage = mSettings.peekPackageLPr( 8221 pkg.mOriginalPackages.get(i))) != null) { 8222 // We do have the package already installed under its 8223 // original name... should we use it? 8224 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8225 // New package is not compatible with original. 8226 origPackage = null; 8227 continue; 8228 } else if (origPackage.sharedUser != null) { 8229 // Make sure uid is compatible between packages. 8230 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8231 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8232 + " to " + pkg.packageName + ": old uid " 8233 + origPackage.sharedUser.name 8234 + " differs from " + pkg.mSharedUserId); 8235 origPackage = null; 8236 continue; 8237 } 8238 // TODO: Add case when shared user id is added [b/28144775] 8239 } else { 8240 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8241 + pkg.packageName + " to old name " + origPackage.name); 8242 } 8243 break; 8244 } 8245 } 8246 } 8247 } 8248 8249 if (mTransferedPackages.contains(pkg.packageName)) { 8250 Slog.w(TAG, "Package " + pkg.packageName 8251 + " was transferred to another, but its .apk remains"); 8252 } 8253 8254 // See comments in nonMutatedPs declaration 8255 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8256 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8257 if (foundPs != null) { 8258 nonMutatedPs = new PackageSetting(foundPs); 8259 } 8260 } 8261 8262 // Just create the setting, don't add it yet. For already existing packages 8263 // the PkgSetting exists already and doesn't have to be created. 8264 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8265 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8266 pkg.applicationInfo.primaryCpuAbi, 8267 pkg.applicationInfo.secondaryCpuAbi, 8268 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8269 user, false); 8270 if (pkgSetting == null) { 8271 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8272 "Creating application package " + pkg.packageName + " failed"); 8273 } 8274 8275 if (pkgSetting.origPackage != null) { 8276 // If we are first transitioning from an original package, 8277 // fix up the new package's name now. We need to do this after 8278 // looking up the package under its new name, so getPackageLP 8279 // can take care of fiddling things correctly. 8280 pkg.setPackageName(origPackage.name); 8281 8282 // File a report about this. 8283 String msg = "New package " + pkgSetting.realName 8284 + " renamed to replace old package " + pkgSetting.name; 8285 reportSettingsProblem(Log.WARN, msg); 8286 8287 // Make a note of it. 8288 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8289 mTransferedPackages.add(origPackage.name); 8290 } 8291 8292 // No longer need to retain this. 8293 pkgSetting.origPackage = null; 8294 } 8295 8296 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8297 // Make a note of it. 8298 mTransferedPackages.add(pkg.packageName); 8299 } 8300 8301 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8302 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8303 } 8304 8305 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8306 // Check all shared libraries and map to their actual file path. 8307 // We only do this here for apps not on a system dir, because those 8308 // are the only ones that can fail an install due to this. We 8309 // will take care of the system apps by updating all of their 8310 // library paths after the scan is done. 8311 updateSharedLibrariesLPw(pkg, null); 8312 } 8313 8314 if (mFoundPolicyFile) { 8315 SELinuxMMAC.assignSeinfoValue(pkg); 8316 } 8317 8318 pkg.applicationInfo.uid = pkgSetting.appId; 8319 pkg.mExtras = pkgSetting; 8320 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8321 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8322 // We just determined the app is signed correctly, so bring 8323 // over the latest parsed certs. 8324 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8325 } else { 8326 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8327 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8328 "Package " + pkg.packageName + " upgrade keys do not match the " 8329 + "previously installed version"); 8330 } else { 8331 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8332 String msg = "System package " + pkg.packageName 8333 + " signature changed; retaining data."; 8334 reportSettingsProblem(Log.WARN, msg); 8335 } 8336 } 8337 } else { 8338 try { 8339 verifySignaturesLP(pkgSetting, pkg); 8340 // We just determined the app is signed correctly, so bring 8341 // over the latest parsed certs. 8342 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8343 } catch (PackageManagerException e) { 8344 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8345 throw e; 8346 } 8347 // The signature has changed, but this package is in the system 8348 // image... let's recover! 8349 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8350 // However... if this package is part of a shared user, but it 8351 // doesn't match the signature of the shared user, let's fail. 8352 // What this means is that you can't change the signatures 8353 // associated with an overall shared user, which doesn't seem all 8354 // that unreasonable. 8355 if (pkgSetting.sharedUser != null) { 8356 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8357 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8358 throw new PackageManagerException( 8359 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8360 "Signature mismatch for shared user: " 8361 + pkgSetting.sharedUser); 8362 } 8363 } 8364 // File a report about this. 8365 String msg = "System package " + pkg.packageName 8366 + " signature changed; retaining data."; 8367 reportSettingsProblem(Log.WARN, msg); 8368 } 8369 } 8370 // Verify that this new package doesn't have any content providers 8371 // that conflict with existing packages. Only do this if the 8372 // package isn't already installed, since we don't want to break 8373 // things that are installed. 8374 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8375 final int N = pkg.providers.size(); 8376 int i; 8377 for (i=0; i<N; i++) { 8378 PackageParser.Provider p = pkg.providers.get(i); 8379 if (p.info.authority != null) { 8380 String names[] = p.info.authority.split(";"); 8381 for (int j = 0; j < names.length; j++) { 8382 if (mProvidersByAuthority.containsKey(names[j])) { 8383 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8384 final String otherPackageName = 8385 ((other != null && other.getComponentName() != null) ? 8386 other.getComponentName().getPackageName() : "?"); 8387 throw new PackageManagerException( 8388 INSTALL_FAILED_CONFLICTING_PROVIDER, 8389 "Can't install because provider name " + names[j] 8390 + " (in package " + pkg.applicationInfo.packageName 8391 + ") is already used by " + otherPackageName); 8392 } 8393 } 8394 } 8395 } 8396 } 8397 8398 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8399 // This package wants to adopt ownership of permissions from 8400 // another package. 8401 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8402 final String origName = pkg.mAdoptPermissions.get(i); 8403 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8404 if (orig != null) { 8405 if (verifyPackageUpdateLPr(orig, pkg)) { 8406 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8407 + pkg.packageName); 8408 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8409 } 8410 } 8411 } 8412 } 8413 } 8414 8415 final String pkgName = pkg.packageName; 8416 8417 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8418 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8419 pkg.applicationInfo.processName = fixProcessName( 8420 pkg.applicationInfo.packageName, 8421 pkg.applicationInfo.processName, 8422 pkg.applicationInfo.uid); 8423 8424 if (pkg != mPlatformPackage) { 8425 // Get all of our default paths setup 8426 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8427 } 8428 8429 final String path = scanFile.getPath(); 8430 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8431 8432 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8433 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8434 8435 // Some system apps still use directory structure for native libraries 8436 // in which case we might end up not detecting abi solely based on apk 8437 // structure. Try to detect abi based on directory structure. 8438 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8439 pkg.applicationInfo.primaryCpuAbi == null) { 8440 setBundledAppAbisAndRoots(pkg, pkgSetting); 8441 setNativeLibraryPaths(pkg); 8442 } 8443 8444 } else { 8445 if ((scanFlags & SCAN_MOVE) != 0) { 8446 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8447 // but we already have this packages package info in the PackageSetting. We just 8448 // use that and derive the native library path based on the new codepath. 8449 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8450 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8451 } 8452 8453 // Set native library paths again. For moves, the path will be updated based on the 8454 // ABIs we've determined above. For non-moves, the path will be updated based on the 8455 // ABIs we determined during compilation, but the path will depend on the final 8456 // package path (after the rename away from the stage path). 8457 setNativeLibraryPaths(pkg); 8458 } 8459 8460 // This is a special case for the "system" package, where the ABI is 8461 // dictated by the zygote configuration (and init.rc). We should keep track 8462 // of this ABI so that we can deal with "normal" applications that run under 8463 // the same UID correctly. 8464 if (mPlatformPackage == pkg) { 8465 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8466 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8467 } 8468 8469 // If there's a mismatch between the abi-override in the package setting 8470 // and the abiOverride specified for the install. Warn about this because we 8471 // would've already compiled the app without taking the package setting into 8472 // account. 8473 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8474 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8475 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8476 " for package " + pkg.packageName); 8477 } 8478 } 8479 8480 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8481 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8482 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8483 8484 // Copy the derived override back to the parsed package, so that we can 8485 // update the package settings accordingly. 8486 pkg.cpuAbiOverride = cpuAbiOverride; 8487 8488 if (DEBUG_ABI_SELECTION) { 8489 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8490 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8491 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8492 } 8493 8494 // Push the derived path down into PackageSettings so we know what to 8495 // clean up at uninstall time. 8496 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8497 8498 if (DEBUG_ABI_SELECTION) { 8499 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8500 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8501 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8502 } 8503 8504 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8505 // We don't do this here during boot because we can do it all 8506 // at once after scanning all existing packages. 8507 // 8508 // We also do this *before* we perform dexopt on this package, so that 8509 // we can avoid redundant dexopts, and also to make sure we've got the 8510 // code and package path correct. 8511 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8512 pkg, true /* boot complete */); 8513 } 8514 8515 if (mFactoryTest && pkg.requestedPermissions.contains( 8516 android.Manifest.permission.FACTORY_TEST)) { 8517 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8518 } 8519 8520 if (isSystemApp(pkg)) { 8521 pkgSetting.isOrphaned = true; 8522 } 8523 8524 ArrayList<PackageParser.Package> clientLibPkgs = null; 8525 8526 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8527 if (nonMutatedPs != null) { 8528 synchronized (mPackages) { 8529 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8530 } 8531 } 8532 return pkg; 8533 } 8534 8535 // Only privileged apps and updated privileged apps can add child packages. 8536 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8537 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8538 throw new PackageManagerException("Only privileged apps and updated " 8539 + "privileged apps can add child packages. Ignoring package " 8540 + pkg.packageName); 8541 } 8542 final int childCount = pkg.childPackages.size(); 8543 for (int i = 0; i < childCount; i++) { 8544 PackageParser.Package childPkg = pkg.childPackages.get(i); 8545 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8546 childPkg.packageName)) { 8547 throw new PackageManagerException("Cannot override a child package of " 8548 + "another disabled system app. Ignoring package " + pkg.packageName); 8549 } 8550 } 8551 } 8552 8553 // writer 8554 synchronized (mPackages) { 8555 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8556 // Only system apps can add new shared libraries. 8557 if (pkg.libraryNames != null) { 8558 for (int i=0; i<pkg.libraryNames.size(); i++) { 8559 String name = pkg.libraryNames.get(i); 8560 boolean allowed = false; 8561 if (pkg.isUpdatedSystemApp()) { 8562 // New library entries can only be added through the 8563 // system image. This is important to get rid of a lot 8564 // of nasty edge cases: for example if we allowed a non- 8565 // system update of the app to add a library, then uninstalling 8566 // the update would make the library go away, and assumptions 8567 // we made such as through app install filtering would now 8568 // have allowed apps on the device which aren't compatible 8569 // with it. Better to just have the restriction here, be 8570 // conservative, and create many fewer cases that can negatively 8571 // impact the user experience. 8572 final PackageSetting sysPs = mSettings 8573 .getDisabledSystemPkgLPr(pkg.packageName); 8574 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8575 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8576 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8577 allowed = true; 8578 break; 8579 } 8580 } 8581 } 8582 } else { 8583 allowed = true; 8584 } 8585 if (allowed) { 8586 if (!mSharedLibraries.containsKey(name)) { 8587 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8588 } else if (!name.equals(pkg.packageName)) { 8589 Slog.w(TAG, "Package " + pkg.packageName + " library " 8590 + name + " already exists; skipping"); 8591 } 8592 } else { 8593 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8594 + name + " that is not declared on system image; skipping"); 8595 } 8596 } 8597 if ((scanFlags & SCAN_BOOTING) == 0) { 8598 // If we are not booting, we need to update any applications 8599 // that are clients of our shared library. If we are booting, 8600 // this will all be done once the scan is complete. 8601 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8602 } 8603 } 8604 } 8605 } 8606 8607 if ((scanFlags & SCAN_BOOTING) != 0) { 8608 // No apps can run during boot scan, so they don't need to be frozen 8609 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8610 // Caller asked to not kill app, so it's probably not frozen 8611 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8612 // Caller asked us to ignore frozen check for some reason; they 8613 // probably didn't know the package name 8614 } else { 8615 // We're doing major surgery on this package, so it better be frozen 8616 // right now to keep it from launching 8617 checkPackageFrozen(pkgName); 8618 } 8619 8620 // Also need to kill any apps that are dependent on the library. 8621 if (clientLibPkgs != null) { 8622 for (int i=0; i<clientLibPkgs.size(); i++) { 8623 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8624 killApplication(clientPkg.applicationInfo.packageName, 8625 clientPkg.applicationInfo.uid, "update lib"); 8626 } 8627 } 8628 8629 // Make sure we're not adding any bogus keyset info 8630 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8631 ksms.assertScannedPackageValid(pkg); 8632 8633 // writer 8634 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8635 8636 boolean createIdmapFailed = false; 8637 synchronized (mPackages) { 8638 // We don't expect installation to fail beyond this point 8639 8640 if (pkgSetting.pkg != null) { 8641 // Note that |user| might be null during the initial boot scan. If a codePath 8642 // for an app has changed during a boot scan, it's due to an app update that's 8643 // part of the system partition and marker changes must be applied to all users. 8644 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8645 (user != null) ? user : UserHandle.ALL); 8646 } 8647 8648 // Add the new setting to mSettings 8649 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8650 // Add the new setting to mPackages 8651 mPackages.put(pkg.applicationInfo.packageName, pkg); 8652 // Make sure we don't accidentally delete its data. 8653 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8654 while (iter.hasNext()) { 8655 PackageCleanItem item = iter.next(); 8656 if (pkgName.equals(item.packageName)) { 8657 iter.remove(); 8658 } 8659 } 8660 8661 // Take care of first install / last update times. 8662 if (currentTime != 0) { 8663 if (pkgSetting.firstInstallTime == 0) { 8664 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8665 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8666 pkgSetting.lastUpdateTime = currentTime; 8667 } 8668 } else if (pkgSetting.firstInstallTime == 0) { 8669 // We need *something*. Take time time stamp of the file. 8670 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8671 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8672 if (scanFileTime != pkgSetting.timeStamp) { 8673 // A package on the system image has changed; consider this 8674 // to be an update. 8675 pkgSetting.lastUpdateTime = scanFileTime; 8676 } 8677 } 8678 8679 // Add the package's KeySets to the global KeySetManagerService 8680 ksms.addScannedPackageLPw(pkg); 8681 8682 int N = pkg.providers.size(); 8683 StringBuilder r = null; 8684 int i; 8685 for (i=0; i<N; i++) { 8686 PackageParser.Provider p = pkg.providers.get(i); 8687 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8688 p.info.processName, pkg.applicationInfo.uid); 8689 mProviders.addProvider(p); 8690 p.syncable = p.info.isSyncable; 8691 if (p.info.authority != null) { 8692 String names[] = p.info.authority.split(";"); 8693 p.info.authority = null; 8694 for (int j = 0; j < names.length; j++) { 8695 if (j == 1 && p.syncable) { 8696 // We only want the first authority for a provider to possibly be 8697 // syncable, so if we already added this provider using a different 8698 // authority clear the syncable flag. We copy the provider before 8699 // changing it because the mProviders object contains a reference 8700 // to a provider that we don't want to change. 8701 // Only do this for the second authority since the resulting provider 8702 // object can be the same for all future authorities for this provider. 8703 p = new PackageParser.Provider(p); 8704 p.syncable = false; 8705 } 8706 if (!mProvidersByAuthority.containsKey(names[j])) { 8707 mProvidersByAuthority.put(names[j], p); 8708 if (p.info.authority == null) { 8709 p.info.authority = names[j]; 8710 } else { 8711 p.info.authority = p.info.authority + ";" + names[j]; 8712 } 8713 if (DEBUG_PACKAGE_SCANNING) { 8714 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8715 Log.d(TAG, "Registered content provider: " + names[j] 8716 + ", className = " + p.info.name + ", isSyncable = " 8717 + p.info.isSyncable); 8718 } 8719 } else { 8720 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8721 Slog.w(TAG, "Skipping provider name " + names[j] + 8722 " (in package " + pkg.applicationInfo.packageName + 8723 "): name already used by " 8724 + ((other != null && other.getComponentName() != null) 8725 ? other.getComponentName().getPackageName() : "?")); 8726 } 8727 } 8728 } 8729 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8730 if (r == null) { 8731 r = new StringBuilder(256); 8732 } else { 8733 r.append(' '); 8734 } 8735 r.append(p.info.name); 8736 } 8737 } 8738 if (r != null) { 8739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8740 } 8741 8742 N = pkg.services.size(); 8743 r = null; 8744 for (i=0; i<N; i++) { 8745 PackageParser.Service s = pkg.services.get(i); 8746 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8747 s.info.processName, pkg.applicationInfo.uid); 8748 mServices.addService(s); 8749 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8750 if (r == null) { 8751 r = new StringBuilder(256); 8752 } else { 8753 r.append(' '); 8754 } 8755 r.append(s.info.name); 8756 } 8757 } 8758 if (r != null) { 8759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8760 } 8761 8762 N = pkg.receivers.size(); 8763 r = null; 8764 for (i=0; i<N; i++) { 8765 PackageParser.Activity a = pkg.receivers.get(i); 8766 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8767 a.info.processName, pkg.applicationInfo.uid); 8768 mReceivers.addActivity(a, "receiver"); 8769 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8770 if (r == null) { 8771 r = new StringBuilder(256); 8772 } else { 8773 r.append(' '); 8774 } 8775 r.append(a.info.name); 8776 } 8777 } 8778 if (r != null) { 8779 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8780 } 8781 8782 N = pkg.activities.size(); 8783 r = null; 8784 for (i=0; i<N; i++) { 8785 PackageParser.Activity a = pkg.activities.get(i); 8786 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8787 a.info.processName, pkg.applicationInfo.uid); 8788 mActivities.addActivity(a, "activity"); 8789 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8790 if (r == null) { 8791 r = new StringBuilder(256); 8792 } else { 8793 r.append(' '); 8794 } 8795 r.append(a.info.name); 8796 } 8797 } 8798 if (r != null) { 8799 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8800 } 8801 8802 N = pkg.permissionGroups.size(); 8803 r = null; 8804 for (i=0; i<N; i++) { 8805 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8806 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8807 final String curPackageName = cur == null ? null : cur.info.packageName; 8808 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8809 if (cur == null || isPackageUpdate) { 8810 mPermissionGroups.put(pg.info.name, pg); 8811 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8812 if (r == null) { 8813 r = new StringBuilder(256); 8814 } else { 8815 r.append(' '); 8816 } 8817 if (isPackageUpdate) { 8818 r.append("UPD:"); 8819 } 8820 r.append(pg.info.name); 8821 } 8822 } else { 8823 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8824 + pg.info.packageName + " ignored: original from " 8825 + cur.info.packageName); 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("DUP:"); 8833 r.append(pg.info.name); 8834 } 8835 } 8836 } 8837 if (r != null) { 8838 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8839 } 8840 8841 N = pkg.permissions.size(); 8842 r = null; 8843 for (i=0; i<N; i++) { 8844 PackageParser.Permission p = pkg.permissions.get(i); 8845 8846 // Assume by default that we did not install this permission into the system. 8847 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8848 8849 // Now that permission groups have a special meaning, we ignore permission 8850 // groups for legacy apps to prevent unexpected behavior. In particular, 8851 // permissions for one app being granted to someone just becase they happen 8852 // to be in a group defined by another app (before this had no implications). 8853 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8854 p.group = mPermissionGroups.get(p.info.group); 8855 // Warn for a permission in an unknown group. 8856 if (p.info.group != null && p.group == null) { 8857 Slog.w(TAG, "Permission " + p.info.name + " from package " 8858 + p.info.packageName + " in an unknown group " + p.info.group); 8859 } 8860 } 8861 8862 ArrayMap<String, BasePermission> permissionMap = 8863 p.tree ? mSettings.mPermissionTrees 8864 : mSettings.mPermissions; 8865 BasePermission bp = permissionMap.get(p.info.name); 8866 8867 // Allow system apps to redefine non-system permissions 8868 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8869 final boolean currentOwnerIsSystem = (bp.perm != null 8870 && isSystemApp(bp.perm.owner)); 8871 if (isSystemApp(p.owner)) { 8872 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8873 // It's a built-in permission and no owner, take ownership now 8874 bp.packageSetting = pkgSetting; 8875 bp.perm = p; 8876 bp.uid = pkg.applicationInfo.uid; 8877 bp.sourcePackage = p.info.packageName; 8878 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8879 } else if (!currentOwnerIsSystem) { 8880 String msg = "New decl " + p.owner + " of permission " 8881 + p.info.name + " is system; overriding " + bp.sourcePackage; 8882 reportSettingsProblem(Log.WARN, msg); 8883 bp = null; 8884 } 8885 } 8886 } 8887 8888 if (bp == null) { 8889 bp = new BasePermission(p.info.name, p.info.packageName, 8890 BasePermission.TYPE_NORMAL); 8891 permissionMap.put(p.info.name, bp); 8892 } 8893 8894 if (bp.perm == null) { 8895 if (bp.sourcePackage == null 8896 || bp.sourcePackage.equals(p.info.packageName)) { 8897 BasePermission tree = findPermissionTreeLP(p.info.name); 8898 if (tree == null 8899 || tree.sourcePackage.equals(p.info.packageName)) { 8900 bp.packageSetting = pkgSetting; 8901 bp.perm = p; 8902 bp.uid = pkg.applicationInfo.uid; 8903 bp.sourcePackage = p.info.packageName; 8904 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8905 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8906 if (r == null) { 8907 r = new StringBuilder(256); 8908 } else { 8909 r.append(' '); 8910 } 8911 r.append(p.info.name); 8912 } 8913 } else { 8914 Slog.w(TAG, "Permission " + p.info.name + " from package " 8915 + p.info.packageName + " ignored: base tree " 8916 + tree.name + " is from package " 8917 + tree.sourcePackage); 8918 } 8919 } else { 8920 Slog.w(TAG, "Permission " + p.info.name + " from package " 8921 + p.info.packageName + " ignored: original from " 8922 + bp.sourcePackage); 8923 } 8924 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8925 if (r == null) { 8926 r = new StringBuilder(256); 8927 } else { 8928 r.append(' '); 8929 } 8930 r.append("DUP:"); 8931 r.append(p.info.name); 8932 } 8933 if (bp.perm == p) { 8934 bp.protectionLevel = p.info.protectionLevel; 8935 } 8936 } 8937 8938 if (r != null) { 8939 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8940 } 8941 8942 N = pkg.instrumentation.size(); 8943 r = null; 8944 for (i=0; i<N; i++) { 8945 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8946 a.info.packageName = pkg.applicationInfo.packageName; 8947 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8948 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8949 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8950 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8951 a.info.dataDir = pkg.applicationInfo.dataDir; 8952 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8953 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8954 8955 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8956 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8957 mInstrumentation.put(a.getComponentName(), a); 8958 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8959 if (r == null) { 8960 r = new StringBuilder(256); 8961 } else { 8962 r.append(' '); 8963 } 8964 r.append(a.info.name); 8965 } 8966 } 8967 if (r != null) { 8968 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8969 } 8970 8971 if (pkg.protectedBroadcasts != null) { 8972 N = pkg.protectedBroadcasts.size(); 8973 for (i=0; i<N; i++) { 8974 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8975 } 8976 } 8977 8978 pkgSetting.setTimeStamp(scanFileTime); 8979 8980 // Create idmap files for pairs of (packages, overlay packages). 8981 // Note: "android", ie framework-res.apk, is handled by native layers. 8982 if (pkg.mOverlayTarget != null) { 8983 // This is an overlay package. 8984 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8985 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8986 mOverlays.put(pkg.mOverlayTarget, 8987 new ArrayMap<String, PackageParser.Package>()); 8988 } 8989 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8990 map.put(pkg.packageName, pkg); 8991 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8992 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8993 createIdmapFailed = true; 8994 } 8995 } 8996 } else if (mOverlays.containsKey(pkg.packageName) && 8997 !pkg.packageName.equals("android")) { 8998 // This is a regular package, with one or more known overlay packages. 8999 createIdmapsForPackageLI(pkg); 9000 } 9001 } 9002 9003 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9004 9005 if (createIdmapFailed) { 9006 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9007 "scanPackageLI failed to createIdmap"); 9008 } 9009 return pkg; 9010 } 9011 9012 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9013 PackageParser.Package update, UserHandle user) { 9014 if (existing.applicationInfo == null || update.applicationInfo == null) { 9015 // This isn't due to an app installation. 9016 return; 9017 } 9018 9019 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9020 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9021 9022 // The codePath hasn't changed, so there's nothing for us to do. 9023 if (Objects.equals(oldCodePath, newCodePath)) { 9024 return; 9025 } 9026 9027 File canonicalNewCodePath; 9028 try { 9029 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9030 } catch (IOException e) { 9031 Slog.w(TAG, "Failed to get canonical path.", e); 9032 return; 9033 } 9034 9035 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9036 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9037 // that the last component of the path (i.e, the name) doesn't need canonicalization 9038 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9039 // but may change in the future. Hopefully this function won't exist at that point. 9040 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9041 oldCodePath.getName()); 9042 9043 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9044 // with "@". 9045 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9046 if (!oldMarkerPrefix.endsWith("@")) { 9047 oldMarkerPrefix += "@"; 9048 } 9049 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9050 if (!newMarkerPrefix.endsWith("@")) { 9051 newMarkerPrefix += "@"; 9052 } 9053 9054 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9055 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9056 for (String updatedPath : updatedPaths) { 9057 String updatedPathName = new File(updatedPath).getName(); 9058 markerSuffixes.add(updatedPathName.replace('/', '@')); 9059 } 9060 9061 for (int userId : resolveUserIds(user.getIdentifier())) { 9062 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9063 9064 for (String markerSuffix : markerSuffixes) { 9065 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9066 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9067 if (oldForeignUseMark.exists()) { 9068 try { 9069 Os.rename(oldForeignUseMark.getAbsolutePath(), 9070 newForeignUseMark.getAbsolutePath()); 9071 } catch (ErrnoException e) { 9072 Slog.w(TAG, "Failed to rename foreign use marker", e); 9073 oldForeignUseMark.delete(); 9074 } 9075 } 9076 } 9077 } 9078 } 9079 9080 /** 9081 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9082 * is derived purely on the basis of the contents of {@code scanFile} and 9083 * {@code cpuAbiOverride}. 9084 * 9085 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9086 */ 9087 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9088 String cpuAbiOverride, boolean extractLibs) 9089 throws PackageManagerException { 9090 // TODO: We can probably be smarter about this stuff. For installed apps, 9091 // we can calculate this information at install time once and for all. For 9092 // system apps, we can probably assume that this information doesn't change 9093 // after the first boot scan. As things stand, we do lots of unnecessary work. 9094 9095 // Give ourselves some initial paths; we'll come back for another 9096 // pass once we've determined ABI below. 9097 setNativeLibraryPaths(pkg); 9098 9099 // We would never need to extract libs for forward-locked and external packages, 9100 // since the container service will do it for us. We shouldn't attempt to 9101 // extract libs from system app when it was not updated. 9102 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9103 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9104 extractLibs = false; 9105 } 9106 9107 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9108 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9109 9110 NativeLibraryHelper.Handle handle = null; 9111 try { 9112 handle = NativeLibraryHelper.Handle.create(pkg); 9113 // TODO(multiArch): This can be null for apps that didn't go through the 9114 // usual installation process. We can calculate it again, like we 9115 // do during install time. 9116 // 9117 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9118 // unnecessary. 9119 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9120 9121 // Null out the abis so that they can be recalculated. 9122 pkg.applicationInfo.primaryCpuAbi = null; 9123 pkg.applicationInfo.secondaryCpuAbi = null; 9124 if (isMultiArch(pkg.applicationInfo)) { 9125 // Warn if we've set an abiOverride for multi-lib packages.. 9126 // By definition, we need to copy both 32 and 64 bit libraries for 9127 // such packages. 9128 if (pkg.cpuAbiOverride != null 9129 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9130 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9131 } 9132 9133 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9134 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9135 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9136 if (extractLibs) { 9137 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9138 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9139 useIsaSpecificSubdirs); 9140 } else { 9141 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9142 } 9143 } 9144 9145 maybeThrowExceptionForMultiArchCopy( 9146 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9147 9148 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9149 if (extractLibs) { 9150 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9151 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9152 useIsaSpecificSubdirs); 9153 } else { 9154 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9155 } 9156 } 9157 9158 maybeThrowExceptionForMultiArchCopy( 9159 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9160 9161 if (abi64 >= 0) { 9162 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9163 } 9164 9165 if (abi32 >= 0) { 9166 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9167 if (abi64 >= 0) { 9168 if (pkg.use32bitAbi) { 9169 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9170 pkg.applicationInfo.primaryCpuAbi = abi; 9171 } else { 9172 pkg.applicationInfo.secondaryCpuAbi = abi; 9173 } 9174 } else { 9175 pkg.applicationInfo.primaryCpuAbi = abi; 9176 } 9177 } 9178 9179 } else { 9180 String[] abiList = (cpuAbiOverride != null) ? 9181 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9182 9183 // Enable gross and lame hacks for apps that are built with old 9184 // SDK tools. We must scan their APKs for renderscript bitcode and 9185 // not launch them if it's present. Don't bother checking on devices 9186 // that don't have 64 bit support. 9187 boolean needsRenderScriptOverride = false; 9188 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9189 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9190 abiList = Build.SUPPORTED_32_BIT_ABIS; 9191 needsRenderScriptOverride = true; 9192 } 9193 9194 final int copyRet; 9195 if (extractLibs) { 9196 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9197 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9198 } else { 9199 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9200 } 9201 9202 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9203 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9204 "Error unpackaging native libs for app, errorCode=" + copyRet); 9205 } 9206 9207 if (copyRet >= 0) { 9208 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9209 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9210 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9211 } else if (needsRenderScriptOverride) { 9212 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9213 } 9214 } 9215 } catch (IOException ioe) { 9216 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9217 } finally { 9218 IoUtils.closeQuietly(handle); 9219 } 9220 9221 // Now that we've calculated the ABIs and determined if it's an internal app, 9222 // we will go ahead and populate the nativeLibraryPath. 9223 setNativeLibraryPaths(pkg); 9224 } 9225 9226 /** 9227 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9228 * i.e, so that all packages can be run inside a single process if required. 9229 * 9230 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9231 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9232 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9233 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9234 * updating a package that belongs to a shared user. 9235 * 9236 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9237 * adds unnecessary complexity. 9238 */ 9239 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9240 PackageParser.Package scannedPackage, boolean bootComplete) { 9241 String requiredInstructionSet = null; 9242 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9243 requiredInstructionSet = VMRuntime.getInstructionSet( 9244 scannedPackage.applicationInfo.primaryCpuAbi); 9245 } 9246 9247 PackageSetting requirer = null; 9248 for (PackageSetting ps : packagesForUser) { 9249 // If packagesForUser contains scannedPackage, we skip it. This will happen 9250 // when scannedPackage is an update of an existing package. Without this check, 9251 // we will never be able to change the ABI of any package belonging to a shared 9252 // user, even if it's compatible with other packages. 9253 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9254 if (ps.primaryCpuAbiString == null) { 9255 continue; 9256 } 9257 9258 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9259 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9260 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9261 // this but there's not much we can do. 9262 String errorMessage = "Instruction set mismatch, " 9263 + ((requirer == null) ? "[caller]" : requirer) 9264 + " requires " + requiredInstructionSet + " whereas " + ps 9265 + " requires " + instructionSet; 9266 Slog.w(TAG, errorMessage); 9267 } 9268 9269 if (requiredInstructionSet == null) { 9270 requiredInstructionSet = instructionSet; 9271 requirer = ps; 9272 } 9273 } 9274 } 9275 9276 if (requiredInstructionSet != null) { 9277 String adjustedAbi; 9278 if (requirer != null) { 9279 // requirer != null implies that either scannedPackage was null or that scannedPackage 9280 // did not require an ABI, in which case we have to adjust scannedPackage to match 9281 // the ABI of the set (which is the same as requirer's ABI) 9282 adjustedAbi = requirer.primaryCpuAbiString; 9283 if (scannedPackage != null) { 9284 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9285 } 9286 } else { 9287 // requirer == null implies that we're updating all ABIs in the set to 9288 // match scannedPackage. 9289 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9290 } 9291 9292 for (PackageSetting ps : packagesForUser) { 9293 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9294 if (ps.primaryCpuAbiString != null) { 9295 continue; 9296 } 9297 9298 ps.primaryCpuAbiString = adjustedAbi; 9299 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9300 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9301 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9302 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9303 + " (requirer=" 9304 + (requirer == null ? "null" : requirer.pkg.packageName) 9305 + ", scannedPackage=" 9306 + (scannedPackage != null ? scannedPackage.packageName : "null") 9307 + ")"); 9308 try { 9309 mInstaller.rmdex(ps.codePathString, 9310 getDexCodeInstructionSet(getPreferredInstructionSet())); 9311 } catch (InstallerException ignored) { 9312 } 9313 } 9314 } 9315 } 9316 } 9317 } 9318 9319 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9320 synchronized (mPackages) { 9321 mResolverReplaced = true; 9322 // Set up information for custom user intent resolution activity. 9323 mResolveActivity.applicationInfo = pkg.applicationInfo; 9324 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9325 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9326 mResolveActivity.processName = pkg.applicationInfo.packageName; 9327 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9328 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9329 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9330 mResolveActivity.theme = 0; 9331 mResolveActivity.exported = true; 9332 mResolveActivity.enabled = true; 9333 mResolveInfo.activityInfo = mResolveActivity; 9334 mResolveInfo.priority = 0; 9335 mResolveInfo.preferredOrder = 0; 9336 mResolveInfo.match = 0; 9337 mResolveComponentName = mCustomResolverComponentName; 9338 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9339 mResolveComponentName); 9340 } 9341 } 9342 9343 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9344 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9345 9346 // Set up information for ephemeral installer activity 9347 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9348 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9349 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9350 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9351 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9352 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9353 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9354 mEphemeralInstallerActivity.theme = 0; 9355 mEphemeralInstallerActivity.exported = true; 9356 mEphemeralInstallerActivity.enabled = true; 9357 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9358 mEphemeralInstallerInfo.priority = 0; 9359 mEphemeralInstallerInfo.preferredOrder = 1; 9360 mEphemeralInstallerInfo.isDefault = true; 9361 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9362 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9363 9364 if (DEBUG_EPHEMERAL) { 9365 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9366 } 9367 } 9368 9369 private static String calculateBundledApkRoot(final String codePathString) { 9370 final File codePath = new File(codePathString); 9371 final File codeRoot; 9372 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9373 codeRoot = Environment.getRootDirectory(); 9374 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9375 codeRoot = Environment.getOemDirectory(); 9376 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9377 codeRoot = Environment.getVendorDirectory(); 9378 } else { 9379 // Unrecognized code path; take its top real segment as the apk root: 9380 // e.g. /something/app/blah.apk => /something 9381 try { 9382 File f = codePath.getCanonicalFile(); 9383 File parent = f.getParentFile(); // non-null because codePath is a file 9384 File tmp; 9385 while ((tmp = parent.getParentFile()) != null) { 9386 f = parent; 9387 parent = tmp; 9388 } 9389 codeRoot = f; 9390 Slog.w(TAG, "Unrecognized code path " 9391 + codePath + " - using " + codeRoot); 9392 } catch (IOException e) { 9393 // Can't canonicalize the code path -- shenanigans? 9394 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9395 return Environment.getRootDirectory().getPath(); 9396 } 9397 } 9398 return codeRoot.getPath(); 9399 } 9400 9401 /** 9402 * Derive and set the location of native libraries for the given package, 9403 * which varies depending on where and how the package was installed. 9404 */ 9405 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9406 final ApplicationInfo info = pkg.applicationInfo; 9407 final String codePath = pkg.codePath; 9408 final File codeFile = new File(codePath); 9409 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9410 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9411 9412 info.nativeLibraryRootDir = null; 9413 info.nativeLibraryRootRequiresIsa = false; 9414 info.nativeLibraryDir = null; 9415 info.secondaryNativeLibraryDir = null; 9416 9417 if (isApkFile(codeFile)) { 9418 // Monolithic install 9419 if (bundledApp) { 9420 // If "/system/lib64/apkname" exists, assume that is the per-package 9421 // native library directory to use; otherwise use "/system/lib/apkname". 9422 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9423 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9424 getPrimaryInstructionSet(info)); 9425 9426 // This is a bundled system app so choose the path based on the ABI. 9427 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9428 // is just the default path. 9429 final String apkName = deriveCodePathName(codePath); 9430 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9431 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9432 apkName).getAbsolutePath(); 9433 9434 if (info.secondaryCpuAbi != null) { 9435 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9436 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9437 secondaryLibDir, apkName).getAbsolutePath(); 9438 } 9439 } else if (asecApp) { 9440 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9441 .getAbsolutePath(); 9442 } else { 9443 final String apkName = deriveCodePathName(codePath); 9444 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9445 .getAbsolutePath(); 9446 } 9447 9448 info.nativeLibraryRootRequiresIsa = false; 9449 info.nativeLibraryDir = info.nativeLibraryRootDir; 9450 } else { 9451 // Cluster install 9452 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9453 info.nativeLibraryRootRequiresIsa = true; 9454 9455 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9456 getPrimaryInstructionSet(info)).getAbsolutePath(); 9457 9458 if (info.secondaryCpuAbi != null) { 9459 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9460 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9461 } 9462 } 9463 } 9464 9465 /** 9466 * Calculate the abis and roots for a bundled app. These can uniquely 9467 * be determined from the contents of the system partition, i.e whether 9468 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9469 * of this information, and instead assume that the system was built 9470 * sensibly. 9471 */ 9472 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9473 PackageSetting pkgSetting) { 9474 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9475 9476 // If "/system/lib64/apkname" exists, assume that is the per-package 9477 // native library directory to use; otherwise use "/system/lib/apkname". 9478 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9479 setBundledAppAbi(pkg, apkRoot, apkName); 9480 // pkgSetting might be null during rescan following uninstall of updates 9481 // to a bundled app, so accommodate that possibility. The settings in 9482 // that case will be established later from the parsed package. 9483 // 9484 // If the settings aren't null, sync them up with what we've just derived. 9485 // note that apkRoot isn't stored in the package settings. 9486 if (pkgSetting != null) { 9487 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9488 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9489 } 9490 } 9491 9492 /** 9493 * Deduces the ABI of a bundled app and sets the relevant fields on the 9494 * parsed pkg object. 9495 * 9496 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9497 * under which system libraries are installed. 9498 * @param apkName the name of the installed package. 9499 */ 9500 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9501 final File codeFile = new File(pkg.codePath); 9502 9503 final boolean has64BitLibs; 9504 final boolean has32BitLibs; 9505 if (isApkFile(codeFile)) { 9506 // Monolithic install 9507 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9508 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9509 } else { 9510 // Cluster install 9511 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9512 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9513 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9514 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9515 has64BitLibs = (new File(rootDir, isa)).exists(); 9516 } else { 9517 has64BitLibs = false; 9518 } 9519 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9520 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9521 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9522 has32BitLibs = (new File(rootDir, isa)).exists(); 9523 } else { 9524 has32BitLibs = false; 9525 } 9526 } 9527 9528 if (has64BitLibs && !has32BitLibs) { 9529 // The package has 64 bit libs, but not 32 bit libs. Its primary 9530 // ABI should be 64 bit. We can safely assume here that the bundled 9531 // native libraries correspond to the most preferred ABI in the list. 9532 9533 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9534 pkg.applicationInfo.secondaryCpuAbi = null; 9535 } else if (has32BitLibs && !has64BitLibs) { 9536 // The package has 32 bit libs but not 64 bit libs. Its primary 9537 // ABI should be 32 bit. 9538 9539 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9540 pkg.applicationInfo.secondaryCpuAbi = null; 9541 } else if (has32BitLibs && has64BitLibs) { 9542 // The application has both 64 and 32 bit bundled libraries. We check 9543 // here that the app declares multiArch support, and warn if it doesn't. 9544 // 9545 // We will be lenient here and record both ABIs. The primary will be the 9546 // ABI that's higher on the list, i.e, a device that's configured to prefer 9547 // 64 bit apps will see a 64 bit primary ABI, 9548 9549 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9550 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9551 } 9552 9553 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9554 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9555 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9556 } else { 9557 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9558 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9559 } 9560 } else { 9561 pkg.applicationInfo.primaryCpuAbi = null; 9562 pkg.applicationInfo.secondaryCpuAbi = null; 9563 } 9564 } 9565 9566 private void killApplication(String pkgName, int appId, String reason) { 9567 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9568 } 9569 9570 private void killApplication(String pkgName, int appId, int userId, String reason) { 9571 // Request the ActivityManager to kill the process(only for existing packages) 9572 // so that we do not end up in a confused state while the user is still using the older 9573 // version of the application while the new one gets installed. 9574 final long token = Binder.clearCallingIdentity(); 9575 try { 9576 IActivityManager am = ActivityManagerNative.getDefault(); 9577 if (am != null) { 9578 try { 9579 am.killApplication(pkgName, appId, userId, reason); 9580 } catch (RemoteException e) { 9581 } 9582 } 9583 } finally { 9584 Binder.restoreCallingIdentity(token); 9585 } 9586 } 9587 9588 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9589 // Remove the parent package setting 9590 PackageSetting ps = (PackageSetting) pkg.mExtras; 9591 if (ps != null) { 9592 removePackageLI(ps, chatty); 9593 } 9594 // Remove the child package setting 9595 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9596 for (int i = 0; i < childCount; i++) { 9597 PackageParser.Package childPkg = pkg.childPackages.get(i); 9598 ps = (PackageSetting) childPkg.mExtras; 9599 if (ps != null) { 9600 removePackageLI(ps, chatty); 9601 } 9602 } 9603 } 9604 9605 void removePackageLI(PackageSetting ps, boolean chatty) { 9606 if (DEBUG_INSTALL) { 9607 if (chatty) 9608 Log.d(TAG, "Removing package " + ps.name); 9609 } 9610 9611 // writer 9612 synchronized (mPackages) { 9613 mPackages.remove(ps.name); 9614 final PackageParser.Package pkg = ps.pkg; 9615 if (pkg != null) { 9616 cleanPackageDataStructuresLILPw(pkg, chatty); 9617 } 9618 } 9619 } 9620 9621 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9622 if (DEBUG_INSTALL) { 9623 if (chatty) 9624 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9625 } 9626 9627 // writer 9628 synchronized (mPackages) { 9629 // Remove the parent package 9630 mPackages.remove(pkg.applicationInfo.packageName); 9631 cleanPackageDataStructuresLILPw(pkg, chatty); 9632 9633 // Remove the child packages 9634 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9635 for (int i = 0; i < childCount; i++) { 9636 PackageParser.Package childPkg = pkg.childPackages.get(i); 9637 mPackages.remove(childPkg.applicationInfo.packageName); 9638 cleanPackageDataStructuresLILPw(childPkg, chatty); 9639 } 9640 } 9641 } 9642 9643 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9644 int N = pkg.providers.size(); 9645 StringBuilder r = null; 9646 int i; 9647 for (i=0; i<N; i++) { 9648 PackageParser.Provider p = pkg.providers.get(i); 9649 mProviders.removeProvider(p); 9650 if (p.info.authority == null) { 9651 9652 /* There was another ContentProvider with this authority when 9653 * this app was installed so this authority is null, 9654 * Ignore it as we don't have to unregister the provider. 9655 */ 9656 continue; 9657 } 9658 String names[] = p.info.authority.split(";"); 9659 for (int j = 0; j < names.length; j++) { 9660 if (mProvidersByAuthority.get(names[j]) == p) { 9661 mProvidersByAuthority.remove(names[j]); 9662 if (DEBUG_REMOVE) { 9663 if (chatty) 9664 Log.d(TAG, "Unregistered content provider: " + names[j] 9665 + ", className = " + p.info.name + ", isSyncable = " 9666 + p.info.isSyncable); 9667 } 9668 } 9669 } 9670 if (DEBUG_REMOVE && chatty) { 9671 if (r == null) { 9672 r = new StringBuilder(256); 9673 } else { 9674 r.append(' '); 9675 } 9676 r.append(p.info.name); 9677 } 9678 } 9679 if (r != null) { 9680 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9681 } 9682 9683 N = pkg.services.size(); 9684 r = null; 9685 for (i=0; i<N; i++) { 9686 PackageParser.Service s = pkg.services.get(i); 9687 mServices.removeService(s); 9688 if (chatty) { 9689 if (r == null) { 9690 r = new StringBuilder(256); 9691 } else { 9692 r.append(' '); 9693 } 9694 r.append(s.info.name); 9695 } 9696 } 9697 if (r != null) { 9698 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9699 } 9700 9701 N = pkg.receivers.size(); 9702 r = null; 9703 for (i=0; i<N; i++) { 9704 PackageParser.Activity a = pkg.receivers.get(i); 9705 mReceivers.removeActivity(a, "receiver"); 9706 if (DEBUG_REMOVE && chatty) { 9707 if (r == null) { 9708 r = new StringBuilder(256); 9709 } else { 9710 r.append(' '); 9711 } 9712 r.append(a.info.name); 9713 } 9714 } 9715 if (r != null) { 9716 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9717 } 9718 9719 N = pkg.activities.size(); 9720 r = null; 9721 for (i=0; i<N; i++) { 9722 PackageParser.Activity a = pkg.activities.get(i); 9723 mActivities.removeActivity(a, "activity"); 9724 if (DEBUG_REMOVE && chatty) { 9725 if (r == null) { 9726 r = new StringBuilder(256); 9727 } else { 9728 r.append(' '); 9729 } 9730 r.append(a.info.name); 9731 } 9732 } 9733 if (r != null) { 9734 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9735 } 9736 9737 N = pkg.permissions.size(); 9738 r = null; 9739 for (i=0; i<N; i++) { 9740 PackageParser.Permission p = pkg.permissions.get(i); 9741 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9742 if (bp == null) { 9743 bp = mSettings.mPermissionTrees.get(p.info.name); 9744 } 9745 if (bp != null && bp.perm == p) { 9746 bp.perm = null; 9747 if (DEBUG_REMOVE && chatty) { 9748 if (r == null) { 9749 r = new StringBuilder(256); 9750 } else { 9751 r.append(' '); 9752 } 9753 r.append(p.info.name); 9754 } 9755 } 9756 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9757 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9758 if (appOpPkgs != null) { 9759 appOpPkgs.remove(pkg.packageName); 9760 } 9761 } 9762 } 9763 if (r != null) { 9764 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9765 } 9766 9767 N = pkg.requestedPermissions.size(); 9768 r = null; 9769 for (i=0; i<N; i++) { 9770 String perm = pkg.requestedPermissions.get(i); 9771 BasePermission bp = mSettings.mPermissions.get(perm); 9772 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9773 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9774 if (appOpPkgs != null) { 9775 appOpPkgs.remove(pkg.packageName); 9776 if (appOpPkgs.isEmpty()) { 9777 mAppOpPermissionPackages.remove(perm); 9778 } 9779 } 9780 } 9781 } 9782 if (r != null) { 9783 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9784 } 9785 9786 N = pkg.instrumentation.size(); 9787 r = null; 9788 for (i=0; i<N; i++) { 9789 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9790 mInstrumentation.remove(a.getComponentName()); 9791 if (DEBUG_REMOVE && chatty) { 9792 if (r == null) { 9793 r = new StringBuilder(256); 9794 } else { 9795 r.append(' '); 9796 } 9797 r.append(a.info.name); 9798 } 9799 } 9800 if (r != null) { 9801 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9802 } 9803 9804 r = null; 9805 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9806 // Only system apps can hold shared libraries. 9807 if (pkg.libraryNames != null) { 9808 for (i=0; i<pkg.libraryNames.size(); i++) { 9809 String name = pkg.libraryNames.get(i); 9810 SharedLibraryEntry cur = mSharedLibraries.get(name); 9811 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9812 mSharedLibraries.remove(name); 9813 if (DEBUG_REMOVE && chatty) { 9814 if (r == null) { 9815 r = new StringBuilder(256); 9816 } else { 9817 r.append(' '); 9818 } 9819 r.append(name); 9820 } 9821 } 9822 } 9823 } 9824 } 9825 if (r != null) { 9826 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9827 } 9828 } 9829 9830 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9831 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9832 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9833 return true; 9834 } 9835 } 9836 return false; 9837 } 9838 9839 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9840 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9841 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9842 9843 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9844 // Update the parent permissions 9845 updatePermissionsLPw(pkg.packageName, pkg, flags); 9846 // Update the child permissions 9847 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9848 for (int i = 0; i < childCount; i++) { 9849 PackageParser.Package childPkg = pkg.childPackages.get(i); 9850 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9851 } 9852 } 9853 9854 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9855 int flags) { 9856 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9857 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9858 } 9859 9860 private void updatePermissionsLPw(String changingPkg, 9861 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9862 // Make sure there are no dangling permission trees. 9863 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9864 while (it.hasNext()) { 9865 final BasePermission bp = it.next(); 9866 if (bp.packageSetting == null) { 9867 // We may not yet have parsed the package, so just see if 9868 // we still know about its settings. 9869 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9870 } 9871 if (bp.packageSetting == null) { 9872 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9873 + " from package " + bp.sourcePackage); 9874 it.remove(); 9875 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9876 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9877 Slog.i(TAG, "Removing old permission tree: " + bp.name 9878 + " from package " + bp.sourcePackage); 9879 flags |= UPDATE_PERMISSIONS_ALL; 9880 it.remove(); 9881 } 9882 } 9883 } 9884 9885 // Make sure all dynamic permissions have been assigned to a package, 9886 // and make sure there are no dangling permissions. 9887 it = mSettings.mPermissions.values().iterator(); 9888 while (it.hasNext()) { 9889 final BasePermission bp = it.next(); 9890 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9891 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9892 + bp.name + " pkg=" + bp.sourcePackage 9893 + " info=" + bp.pendingInfo); 9894 if (bp.packageSetting == null && bp.pendingInfo != null) { 9895 final BasePermission tree = findPermissionTreeLP(bp.name); 9896 if (tree != null && tree.perm != null) { 9897 bp.packageSetting = tree.packageSetting; 9898 bp.perm = new PackageParser.Permission(tree.perm.owner, 9899 new PermissionInfo(bp.pendingInfo)); 9900 bp.perm.info.packageName = tree.perm.info.packageName; 9901 bp.perm.info.name = bp.name; 9902 bp.uid = tree.uid; 9903 } 9904 } 9905 } 9906 if (bp.packageSetting == null) { 9907 // We may not yet have parsed the package, so just see if 9908 // we still know about its settings. 9909 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9910 } 9911 if (bp.packageSetting == null) { 9912 Slog.w(TAG, "Removing dangling permission: " + bp.name 9913 + " from package " + bp.sourcePackage); 9914 it.remove(); 9915 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9916 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9917 Slog.i(TAG, "Removing old permission: " + bp.name 9918 + " from package " + bp.sourcePackage); 9919 flags |= UPDATE_PERMISSIONS_ALL; 9920 it.remove(); 9921 } 9922 } 9923 } 9924 9925 // Now update the permissions for all packages, in particular 9926 // replace the granted permissions of the system packages. 9927 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9928 for (PackageParser.Package pkg : mPackages.values()) { 9929 if (pkg != pkgInfo) { 9930 // Only replace for packages on requested volume 9931 final String volumeUuid = getVolumeUuidForPackage(pkg); 9932 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9933 && Objects.equals(replaceVolumeUuid, volumeUuid); 9934 grantPermissionsLPw(pkg, replace, changingPkg); 9935 } 9936 } 9937 } 9938 9939 if (pkgInfo != null) { 9940 // Only replace for packages on requested volume 9941 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9942 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9943 && Objects.equals(replaceVolumeUuid, volumeUuid); 9944 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9945 } 9946 } 9947 9948 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9949 String packageOfInterest) { 9950 // IMPORTANT: There are two types of permissions: install and runtime. 9951 // Install time permissions are granted when the app is installed to 9952 // all device users and users added in the future. Runtime permissions 9953 // are granted at runtime explicitly to specific users. Normal and signature 9954 // protected permissions are install time permissions. Dangerous permissions 9955 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9956 // otherwise they are runtime permissions. This function does not manage 9957 // runtime permissions except for the case an app targeting Lollipop MR1 9958 // being upgraded to target a newer SDK, in which case dangerous permissions 9959 // are transformed from install time to runtime ones. 9960 9961 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9962 if (ps == null) { 9963 return; 9964 } 9965 9966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9967 9968 PermissionsState permissionsState = ps.getPermissionsState(); 9969 PermissionsState origPermissions = permissionsState; 9970 9971 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9972 9973 boolean runtimePermissionsRevoked = false; 9974 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9975 9976 boolean changedInstallPermission = false; 9977 9978 if (replace) { 9979 ps.installPermissionsFixed = false; 9980 if (!ps.isSharedUser()) { 9981 origPermissions = new PermissionsState(permissionsState); 9982 permissionsState.reset(); 9983 } else { 9984 // We need to know only about runtime permission changes since the 9985 // calling code always writes the install permissions state but 9986 // the runtime ones are written only if changed. The only cases of 9987 // changed runtime permissions here are promotion of an install to 9988 // runtime and revocation of a runtime from a shared user. 9989 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9990 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9991 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9992 runtimePermissionsRevoked = true; 9993 } 9994 } 9995 } 9996 9997 permissionsState.setGlobalGids(mGlobalGids); 9998 9999 final int N = pkg.requestedPermissions.size(); 10000 for (int i=0; i<N; i++) { 10001 final String name = pkg.requestedPermissions.get(i); 10002 final BasePermission bp = mSettings.mPermissions.get(name); 10003 10004 if (DEBUG_INSTALL) { 10005 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10006 } 10007 10008 if (bp == null || bp.packageSetting == null) { 10009 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10010 Slog.w(TAG, "Unknown permission " + name 10011 + " in package " + pkg.packageName); 10012 } 10013 continue; 10014 } 10015 10016 final String perm = bp.name; 10017 boolean allowedSig = false; 10018 int grant = GRANT_DENIED; 10019 10020 // Keep track of app op permissions. 10021 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10022 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10023 if (pkgs == null) { 10024 pkgs = new ArraySet<>(); 10025 mAppOpPermissionPackages.put(bp.name, pkgs); 10026 } 10027 pkgs.add(pkg.packageName); 10028 } 10029 10030 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10031 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10032 >= Build.VERSION_CODES.M; 10033 switch (level) { 10034 case PermissionInfo.PROTECTION_NORMAL: { 10035 // For all apps normal permissions are install time ones. 10036 grant = GRANT_INSTALL; 10037 } break; 10038 10039 case PermissionInfo.PROTECTION_DANGEROUS: { 10040 // If a permission review is required for legacy apps we represent 10041 // their permissions as always granted runtime ones since we need 10042 // to keep the review required permission flag per user while an 10043 // install permission's state is shared across all users. 10044 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired 10045 && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10046 // For legacy apps dangerous permissions are install time ones. 10047 grant = GRANT_INSTALL; 10048 } else if (origPermissions.hasInstallPermission(bp.name)) { 10049 // For legacy apps that became modern, install becomes runtime. 10050 grant = GRANT_UPGRADE; 10051 } else if (mPromoteSystemApps 10052 && isSystemApp(ps) 10053 && mExistingSystemPackages.contains(ps.name)) { 10054 // For legacy system apps, install becomes runtime. 10055 // We cannot check hasInstallPermission() for system apps since those 10056 // permissions were granted implicitly and not persisted pre-M. 10057 grant = GRANT_UPGRADE; 10058 } else { 10059 // For modern apps keep runtime permissions unchanged. 10060 grant = GRANT_RUNTIME; 10061 } 10062 } break; 10063 10064 case PermissionInfo.PROTECTION_SIGNATURE: { 10065 // For all apps signature permissions are install time ones. 10066 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10067 if (allowedSig) { 10068 grant = GRANT_INSTALL; 10069 } 10070 } break; 10071 } 10072 10073 if (DEBUG_INSTALL) { 10074 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10075 } 10076 10077 if (grant != GRANT_DENIED) { 10078 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10079 // If this is an existing, non-system package, then 10080 // we can't add any new permissions to it. 10081 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10082 // Except... if this is a permission that was added 10083 // to the platform (note: need to only do this when 10084 // updating the platform). 10085 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10086 grant = GRANT_DENIED; 10087 } 10088 } 10089 } 10090 10091 switch (grant) { 10092 case GRANT_INSTALL: { 10093 // Revoke this as runtime permission to handle the case of 10094 // a runtime permission being downgraded to an install one. 10095 // Also in permission review mode we keep dangerous permissions 10096 // for legacy apps 10097 for (int userId : UserManagerService.getInstance().getUserIds()) { 10098 if (origPermissions.getRuntimePermissionState( 10099 bp.name, userId) != null) { 10100 // Revoke the runtime permission and clear the flags. 10101 origPermissions.revokeRuntimePermission(bp, userId); 10102 origPermissions.updatePermissionFlags(bp, userId, 10103 PackageManager.MASK_PERMISSION_FLAGS, 0); 10104 // If we revoked a permission permission, we have to write. 10105 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10106 changedRuntimePermissionUserIds, userId); 10107 } 10108 } 10109 // Grant an install permission. 10110 if (permissionsState.grantInstallPermission(bp) != 10111 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10112 changedInstallPermission = true; 10113 } 10114 } break; 10115 10116 case GRANT_RUNTIME: { 10117 // Grant previously granted runtime permissions. 10118 for (int userId : UserManagerService.getInstance().getUserIds()) { 10119 PermissionState permissionState = origPermissions 10120 .getRuntimePermissionState(bp.name, userId); 10121 int flags = permissionState != null 10122 ? permissionState.getFlags() : 0; 10123 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10124 // Don't propagate the permission in a permission review mode if 10125 // the former was revoked, i.e. marked to not propagate on upgrade. 10126 // Note that in a permission review mode install permissions are 10127 // represented as constantly granted runtime ones since we need to 10128 // keep a per user state associated with the permission. Also the 10129 // revoke on upgrade flag is no longer applicable and is reset. 10130 final boolean revokeOnUpgrade = (flags & PackageManager 10131 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 10132 if (revokeOnUpgrade) { 10133 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 10134 // Since we changed the flags, we have to write. 10135 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10136 changedRuntimePermissionUserIds, userId); 10137 } 10138 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 10139 if (permissionsState.grantRuntimePermission(bp, userId) == 10140 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10141 // If we cannot put the permission as it was, 10142 // we have to write. 10143 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10144 changedRuntimePermissionUserIds, userId); 10145 } 10146 } 10147 10148 // If the app supports runtime permissions no need for a review. 10149 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 10150 && appSupportsRuntimePermissions 10151 && (flags & PackageManager 10152 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10153 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10154 // Since we changed the flags, we have to write. 10155 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10156 changedRuntimePermissionUserIds, userId); 10157 } 10158 } else if ((mPermissionReviewRequired 10159 || Build.PERMISSIONS_REVIEW_REQUIRED) 10160 && !appSupportsRuntimePermissions) { 10161 // For legacy apps that need a permission review, every new 10162 // runtime permission is granted but it is pending a review. 10163 // We also need to review only platform defined runtime 10164 // permissions as these are the only ones the platform knows 10165 // how to disable the API to simulate revocation as legacy 10166 // apps don't expect to run with revoked permissions. 10167 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10168 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10169 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10170 // We changed the flags, hence have to write. 10171 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10172 changedRuntimePermissionUserIds, userId); 10173 } 10174 } 10175 if (permissionsState.grantRuntimePermission(bp, userId) 10176 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10177 // We changed the permission, hence have to write. 10178 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10179 changedRuntimePermissionUserIds, userId); 10180 } 10181 } 10182 // Propagate the permission flags. 10183 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10184 } 10185 } break; 10186 10187 case GRANT_UPGRADE: { 10188 // Grant runtime permissions for a previously held install permission. 10189 PermissionState permissionState = origPermissions 10190 .getInstallPermissionState(bp.name); 10191 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10192 10193 if (origPermissions.revokeInstallPermission(bp) 10194 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10195 // We will be transferring the permission flags, so clear them. 10196 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10197 PackageManager.MASK_PERMISSION_FLAGS, 0); 10198 changedInstallPermission = true; 10199 } 10200 10201 // If the permission is not to be promoted to runtime we ignore it and 10202 // also its other flags as they are not applicable to install permissions. 10203 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10204 for (int userId : currentUserIds) { 10205 if (permissionsState.grantRuntimePermission(bp, userId) != 10206 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10207 // Transfer the permission flags. 10208 permissionsState.updatePermissionFlags(bp, userId, 10209 flags, flags); 10210 // If we granted the permission, we have to write. 10211 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10212 changedRuntimePermissionUserIds, userId); 10213 } 10214 } 10215 } 10216 } break; 10217 10218 default: { 10219 if (packageOfInterest == null 10220 || packageOfInterest.equals(pkg.packageName)) { 10221 Slog.w(TAG, "Not granting permission " + perm 10222 + " to package " + pkg.packageName 10223 + " because it was previously installed without"); 10224 } 10225 } break; 10226 } 10227 } else { 10228 if (permissionsState.revokeInstallPermission(bp) != 10229 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10230 // Also drop the permission flags. 10231 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10232 PackageManager.MASK_PERMISSION_FLAGS, 0); 10233 changedInstallPermission = true; 10234 Slog.i(TAG, "Un-granting permission " + perm 10235 + " from package " + pkg.packageName 10236 + " (protectionLevel=" + bp.protectionLevel 10237 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10238 + ")"); 10239 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10240 // Don't print warning for app op permissions, since it is fine for them 10241 // not to be granted, there is a UI for the user to decide. 10242 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10243 Slog.w(TAG, "Not granting permission " + perm 10244 + " to package " + pkg.packageName 10245 + " (protectionLevel=" + bp.protectionLevel 10246 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10247 + ")"); 10248 } 10249 } 10250 } 10251 } 10252 10253 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10254 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10255 // This is the first that we have heard about this package, so the 10256 // permissions we have now selected are fixed until explicitly 10257 // changed. 10258 ps.installPermissionsFixed = true; 10259 } 10260 10261 // Persist the runtime permissions state for users with changes. If permissions 10262 // were revoked because no app in the shared user declares them we have to 10263 // write synchronously to avoid losing runtime permissions state. 10264 for (int userId : changedRuntimePermissionUserIds) { 10265 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10266 } 10267 10268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10269 } 10270 10271 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10272 boolean allowed = false; 10273 final int NP = PackageParser.NEW_PERMISSIONS.length; 10274 for (int ip=0; ip<NP; ip++) { 10275 final PackageParser.NewPermissionInfo npi 10276 = PackageParser.NEW_PERMISSIONS[ip]; 10277 if (npi.name.equals(perm) 10278 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10279 allowed = true; 10280 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10281 + pkg.packageName); 10282 break; 10283 } 10284 } 10285 return allowed; 10286 } 10287 10288 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10289 BasePermission bp, PermissionsState origPermissions) { 10290 boolean allowed; 10291 allowed = (compareSignatures( 10292 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10293 == PackageManager.SIGNATURE_MATCH) 10294 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10295 == PackageManager.SIGNATURE_MATCH); 10296 if (!allowed && (bp.protectionLevel 10297 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10298 if (isSystemApp(pkg)) { 10299 // For updated system applications, a system permission 10300 // is granted only if it had been defined by the original application. 10301 if (pkg.isUpdatedSystemApp()) { 10302 final PackageSetting sysPs = mSettings 10303 .getDisabledSystemPkgLPr(pkg.packageName); 10304 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10305 // If the original was granted this permission, we take 10306 // that grant decision as read and propagate it to the 10307 // update. 10308 if (sysPs.isPrivileged()) { 10309 allowed = true; 10310 } 10311 } else { 10312 // The system apk may have been updated with an older 10313 // version of the one on the data partition, but which 10314 // granted a new system permission that it didn't have 10315 // before. In this case we do want to allow the app to 10316 // now get the new permission if the ancestral apk is 10317 // privileged to get it. 10318 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10319 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10320 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10321 allowed = true; 10322 break; 10323 } 10324 } 10325 } 10326 // Also if a privileged parent package on the system image or any of 10327 // its children requested a privileged permission, the updated child 10328 // packages can also get the permission. 10329 if (pkg.parentPackage != null) { 10330 final PackageSetting disabledSysParentPs = mSettings 10331 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10332 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10333 && disabledSysParentPs.isPrivileged()) { 10334 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10335 allowed = true; 10336 } else if (disabledSysParentPs.pkg.childPackages != null) { 10337 final int count = disabledSysParentPs.pkg.childPackages.size(); 10338 for (int i = 0; i < count; i++) { 10339 PackageParser.Package disabledSysChildPkg = 10340 disabledSysParentPs.pkg.childPackages.get(i); 10341 if (isPackageRequestingPermission(disabledSysChildPkg, 10342 perm)) { 10343 allowed = true; 10344 break; 10345 } 10346 } 10347 } 10348 } 10349 } 10350 } 10351 } else { 10352 allowed = isPrivilegedApp(pkg); 10353 } 10354 } 10355 } 10356 if (!allowed) { 10357 if (!allowed && (bp.protectionLevel 10358 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10359 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10360 // If this was a previously normal/dangerous permission that got moved 10361 // to a system permission as part of the runtime permission redesign, then 10362 // we still want to blindly grant it to old apps. 10363 allowed = true; 10364 } 10365 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10366 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10367 // If this permission is to be granted to the system installer and 10368 // this app is an installer, then it gets the permission. 10369 allowed = true; 10370 } 10371 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10372 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10373 // If this permission is to be granted to the system verifier and 10374 // this app is a verifier, then it gets the permission. 10375 allowed = true; 10376 } 10377 if (!allowed && (bp.protectionLevel 10378 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10379 && isSystemApp(pkg)) { 10380 // Any pre-installed system app is allowed to get this permission. 10381 allowed = true; 10382 } 10383 if (!allowed && (bp.protectionLevel 10384 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10385 // For development permissions, a development permission 10386 // is granted only if it was already granted. 10387 allowed = origPermissions.hasInstallPermission(perm); 10388 } 10389 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10390 && pkg.packageName.equals(mSetupWizardPackage)) { 10391 // If this permission is to be granted to the system setup wizard and 10392 // this app is a setup wizard, then it gets the permission. 10393 allowed = true; 10394 } 10395 } 10396 return allowed; 10397 } 10398 10399 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10400 final int permCount = pkg.requestedPermissions.size(); 10401 for (int j = 0; j < permCount; j++) { 10402 String requestedPermission = pkg.requestedPermissions.get(j); 10403 if (permission.equals(requestedPermission)) { 10404 return true; 10405 } 10406 } 10407 return false; 10408 } 10409 10410 final class ActivityIntentResolver 10411 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10412 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10413 boolean defaultOnly, int userId) { 10414 if (!sUserManager.exists(userId)) return null; 10415 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10416 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10417 } 10418 10419 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10420 int userId) { 10421 if (!sUserManager.exists(userId)) return null; 10422 mFlags = flags; 10423 return super.queryIntent(intent, resolvedType, 10424 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10425 } 10426 10427 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10428 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10429 if (!sUserManager.exists(userId)) return null; 10430 if (packageActivities == null) { 10431 return null; 10432 } 10433 mFlags = flags; 10434 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10435 final int N = packageActivities.size(); 10436 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10437 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10438 10439 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10440 for (int i = 0; i < N; ++i) { 10441 intentFilters = packageActivities.get(i).intents; 10442 if (intentFilters != null && intentFilters.size() > 0) { 10443 PackageParser.ActivityIntentInfo[] array = 10444 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10445 intentFilters.toArray(array); 10446 listCut.add(array); 10447 } 10448 } 10449 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10450 } 10451 10452 /** 10453 * Finds a privileged activity that matches the specified activity names. 10454 */ 10455 private PackageParser.Activity findMatchingActivity( 10456 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10457 for (PackageParser.Activity sysActivity : activityList) { 10458 if (sysActivity.info.name.equals(activityInfo.name)) { 10459 return sysActivity; 10460 } 10461 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10462 return sysActivity; 10463 } 10464 if (sysActivity.info.targetActivity != null) { 10465 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10466 return sysActivity; 10467 } 10468 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10469 return sysActivity; 10470 } 10471 } 10472 } 10473 return null; 10474 } 10475 10476 public class IterGenerator<E> { 10477 public Iterator<E> generate(ActivityIntentInfo info) { 10478 return null; 10479 } 10480 } 10481 10482 public class ActionIterGenerator extends IterGenerator<String> { 10483 @Override 10484 public Iterator<String> generate(ActivityIntentInfo info) { 10485 return info.actionsIterator(); 10486 } 10487 } 10488 10489 public class CategoriesIterGenerator extends IterGenerator<String> { 10490 @Override 10491 public Iterator<String> generate(ActivityIntentInfo info) { 10492 return info.categoriesIterator(); 10493 } 10494 } 10495 10496 public class SchemesIterGenerator extends IterGenerator<String> { 10497 @Override 10498 public Iterator<String> generate(ActivityIntentInfo info) { 10499 return info.schemesIterator(); 10500 } 10501 } 10502 10503 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10504 @Override 10505 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10506 return info.authoritiesIterator(); 10507 } 10508 } 10509 10510 /** 10511 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10512 * MODIFIED. Do not pass in a list that should not be changed. 10513 */ 10514 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10515 IterGenerator<T> generator, Iterator<T> searchIterator) { 10516 // loop through the set of actions; every one must be found in the intent filter 10517 while (searchIterator.hasNext()) { 10518 // we must have at least one filter in the list to consider a match 10519 if (intentList.size() == 0) { 10520 break; 10521 } 10522 10523 final T searchAction = searchIterator.next(); 10524 10525 // loop through the set of intent filters 10526 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10527 while (intentIter.hasNext()) { 10528 final ActivityIntentInfo intentInfo = intentIter.next(); 10529 boolean selectionFound = false; 10530 10531 // loop through the intent filter's selection criteria; at least one 10532 // of them must match the searched criteria 10533 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10534 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10535 final T intentSelection = intentSelectionIter.next(); 10536 if (intentSelection != null && intentSelection.equals(searchAction)) { 10537 selectionFound = true; 10538 break; 10539 } 10540 } 10541 10542 // the selection criteria wasn't found in this filter's set; this filter 10543 // is not a potential match 10544 if (!selectionFound) { 10545 intentIter.remove(); 10546 } 10547 } 10548 } 10549 } 10550 10551 private boolean isProtectedAction(ActivityIntentInfo filter) { 10552 final Iterator<String> actionsIter = filter.actionsIterator(); 10553 while (actionsIter != null && actionsIter.hasNext()) { 10554 final String filterAction = actionsIter.next(); 10555 if (PROTECTED_ACTIONS.contains(filterAction)) { 10556 return true; 10557 } 10558 } 10559 return false; 10560 } 10561 10562 /** 10563 * Adjusts the priority of the given intent filter according to policy. 10564 * <p> 10565 * <ul> 10566 * <li>The priority for non privileged applications is capped to '0'</li> 10567 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10568 * <li>The priority for unbundled updates to privileged applications is capped to the 10569 * priority defined on the system partition</li> 10570 * </ul> 10571 * <p> 10572 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10573 * allowed to obtain any priority on any action. 10574 */ 10575 private void adjustPriority( 10576 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10577 // nothing to do; priority is fine as-is 10578 if (intent.getPriority() <= 0) { 10579 return; 10580 } 10581 10582 final ActivityInfo activityInfo = intent.activity.info; 10583 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10584 10585 final boolean privilegedApp = 10586 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10587 if (!privilegedApp) { 10588 // non-privileged applications can never define a priority >0 10589 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10590 + " package: " + applicationInfo.packageName 10591 + " activity: " + intent.activity.className 10592 + " origPrio: " + intent.getPriority()); 10593 intent.setPriority(0); 10594 return; 10595 } 10596 10597 if (systemActivities == null) { 10598 // the system package is not disabled; we're parsing the system partition 10599 if (isProtectedAction(intent)) { 10600 if (mDeferProtectedFilters) { 10601 // We can't deal with these just yet. No component should ever obtain a 10602 // >0 priority for a protected actions, with ONE exception -- the setup 10603 // wizard. The setup wizard, however, cannot be known until we're able to 10604 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10605 // until all intent filters have been processed. Chicken, meet egg. 10606 // Let the filter temporarily have a high priority and rectify the 10607 // priorities after all system packages have been scanned. 10608 mProtectedFilters.add(intent); 10609 if (DEBUG_FILTERS) { 10610 Slog.i(TAG, "Protected action; save for later;" 10611 + " package: " + applicationInfo.packageName 10612 + " activity: " + intent.activity.className 10613 + " origPrio: " + intent.getPriority()); 10614 } 10615 return; 10616 } else { 10617 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10618 Slog.i(TAG, "No setup wizard;" 10619 + " All protected intents capped to priority 0"); 10620 } 10621 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10622 if (DEBUG_FILTERS) { 10623 Slog.i(TAG, "Found setup wizard;" 10624 + " allow priority " + intent.getPriority() + ";" 10625 + " package: " + intent.activity.info.packageName 10626 + " activity: " + intent.activity.className 10627 + " priority: " + intent.getPriority()); 10628 } 10629 // setup wizard gets whatever it wants 10630 return; 10631 } 10632 Slog.w(TAG, "Protected action; cap priority to 0;" 10633 + " package: " + intent.activity.info.packageName 10634 + " activity: " + intent.activity.className 10635 + " origPrio: " + intent.getPriority()); 10636 intent.setPriority(0); 10637 return; 10638 } 10639 } 10640 // privileged apps on the system image get whatever priority they request 10641 return; 10642 } 10643 10644 // privileged app unbundled update ... try to find the same activity 10645 final PackageParser.Activity foundActivity = 10646 findMatchingActivity(systemActivities, activityInfo); 10647 if (foundActivity == null) { 10648 // this is a new activity; it cannot obtain >0 priority 10649 if (DEBUG_FILTERS) { 10650 Slog.i(TAG, "New activity; cap priority to 0;" 10651 + " package: " + applicationInfo.packageName 10652 + " activity: " + intent.activity.className 10653 + " origPrio: " + intent.getPriority()); 10654 } 10655 intent.setPriority(0); 10656 return; 10657 } 10658 10659 // found activity, now check for filter equivalence 10660 10661 // a shallow copy is enough; we modify the list, not its contents 10662 final List<ActivityIntentInfo> intentListCopy = 10663 new ArrayList<>(foundActivity.intents); 10664 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10665 10666 // find matching action subsets 10667 final Iterator<String> actionsIterator = intent.actionsIterator(); 10668 if (actionsIterator != null) { 10669 getIntentListSubset( 10670 intentListCopy, new ActionIterGenerator(), actionsIterator); 10671 if (intentListCopy.size() == 0) { 10672 // no more intents to match; we're not equivalent 10673 if (DEBUG_FILTERS) { 10674 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10675 + " package: " + applicationInfo.packageName 10676 + " activity: " + intent.activity.className 10677 + " origPrio: " + intent.getPriority()); 10678 } 10679 intent.setPriority(0); 10680 return; 10681 } 10682 } 10683 10684 // find matching category subsets 10685 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10686 if (categoriesIterator != null) { 10687 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10688 categoriesIterator); 10689 if (intentListCopy.size() == 0) { 10690 // no more intents to match; we're not equivalent 10691 if (DEBUG_FILTERS) { 10692 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10693 + " package: " + applicationInfo.packageName 10694 + " activity: " + intent.activity.className 10695 + " origPrio: " + intent.getPriority()); 10696 } 10697 intent.setPriority(0); 10698 return; 10699 } 10700 } 10701 10702 // find matching schemes subsets 10703 final Iterator<String> schemesIterator = intent.schemesIterator(); 10704 if (schemesIterator != null) { 10705 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10706 schemesIterator); 10707 if (intentListCopy.size() == 0) { 10708 // no more intents to match; we're not equivalent 10709 if (DEBUG_FILTERS) { 10710 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10711 + " package: " + applicationInfo.packageName 10712 + " activity: " + intent.activity.className 10713 + " origPrio: " + intent.getPriority()); 10714 } 10715 intent.setPriority(0); 10716 return; 10717 } 10718 } 10719 10720 // find matching authorities subsets 10721 final Iterator<IntentFilter.AuthorityEntry> 10722 authoritiesIterator = intent.authoritiesIterator(); 10723 if (authoritiesIterator != null) { 10724 getIntentListSubset(intentListCopy, 10725 new AuthoritiesIterGenerator(), 10726 authoritiesIterator); 10727 if (intentListCopy.size() == 0) { 10728 // no more intents to match; we're not equivalent 10729 if (DEBUG_FILTERS) { 10730 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10731 + " package: " + applicationInfo.packageName 10732 + " activity: " + intent.activity.className 10733 + " origPrio: " + intent.getPriority()); 10734 } 10735 intent.setPriority(0); 10736 return; 10737 } 10738 } 10739 10740 // we found matching filter(s); app gets the max priority of all intents 10741 int cappedPriority = 0; 10742 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10743 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10744 } 10745 if (intent.getPriority() > cappedPriority) { 10746 if (DEBUG_FILTERS) { 10747 Slog.i(TAG, "Found matching filter(s);" 10748 + " cap priority to " + cappedPriority + ";" 10749 + " package: " + applicationInfo.packageName 10750 + " activity: " + intent.activity.className 10751 + " origPrio: " + intent.getPriority()); 10752 } 10753 intent.setPriority(cappedPriority); 10754 return; 10755 } 10756 // all this for nothing; the requested priority was <= what was on the system 10757 } 10758 10759 public final void addActivity(PackageParser.Activity a, String type) { 10760 mActivities.put(a.getComponentName(), a); 10761 if (DEBUG_SHOW_INFO) 10762 Log.v( 10763 TAG, " " + type + " " + 10764 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10765 if (DEBUG_SHOW_INFO) 10766 Log.v(TAG, " Class=" + a.info.name); 10767 final int NI = a.intents.size(); 10768 for (int j=0; j<NI; j++) { 10769 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10770 if ("activity".equals(type)) { 10771 final PackageSetting ps = 10772 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10773 final List<PackageParser.Activity> systemActivities = 10774 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10775 adjustPriority(systemActivities, intent); 10776 } 10777 if (DEBUG_SHOW_INFO) { 10778 Log.v(TAG, " IntentFilter:"); 10779 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10780 } 10781 if (!intent.debugCheck()) { 10782 Log.w(TAG, "==> For Activity " + a.info.name); 10783 } 10784 addFilter(intent); 10785 } 10786 } 10787 10788 public final void removeActivity(PackageParser.Activity a, String type) { 10789 mActivities.remove(a.getComponentName()); 10790 if (DEBUG_SHOW_INFO) { 10791 Log.v(TAG, " " + type + " " 10792 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10793 : a.info.name) + ":"); 10794 Log.v(TAG, " Class=" + a.info.name); 10795 } 10796 final int NI = a.intents.size(); 10797 for (int j=0; j<NI; j++) { 10798 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10799 if (DEBUG_SHOW_INFO) { 10800 Log.v(TAG, " IntentFilter:"); 10801 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10802 } 10803 removeFilter(intent); 10804 } 10805 } 10806 10807 @Override 10808 protected boolean allowFilterResult( 10809 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10810 ActivityInfo filterAi = filter.activity.info; 10811 for (int i=dest.size()-1; i>=0; i--) { 10812 ActivityInfo destAi = dest.get(i).activityInfo; 10813 if (destAi.name == filterAi.name 10814 && destAi.packageName == filterAi.packageName) { 10815 return false; 10816 } 10817 } 10818 return true; 10819 } 10820 10821 @Override 10822 protected ActivityIntentInfo[] newArray(int size) { 10823 return new ActivityIntentInfo[size]; 10824 } 10825 10826 @Override 10827 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10828 if (!sUserManager.exists(userId)) return true; 10829 PackageParser.Package p = filter.activity.owner; 10830 if (p != null) { 10831 PackageSetting ps = (PackageSetting)p.mExtras; 10832 if (ps != null) { 10833 // System apps are never considered stopped for purposes of 10834 // filtering, because there may be no way for the user to 10835 // actually re-launch them. 10836 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10837 && ps.getStopped(userId); 10838 } 10839 } 10840 return false; 10841 } 10842 10843 @Override 10844 protected boolean isPackageForFilter(String packageName, 10845 PackageParser.ActivityIntentInfo info) { 10846 return packageName.equals(info.activity.owner.packageName); 10847 } 10848 10849 @Override 10850 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10851 int match, int userId) { 10852 if (!sUserManager.exists(userId)) return null; 10853 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10854 return null; 10855 } 10856 final PackageParser.Activity activity = info.activity; 10857 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10858 if (ps == null) { 10859 return null; 10860 } 10861 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10862 ps.readUserState(userId), userId); 10863 if (ai == null) { 10864 return null; 10865 } 10866 final ResolveInfo res = new ResolveInfo(); 10867 res.activityInfo = ai; 10868 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10869 res.filter = info; 10870 } 10871 if (info != null) { 10872 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10873 } 10874 res.priority = info.getPriority(); 10875 res.preferredOrder = activity.owner.mPreferredOrder; 10876 //System.out.println("Result: " + res.activityInfo.className + 10877 // " = " + res.priority); 10878 res.match = match; 10879 res.isDefault = info.hasDefault; 10880 res.labelRes = info.labelRes; 10881 res.nonLocalizedLabel = info.nonLocalizedLabel; 10882 if (userNeedsBadging(userId)) { 10883 res.noResourceId = true; 10884 } else { 10885 res.icon = info.icon; 10886 } 10887 res.iconResourceId = info.icon; 10888 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10889 return res; 10890 } 10891 10892 @Override 10893 protected void sortResults(List<ResolveInfo> results) { 10894 Collections.sort(results, mResolvePrioritySorter); 10895 } 10896 10897 @Override 10898 protected void dumpFilter(PrintWriter out, String prefix, 10899 PackageParser.ActivityIntentInfo filter) { 10900 out.print(prefix); out.print( 10901 Integer.toHexString(System.identityHashCode(filter.activity))); 10902 out.print(' '); 10903 filter.activity.printComponentShortName(out); 10904 out.print(" filter "); 10905 out.println(Integer.toHexString(System.identityHashCode(filter))); 10906 } 10907 10908 @Override 10909 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10910 return filter.activity; 10911 } 10912 10913 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10914 PackageParser.Activity activity = (PackageParser.Activity)label; 10915 out.print(prefix); out.print( 10916 Integer.toHexString(System.identityHashCode(activity))); 10917 out.print(' '); 10918 activity.printComponentShortName(out); 10919 if (count > 1) { 10920 out.print(" ("); out.print(count); out.print(" filters)"); 10921 } 10922 out.println(); 10923 } 10924 10925 // Keys are String (activity class name), values are Activity. 10926 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10927 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10928 private int mFlags; 10929 } 10930 10931 private final class ServiceIntentResolver 10932 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10933 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10934 boolean defaultOnly, int userId) { 10935 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10936 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10937 } 10938 10939 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10940 int userId) { 10941 if (!sUserManager.exists(userId)) return null; 10942 mFlags = flags; 10943 return super.queryIntent(intent, resolvedType, 10944 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10945 } 10946 10947 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10948 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10949 if (!sUserManager.exists(userId)) return null; 10950 if (packageServices == null) { 10951 return null; 10952 } 10953 mFlags = flags; 10954 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10955 final int N = packageServices.size(); 10956 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10957 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10958 10959 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10960 for (int i = 0; i < N; ++i) { 10961 intentFilters = packageServices.get(i).intents; 10962 if (intentFilters != null && intentFilters.size() > 0) { 10963 PackageParser.ServiceIntentInfo[] array = 10964 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10965 intentFilters.toArray(array); 10966 listCut.add(array); 10967 } 10968 } 10969 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10970 } 10971 10972 public final void addService(PackageParser.Service s) { 10973 mServices.put(s.getComponentName(), s); 10974 if (DEBUG_SHOW_INFO) { 10975 Log.v(TAG, " " 10976 + (s.info.nonLocalizedLabel != null 10977 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10978 Log.v(TAG, " Class=" + s.info.name); 10979 } 10980 final int NI = s.intents.size(); 10981 int j; 10982 for (j=0; j<NI; j++) { 10983 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10984 if (DEBUG_SHOW_INFO) { 10985 Log.v(TAG, " IntentFilter:"); 10986 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10987 } 10988 if (!intent.debugCheck()) { 10989 Log.w(TAG, "==> For Service " + s.info.name); 10990 } 10991 addFilter(intent); 10992 } 10993 } 10994 10995 public final void removeService(PackageParser.Service s) { 10996 mServices.remove(s.getComponentName()); 10997 if (DEBUG_SHOW_INFO) { 10998 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10999 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11000 Log.v(TAG, " Class=" + s.info.name); 11001 } 11002 final int NI = s.intents.size(); 11003 int j; 11004 for (j=0; j<NI; j++) { 11005 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11006 if (DEBUG_SHOW_INFO) { 11007 Log.v(TAG, " IntentFilter:"); 11008 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11009 } 11010 removeFilter(intent); 11011 } 11012 } 11013 11014 @Override 11015 protected boolean allowFilterResult( 11016 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11017 ServiceInfo filterSi = filter.service.info; 11018 for (int i=dest.size()-1; i>=0; i--) { 11019 ServiceInfo destAi = dest.get(i).serviceInfo; 11020 if (destAi.name == filterSi.name 11021 && destAi.packageName == filterSi.packageName) { 11022 return false; 11023 } 11024 } 11025 return true; 11026 } 11027 11028 @Override 11029 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11030 return new PackageParser.ServiceIntentInfo[size]; 11031 } 11032 11033 @Override 11034 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11035 if (!sUserManager.exists(userId)) return true; 11036 PackageParser.Package p = filter.service.owner; 11037 if (p != null) { 11038 PackageSetting ps = (PackageSetting)p.mExtras; 11039 if (ps != null) { 11040 // System apps are never considered stopped for purposes of 11041 // filtering, because there may be no way for the user to 11042 // actually re-launch them. 11043 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11044 && ps.getStopped(userId); 11045 } 11046 } 11047 return false; 11048 } 11049 11050 @Override 11051 protected boolean isPackageForFilter(String packageName, 11052 PackageParser.ServiceIntentInfo info) { 11053 return packageName.equals(info.service.owner.packageName); 11054 } 11055 11056 @Override 11057 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11058 int match, int userId) { 11059 if (!sUserManager.exists(userId)) return null; 11060 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11061 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11062 return null; 11063 } 11064 final PackageParser.Service service = info.service; 11065 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11066 if (ps == null) { 11067 return null; 11068 } 11069 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11070 ps.readUserState(userId), userId); 11071 if (si == null) { 11072 return null; 11073 } 11074 final ResolveInfo res = new ResolveInfo(); 11075 res.serviceInfo = si; 11076 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11077 res.filter = filter; 11078 } 11079 res.priority = info.getPriority(); 11080 res.preferredOrder = service.owner.mPreferredOrder; 11081 res.match = match; 11082 res.isDefault = info.hasDefault; 11083 res.labelRes = info.labelRes; 11084 res.nonLocalizedLabel = info.nonLocalizedLabel; 11085 res.icon = info.icon; 11086 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11087 return res; 11088 } 11089 11090 @Override 11091 protected void sortResults(List<ResolveInfo> results) { 11092 Collections.sort(results, mResolvePrioritySorter); 11093 } 11094 11095 @Override 11096 protected void dumpFilter(PrintWriter out, String prefix, 11097 PackageParser.ServiceIntentInfo filter) { 11098 out.print(prefix); out.print( 11099 Integer.toHexString(System.identityHashCode(filter.service))); 11100 out.print(' '); 11101 filter.service.printComponentShortName(out); 11102 out.print(" filter "); 11103 out.println(Integer.toHexString(System.identityHashCode(filter))); 11104 } 11105 11106 @Override 11107 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11108 return filter.service; 11109 } 11110 11111 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11112 PackageParser.Service service = (PackageParser.Service)label; 11113 out.print(prefix); out.print( 11114 Integer.toHexString(System.identityHashCode(service))); 11115 out.print(' '); 11116 service.printComponentShortName(out); 11117 if (count > 1) { 11118 out.print(" ("); out.print(count); out.print(" filters)"); 11119 } 11120 out.println(); 11121 } 11122 11123// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11124// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11125// final List<ResolveInfo> retList = Lists.newArrayList(); 11126// while (i.hasNext()) { 11127// final ResolveInfo resolveInfo = (ResolveInfo) i; 11128// if (isEnabledLP(resolveInfo.serviceInfo)) { 11129// retList.add(resolveInfo); 11130// } 11131// } 11132// return retList; 11133// } 11134 11135 // Keys are String (activity class name), values are Activity. 11136 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11137 = new ArrayMap<ComponentName, PackageParser.Service>(); 11138 private int mFlags; 11139 }; 11140 11141 private final class ProviderIntentResolver 11142 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11143 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11144 boolean defaultOnly, int userId) { 11145 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11146 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11147 } 11148 11149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11150 int userId) { 11151 if (!sUserManager.exists(userId)) 11152 return null; 11153 mFlags = flags; 11154 return super.queryIntent(intent, resolvedType, 11155 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11156 } 11157 11158 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11159 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11160 if (!sUserManager.exists(userId)) 11161 return null; 11162 if (packageProviders == null) { 11163 return null; 11164 } 11165 mFlags = flags; 11166 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11167 final int N = packageProviders.size(); 11168 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11169 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11170 11171 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11172 for (int i = 0; i < N; ++i) { 11173 intentFilters = packageProviders.get(i).intents; 11174 if (intentFilters != null && intentFilters.size() > 0) { 11175 PackageParser.ProviderIntentInfo[] array = 11176 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11177 intentFilters.toArray(array); 11178 listCut.add(array); 11179 } 11180 } 11181 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11182 } 11183 11184 public final void addProvider(PackageParser.Provider p) { 11185 if (mProviders.containsKey(p.getComponentName())) { 11186 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11187 return; 11188 } 11189 11190 mProviders.put(p.getComponentName(), p); 11191 if (DEBUG_SHOW_INFO) { 11192 Log.v(TAG, " " 11193 + (p.info.nonLocalizedLabel != null 11194 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11195 Log.v(TAG, " Class=" + p.info.name); 11196 } 11197 final int NI = p.intents.size(); 11198 int j; 11199 for (j = 0; j < NI; j++) { 11200 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11201 if (DEBUG_SHOW_INFO) { 11202 Log.v(TAG, " IntentFilter:"); 11203 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11204 } 11205 if (!intent.debugCheck()) { 11206 Log.w(TAG, "==> For Provider " + p.info.name); 11207 } 11208 addFilter(intent); 11209 } 11210 } 11211 11212 public final void removeProvider(PackageParser.Provider p) { 11213 mProviders.remove(p.getComponentName()); 11214 if (DEBUG_SHOW_INFO) { 11215 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11216 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11217 Log.v(TAG, " Class=" + p.info.name); 11218 } 11219 final int NI = p.intents.size(); 11220 int j; 11221 for (j = 0; j < NI; j++) { 11222 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11223 if (DEBUG_SHOW_INFO) { 11224 Log.v(TAG, " IntentFilter:"); 11225 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11226 } 11227 removeFilter(intent); 11228 } 11229 } 11230 11231 @Override 11232 protected boolean allowFilterResult( 11233 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11234 ProviderInfo filterPi = filter.provider.info; 11235 for (int i = dest.size() - 1; i >= 0; i--) { 11236 ProviderInfo destPi = dest.get(i).providerInfo; 11237 if (destPi.name == filterPi.name 11238 && destPi.packageName == filterPi.packageName) { 11239 return false; 11240 } 11241 } 11242 return true; 11243 } 11244 11245 @Override 11246 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11247 return new PackageParser.ProviderIntentInfo[size]; 11248 } 11249 11250 @Override 11251 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11252 if (!sUserManager.exists(userId)) 11253 return true; 11254 PackageParser.Package p = filter.provider.owner; 11255 if (p != null) { 11256 PackageSetting ps = (PackageSetting) p.mExtras; 11257 if (ps != null) { 11258 // System apps are never considered stopped for purposes of 11259 // filtering, because there may be no way for the user to 11260 // actually re-launch them. 11261 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11262 && ps.getStopped(userId); 11263 } 11264 } 11265 return false; 11266 } 11267 11268 @Override 11269 protected boolean isPackageForFilter(String packageName, 11270 PackageParser.ProviderIntentInfo info) { 11271 return packageName.equals(info.provider.owner.packageName); 11272 } 11273 11274 @Override 11275 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11276 int match, int userId) { 11277 if (!sUserManager.exists(userId)) 11278 return null; 11279 final PackageParser.ProviderIntentInfo info = filter; 11280 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11281 return null; 11282 } 11283 final PackageParser.Provider provider = info.provider; 11284 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11285 if (ps == null) { 11286 return null; 11287 } 11288 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11289 ps.readUserState(userId), userId); 11290 if (pi == null) { 11291 return null; 11292 } 11293 final ResolveInfo res = new ResolveInfo(); 11294 res.providerInfo = pi; 11295 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11296 res.filter = filter; 11297 } 11298 res.priority = info.getPriority(); 11299 res.preferredOrder = provider.owner.mPreferredOrder; 11300 res.match = match; 11301 res.isDefault = info.hasDefault; 11302 res.labelRes = info.labelRes; 11303 res.nonLocalizedLabel = info.nonLocalizedLabel; 11304 res.icon = info.icon; 11305 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11306 return res; 11307 } 11308 11309 @Override 11310 protected void sortResults(List<ResolveInfo> results) { 11311 Collections.sort(results, mResolvePrioritySorter); 11312 } 11313 11314 @Override 11315 protected void dumpFilter(PrintWriter out, String prefix, 11316 PackageParser.ProviderIntentInfo filter) { 11317 out.print(prefix); 11318 out.print( 11319 Integer.toHexString(System.identityHashCode(filter.provider))); 11320 out.print(' '); 11321 filter.provider.printComponentShortName(out); 11322 out.print(" filter "); 11323 out.println(Integer.toHexString(System.identityHashCode(filter))); 11324 } 11325 11326 @Override 11327 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11328 return filter.provider; 11329 } 11330 11331 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11332 PackageParser.Provider provider = (PackageParser.Provider)label; 11333 out.print(prefix); out.print( 11334 Integer.toHexString(System.identityHashCode(provider))); 11335 out.print(' '); 11336 provider.printComponentShortName(out); 11337 if (count > 1) { 11338 out.print(" ("); out.print(count); out.print(" filters)"); 11339 } 11340 out.println(); 11341 } 11342 11343 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11344 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11345 private int mFlags; 11346 } 11347 11348 private static final class EphemeralIntentResolver 11349 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11350 /** 11351 * The result that has the highest defined order. Ordering applies on a 11352 * per-package basis. Mapping is from package name to Pair of order and 11353 * EphemeralResolveInfo. 11354 * <p> 11355 * NOTE: This is implemented as a field variable for convenience and efficiency. 11356 * By having a field variable, we're able to track filter ordering as soon as 11357 * a non-zero order is defined. Otherwise, multiple loops across the result set 11358 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11359 * this needs to be contained entirely within {@link #filterResults()}. 11360 */ 11361 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11362 11363 @Override 11364 protected EphemeralResolveIntentInfo[] newArray(int size) { 11365 return new EphemeralResolveIntentInfo[size]; 11366 } 11367 11368 @Override 11369 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11370 return true; 11371 } 11372 11373 @Override 11374 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11375 int userId) { 11376 if (!sUserManager.exists(userId)) { 11377 return null; 11378 } 11379 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11380 final Integer order = info.getOrder(); 11381 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11382 mOrderResult.get(packageName); 11383 // ordering is enabled and this item's order isn't high enough 11384 if (lastOrderResult != null && lastOrderResult.first >= order) { 11385 return null; 11386 } 11387 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11388 if (order > 0) { 11389 // non-zero order, enable ordering 11390 mOrderResult.put(packageName, new Pair<>(order, res)); 11391 } 11392 return res; 11393 } 11394 11395 @Override 11396 protected void filterResults(List<EphemeralResolveInfo> results) { 11397 // only do work if ordering is enabled [most of the time it won't be] 11398 if (mOrderResult.size() == 0) { 11399 return; 11400 } 11401 int resultSize = results.size(); 11402 for (int i = 0; i < resultSize; i++) { 11403 final EphemeralResolveInfo info = results.get(i); 11404 final String packageName = info.getPackageName(); 11405 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11406 if (savedInfo == null) { 11407 // package doesn't having ordering 11408 continue; 11409 } 11410 if (savedInfo.second == info) { 11411 // circled back to the highest ordered item; remove from order list 11412 mOrderResult.remove(savedInfo); 11413 if (mOrderResult.size() == 0) { 11414 // no more ordered items 11415 break; 11416 } 11417 continue; 11418 } 11419 // item has a worse order, remove it from the result list 11420 results.remove(i); 11421 resultSize--; 11422 i--; 11423 } 11424 } 11425 } 11426 11427 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11428 new Comparator<ResolveInfo>() { 11429 public int compare(ResolveInfo r1, ResolveInfo r2) { 11430 int v1 = r1.priority; 11431 int v2 = r2.priority; 11432 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11433 if (v1 != v2) { 11434 return (v1 > v2) ? -1 : 1; 11435 } 11436 v1 = r1.preferredOrder; 11437 v2 = r2.preferredOrder; 11438 if (v1 != v2) { 11439 return (v1 > v2) ? -1 : 1; 11440 } 11441 if (r1.isDefault != r2.isDefault) { 11442 return r1.isDefault ? -1 : 1; 11443 } 11444 v1 = r1.match; 11445 v2 = r2.match; 11446 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11447 if (v1 != v2) { 11448 return (v1 > v2) ? -1 : 1; 11449 } 11450 if (r1.system != r2.system) { 11451 return r1.system ? -1 : 1; 11452 } 11453 if (r1.activityInfo != null) { 11454 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11455 } 11456 if (r1.serviceInfo != null) { 11457 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11458 } 11459 if (r1.providerInfo != null) { 11460 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11461 } 11462 return 0; 11463 } 11464 }; 11465 11466 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11467 new Comparator<ProviderInfo>() { 11468 public int compare(ProviderInfo p1, ProviderInfo p2) { 11469 final int v1 = p1.initOrder; 11470 final int v2 = p2.initOrder; 11471 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11472 } 11473 }; 11474 11475 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11476 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11477 final int[] userIds) { 11478 mHandler.post(new Runnable() { 11479 @Override 11480 public void run() { 11481 try { 11482 final IActivityManager am = ActivityManagerNative.getDefault(); 11483 if (am == null) return; 11484 final int[] resolvedUserIds; 11485 if (userIds == null) { 11486 resolvedUserIds = am.getRunningUserIds(); 11487 } else { 11488 resolvedUserIds = userIds; 11489 } 11490 for (int id : resolvedUserIds) { 11491 final Intent intent = new Intent(action, 11492 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11493 if (extras != null) { 11494 intent.putExtras(extras); 11495 } 11496 if (targetPkg != null) { 11497 intent.setPackage(targetPkg); 11498 } 11499 // Modify the UID when posting to other users 11500 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11501 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11502 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11503 intent.putExtra(Intent.EXTRA_UID, uid); 11504 } 11505 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11506 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11507 if (DEBUG_BROADCASTS) { 11508 RuntimeException here = new RuntimeException("here"); 11509 here.fillInStackTrace(); 11510 Slog.d(TAG, "Sending to user " + id + ": " 11511 + intent.toShortString(false, true, false, false) 11512 + " " + intent.getExtras(), here); 11513 } 11514 am.broadcastIntent(null, intent, null, finishedReceiver, 11515 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11516 null, finishedReceiver != null, false, id); 11517 } 11518 } catch (RemoteException ex) { 11519 } 11520 } 11521 }); 11522 } 11523 11524 /** 11525 * Check if the external storage media is available. This is true if there 11526 * is a mounted external storage medium or if the external storage is 11527 * emulated. 11528 */ 11529 private boolean isExternalMediaAvailable() { 11530 return mMediaMounted || Environment.isExternalStorageEmulated(); 11531 } 11532 11533 @Override 11534 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11535 // writer 11536 synchronized (mPackages) { 11537 if (!isExternalMediaAvailable()) { 11538 // If the external storage is no longer mounted at this point, 11539 // the caller may not have been able to delete all of this 11540 // packages files and can not delete any more. Bail. 11541 return null; 11542 } 11543 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11544 if (lastPackage != null) { 11545 pkgs.remove(lastPackage); 11546 } 11547 if (pkgs.size() > 0) { 11548 return pkgs.get(0); 11549 } 11550 } 11551 return null; 11552 } 11553 11554 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11555 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11556 userId, andCode ? 1 : 0, packageName); 11557 if (mSystemReady) { 11558 msg.sendToTarget(); 11559 } else { 11560 if (mPostSystemReadyMessages == null) { 11561 mPostSystemReadyMessages = new ArrayList<>(); 11562 } 11563 mPostSystemReadyMessages.add(msg); 11564 } 11565 } 11566 11567 void startCleaningPackages() { 11568 // reader 11569 if (!isExternalMediaAvailable()) { 11570 return; 11571 } 11572 synchronized (mPackages) { 11573 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11574 return; 11575 } 11576 } 11577 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11578 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11579 IActivityManager am = ActivityManagerNative.getDefault(); 11580 if (am != null) { 11581 try { 11582 am.startService(null, intent, null, mContext.getOpPackageName(), 11583 UserHandle.USER_SYSTEM); 11584 } catch (RemoteException e) { 11585 } 11586 } 11587 } 11588 11589 @Override 11590 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11591 int installFlags, String installerPackageName, int userId) { 11592 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11593 11594 final int callingUid = Binder.getCallingUid(); 11595 enforceCrossUserPermission(callingUid, userId, 11596 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11597 11598 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11599 try { 11600 if (observer != null) { 11601 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11602 } 11603 } catch (RemoteException re) { 11604 } 11605 return; 11606 } 11607 11608 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11609 installFlags |= PackageManager.INSTALL_FROM_ADB; 11610 11611 } else { 11612 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11613 // about installerPackageName. 11614 11615 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11616 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11617 } 11618 11619 UserHandle user; 11620 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11621 user = UserHandle.ALL; 11622 } else { 11623 user = new UserHandle(userId); 11624 } 11625 11626 // Only system components can circumvent runtime permissions when installing. 11627 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11628 && mContext.checkCallingOrSelfPermission(Manifest.permission 11629 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11630 throw new SecurityException("You need the " 11631 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11632 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11633 } 11634 11635 final File originFile = new File(originPath); 11636 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11637 11638 final Message msg = mHandler.obtainMessage(INIT_COPY); 11639 final VerificationInfo verificationInfo = new VerificationInfo( 11640 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11641 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11642 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11643 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11644 null /*certificates*/); 11645 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11646 msg.obj = params; 11647 11648 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11649 System.identityHashCode(msg.obj)); 11650 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11651 System.identityHashCode(msg.obj)); 11652 11653 mHandler.sendMessage(msg); 11654 } 11655 11656 void installStage(String packageName, File stagedDir, String stagedCid, 11657 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11658 String installerPackageName, int installerUid, UserHandle user, 11659 Certificate[][] certificates) { 11660 if (DEBUG_EPHEMERAL) { 11661 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11662 Slog.d(TAG, "Ephemeral install of " + packageName); 11663 } 11664 } 11665 final VerificationInfo verificationInfo = new VerificationInfo( 11666 sessionParams.originatingUri, sessionParams.referrerUri, 11667 sessionParams.originatingUid, installerUid); 11668 11669 final OriginInfo origin; 11670 if (stagedDir != null) { 11671 origin = OriginInfo.fromStagedFile(stagedDir); 11672 } else { 11673 origin = OriginInfo.fromStagedContainer(stagedCid); 11674 } 11675 11676 final Message msg = mHandler.obtainMessage(INIT_COPY); 11677 final InstallParams params = new InstallParams(origin, null, observer, 11678 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11679 verificationInfo, user, sessionParams.abiOverride, 11680 sessionParams.grantedRuntimePermissions, certificates); 11681 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11682 msg.obj = params; 11683 11684 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11685 System.identityHashCode(msg.obj)); 11686 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11687 System.identityHashCode(msg.obj)); 11688 11689 mHandler.sendMessage(msg); 11690 } 11691 11692 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11693 int userId) { 11694 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11695 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11696 } 11697 11698 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11699 int appId, int userId) { 11700 Bundle extras = new Bundle(1); 11701 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11702 11703 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11704 packageName, extras, 0, null, null, new int[] {userId}); 11705 try { 11706 IActivityManager am = ActivityManagerNative.getDefault(); 11707 if (isSystem && am.isUserRunning(userId, 0)) { 11708 // The just-installed/enabled app is bundled on the system, so presumed 11709 // to be able to run automatically without needing an explicit launch. 11710 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11711 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11712 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11713 .setPackage(packageName); 11714 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11715 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11716 } 11717 } catch (RemoteException e) { 11718 // shouldn't happen 11719 Slog.w(TAG, "Unable to bootstrap installed package", e); 11720 } 11721 } 11722 11723 @Override 11724 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11725 int userId) { 11726 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11727 PackageSetting pkgSetting; 11728 final int uid = Binder.getCallingUid(); 11729 enforceCrossUserPermission(uid, userId, 11730 true /* requireFullPermission */, true /* checkShell */, 11731 "setApplicationHiddenSetting for user " + userId); 11732 11733 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11734 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11735 return false; 11736 } 11737 11738 long callingId = Binder.clearCallingIdentity(); 11739 try { 11740 boolean sendAdded = false; 11741 boolean sendRemoved = false; 11742 // writer 11743 synchronized (mPackages) { 11744 pkgSetting = mSettings.mPackages.get(packageName); 11745 if (pkgSetting == null) { 11746 return false; 11747 } 11748 // Do not allow "android" is being disabled 11749 if ("android".equals(packageName)) { 11750 Slog.w(TAG, "Cannot hide package: android"); 11751 return false; 11752 } 11753 // Only allow protected packages to hide themselves. 11754 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11755 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11756 Slog.w(TAG, "Not hiding protected package: " + packageName); 11757 return false; 11758 } 11759 11760 if (pkgSetting.getHidden(userId) != hidden) { 11761 pkgSetting.setHidden(hidden, userId); 11762 mSettings.writePackageRestrictionsLPr(userId); 11763 if (hidden) { 11764 sendRemoved = true; 11765 } else { 11766 sendAdded = true; 11767 } 11768 } 11769 } 11770 if (sendAdded) { 11771 sendPackageAddedForUser(packageName, pkgSetting, userId); 11772 return true; 11773 } 11774 if (sendRemoved) { 11775 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11776 "hiding pkg"); 11777 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11778 return true; 11779 } 11780 } finally { 11781 Binder.restoreCallingIdentity(callingId); 11782 } 11783 return false; 11784 } 11785 11786 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11787 int userId) { 11788 final PackageRemovedInfo info = new PackageRemovedInfo(); 11789 info.removedPackage = packageName; 11790 info.removedUsers = new int[] {userId}; 11791 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11792 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11793 } 11794 11795 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11796 if (pkgList.length > 0) { 11797 Bundle extras = new Bundle(1); 11798 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11799 11800 sendPackageBroadcast( 11801 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11802 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11803 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11804 new int[] {userId}); 11805 } 11806 } 11807 11808 /** 11809 * Returns true if application is not found or there was an error. Otherwise it returns 11810 * the hidden state of the package for the given user. 11811 */ 11812 @Override 11813 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11816 true /* requireFullPermission */, false /* checkShell */, 11817 "getApplicationHidden for user " + userId); 11818 PackageSetting pkgSetting; 11819 long callingId = Binder.clearCallingIdentity(); 11820 try { 11821 // writer 11822 synchronized (mPackages) { 11823 pkgSetting = mSettings.mPackages.get(packageName); 11824 if (pkgSetting == null) { 11825 return true; 11826 } 11827 return pkgSetting.getHidden(userId); 11828 } 11829 } finally { 11830 Binder.restoreCallingIdentity(callingId); 11831 } 11832 } 11833 11834 /** 11835 * @hide 11836 */ 11837 @Override 11838 public int installExistingPackageAsUser(String packageName, int userId) { 11839 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11840 null); 11841 PackageSetting pkgSetting; 11842 final int uid = Binder.getCallingUid(); 11843 enforceCrossUserPermission(uid, userId, 11844 true /* requireFullPermission */, true /* checkShell */, 11845 "installExistingPackage for user " + userId); 11846 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11847 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11848 } 11849 11850 long callingId = Binder.clearCallingIdentity(); 11851 try { 11852 boolean installed = false; 11853 11854 // writer 11855 synchronized (mPackages) { 11856 pkgSetting = mSettings.mPackages.get(packageName); 11857 if (pkgSetting == null) { 11858 return PackageManager.INSTALL_FAILED_INVALID_URI; 11859 } 11860 if (!pkgSetting.getInstalled(userId)) { 11861 pkgSetting.setInstalled(true, userId); 11862 pkgSetting.setHidden(false, userId); 11863 mSettings.writePackageRestrictionsLPr(userId); 11864 installed = true; 11865 } 11866 } 11867 11868 if (installed) { 11869 if (pkgSetting.pkg != null) { 11870 synchronized (mInstallLock) { 11871 // We don't need to freeze for a brand new install 11872 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11873 } 11874 } 11875 sendPackageAddedForUser(packageName, pkgSetting, userId); 11876 } 11877 } finally { 11878 Binder.restoreCallingIdentity(callingId); 11879 } 11880 11881 return PackageManager.INSTALL_SUCCEEDED; 11882 } 11883 11884 boolean isUserRestricted(int userId, String restrictionKey) { 11885 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11886 if (restrictions.getBoolean(restrictionKey, false)) { 11887 Log.w(TAG, "User is restricted: " + restrictionKey); 11888 return true; 11889 } 11890 return false; 11891 } 11892 11893 @Override 11894 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11895 int userId) { 11896 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11897 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11898 true /* requireFullPermission */, true /* checkShell */, 11899 "setPackagesSuspended for user " + userId); 11900 11901 if (ArrayUtils.isEmpty(packageNames)) { 11902 return packageNames; 11903 } 11904 11905 // List of package names for whom the suspended state has changed. 11906 List<String> changedPackages = new ArrayList<>(packageNames.length); 11907 // List of package names for whom the suspended state is not set as requested in this 11908 // method. 11909 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11910 long callingId = Binder.clearCallingIdentity(); 11911 try { 11912 for (int i = 0; i < packageNames.length; i++) { 11913 String packageName = packageNames[i]; 11914 boolean changed = false; 11915 final int appId; 11916 synchronized (mPackages) { 11917 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11918 if (pkgSetting == null) { 11919 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11920 + "\". Skipping suspending/un-suspending."); 11921 unactionedPackages.add(packageName); 11922 continue; 11923 } 11924 appId = pkgSetting.appId; 11925 if (pkgSetting.getSuspended(userId) != suspended) { 11926 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11927 unactionedPackages.add(packageName); 11928 continue; 11929 } 11930 pkgSetting.setSuspended(suspended, userId); 11931 mSettings.writePackageRestrictionsLPr(userId); 11932 changed = true; 11933 changedPackages.add(packageName); 11934 } 11935 } 11936 11937 if (changed && suspended) { 11938 killApplication(packageName, UserHandle.getUid(userId, appId), 11939 "suspending package"); 11940 } 11941 } 11942 } finally { 11943 Binder.restoreCallingIdentity(callingId); 11944 } 11945 11946 if (!changedPackages.isEmpty()) { 11947 sendPackagesSuspendedForUser(changedPackages.toArray( 11948 new String[changedPackages.size()]), userId, suspended); 11949 } 11950 11951 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11952 } 11953 11954 @Override 11955 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11956 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11957 true /* requireFullPermission */, false /* checkShell */, 11958 "isPackageSuspendedForUser for user " + userId); 11959 synchronized (mPackages) { 11960 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11961 if (pkgSetting == null) { 11962 throw new IllegalArgumentException("Unknown target package: " + packageName); 11963 } 11964 return pkgSetting.getSuspended(userId); 11965 } 11966 } 11967 11968 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11969 if (isPackageDeviceAdmin(packageName, userId)) { 11970 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11971 + "\": has an active device admin"); 11972 return false; 11973 } 11974 11975 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11976 if (packageName.equals(activeLauncherPackageName)) { 11977 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11978 + "\": contains the active launcher"); 11979 return false; 11980 } 11981 11982 if (packageName.equals(mRequiredInstallerPackage)) { 11983 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11984 + "\": required for package installation"); 11985 return false; 11986 } 11987 11988 if (packageName.equals(mRequiredUninstallerPackage)) { 11989 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11990 + "\": required for package uninstallation"); 11991 return false; 11992 } 11993 11994 if (packageName.equals(mRequiredVerifierPackage)) { 11995 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11996 + "\": required for package verification"); 11997 return false; 11998 } 11999 12000 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12001 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12002 + "\": is the default dialer"); 12003 return false; 12004 } 12005 12006 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12007 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12008 + "\": protected package"); 12009 return false; 12010 } 12011 12012 return true; 12013 } 12014 12015 private String getActiveLauncherPackageName(int userId) { 12016 Intent intent = new Intent(Intent.ACTION_MAIN); 12017 intent.addCategory(Intent.CATEGORY_HOME); 12018 ResolveInfo resolveInfo = resolveIntent( 12019 intent, 12020 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12021 PackageManager.MATCH_DEFAULT_ONLY, 12022 userId); 12023 12024 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12025 } 12026 12027 private String getDefaultDialerPackageName(int userId) { 12028 synchronized (mPackages) { 12029 return mSettings.getDefaultDialerPackageNameLPw(userId); 12030 } 12031 } 12032 12033 @Override 12034 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12035 mContext.enforceCallingOrSelfPermission( 12036 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12037 "Only package verification agents can verify applications"); 12038 12039 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12040 final PackageVerificationResponse response = new PackageVerificationResponse( 12041 verificationCode, Binder.getCallingUid()); 12042 msg.arg1 = id; 12043 msg.obj = response; 12044 mHandler.sendMessage(msg); 12045 } 12046 12047 @Override 12048 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12049 long millisecondsToDelay) { 12050 mContext.enforceCallingOrSelfPermission( 12051 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12052 "Only package verification agents can extend verification timeouts"); 12053 12054 final PackageVerificationState state = mPendingVerification.get(id); 12055 final PackageVerificationResponse response = new PackageVerificationResponse( 12056 verificationCodeAtTimeout, Binder.getCallingUid()); 12057 12058 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12059 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12060 } 12061 if (millisecondsToDelay < 0) { 12062 millisecondsToDelay = 0; 12063 } 12064 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12065 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12066 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12067 } 12068 12069 if ((state != null) && !state.timeoutExtended()) { 12070 state.extendTimeout(); 12071 12072 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12073 msg.arg1 = id; 12074 msg.obj = response; 12075 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12076 } 12077 } 12078 12079 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12080 int verificationCode, UserHandle user) { 12081 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12082 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12083 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12084 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12085 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12086 12087 mContext.sendBroadcastAsUser(intent, user, 12088 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12089 } 12090 12091 private ComponentName matchComponentForVerifier(String packageName, 12092 List<ResolveInfo> receivers) { 12093 ActivityInfo targetReceiver = null; 12094 12095 final int NR = receivers.size(); 12096 for (int i = 0; i < NR; i++) { 12097 final ResolveInfo info = receivers.get(i); 12098 if (info.activityInfo == null) { 12099 continue; 12100 } 12101 12102 if (packageName.equals(info.activityInfo.packageName)) { 12103 targetReceiver = info.activityInfo; 12104 break; 12105 } 12106 } 12107 12108 if (targetReceiver == null) { 12109 return null; 12110 } 12111 12112 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12113 } 12114 12115 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12116 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12117 if (pkgInfo.verifiers.length == 0) { 12118 return null; 12119 } 12120 12121 final int N = pkgInfo.verifiers.length; 12122 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12123 for (int i = 0; i < N; i++) { 12124 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12125 12126 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12127 receivers); 12128 if (comp == null) { 12129 continue; 12130 } 12131 12132 final int verifierUid = getUidForVerifier(verifierInfo); 12133 if (verifierUid == -1) { 12134 continue; 12135 } 12136 12137 if (DEBUG_VERIFY) { 12138 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12139 + " with the correct signature"); 12140 } 12141 sufficientVerifiers.add(comp); 12142 verificationState.addSufficientVerifier(verifierUid); 12143 } 12144 12145 return sufficientVerifiers; 12146 } 12147 12148 private int getUidForVerifier(VerifierInfo verifierInfo) { 12149 synchronized (mPackages) { 12150 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12151 if (pkg == null) { 12152 return -1; 12153 } else if (pkg.mSignatures.length != 1) { 12154 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12155 + " has more than one signature; ignoring"); 12156 return -1; 12157 } 12158 12159 /* 12160 * If the public key of the package's signature does not match 12161 * our expected public key, then this is a different package and 12162 * we should skip. 12163 */ 12164 12165 final byte[] expectedPublicKey; 12166 try { 12167 final Signature verifierSig = pkg.mSignatures[0]; 12168 final PublicKey publicKey = verifierSig.getPublicKey(); 12169 expectedPublicKey = publicKey.getEncoded(); 12170 } catch (CertificateException e) { 12171 return -1; 12172 } 12173 12174 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12175 12176 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12177 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12178 + " does not have the expected public key; ignoring"); 12179 return -1; 12180 } 12181 12182 return pkg.applicationInfo.uid; 12183 } 12184 } 12185 12186 @Override 12187 public void finishPackageInstall(int token, boolean didLaunch) { 12188 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12189 12190 if (DEBUG_INSTALL) { 12191 Slog.v(TAG, "BM finishing package install for " + token); 12192 } 12193 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12194 12195 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12196 mHandler.sendMessage(msg); 12197 } 12198 12199 /** 12200 * Get the verification agent timeout. 12201 * 12202 * @return verification timeout in milliseconds 12203 */ 12204 private long getVerificationTimeout() { 12205 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12206 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12207 DEFAULT_VERIFICATION_TIMEOUT); 12208 } 12209 12210 /** 12211 * Get the default verification agent response code. 12212 * 12213 * @return default verification response code 12214 */ 12215 private int getDefaultVerificationResponse() { 12216 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12217 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12218 DEFAULT_VERIFICATION_RESPONSE); 12219 } 12220 12221 /** 12222 * Check whether or not package verification has been enabled. 12223 * 12224 * @return true if verification should be performed 12225 */ 12226 private boolean isVerificationEnabled(int userId, int installFlags) { 12227 if (!DEFAULT_VERIFY_ENABLE) { 12228 return false; 12229 } 12230 // Ephemeral apps don't get the full verification treatment 12231 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12232 if (DEBUG_EPHEMERAL) { 12233 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12234 } 12235 return false; 12236 } 12237 12238 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12239 12240 // Check if installing from ADB 12241 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12242 // Do not run verification in a test harness environment 12243 if (ActivityManager.isRunningInTestHarness()) { 12244 return false; 12245 } 12246 if (ensureVerifyAppsEnabled) { 12247 return true; 12248 } 12249 // Check if the developer does not want package verification for ADB installs 12250 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12251 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12252 return false; 12253 } 12254 } 12255 12256 if (ensureVerifyAppsEnabled) { 12257 return true; 12258 } 12259 12260 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12261 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12262 } 12263 12264 @Override 12265 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12266 throws RemoteException { 12267 mContext.enforceCallingOrSelfPermission( 12268 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12269 "Only intentfilter verification agents can verify applications"); 12270 12271 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12272 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12273 Binder.getCallingUid(), verificationCode, failedDomains); 12274 msg.arg1 = id; 12275 msg.obj = response; 12276 mHandler.sendMessage(msg); 12277 } 12278 12279 @Override 12280 public int getIntentVerificationStatus(String packageName, int userId) { 12281 synchronized (mPackages) { 12282 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12283 } 12284 } 12285 12286 @Override 12287 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12288 mContext.enforceCallingOrSelfPermission( 12289 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12290 12291 boolean result = false; 12292 synchronized (mPackages) { 12293 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12294 } 12295 if (result) { 12296 scheduleWritePackageRestrictionsLocked(userId); 12297 } 12298 return result; 12299 } 12300 12301 @Override 12302 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12303 String packageName) { 12304 synchronized (mPackages) { 12305 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12306 } 12307 } 12308 12309 @Override 12310 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12311 if (TextUtils.isEmpty(packageName)) { 12312 return ParceledListSlice.emptyList(); 12313 } 12314 synchronized (mPackages) { 12315 PackageParser.Package pkg = mPackages.get(packageName); 12316 if (pkg == null || pkg.activities == null) { 12317 return ParceledListSlice.emptyList(); 12318 } 12319 final int count = pkg.activities.size(); 12320 ArrayList<IntentFilter> result = new ArrayList<>(); 12321 for (int n=0; n<count; n++) { 12322 PackageParser.Activity activity = pkg.activities.get(n); 12323 if (activity.intents != null && activity.intents.size() > 0) { 12324 result.addAll(activity.intents); 12325 } 12326 } 12327 return new ParceledListSlice<>(result); 12328 } 12329 } 12330 12331 @Override 12332 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12333 mContext.enforceCallingOrSelfPermission( 12334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12335 12336 synchronized (mPackages) { 12337 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12338 if (packageName != null) { 12339 result |= updateIntentVerificationStatus(packageName, 12340 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12341 userId); 12342 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12343 packageName, userId); 12344 } 12345 return result; 12346 } 12347 } 12348 12349 @Override 12350 public String getDefaultBrowserPackageName(int userId) { 12351 synchronized (mPackages) { 12352 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12353 } 12354 } 12355 12356 /** 12357 * Get the "allow unknown sources" setting. 12358 * 12359 * @return the current "allow unknown sources" setting 12360 */ 12361 private int getUnknownSourcesSettings() { 12362 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12363 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12364 -1); 12365 } 12366 12367 @Override 12368 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12369 final int uid = Binder.getCallingUid(); 12370 // writer 12371 synchronized (mPackages) { 12372 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12373 if (targetPackageSetting == null) { 12374 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12375 } 12376 12377 PackageSetting installerPackageSetting; 12378 if (installerPackageName != null) { 12379 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12380 if (installerPackageSetting == null) { 12381 throw new IllegalArgumentException("Unknown installer package: " 12382 + installerPackageName); 12383 } 12384 } else { 12385 installerPackageSetting = null; 12386 } 12387 12388 Signature[] callerSignature; 12389 Object obj = mSettings.getUserIdLPr(uid); 12390 if (obj != null) { 12391 if (obj instanceof SharedUserSetting) { 12392 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12393 } else if (obj instanceof PackageSetting) { 12394 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12395 } else { 12396 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12397 } 12398 } else { 12399 throw new SecurityException("Unknown calling UID: " + uid); 12400 } 12401 12402 // Verify: can't set installerPackageName to a package that is 12403 // not signed with the same cert as the caller. 12404 if (installerPackageSetting != null) { 12405 if (compareSignatures(callerSignature, 12406 installerPackageSetting.signatures.mSignatures) 12407 != PackageManager.SIGNATURE_MATCH) { 12408 throw new SecurityException( 12409 "Caller does not have same cert as new installer package " 12410 + installerPackageName); 12411 } 12412 } 12413 12414 // Verify: if target already has an installer package, it must 12415 // be signed with the same cert as the caller. 12416 if (targetPackageSetting.installerPackageName != null) { 12417 PackageSetting setting = mSettings.mPackages.get( 12418 targetPackageSetting.installerPackageName); 12419 // If the currently set package isn't valid, then it's always 12420 // okay to change it. 12421 if (setting != null) { 12422 if (compareSignatures(callerSignature, 12423 setting.signatures.mSignatures) 12424 != PackageManager.SIGNATURE_MATCH) { 12425 throw new SecurityException( 12426 "Caller does not have same cert as old installer package " 12427 + targetPackageSetting.installerPackageName); 12428 } 12429 } 12430 } 12431 12432 // Okay! 12433 targetPackageSetting.installerPackageName = installerPackageName; 12434 if (installerPackageName != null) { 12435 mSettings.mInstallerPackages.add(installerPackageName); 12436 } 12437 scheduleWriteSettingsLocked(); 12438 } 12439 } 12440 12441 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12442 // Queue up an async operation since the package installation may take a little while. 12443 mHandler.post(new Runnable() { 12444 public void run() { 12445 mHandler.removeCallbacks(this); 12446 // Result object to be returned 12447 PackageInstalledInfo res = new PackageInstalledInfo(); 12448 res.setReturnCode(currentStatus); 12449 res.uid = -1; 12450 res.pkg = null; 12451 res.removedInfo = null; 12452 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12453 args.doPreInstall(res.returnCode); 12454 synchronized (mInstallLock) { 12455 installPackageTracedLI(args, res); 12456 } 12457 args.doPostInstall(res.returnCode, res.uid); 12458 } 12459 12460 // A restore should be performed at this point if (a) the install 12461 // succeeded, (b) the operation is not an update, and (c) the new 12462 // package has not opted out of backup participation. 12463 final boolean update = res.removedInfo != null 12464 && res.removedInfo.removedPackage != null; 12465 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12466 boolean doRestore = !update 12467 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12468 12469 // Set up the post-install work request bookkeeping. This will be used 12470 // and cleaned up by the post-install event handling regardless of whether 12471 // there's a restore pass performed. Token values are >= 1. 12472 int token; 12473 if (mNextInstallToken < 0) mNextInstallToken = 1; 12474 token = mNextInstallToken++; 12475 12476 PostInstallData data = new PostInstallData(args, res); 12477 mRunningInstalls.put(token, data); 12478 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12479 12480 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12481 // Pass responsibility to the Backup Manager. It will perform a 12482 // restore if appropriate, then pass responsibility back to the 12483 // Package Manager to run the post-install observer callbacks 12484 // and broadcasts. 12485 IBackupManager bm = IBackupManager.Stub.asInterface( 12486 ServiceManager.getService(Context.BACKUP_SERVICE)); 12487 if (bm != null) { 12488 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12489 + " to BM for possible restore"); 12490 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12491 try { 12492 // TODO: http://b/22388012 12493 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12494 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12495 } else { 12496 doRestore = false; 12497 } 12498 } catch (RemoteException e) { 12499 // can't happen; the backup manager is local 12500 } catch (Exception e) { 12501 Slog.e(TAG, "Exception trying to enqueue restore", e); 12502 doRestore = false; 12503 } 12504 } else { 12505 Slog.e(TAG, "Backup Manager not found!"); 12506 doRestore = false; 12507 } 12508 } 12509 12510 if (!doRestore) { 12511 // No restore possible, or the Backup Manager was mysteriously not 12512 // available -- just fire the post-install work request directly. 12513 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12514 12515 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12516 12517 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12518 mHandler.sendMessage(msg); 12519 } 12520 } 12521 }); 12522 } 12523 12524 /** 12525 * Callback from PackageSettings whenever an app is first transitioned out of the 12526 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12527 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12528 * here whether the app is the target of an ongoing install, and only send the 12529 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12530 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12531 * handling. 12532 */ 12533 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12534 // Serialize this with the rest of the install-process message chain. In the 12535 // restore-at-install case, this Runnable will necessarily run before the 12536 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12537 // are coherent. In the non-restore case, the app has already completed install 12538 // and been launched through some other means, so it is not in a problematic 12539 // state for observers to see the FIRST_LAUNCH signal. 12540 mHandler.post(new Runnable() { 12541 @Override 12542 public void run() { 12543 for (int i = 0; i < mRunningInstalls.size(); i++) { 12544 final PostInstallData data = mRunningInstalls.valueAt(i); 12545 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12546 continue; 12547 } 12548 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12549 // right package; but is it for the right user? 12550 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12551 if (userId == data.res.newUsers[uIndex]) { 12552 if (DEBUG_BACKUP) { 12553 Slog.i(TAG, "Package " + pkgName 12554 + " being restored so deferring FIRST_LAUNCH"); 12555 } 12556 return; 12557 } 12558 } 12559 } 12560 } 12561 // didn't find it, so not being restored 12562 if (DEBUG_BACKUP) { 12563 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12564 } 12565 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12566 } 12567 }); 12568 } 12569 12570 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12571 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12572 installerPkg, null, userIds); 12573 } 12574 12575 private abstract class HandlerParams { 12576 private static final int MAX_RETRIES = 4; 12577 12578 /** 12579 * Number of times startCopy() has been attempted and had a non-fatal 12580 * error. 12581 */ 12582 private int mRetries = 0; 12583 12584 /** User handle for the user requesting the information or installation. */ 12585 private final UserHandle mUser; 12586 String traceMethod; 12587 int traceCookie; 12588 12589 HandlerParams(UserHandle user) { 12590 mUser = user; 12591 } 12592 12593 UserHandle getUser() { 12594 return mUser; 12595 } 12596 12597 HandlerParams setTraceMethod(String traceMethod) { 12598 this.traceMethod = traceMethod; 12599 return this; 12600 } 12601 12602 HandlerParams setTraceCookie(int traceCookie) { 12603 this.traceCookie = traceCookie; 12604 return this; 12605 } 12606 12607 final boolean startCopy() { 12608 boolean res; 12609 try { 12610 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12611 12612 if (++mRetries > MAX_RETRIES) { 12613 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12614 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12615 handleServiceError(); 12616 return false; 12617 } else { 12618 handleStartCopy(); 12619 res = true; 12620 } 12621 } catch (RemoteException e) { 12622 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12623 mHandler.sendEmptyMessage(MCS_RECONNECT); 12624 res = false; 12625 } 12626 handleReturnCode(); 12627 return res; 12628 } 12629 12630 final void serviceError() { 12631 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12632 handleServiceError(); 12633 handleReturnCode(); 12634 } 12635 12636 abstract void handleStartCopy() throws RemoteException; 12637 abstract void handleServiceError(); 12638 abstract void handleReturnCode(); 12639 } 12640 12641 class MeasureParams extends HandlerParams { 12642 private final PackageStats mStats; 12643 private boolean mSuccess; 12644 12645 private final IPackageStatsObserver mObserver; 12646 12647 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12648 super(new UserHandle(stats.userHandle)); 12649 mObserver = observer; 12650 mStats = stats; 12651 } 12652 12653 @Override 12654 public String toString() { 12655 return "MeasureParams{" 12656 + Integer.toHexString(System.identityHashCode(this)) 12657 + " " + mStats.packageName + "}"; 12658 } 12659 12660 @Override 12661 void handleStartCopy() throws RemoteException { 12662 synchronized (mInstallLock) { 12663 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12664 } 12665 12666 if (mSuccess) { 12667 boolean mounted = false; 12668 try { 12669 final String status = Environment.getExternalStorageState(); 12670 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12671 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12672 } catch (Exception e) { 12673 } 12674 12675 if (mounted) { 12676 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12677 12678 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12679 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12680 12681 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12682 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12683 12684 // Always subtract cache size, since it's a subdirectory 12685 mStats.externalDataSize -= mStats.externalCacheSize; 12686 12687 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12688 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12689 12690 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12691 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12692 } 12693 } 12694 } 12695 12696 @Override 12697 void handleReturnCode() { 12698 if (mObserver != null) { 12699 try { 12700 mObserver.onGetStatsCompleted(mStats, mSuccess); 12701 } catch (RemoteException e) { 12702 Slog.i(TAG, "Observer no longer exists."); 12703 } 12704 } 12705 } 12706 12707 @Override 12708 void handleServiceError() { 12709 Slog.e(TAG, "Could not measure application " + mStats.packageName 12710 + " external storage"); 12711 } 12712 } 12713 12714 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12715 throws RemoteException { 12716 long result = 0; 12717 for (File path : paths) { 12718 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12719 } 12720 return result; 12721 } 12722 12723 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12724 for (File path : paths) { 12725 try { 12726 mcs.clearDirectory(path.getAbsolutePath()); 12727 } catch (RemoteException e) { 12728 } 12729 } 12730 } 12731 12732 static class OriginInfo { 12733 /** 12734 * Location where install is coming from, before it has been 12735 * copied/renamed into place. This could be a single monolithic APK 12736 * file, or a cluster directory. This location may be untrusted. 12737 */ 12738 final File file; 12739 final String cid; 12740 12741 /** 12742 * Flag indicating that {@link #file} or {@link #cid} has already been 12743 * staged, meaning downstream users don't need to defensively copy the 12744 * contents. 12745 */ 12746 final boolean staged; 12747 12748 /** 12749 * Flag indicating that {@link #file} or {@link #cid} is an already 12750 * installed app that is being moved. 12751 */ 12752 final boolean existing; 12753 12754 final String resolvedPath; 12755 final File resolvedFile; 12756 12757 static OriginInfo fromNothing() { 12758 return new OriginInfo(null, null, false, false); 12759 } 12760 12761 static OriginInfo fromUntrustedFile(File file) { 12762 return new OriginInfo(file, null, false, false); 12763 } 12764 12765 static OriginInfo fromExistingFile(File file) { 12766 return new OriginInfo(file, null, false, true); 12767 } 12768 12769 static OriginInfo fromStagedFile(File file) { 12770 return new OriginInfo(file, null, true, false); 12771 } 12772 12773 static OriginInfo fromStagedContainer(String cid) { 12774 return new OriginInfo(null, cid, true, false); 12775 } 12776 12777 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12778 this.file = file; 12779 this.cid = cid; 12780 this.staged = staged; 12781 this.existing = existing; 12782 12783 if (cid != null) { 12784 resolvedPath = PackageHelper.getSdDir(cid); 12785 resolvedFile = new File(resolvedPath); 12786 } else if (file != null) { 12787 resolvedPath = file.getAbsolutePath(); 12788 resolvedFile = file; 12789 } else { 12790 resolvedPath = null; 12791 resolvedFile = null; 12792 } 12793 } 12794 } 12795 12796 static class MoveInfo { 12797 final int moveId; 12798 final String fromUuid; 12799 final String toUuid; 12800 final String packageName; 12801 final String dataAppName; 12802 final int appId; 12803 final String seinfo; 12804 final int targetSdkVersion; 12805 12806 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12807 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12808 this.moveId = moveId; 12809 this.fromUuid = fromUuid; 12810 this.toUuid = toUuid; 12811 this.packageName = packageName; 12812 this.dataAppName = dataAppName; 12813 this.appId = appId; 12814 this.seinfo = seinfo; 12815 this.targetSdkVersion = targetSdkVersion; 12816 } 12817 } 12818 12819 static class VerificationInfo { 12820 /** A constant used to indicate that a uid value is not present. */ 12821 public static final int NO_UID = -1; 12822 12823 /** URI referencing where the package was downloaded from. */ 12824 final Uri originatingUri; 12825 12826 /** HTTP referrer URI associated with the originatingURI. */ 12827 final Uri referrer; 12828 12829 /** UID of the application that the install request originated from. */ 12830 final int originatingUid; 12831 12832 /** UID of application requesting the install */ 12833 final int installerUid; 12834 12835 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12836 this.originatingUri = originatingUri; 12837 this.referrer = referrer; 12838 this.originatingUid = originatingUid; 12839 this.installerUid = installerUid; 12840 } 12841 } 12842 12843 class InstallParams extends HandlerParams { 12844 final OriginInfo origin; 12845 final MoveInfo move; 12846 final IPackageInstallObserver2 observer; 12847 int installFlags; 12848 final String installerPackageName; 12849 final String volumeUuid; 12850 private InstallArgs mArgs; 12851 private int mRet; 12852 final String packageAbiOverride; 12853 final String[] grantedRuntimePermissions; 12854 final VerificationInfo verificationInfo; 12855 final Certificate[][] certificates; 12856 12857 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12858 int installFlags, String installerPackageName, String volumeUuid, 12859 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12860 String[] grantedPermissions, Certificate[][] certificates) { 12861 super(user); 12862 this.origin = origin; 12863 this.move = move; 12864 this.observer = observer; 12865 this.installFlags = installFlags; 12866 this.installerPackageName = installerPackageName; 12867 this.volumeUuid = volumeUuid; 12868 this.verificationInfo = verificationInfo; 12869 this.packageAbiOverride = packageAbiOverride; 12870 this.grantedRuntimePermissions = grantedPermissions; 12871 this.certificates = certificates; 12872 } 12873 12874 @Override 12875 public String toString() { 12876 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12877 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12878 } 12879 12880 private int installLocationPolicy(PackageInfoLite pkgLite) { 12881 String packageName = pkgLite.packageName; 12882 int installLocation = pkgLite.installLocation; 12883 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12884 // reader 12885 synchronized (mPackages) { 12886 // Currently installed package which the new package is attempting to replace or 12887 // null if no such package is installed. 12888 PackageParser.Package installedPkg = mPackages.get(packageName); 12889 // Package which currently owns the data which the new package will own if installed. 12890 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12891 // will be null whereas dataOwnerPkg will contain information about the package 12892 // which was uninstalled while keeping its data. 12893 PackageParser.Package dataOwnerPkg = installedPkg; 12894 if (dataOwnerPkg == null) { 12895 PackageSetting ps = mSettings.mPackages.get(packageName); 12896 if (ps != null) { 12897 dataOwnerPkg = ps.pkg; 12898 } 12899 } 12900 12901 if (dataOwnerPkg != null) { 12902 // If installed, the package will get access to data left on the device by its 12903 // predecessor. As a security measure, this is permited only if this is not a 12904 // version downgrade or if the predecessor package is marked as debuggable and 12905 // a downgrade is explicitly requested. 12906 // 12907 // On debuggable platform builds, downgrades are permitted even for 12908 // non-debuggable packages to make testing easier. Debuggable platform builds do 12909 // not offer security guarantees and thus it's OK to disable some security 12910 // mechanisms to make debugging/testing easier on those builds. However, even on 12911 // debuggable builds downgrades of packages are permitted only if requested via 12912 // installFlags. This is because we aim to keep the behavior of debuggable 12913 // platform builds as close as possible to the behavior of non-debuggable 12914 // platform builds. 12915 final boolean downgradeRequested = 12916 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12917 final boolean packageDebuggable = 12918 (dataOwnerPkg.applicationInfo.flags 12919 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12920 final boolean downgradePermitted = 12921 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12922 if (!downgradePermitted) { 12923 try { 12924 checkDowngrade(dataOwnerPkg, pkgLite); 12925 } catch (PackageManagerException e) { 12926 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12927 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12928 } 12929 } 12930 } 12931 12932 if (installedPkg != null) { 12933 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12934 // Check for updated system application. 12935 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12936 if (onSd) { 12937 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12938 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12939 } 12940 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12941 } else { 12942 if (onSd) { 12943 // Install flag overrides everything. 12944 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12945 } 12946 // If current upgrade specifies particular preference 12947 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12948 // Application explicitly specified internal. 12949 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12950 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12951 // App explictly prefers external. Let policy decide 12952 } else { 12953 // Prefer previous location 12954 if (isExternal(installedPkg)) { 12955 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12956 } 12957 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12958 } 12959 } 12960 } else { 12961 // Invalid install. Return error code 12962 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12963 } 12964 } 12965 } 12966 // All the special cases have been taken care of. 12967 // Return result based on recommended install location. 12968 if (onSd) { 12969 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12970 } 12971 return pkgLite.recommendedInstallLocation; 12972 } 12973 12974 /* 12975 * Invoke remote method to get package information and install 12976 * location values. Override install location based on default 12977 * policy if needed and then create install arguments based 12978 * on the install location. 12979 */ 12980 public void handleStartCopy() throws RemoteException { 12981 int ret = PackageManager.INSTALL_SUCCEEDED; 12982 12983 // If we're already staged, we've firmly committed to an install location 12984 if (origin.staged) { 12985 if (origin.file != null) { 12986 installFlags |= PackageManager.INSTALL_INTERNAL; 12987 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12988 } else if (origin.cid != null) { 12989 installFlags |= PackageManager.INSTALL_EXTERNAL; 12990 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12991 } else { 12992 throw new IllegalStateException("Invalid stage location"); 12993 } 12994 } 12995 12996 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12997 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12998 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12999 PackageInfoLite pkgLite = null; 13000 13001 if (onInt && onSd) { 13002 // Check if both bits are set. 13003 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13004 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13005 } else if (onSd && ephemeral) { 13006 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13007 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13008 } else { 13009 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13010 packageAbiOverride); 13011 13012 if (DEBUG_EPHEMERAL && ephemeral) { 13013 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13014 } 13015 13016 /* 13017 * If we have too little free space, try to free cache 13018 * before giving up. 13019 */ 13020 if (!origin.staged && pkgLite.recommendedInstallLocation 13021 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13022 // TODO: focus freeing disk space on the target device 13023 final StorageManager storage = StorageManager.from(mContext); 13024 final long lowThreshold = storage.getStorageLowBytes( 13025 Environment.getDataDirectory()); 13026 13027 final long sizeBytes = mContainerService.calculateInstalledSize( 13028 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13029 13030 try { 13031 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13032 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13033 installFlags, packageAbiOverride); 13034 } catch (InstallerException e) { 13035 Slog.w(TAG, "Failed to free cache", e); 13036 } 13037 13038 /* 13039 * The cache free must have deleted the file we 13040 * downloaded to install. 13041 * 13042 * TODO: fix the "freeCache" call to not delete 13043 * the file we care about. 13044 */ 13045 if (pkgLite.recommendedInstallLocation 13046 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13047 pkgLite.recommendedInstallLocation 13048 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13049 } 13050 } 13051 } 13052 13053 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13054 int loc = pkgLite.recommendedInstallLocation; 13055 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13056 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13057 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13058 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13059 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13060 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13061 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13062 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13063 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13064 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13065 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13066 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13067 } else { 13068 // Override with defaults if needed. 13069 loc = installLocationPolicy(pkgLite); 13070 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13071 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13072 } else if (!onSd && !onInt) { 13073 // Override install location with flags 13074 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13075 // Set the flag to install on external media. 13076 installFlags |= PackageManager.INSTALL_EXTERNAL; 13077 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13078 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13079 if (DEBUG_EPHEMERAL) { 13080 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13081 } 13082 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13083 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13084 |PackageManager.INSTALL_INTERNAL); 13085 } else { 13086 // Make sure the flag for installing on external 13087 // media is unset 13088 installFlags |= PackageManager.INSTALL_INTERNAL; 13089 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13090 } 13091 } 13092 } 13093 } 13094 13095 final InstallArgs args = createInstallArgs(this); 13096 mArgs = args; 13097 13098 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13099 // TODO: http://b/22976637 13100 // Apps installed for "all" users use the device owner to verify the app 13101 UserHandle verifierUser = getUser(); 13102 if (verifierUser == UserHandle.ALL) { 13103 verifierUser = UserHandle.SYSTEM; 13104 } 13105 13106 /* 13107 * Determine if we have any installed package verifiers. If we 13108 * do, then we'll defer to them to verify the packages. 13109 */ 13110 final int requiredUid = mRequiredVerifierPackage == null ? -1 13111 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13112 verifierUser.getIdentifier()); 13113 if (!origin.existing && requiredUid != -1 13114 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13115 final Intent verification = new Intent( 13116 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13117 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13118 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13119 PACKAGE_MIME_TYPE); 13120 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13121 13122 // Query all live verifiers based on current user state 13123 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13124 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13125 13126 if (DEBUG_VERIFY) { 13127 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13128 + verification.toString() + " with " + pkgLite.verifiers.length 13129 + " optional verifiers"); 13130 } 13131 13132 final int verificationId = mPendingVerificationToken++; 13133 13134 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13135 13136 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13137 installerPackageName); 13138 13139 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13140 installFlags); 13141 13142 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13143 pkgLite.packageName); 13144 13145 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13146 pkgLite.versionCode); 13147 13148 if (verificationInfo != null) { 13149 if (verificationInfo.originatingUri != null) { 13150 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13151 verificationInfo.originatingUri); 13152 } 13153 if (verificationInfo.referrer != null) { 13154 verification.putExtra(Intent.EXTRA_REFERRER, 13155 verificationInfo.referrer); 13156 } 13157 if (verificationInfo.originatingUid >= 0) { 13158 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13159 verificationInfo.originatingUid); 13160 } 13161 if (verificationInfo.installerUid >= 0) { 13162 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13163 verificationInfo.installerUid); 13164 } 13165 } 13166 13167 final PackageVerificationState verificationState = new PackageVerificationState( 13168 requiredUid, args); 13169 13170 mPendingVerification.append(verificationId, verificationState); 13171 13172 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13173 receivers, verificationState); 13174 13175 /* 13176 * If any sufficient verifiers were listed in the package 13177 * manifest, attempt to ask them. 13178 */ 13179 if (sufficientVerifiers != null) { 13180 final int N = sufficientVerifiers.size(); 13181 if (N == 0) { 13182 Slog.i(TAG, "Additional verifiers required, but none installed."); 13183 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13184 } else { 13185 for (int i = 0; i < N; i++) { 13186 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13187 13188 final Intent sufficientIntent = new Intent(verification); 13189 sufficientIntent.setComponent(verifierComponent); 13190 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13191 } 13192 } 13193 } 13194 13195 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13196 mRequiredVerifierPackage, receivers); 13197 if (ret == PackageManager.INSTALL_SUCCEEDED 13198 && mRequiredVerifierPackage != null) { 13199 Trace.asyncTraceBegin( 13200 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13201 /* 13202 * Send the intent to the required verification agent, 13203 * but only start the verification timeout after the 13204 * target BroadcastReceivers have run. 13205 */ 13206 verification.setComponent(requiredVerifierComponent); 13207 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13208 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13209 new BroadcastReceiver() { 13210 @Override 13211 public void onReceive(Context context, Intent intent) { 13212 final Message msg = mHandler 13213 .obtainMessage(CHECK_PENDING_VERIFICATION); 13214 msg.arg1 = verificationId; 13215 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13216 } 13217 }, null, 0, null, null); 13218 13219 /* 13220 * We don't want the copy to proceed until verification 13221 * succeeds, so null out this field. 13222 */ 13223 mArgs = null; 13224 } 13225 } else { 13226 /* 13227 * No package verification is enabled, so immediately start 13228 * the remote call to initiate copy using temporary file. 13229 */ 13230 ret = args.copyApk(mContainerService, true); 13231 } 13232 } 13233 13234 mRet = ret; 13235 } 13236 13237 @Override 13238 void handleReturnCode() { 13239 // If mArgs is null, then MCS couldn't be reached. When it 13240 // reconnects, it will try again to install. At that point, this 13241 // will succeed. 13242 if (mArgs != null) { 13243 processPendingInstall(mArgs, mRet); 13244 } 13245 } 13246 13247 @Override 13248 void handleServiceError() { 13249 mArgs = createInstallArgs(this); 13250 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13251 } 13252 13253 public boolean isForwardLocked() { 13254 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13255 } 13256 } 13257 13258 /** 13259 * Used during creation of InstallArgs 13260 * 13261 * @param installFlags package installation flags 13262 * @return true if should be installed on external storage 13263 */ 13264 private static boolean installOnExternalAsec(int installFlags) { 13265 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13266 return false; 13267 } 13268 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13269 return true; 13270 } 13271 return false; 13272 } 13273 13274 /** 13275 * Used during creation of InstallArgs 13276 * 13277 * @param installFlags package installation flags 13278 * @return true if should be installed as forward locked 13279 */ 13280 private static boolean installForwardLocked(int installFlags) { 13281 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13282 } 13283 13284 private InstallArgs createInstallArgs(InstallParams params) { 13285 if (params.move != null) { 13286 return new MoveInstallArgs(params); 13287 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13288 return new AsecInstallArgs(params); 13289 } else { 13290 return new FileInstallArgs(params); 13291 } 13292 } 13293 13294 /** 13295 * Create args that describe an existing installed package. Typically used 13296 * when cleaning up old installs, or used as a move source. 13297 */ 13298 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13299 String resourcePath, String[] instructionSets) { 13300 final boolean isInAsec; 13301 if (installOnExternalAsec(installFlags)) { 13302 /* Apps on SD card are always in ASEC containers. */ 13303 isInAsec = true; 13304 } else if (installForwardLocked(installFlags) 13305 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13306 /* 13307 * Forward-locked apps are only in ASEC containers if they're the 13308 * new style 13309 */ 13310 isInAsec = true; 13311 } else { 13312 isInAsec = false; 13313 } 13314 13315 if (isInAsec) { 13316 return new AsecInstallArgs(codePath, instructionSets, 13317 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13318 } else { 13319 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13320 } 13321 } 13322 13323 static abstract class InstallArgs { 13324 /** @see InstallParams#origin */ 13325 final OriginInfo origin; 13326 /** @see InstallParams#move */ 13327 final MoveInfo move; 13328 13329 final IPackageInstallObserver2 observer; 13330 // Always refers to PackageManager flags only 13331 final int installFlags; 13332 final String installerPackageName; 13333 final String volumeUuid; 13334 final UserHandle user; 13335 final String abiOverride; 13336 final String[] installGrantPermissions; 13337 /** If non-null, drop an async trace when the install completes */ 13338 final String traceMethod; 13339 final int traceCookie; 13340 final Certificate[][] certificates; 13341 13342 // The list of instruction sets supported by this app. This is currently 13343 // only used during the rmdex() phase to clean up resources. We can get rid of this 13344 // if we move dex files under the common app path. 13345 /* nullable */ String[] instructionSets; 13346 13347 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13348 int installFlags, String installerPackageName, String volumeUuid, 13349 UserHandle user, String[] instructionSets, 13350 String abiOverride, String[] installGrantPermissions, 13351 String traceMethod, int traceCookie, Certificate[][] certificates) { 13352 this.origin = origin; 13353 this.move = move; 13354 this.installFlags = installFlags; 13355 this.observer = observer; 13356 this.installerPackageName = installerPackageName; 13357 this.volumeUuid = volumeUuid; 13358 this.user = user; 13359 this.instructionSets = instructionSets; 13360 this.abiOverride = abiOverride; 13361 this.installGrantPermissions = installGrantPermissions; 13362 this.traceMethod = traceMethod; 13363 this.traceCookie = traceCookie; 13364 this.certificates = certificates; 13365 } 13366 13367 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13368 abstract int doPreInstall(int status); 13369 13370 /** 13371 * Rename package into final resting place. All paths on the given 13372 * scanned package should be updated to reflect the rename. 13373 */ 13374 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13375 abstract int doPostInstall(int status, int uid); 13376 13377 /** @see PackageSettingBase#codePathString */ 13378 abstract String getCodePath(); 13379 /** @see PackageSettingBase#resourcePathString */ 13380 abstract String getResourcePath(); 13381 13382 // Need installer lock especially for dex file removal. 13383 abstract void cleanUpResourcesLI(); 13384 abstract boolean doPostDeleteLI(boolean delete); 13385 13386 /** 13387 * Called before the source arguments are copied. This is used mostly 13388 * for MoveParams when it needs to read the source file to put it in the 13389 * destination. 13390 */ 13391 int doPreCopy() { 13392 return PackageManager.INSTALL_SUCCEEDED; 13393 } 13394 13395 /** 13396 * Called after the source arguments are copied. This is used mostly for 13397 * MoveParams when it needs to read the source file to put it in the 13398 * destination. 13399 */ 13400 int doPostCopy(int uid) { 13401 return PackageManager.INSTALL_SUCCEEDED; 13402 } 13403 13404 protected boolean isFwdLocked() { 13405 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13406 } 13407 13408 protected boolean isExternalAsec() { 13409 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13410 } 13411 13412 protected boolean isEphemeral() { 13413 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13414 } 13415 13416 UserHandle getUser() { 13417 return user; 13418 } 13419 } 13420 13421 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13422 if (!allCodePaths.isEmpty()) { 13423 if (instructionSets == null) { 13424 throw new IllegalStateException("instructionSet == null"); 13425 } 13426 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13427 for (String codePath : allCodePaths) { 13428 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13429 try { 13430 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13431 } catch (InstallerException ignored) { 13432 } 13433 } 13434 } 13435 } 13436 } 13437 13438 /** 13439 * Logic to handle installation of non-ASEC applications, including copying 13440 * and renaming logic. 13441 */ 13442 class FileInstallArgs extends InstallArgs { 13443 private File codeFile; 13444 private File resourceFile; 13445 13446 // Example topology: 13447 // /data/app/com.example/base.apk 13448 // /data/app/com.example/split_foo.apk 13449 // /data/app/com.example/lib/arm/libfoo.so 13450 // /data/app/com.example/lib/arm64/libfoo.so 13451 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13452 13453 /** New install */ 13454 FileInstallArgs(InstallParams params) { 13455 super(params.origin, params.move, params.observer, params.installFlags, 13456 params.installerPackageName, params.volumeUuid, 13457 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13458 params.grantedRuntimePermissions, 13459 params.traceMethod, params.traceCookie, params.certificates); 13460 if (isFwdLocked()) { 13461 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13462 } 13463 } 13464 13465 /** Existing install */ 13466 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13467 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13468 null, null, null, 0, null /*certificates*/); 13469 this.codeFile = (codePath != null) ? new File(codePath) : null; 13470 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13471 } 13472 13473 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13475 try { 13476 return doCopyApk(imcs, temp); 13477 } finally { 13478 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13479 } 13480 } 13481 13482 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13483 if (origin.staged) { 13484 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13485 codeFile = origin.file; 13486 resourceFile = origin.file; 13487 return PackageManager.INSTALL_SUCCEEDED; 13488 } 13489 13490 try { 13491 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13492 final File tempDir = 13493 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13494 codeFile = tempDir; 13495 resourceFile = tempDir; 13496 } catch (IOException e) { 13497 Slog.w(TAG, "Failed to create copy file: " + e); 13498 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13499 } 13500 13501 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13502 @Override 13503 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13504 if (!FileUtils.isValidExtFilename(name)) { 13505 throw new IllegalArgumentException("Invalid filename: " + name); 13506 } 13507 try { 13508 final File file = new File(codeFile, name); 13509 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13510 O_RDWR | O_CREAT, 0644); 13511 Os.chmod(file.getAbsolutePath(), 0644); 13512 return new ParcelFileDescriptor(fd); 13513 } catch (ErrnoException e) { 13514 throw new RemoteException("Failed to open: " + e.getMessage()); 13515 } 13516 } 13517 }; 13518 13519 int ret = PackageManager.INSTALL_SUCCEEDED; 13520 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13521 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13522 Slog.e(TAG, "Failed to copy package"); 13523 return ret; 13524 } 13525 13526 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13527 NativeLibraryHelper.Handle handle = null; 13528 try { 13529 handle = NativeLibraryHelper.Handle.create(codeFile); 13530 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13531 abiOverride); 13532 } catch (IOException e) { 13533 Slog.e(TAG, "Copying native libraries failed", e); 13534 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13535 } finally { 13536 IoUtils.closeQuietly(handle); 13537 } 13538 13539 return ret; 13540 } 13541 13542 int doPreInstall(int status) { 13543 if (status != PackageManager.INSTALL_SUCCEEDED) { 13544 cleanUp(); 13545 } 13546 return status; 13547 } 13548 13549 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13550 if (status != PackageManager.INSTALL_SUCCEEDED) { 13551 cleanUp(); 13552 return false; 13553 } 13554 13555 final File targetDir = codeFile.getParentFile(); 13556 final File beforeCodeFile = codeFile; 13557 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13558 13559 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13560 try { 13561 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13562 } catch (ErrnoException e) { 13563 Slog.w(TAG, "Failed to rename", e); 13564 return false; 13565 } 13566 13567 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13568 Slog.w(TAG, "Failed to restorecon"); 13569 return false; 13570 } 13571 13572 // Reflect the rename internally 13573 codeFile = afterCodeFile; 13574 resourceFile = afterCodeFile; 13575 13576 // Reflect the rename in scanned details 13577 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13578 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13579 afterCodeFile, pkg.baseCodePath)); 13580 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13581 afterCodeFile, pkg.splitCodePaths)); 13582 13583 // Reflect the rename in app info 13584 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13585 pkg.setApplicationInfoCodePath(pkg.codePath); 13586 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13587 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13588 pkg.setApplicationInfoResourcePath(pkg.codePath); 13589 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13590 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13591 13592 return true; 13593 } 13594 13595 int doPostInstall(int status, int uid) { 13596 if (status != PackageManager.INSTALL_SUCCEEDED) { 13597 cleanUp(); 13598 } 13599 return status; 13600 } 13601 13602 @Override 13603 String getCodePath() { 13604 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13605 } 13606 13607 @Override 13608 String getResourcePath() { 13609 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13610 } 13611 13612 private boolean cleanUp() { 13613 if (codeFile == null || !codeFile.exists()) { 13614 return false; 13615 } 13616 13617 removeCodePathLI(codeFile); 13618 13619 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13620 resourceFile.delete(); 13621 } 13622 13623 return true; 13624 } 13625 13626 void cleanUpResourcesLI() { 13627 // Try enumerating all code paths before deleting 13628 List<String> allCodePaths = Collections.EMPTY_LIST; 13629 if (codeFile != null && codeFile.exists()) { 13630 try { 13631 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13632 allCodePaths = pkg.getAllCodePaths(); 13633 } catch (PackageParserException e) { 13634 // Ignored; we tried our best 13635 } 13636 } 13637 13638 cleanUp(); 13639 removeDexFiles(allCodePaths, instructionSets); 13640 } 13641 13642 boolean doPostDeleteLI(boolean delete) { 13643 // XXX err, shouldn't we respect the delete flag? 13644 cleanUpResourcesLI(); 13645 return true; 13646 } 13647 } 13648 13649 private boolean isAsecExternal(String cid) { 13650 final String asecPath = PackageHelper.getSdFilesystem(cid); 13651 return !asecPath.startsWith(mAsecInternalPath); 13652 } 13653 13654 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13655 PackageManagerException { 13656 if (copyRet < 0) { 13657 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13658 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13659 throw new PackageManagerException(copyRet, message); 13660 } 13661 } 13662 } 13663 13664 /** 13665 * Extract the MountService "container ID" from the full code path of an 13666 * .apk. 13667 */ 13668 static String cidFromCodePath(String fullCodePath) { 13669 int eidx = fullCodePath.lastIndexOf("/"); 13670 String subStr1 = fullCodePath.substring(0, eidx); 13671 int sidx = subStr1.lastIndexOf("/"); 13672 return subStr1.substring(sidx+1, eidx); 13673 } 13674 13675 /** 13676 * Logic to handle installation of ASEC applications, including copying and 13677 * renaming logic. 13678 */ 13679 class AsecInstallArgs extends InstallArgs { 13680 static final String RES_FILE_NAME = "pkg.apk"; 13681 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13682 13683 String cid; 13684 String packagePath; 13685 String resourcePath; 13686 13687 /** New install */ 13688 AsecInstallArgs(InstallParams params) { 13689 super(params.origin, params.move, params.observer, params.installFlags, 13690 params.installerPackageName, params.volumeUuid, 13691 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13692 params.grantedRuntimePermissions, 13693 params.traceMethod, params.traceCookie, params.certificates); 13694 } 13695 13696 /** Existing install */ 13697 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13698 boolean isExternal, boolean isForwardLocked) { 13699 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13700 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13701 instructionSets, null, null, null, 0, null /*certificates*/); 13702 // Hackily pretend we're still looking at a full code path 13703 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13704 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13705 } 13706 13707 // Extract cid from fullCodePath 13708 int eidx = fullCodePath.lastIndexOf("/"); 13709 String subStr1 = fullCodePath.substring(0, eidx); 13710 int sidx = subStr1.lastIndexOf("/"); 13711 cid = subStr1.substring(sidx+1, eidx); 13712 setMountPath(subStr1); 13713 } 13714 13715 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13716 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13717 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13718 instructionSets, null, null, null, 0, null /*certificates*/); 13719 this.cid = cid; 13720 setMountPath(PackageHelper.getSdDir(cid)); 13721 } 13722 13723 void createCopyFile() { 13724 cid = mInstallerService.allocateExternalStageCidLegacy(); 13725 } 13726 13727 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13728 if (origin.staged && origin.cid != null) { 13729 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13730 cid = origin.cid; 13731 setMountPath(PackageHelper.getSdDir(cid)); 13732 return PackageManager.INSTALL_SUCCEEDED; 13733 } 13734 13735 if (temp) { 13736 createCopyFile(); 13737 } else { 13738 /* 13739 * Pre-emptively destroy the container since it's destroyed if 13740 * copying fails due to it existing anyway. 13741 */ 13742 PackageHelper.destroySdDir(cid); 13743 } 13744 13745 final String newMountPath = imcs.copyPackageToContainer( 13746 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13747 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13748 13749 if (newMountPath != null) { 13750 setMountPath(newMountPath); 13751 return PackageManager.INSTALL_SUCCEEDED; 13752 } else { 13753 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13754 } 13755 } 13756 13757 @Override 13758 String getCodePath() { 13759 return packagePath; 13760 } 13761 13762 @Override 13763 String getResourcePath() { 13764 return resourcePath; 13765 } 13766 13767 int doPreInstall(int status) { 13768 if (status != PackageManager.INSTALL_SUCCEEDED) { 13769 // Destroy container 13770 PackageHelper.destroySdDir(cid); 13771 } else { 13772 boolean mounted = PackageHelper.isContainerMounted(cid); 13773 if (!mounted) { 13774 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13775 Process.SYSTEM_UID); 13776 if (newMountPath != null) { 13777 setMountPath(newMountPath); 13778 } else { 13779 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13780 } 13781 } 13782 } 13783 return status; 13784 } 13785 13786 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13787 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13788 String newMountPath = null; 13789 if (PackageHelper.isContainerMounted(cid)) { 13790 // Unmount the container 13791 if (!PackageHelper.unMountSdDir(cid)) { 13792 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13793 return false; 13794 } 13795 } 13796 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13797 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13798 " which might be stale. Will try to clean up."); 13799 // Clean up the stale container and proceed to recreate. 13800 if (!PackageHelper.destroySdDir(newCacheId)) { 13801 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13802 return false; 13803 } 13804 // Successfully cleaned up stale container. Try to rename again. 13805 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13806 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13807 + " inspite of cleaning it up."); 13808 return false; 13809 } 13810 } 13811 if (!PackageHelper.isContainerMounted(newCacheId)) { 13812 Slog.w(TAG, "Mounting container " + newCacheId); 13813 newMountPath = PackageHelper.mountSdDir(newCacheId, 13814 getEncryptKey(), Process.SYSTEM_UID); 13815 } else { 13816 newMountPath = PackageHelper.getSdDir(newCacheId); 13817 } 13818 if (newMountPath == null) { 13819 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13820 return false; 13821 } 13822 Log.i(TAG, "Succesfully renamed " + cid + 13823 " to " + newCacheId + 13824 " at new path: " + newMountPath); 13825 cid = newCacheId; 13826 13827 final File beforeCodeFile = new File(packagePath); 13828 setMountPath(newMountPath); 13829 final File afterCodeFile = new File(packagePath); 13830 13831 // Reflect the rename in scanned details 13832 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13833 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13834 afterCodeFile, pkg.baseCodePath)); 13835 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13836 afterCodeFile, pkg.splitCodePaths)); 13837 13838 // Reflect the rename in app info 13839 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13840 pkg.setApplicationInfoCodePath(pkg.codePath); 13841 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13842 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13843 pkg.setApplicationInfoResourcePath(pkg.codePath); 13844 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13845 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13846 13847 return true; 13848 } 13849 13850 private void setMountPath(String mountPath) { 13851 final File mountFile = new File(mountPath); 13852 13853 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13854 if (monolithicFile.exists()) { 13855 packagePath = monolithicFile.getAbsolutePath(); 13856 if (isFwdLocked()) { 13857 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13858 } else { 13859 resourcePath = packagePath; 13860 } 13861 } else { 13862 packagePath = mountFile.getAbsolutePath(); 13863 resourcePath = packagePath; 13864 } 13865 } 13866 13867 int doPostInstall(int status, int uid) { 13868 if (status != PackageManager.INSTALL_SUCCEEDED) { 13869 cleanUp(); 13870 } else { 13871 final int groupOwner; 13872 final String protectedFile; 13873 if (isFwdLocked()) { 13874 groupOwner = UserHandle.getSharedAppGid(uid); 13875 protectedFile = RES_FILE_NAME; 13876 } else { 13877 groupOwner = -1; 13878 protectedFile = null; 13879 } 13880 13881 if (uid < Process.FIRST_APPLICATION_UID 13882 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13883 Slog.e(TAG, "Failed to finalize " + cid); 13884 PackageHelper.destroySdDir(cid); 13885 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13886 } 13887 13888 boolean mounted = PackageHelper.isContainerMounted(cid); 13889 if (!mounted) { 13890 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13891 } 13892 } 13893 return status; 13894 } 13895 13896 private void cleanUp() { 13897 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13898 13899 // Destroy secure container 13900 PackageHelper.destroySdDir(cid); 13901 } 13902 13903 private List<String> getAllCodePaths() { 13904 final File codeFile = new File(getCodePath()); 13905 if (codeFile != null && codeFile.exists()) { 13906 try { 13907 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13908 return pkg.getAllCodePaths(); 13909 } catch (PackageParserException e) { 13910 // Ignored; we tried our best 13911 } 13912 } 13913 return Collections.EMPTY_LIST; 13914 } 13915 13916 void cleanUpResourcesLI() { 13917 // Enumerate all code paths before deleting 13918 cleanUpResourcesLI(getAllCodePaths()); 13919 } 13920 13921 private void cleanUpResourcesLI(List<String> allCodePaths) { 13922 cleanUp(); 13923 removeDexFiles(allCodePaths, instructionSets); 13924 } 13925 13926 String getPackageName() { 13927 return getAsecPackageName(cid); 13928 } 13929 13930 boolean doPostDeleteLI(boolean delete) { 13931 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13932 final List<String> allCodePaths = getAllCodePaths(); 13933 boolean mounted = PackageHelper.isContainerMounted(cid); 13934 if (mounted) { 13935 // Unmount first 13936 if (PackageHelper.unMountSdDir(cid)) { 13937 mounted = false; 13938 } 13939 } 13940 if (!mounted && delete) { 13941 cleanUpResourcesLI(allCodePaths); 13942 } 13943 return !mounted; 13944 } 13945 13946 @Override 13947 int doPreCopy() { 13948 if (isFwdLocked()) { 13949 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13950 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13951 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13952 } 13953 } 13954 13955 return PackageManager.INSTALL_SUCCEEDED; 13956 } 13957 13958 @Override 13959 int doPostCopy(int uid) { 13960 if (isFwdLocked()) { 13961 if (uid < Process.FIRST_APPLICATION_UID 13962 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13963 RES_FILE_NAME)) { 13964 Slog.e(TAG, "Failed to finalize " + cid); 13965 PackageHelper.destroySdDir(cid); 13966 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13967 } 13968 } 13969 13970 return PackageManager.INSTALL_SUCCEEDED; 13971 } 13972 } 13973 13974 /** 13975 * Logic to handle movement of existing installed applications. 13976 */ 13977 class MoveInstallArgs extends InstallArgs { 13978 private File codeFile; 13979 private File resourceFile; 13980 13981 /** New install */ 13982 MoveInstallArgs(InstallParams params) { 13983 super(params.origin, params.move, params.observer, params.installFlags, 13984 params.installerPackageName, params.volumeUuid, 13985 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13986 params.grantedRuntimePermissions, 13987 params.traceMethod, params.traceCookie, params.certificates); 13988 } 13989 13990 int copyApk(IMediaContainerService imcs, boolean temp) { 13991 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13992 + move.fromUuid + " to " + move.toUuid); 13993 synchronized (mInstaller) { 13994 try { 13995 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13996 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13997 } catch (InstallerException e) { 13998 Slog.w(TAG, "Failed to move app", e); 13999 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14000 } 14001 } 14002 14003 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14004 resourceFile = codeFile; 14005 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14006 14007 return PackageManager.INSTALL_SUCCEEDED; 14008 } 14009 14010 int doPreInstall(int status) { 14011 if (status != PackageManager.INSTALL_SUCCEEDED) { 14012 cleanUp(move.toUuid); 14013 } 14014 return status; 14015 } 14016 14017 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14018 if (status != PackageManager.INSTALL_SUCCEEDED) { 14019 cleanUp(move.toUuid); 14020 return false; 14021 } 14022 14023 // Reflect the move in app info 14024 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14025 pkg.setApplicationInfoCodePath(pkg.codePath); 14026 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14027 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14028 pkg.setApplicationInfoResourcePath(pkg.codePath); 14029 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14030 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14031 14032 return true; 14033 } 14034 14035 int doPostInstall(int status, int uid) { 14036 if (status == PackageManager.INSTALL_SUCCEEDED) { 14037 cleanUp(move.fromUuid); 14038 } else { 14039 cleanUp(move.toUuid); 14040 } 14041 return status; 14042 } 14043 14044 @Override 14045 String getCodePath() { 14046 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14047 } 14048 14049 @Override 14050 String getResourcePath() { 14051 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14052 } 14053 14054 private boolean cleanUp(String volumeUuid) { 14055 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14056 move.dataAppName); 14057 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14058 final int[] userIds = sUserManager.getUserIds(); 14059 synchronized (mInstallLock) { 14060 // Clean up both app data and code 14061 // All package moves are frozen until finished 14062 for (int userId : userIds) { 14063 try { 14064 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14065 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14066 } catch (InstallerException e) { 14067 Slog.w(TAG, String.valueOf(e)); 14068 } 14069 } 14070 removeCodePathLI(codeFile); 14071 } 14072 return true; 14073 } 14074 14075 void cleanUpResourcesLI() { 14076 throw new UnsupportedOperationException(); 14077 } 14078 14079 boolean doPostDeleteLI(boolean delete) { 14080 throw new UnsupportedOperationException(); 14081 } 14082 } 14083 14084 static String getAsecPackageName(String packageCid) { 14085 int idx = packageCid.lastIndexOf("-"); 14086 if (idx == -1) { 14087 return packageCid; 14088 } 14089 return packageCid.substring(0, idx); 14090 } 14091 14092 // Utility method used to create code paths based on package name and available index. 14093 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14094 String idxStr = ""; 14095 int idx = 1; 14096 // Fall back to default value of idx=1 if prefix is not 14097 // part of oldCodePath 14098 if (oldCodePath != null) { 14099 String subStr = oldCodePath; 14100 // Drop the suffix right away 14101 if (suffix != null && subStr.endsWith(suffix)) { 14102 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14103 } 14104 // If oldCodePath already contains prefix find out the 14105 // ending index to either increment or decrement. 14106 int sidx = subStr.lastIndexOf(prefix); 14107 if (sidx != -1) { 14108 subStr = subStr.substring(sidx + prefix.length()); 14109 if (subStr != null) { 14110 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14111 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14112 } 14113 try { 14114 idx = Integer.parseInt(subStr); 14115 if (idx <= 1) { 14116 idx++; 14117 } else { 14118 idx--; 14119 } 14120 } catch(NumberFormatException e) { 14121 } 14122 } 14123 } 14124 } 14125 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14126 return prefix + idxStr; 14127 } 14128 14129 private File getNextCodePath(File targetDir, String packageName) { 14130 int suffix = 1; 14131 File result; 14132 do { 14133 result = new File(targetDir, packageName + "-" + suffix); 14134 suffix++; 14135 } while (result.exists()); 14136 return result; 14137 } 14138 14139 // Utility method that returns the relative package path with respect 14140 // to the installation directory. Like say for /data/data/com.test-1.apk 14141 // string com.test-1 is returned. 14142 static String deriveCodePathName(String codePath) { 14143 if (codePath == null) { 14144 return null; 14145 } 14146 final File codeFile = new File(codePath); 14147 final String name = codeFile.getName(); 14148 if (codeFile.isDirectory()) { 14149 return name; 14150 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14151 final int lastDot = name.lastIndexOf('.'); 14152 return name.substring(0, lastDot); 14153 } else { 14154 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14155 return null; 14156 } 14157 } 14158 14159 static class PackageInstalledInfo { 14160 String name; 14161 int uid; 14162 // The set of users that originally had this package installed. 14163 int[] origUsers; 14164 // The set of users that now have this package installed. 14165 int[] newUsers; 14166 PackageParser.Package pkg; 14167 int returnCode; 14168 String returnMsg; 14169 PackageRemovedInfo removedInfo; 14170 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14171 14172 public void setError(int code, String msg) { 14173 setReturnCode(code); 14174 setReturnMessage(msg); 14175 Slog.w(TAG, msg); 14176 } 14177 14178 public void setError(String msg, PackageParserException e) { 14179 setReturnCode(e.error); 14180 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14181 Slog.w(TAG, msg, e); 14182 } 14183 14184 public void setError(String msg, PackageManagerException e) { 14185 returnCode = e.error; 14186 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14187 Slog.w(TAG, msg, e); 14188 } 14189 14190 public void setReturnCode(int returnCode) { 14191 this.returnCode = returnCode; 14192 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14193 for (int i = 0; i < childCount; i++) { 14194 addedChildPackages.valueAt(i).returnCode = returnCode; 14195 } 14196 } 14197 14198 private void setReturnMessage(String returnMsg) { 14199 this.returnMsg = returnMsg; 14200 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14201 for (int i = 0; i < childCount; i++) { 14202 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14203 } 14204 } 14205 14206 // In some error cases we want to convey more info back to the observer 14207 String origPackage; 14208 String origPermission; 14209 } 14210 14211 /* 14212 * Install a non-existing package. 14213 */ 14214 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14215 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14216 PackageInstalledInfo res) { 14217 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14218 14219 // Remember this for later, in case we need to rollback this install 14220 String pkgName = pkg.packageName; 14221 14222 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14223 14224 synchronized(mPackages) { 14225 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14226 // A package with the same name is already installed, though 14227 // it has been renamed to an older name. The package we 14228 // are trying to install should be installed as an update to 14229 // the existing one, but that has not been requested, so bail. 14230 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14231 + " without first uninstalling package running as " 14232 + mSettings.mRenamedPackages.get(pkgName)); 14233 return; 14234 } 14235 if (mPackages.containsKey(pkgName)) { 14236 // Don't allow installation over an existing package with the same name. 14237 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14238 + " without first uninstalling."); 14239 return; 14240 } 14241 } 14242 14243 try { 14244 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14245 System.currentTimeMillis(), user); 14246 14247 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14248 14249 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14250 prepareAppDataAfterInstallLIF(newPackage); 14251 14252 } else { 14253 // Remove package from internal structures, but keep around any 14254 // data that might have already existed 14255 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14256 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14257 } 14258 } catch (PackageManagerException e) { 14259 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14260 } 14261 14262 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14263 } 14264 14265 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14266 // Can't rotate keys during boot or if sharedUser. 14267 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14268 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14269 return false; 14270 } 14271 // app is using upgradeKeySets; make sure all are valid 14272 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14273 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14274 for (int i = 0; i < upgradeKeySets.length; i++) { 14275 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14276 Slog.wtf(TAG, "Package " 14277 + (oldPs.name != null ? oldPs.name : "<null>") 14278 + " contains upgrade-key-set reference to unknown key-set: " 14279 + upgradeKeySets[i] 14280 + " reverting to signatures check."); 14281 return false; 14282 } 14283 } 14284 return true; 14285 } 14286 14287 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14288 // Upgrade keysets are being used. Determine if new package has a superset of the 14289 // required keys. 14290 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14291 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14292 for (int i = 0; i < upgradeKeySets.length; i++) { 14293 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14294 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14295 return true; 14296 } 14297 } 14298 return false; 14299 } 14300 14301 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14302 try (DigestInputStream digestStream = 14303 new DigestInputStream(new FileInputStream(file), digest)) { 14304 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14305 } 14306 } 14307 14308 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14309 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14310 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14311 14312 final PackageParser.Package oldPackage; 14313 final String pkgName = pkg.packageName; 14314 final int[] allUsers; 14315 final int[] installedUsers; 14316 14317 synchronized(mPackages) { 14318 oldPackage = mPackages.get(pkgName); 14319 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14320 14321 // don't allow upgrade to target a release SDK from a pre-release SDK 14322 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14323 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14324 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14325 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14326 if (oldTargetsPreRelease 14327 && !newTargetsPreRelease 14328 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14329 Slog.w(TAG, "Can't install package targeting released sdk"); 14330 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14331 return; 14332 } 14333 14334 // don't allow an upgrade from full to ephemeral 14335 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14336 if (isEphemeral && !oldIsEphemeral) { 14337 // can't downgrade from full to ephemeral 14338 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14339 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14340 return; 14341 } 14342 14343 // verify signatures are valid 14344 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14345 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14346 if (!checkUpgradeKeySetLP(ps, pkg)) { 14347 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14348 "New package not signed by keys specified by upgrade-keysets: " 14349 + pkgName); 14350 return; 14351 } 14352 } else { 14353 // default to original signature matching 14354 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14355 != PackageManager.SIGNATURE_MATCH) { 14356 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14357 "New package has a different signature: " + pkgName); 14358 return; 14359 } 14360 } 14361 14362 // don't allow a system upgrade unless the upgrade hash matches 14363 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14364 byte[] digestBytes = null; 14365 try { 14366 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14367 updateDigest(digest, new File(pkg.baseCodePath)); 14368 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14369 for (String path : pkg.splitCodePaths) { 14370 updateDigest(digest, new File(path)); 14371 } 14372 } 14373 digestBytes = digest.digest(); 14374 } catch (NoSuchAlgorithmException | IOException e) { 14375 res.setError(INSTALL_FAILED_INVALID_APK, 14376 "Could not compute hash: " + pkgName); 14377 return; 14378 } 14379 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14380 res.setError(INSTALL_FAILED_INVALID_APK, 14381 "New package fails restrict-update check: " + pkgName); 14382 return; 14383 } 14384 // retain upgrade restriction 14385 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14386 } 14387 14388 // Check for shared user id changes 14389 String invalidPackageName = 14390 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14391 if (invalidPackageName != null) { 14392 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14393 "Package " + invalidPackageName + " tried to change user " 14394 + oldPackage.mSharedUserId); 14395 return; 14396 } 14397 14398 // In case of rollback, remember per-user/profile install state 14399 allUsers = sUserManager.getUserIds(); 14400 installedUsers = ps.queryInstalledUsers(allUsers, true); 14401 } 14402 14403 // Update what is removed 14404 res.removedInfo = new PackageRemovedInfo(); 14405 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14406 res.removedInfo.removedPackage = oldPackage.packageName; 14407 res.removedInfo.isUpdate = true; 14408 res.removedInfo.origUsers = installedUsers; 14409 final int childCount = (oldPackage.childPackages != null) 14410 ? oldPackage.childPackages.size() : 0; 14411 for (int i = 0; i < childCount; i++) { 14412 boolean childPackageUpdated = false; 14413 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14414 if (res.addedChildPackages != null) { 14415 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14416 if (childRes != null) { 14417 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14418 childRes.removedInfo.removedPackage = childPkg.packageName; 14419 childRes.removedInfo.isUpdate = true; 14420 childPackageUpdated = true; 14421 } 14422 } 14423 if (!childPackageUpdated) { 14424 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14425 childRemovedRes.removedPackage = childPkg.packageName; 14426 childRemovedRes.isUpdate = false; 14427 childRemovedRes.dataRemoved = true; 14428 synchronized (mPackages) { 14429 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14430 if (childPs != null) { 14431 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14432 } 14433 } 14434 if (res.removedInfo.removedChildPackages == null) { 14435 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14436 } 14437 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14438 } 14439 } 14440 14441 boolean sysPkg = (isSystemApp(oldPackage)); 14442 if (sysPkg) { 14443 // Set the system/privileged flags as needed 14444 final boolean privileged = 14445 (oldPackage.applicationInfo.privateFlags 14446 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14447 final int systemPolicyFlags = policyFlags 14448 | PackageParser.PARSE_IS_SYSTEM 14449 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14450 14451 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14452 user, allUsers, installerPackageName, res); 14453 } else { 14454 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14455 user, allUsers, installerPackageName, res); 14456 } 14457 } 14458 14459 public List<String> getPreviousCodePaths(String packageName) { 14460 final PackageSetting ps = mSettings.mPackages.get(packageName); 14461 final List<String> result = new ArrayList<String>(); 14462 if (ps != null && ps.oldCodePaths != null) { 14463 result.addAll(ps.oldCodePaths); 14464 } 14465 return result; 14466 } 14467 14468 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14469 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14470 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14471 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14472 + deletedPackage); 14473 14474 String pkgName = deletedPackage.packageName; 14475 boolean deletedPkg = true; 14476 boolean addedPkg = false; 14477 boolean updatedSettings = false; 14478 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14479 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14480 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14481 14482 final long origUpdateTime = (pkg.mExtras != null) 14483 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14484 14485 // First delete the existing package while retaining the data directory 14486 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14487 res.removedInfo, true, pkg)) { 14488 // If the existing package wasn't successfully deleted 14489 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14490 deletedPkg = false; 14491 } else { 14492 // Successfully deleted the old package; proceed with replace. 14493 14494 // If deleted package lived in a container, give users a chance to 14495 // relinquish resources before killing. 14496 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14497 if (DEBUG_INSTALL) { 14498 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14499 } 14500 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14501 final ArrayList<String> pkgList = new ArrayList<String>(1); 14502 pkgList.add(deletedPackage.applicationInfo.packageName); 14503 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14504 } 14505 14506 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14507 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14508 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14509 14510 try { 14511 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14512 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14513 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14514 14515 // Update the in-memory copy of the previous code paths. 14516 PackageSetting ps = mSettings.mPackages.get(pkgName); 14517 if (!killApp) { 14518 if (ps.oldCodePaths == null) { 14519 ps.oldCodePaths = new ArraySet<>(); 14520 } 14521 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14522 if (deletedPackage.splitCodePaths != null) { 14523 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14524 } 14525 } else { 14526 ps.oldCodePaths = null; 14527 } 14528 if (ps.childPackageNames != null) { 14529 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14530 final String childPkgName = ps.childPackageNames.get(i); 14531 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14532 childPs.oldCodePaths = ps.oldCodePaths; 14533 } 14534 } 14535 prepareAppDataAfterInstallLIF(newPackage); 14536 addedPkg = true; 14537 } catch (PackageManagerException e) { 14538 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14539 } 14540 } 14541 14542 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14543 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14544 14545 // Revert all internal state mutations and added folders for the failed install 14546 if (addedPkg) { 14547 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14548 res.removedInfo, true, null); 14549 } 14550 14551 // Restore the old package 14552 if (deletedPkg) { 14553 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14554 File restoreFile = new File(deletedPackage.codePath); 14555 // Parse old package 14556 boolean oldExternal = isExternal(deletedPackage); 14557 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14558 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14559 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14560 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14561 try { 14562 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14563 null); 14564 } catch (PackageManagerException e) { 14565 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14566 + e.getMessage()); 14567 return; 14568 } 14569 14570 synchronized (mPackages) { 14571 // Ensure the installer package name up to date 14572 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14573 14574 // Update permissions for restored package 14575 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14576 14577 mSettings.writeLPr(); 14578 } 14579 14580 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14581 } 14582 } else { 14583 synchronized (mPackages) { 14584 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14585 if (ps != null) { 14586 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14587 if (res.removedInfo.removedChildPackages != null) { 14588 final int childCount = res.removedInfo.removedChildPackages.size(); 14589 // Iterate in reverse as we may modify the collection 14590 for (int i = childCount - 1; i >= 0; i--) { 14591 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14592 if (res.addedChildPackages.containsKey(childPackageName)) { 14593 res.removedInfo.removedChildPackages.removeAt(i); 14594 } else { 14595 PackageRemovedInfo childInfo = res.removedInfo 14596 .removedChildPackages.valueAt(i); 14597 childInfo.removedForAllUsers = mPackages.get( 14598 childInfo.removedPackage) == null; 14599 } 14600 } 14601 } 14602 } 14603 } 14604 } 14605 } 14606 14607 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14608 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14609 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14610 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14611 + ", old=" + deletedPackage); 14612 14613 final boolean disabledSystem; 14614 14615 // Remove existing system package 14616 removePackageLI(deletedPackage, true); 14617 14618 synchronized (mPackages) { 14619 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14620 } 14621 if (!disabledSystem) { 14622 // We didn't need to disable the .apk as a current system package, 14623 // which means we are replacing another update that is already 14624 // installed. We need to make sure to delete the older one's .apk. 14625 res.removedInfo.args = createInstallArgsForExisting(0, 14626 deletedPackage.applicationInfo.getCodePath(), 14627 deletedPackage.applicationInfo.getResourcePath(), 14628 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14629 } else { 14630 res.removedInfo.args = null; 14631 } 14632 14633 // Successfully disabled the old package. Now proceed with re-installation 14634 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14635 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14636 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14637 14638 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14639 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14640 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14641 14642 PackageParser.Package newPackage = null; 14643 try { 14644 // Add the package to the internal data structures 14645 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14646 14647 // Set the update and install times 14648 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14649 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14650 System.currentTimeMillis()); 14651 14652 // Update the package dynamic state if succeeded 14653 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14654 // Now that the install succeeded make sure we remove data 14655 // directories for any child package the update removed. 14656 final int deletedChildCount = (deletedPackage.childPackages != null) 14657 ? deletedPackage.childPackages.size() : 0; 14658 final int newChildCount = (newPackage.childPackages != null) 14659 ? newPackage.childPackages.size() : 0; 14660 for (int i = 0; i < deletedChildCount; i++) { 14661 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14662 boolean childPackageDeleted = true; 14663 for (int j = 0; j < newChildCount; j++) { 14664 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14665 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14666 childPackageDeleted = false; 14667 break; 14668 } 14669 } 14670 if (childPackageDeleted) { 14671 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14672 deletedChildPkg.packageName); 14673 if (ps != null && res.removedInfo.removedChildPackages != null) { 14674 PackageRemovedInfo removedChildRes = res.removedInfo 14675 .removedChildPackages.get(deletedChildPkg.packageName); 14676 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14677 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14678 } 14679 } 14680 } 14681 14682 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14683 prepareAppDataAfterInstallLIF(newPackage); 14684 } 14685 } catch (PackageManagerException e) { 14686 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14687 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14688 } 14689 14690 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14691 // Re installation failed. Restore old information 14692 // Remove new pkg information 14693 if (newPackage != null) { 14694 removeInstalledPackageLI(newPackage, true); 14695 } 14696 // Add back the old system package 14697 try { 14698 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14699 } catch (PackageManagerException e) { 14700 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14701 } 14702 14703 synchronized (mPackages) { 14704 if (disabledSystem) { 14705 enableSystemPackageLPw(deletedPackage); 14706 } 14707 14708 // Ensure the installer package name up to date 14709 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14710 14711 // Update permissions for restored package 14712 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14713 14714 mSettings.writeLPr(); 14715 } 14716 14717 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14718 + " after failed upgrade"); 14719 } 14720 } 14721 14722 /** 14723 * Checks whether the parent or any of the child packages have a change shared 14724 * user. For a package to be a valid update the shred users of the parent and 14725 * the children should match. We may later support changing child shared users. 14726 * @param oldPkg The updated package. 14727 * @param newPkg The update package. 14728 * @return The shared user that change between the versions. 14729 */ 14730 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14731 PackageParser.Package newPkg) { 14732 // Check parent shared user 14733 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14734 return newPkg.packageName; 14735 } 14736 // Check child shared users 14737 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14738 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14739 for (int i = 0; i < newChildCount; i++) { 14740 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14741 // If this child was present, did it have the same shared user? 14742 for (int j = 0; j < oldChildCount; j++) { 14743 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14744 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14745 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14746 return newChildPkg.packageName; 14747 } 14748 } 14749 } 14750 return null; 14751 } 14752 14753 private void removeNativeBinariesLI(PackageSetting ps) { 14754 // Remove the lib path for the parent package 14755 if (ps != null) { 14756 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14757 // Remove the lib path for the child packages 14758 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14759 for (int i = 0; i < childCount; i++) { 14760 PackageSetting childPs = null; 14761 synchronized (mPackages) { 14762 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14763 } 14764 if (childPs != null) { 14765 NativeLibraryHelper.removeNativeBinariesLI(childPs 14766 .legacyNativeLibraryPathString); 14767 } 14768 } 14769 } 14770 } 14771 14772 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14773 // Enable the parent package 14774 mSettings.enableSystemPackageLPw(pkg.packageName); 14775 // Enable the child packages 14776 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14777 for (int i = 0; i < childCount; i++) { 14778 PackageParser.Package childPkg = pkg.childPackages.get(i); 14779 mSettings.enableSystemPackageLPw(childPkg.packageName); 14780 } 14781 } 14782 14783 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14784 PackageParser.Package newPkg) { 14785 // Disable the parent package (parent always replaced) 14786 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14787 // Disable the child packages 14788 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14789 for (int i = 0; i < childCount; i++) { 14790 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14791 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14792 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14793 } 14794 return disabled; 14795 } 14796 14797 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14798 String installerPackageName) { 14799 // Enable the parent package 14800 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14801 // Enable the child packages 14802 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14803 for (int i = 0; i < childCount; i++) { 14804 PackageParser.Package childPkg = pkg.childPackages.get(i); 14805 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14806 } 14807 } 14808 14809 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14810 // Collect all used permissions in the UID 14811 ArraySet<String> usedPermissions = new ArraySet<>(); 14812 final int packageCount = su.packages.size(); 14813 for (int i = 0; i < packageCount; i++) { 14814 PackageSetting ps = su.packages.valueAt(i); 14815 if (ps.pkg == null) { 14816 continue; 14817 } 14818 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14819 for (int j = 0; j < requestedPermCount; j++) { 14820 String permission = ps.pkg.requestedPermissions.get(j); 14821 BasePermission bp = mSettings.mPermissions.get(permission); 14822 if (bp != null) { 14823 usedPermissions.add(permission); 14824 } 14825 } 14826 } 14827 14828 PermissionsState permissionsState = su.getPermissionsState(); 14829 // Prune install permissions 14830 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14831 final int installPermCount = installPermStates.size(); 14832 for (int i = installPermCount - 1; i >= 0; i--) { 14833 PermissionState permissionState = installPermStates.get(i); 14834 if (!usedPermissions.contains(permissionState.getName())) { 14835 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14836 if (bp != null) { 14837 permissionsState.revokeInstallPermission(bp); 14838 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14839 PackageManager.MASK_PERMISSION_FLAGS, 0); 14840 } 14841 } 14842 } 14843 14844 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14845 14846 // Prune runtime permissions 14847 for (int userId : allUserIds) { 14848 List<PermissionState> runtimePermStates = permissionsState 14849 .getRuntimePermissionStates(userId); 14850 final int runtimePermCount = runtimePermStates.size(); 14851 for (int i = runtimePermCount - 1; i >= 0; i--) { 14852 PermissionState permissionState = runtimePermStates.get(i); 14853 if (!usedPermissions.contains(permissionState.getName())) { 14854 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14855 if (bp != null) { 14856 permissionsState.revokeRuntimePermission(bp, userId); 14857 permissionsState.updatePermissionFlags(bp, userId, 14858 PackageManager.MASK_PERMISSION_FLAGS, 0); 14859 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14860 runtimePermissionChangedUserIds, userId); 14861 } 14862 } 14863 } 14864 } 14865 14866 return runtimePermissionChangedUserIds; 14867 } 14868 14869 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14870 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14871 // Update the parent package setting 14872 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14873 res, user); 14874 // Update the child packages setting 14875 final int childCount = (newPackage.childPackages != null) 14876 ? newPackage.childPackages.size() : 0; 14877 for (int i = 0; i < childCount; i++) { 14878 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14879 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14880 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14881 childRes.origUsers, childRes, user); 14882 } 14883 } 14884 14885 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14886 String installerPackageName, int[] allUsers, int[] installedForUsers, 14887 PackageInstalledInfo res, UserHandle user) { 14888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14889 14890 String pkgName = newPackage.packageName; 14891 synchronized (mPackages) { 14892 //write settings. the installStatus will be incomplete at this stage. 14893 //note that the new package setting would have already been 14894 //added to mPackages. It hasn't been persisted yet. 14895 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14896 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14897 mSettings.writeLPr(); 14898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14899 } 14900 14901 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14902 synchronized (mPackages) { 14903 updatePermissionsLPw(newPackage.packageName, newPackage, 14904 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14905 ? UPDATE_PERMISSIONS_ALL : 0)); 14906 // For system-bundled packages, we assume that installing an upgraded version 14907 // of the package implies that the user actually wants to run that new code, 14908 // so we enable the package. 14909 PackageSetting ps = mSettings.mPackages.get(pkgName); 14910 final int userId = user.getIdentifier(); 14911 if (ps != null) { 14912 if (isSystemApp(newPackage)) { 14913 if (DEBUG_INSTALL) { 14914 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14915 } 14916 // Enable system package for requested users 14917 if (res.origUsers != null) { 14918 for (int origUserId : res.origUsers) { 14919 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14920 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14921 origUserId, installerPackageName); 14922 } 14923 } 14924 } 14925 // Also convey the prior install/uninstall state 14926 if (allUsers != null && installedForUsers != null) { 14927 for (int currentUserId : allUsers) { 14928 final boolean installed = ArrayUtils.contains( 14929 installedForUsers, currentUserId); 14930 if (DEBUG_INSTALL) { 14931 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14932 } 14933 ps.setInstalled(installed, currentUserId); 14934 } 14935 // these install state changes will be persisted in the 14936 // upcoming call to mSettings.writeLPr(). 14937 } 14938 } 14939 // It's implied that when a user requests installation, they want the app to be 14940 // installed and enabled. 14941 if (userId != UserHandle.USER_ALL) { 14942 ps.setInstalled(true, userId); 14943 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14944 } 14945 } 14946 res.name = pkgName; 14947 res.uid = newPackage.applicationInfo.uid; 14948 res.pkg = newPackage; 14949 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14950 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14951 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14952 //to update install status 14953 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14954 mSettings.writeLPr(); 14955 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14956 } 14957 14958 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14959 } 14960 14961 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14962 try { 14963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14964 installPackageLI(args, res); 14965 } finally { 14966 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14967 } 14968 } 14969 14970 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14971 final int installFlags = args.installFlags; 14972 final String installerPackageName = args.installerPackageName; 14973 final String volumeUuid = args.volumeUuid; 14974 final File tmpPackageFile = new File(args.getCodePath()); 14975 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14976 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14977 || (args.volumeUuid != null)); 14978 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14979 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14980 boolean replace = false; 14981 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14982 if (args.move != null) { 14983 // moving a complete application; perform an initial scan on the new install location 14984 scanFlags |= SCAN_INITIAL; 14985 } 14986 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14987 scanFlags |= SCAN_DONT_KILL_APP; 14988 } 14989 14990 // Result object to be returned 14991 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14992 14993 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14994 14995 // Sanity check 14996 if (ephemeral && (forwardLocked || onExternal)) { 14997 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14998 + " external=" + onExternal); 14999 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15000 return; 15001 } 15002 15003 // Retrieve PackageSettings and parse package 15004 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15005 | PackageParser.PARSE_ENFORCE_CODE 15006 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15007 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15008 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15009 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15010 PackageParser pp = new PackageParser(); 15011 pp.setSeparateProcesses(mSeparateProcesses); 15012 pp.setDisplayMetrics(mMetrics); 15013 15014 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15015 final PackageParser.Package pkg; 15016 try { 15017 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15018 } catch (PackageParserException e) { 15019 res.setError("Failed parse during installPackageLI", e); 15020 return; 15021 } finally { 15022 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15023 } 15024 15025 // If we are installing a clustered package add results for the children 15026 if (pkg.childPackages != null) { 15027 synchronized (mPackages) { 15028 final int childCount = pkg.childPackages.size(); 15029 for (int i = 0; i < childCount; i++) { 15030 PackageParser.Package childPkg = pkg.childPackages.get(i); 15031 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15032 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15033 childRes.pkg = childPkg; 15034 childRes.name = childPkg.packageName; 15035 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15036 if (childPs != null) { 15037 childRes.origUsers = childPs.queryInstalledUsers( 15038 sUserManager.getUserIds(), true); 15039 } 15040 if ((mPackages.containsKey(childPkg.packageName))) { 15041 childRes.removedInfo = new PackageRemovedInfo(); 15042 childRes.removedInfo.removedPackage = childPkg.packageName; 15043 } 15044 if (res.addedChildPackages == null) { 15045 res.addedChildPackages = new ArrayMap<>(); 15046 } 15047 res.addedChildPackages.put(childPkg.packageName, childRes); 15048 } 15049 } 15050 } 15051 15052 // If package doesn't declare API override, mark that we have an install 15053 // time CPU ABI override. 15054 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15055 pkg.cpuAbiOverride = args.abiOverride; 15056 } 15057 15058 String pkgName = res.name = pkg.packageName; 15059 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15060 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15061 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15062 return; 15063 } 15064 } 15065 15066 try { 15067 // either use what we've been given or parse directly from the APK 15068 if (args.certificates != null) { 15069 try { 15070 PackageParser.populateCertificates(pkg, args.certificates); 15071 } catch (PackageParserException e) { 15072 // there was something wrong with the certificates we were given; 15073 // try to pull them from the APK 15074 PackageParser.collectCertificates(pkg, parseFlags); 15075 } 15076 } else { 15077 PackageParser.collectCertificates(pkg, parseFlags); 15078 } 15079 } catch (PackageParserException e) { 15080 res.setError("Failed collect during installPackageLI", e); 15081 return; 15082 } 15083 15084 // Get rid of all references to package scan path via parser. 15085 pp = null; 15086 String oldCodePath = null; 15087 boolean systemApp = false; 15088 synchronized (mPackages) { 15089 // Check if installing already existing package 15090 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15091 String oldName = mSettings.mRenamedPackages.get(pkgName); 15092 if (pkg.mOriginalPackages != null 15093 && pkg.mOriginalPackages.contains(oldName) 15094 && mPackages.containsKey(oldName)) { 15095 // This package is derived from an original package, 15096 // and this device has been updating from that original 15097 // name. We must continue using the original name, so 15098 // rename the new package here. 15099 pkg.setPackageName(oldName); 15100 pkgName = pkg.packageName; 15101 replace = true; 15102 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15103 + oldName + " pkgName=" + pkgName); 15104 } else if (mPackages.containsKey(pkgName)) { 15105 // This package, under its official name, already exists 15106 // on the device; we should replace it. 15107 replace = true; 15108 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15109 } 15110 15111 // Child packages are installed through the parent package 15112 if (pkg.parentPackage != null) { 15113 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15114 "Package " + pkg.packageName + " is child of package " 15115 + pkg.parentPackage.parentPackage + ". Child packages " 15116 + "can be updated only through the parent package."); 15117 return; 15118 } 15119 15120 if (replace) { 15121 // Prevent apps opting out from runtime permissions 15122 PackageParser.Package oldPackage = mPackages.get(pkgName); 15123 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15124 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15125 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15126 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15127 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15128 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15129 + " doesn't support runtime permissions but the old" 15130 + " target SDK " + oldTargetSdk + " does."); 15131 return; 15132 } 15133 15134 // Prevent installing of child packages 15135 if (oldPackage.parentPackage != null) { 15136 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15137 "Package " + pkg.packageName + " is child of package " 15138 + oldPackage.parentPackage + ". Child packages " 15139 + "can be updated only through the parent package."); 15140 return; 15141 } 15142 } 15143 } 15144 15145 PackageSetting ps = mSettings.mPackages.get(pkgName); 15146 if (ps != null) { 15147 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15148 15149 // Quick sanity check that we're signed correctly if updating; 15150 // we'll check this again later when scanning, but we want to 15151 // bail early here before tripping over redefined permissions. 15152 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15153 if (!checkUpgradeKeySetLP(ps, pkg)) { 15154 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15155 + pkg.packageName + " upgrade keys do not match the " 15156 + "previously installed version"); 15157 return; 15158 } 15159 } else { 15160 try { 15161 verifySignaturesLP(ps, pkg); 15162 } catch (PackageManagerException e) { 15163 res.setError(e.error, e.getMessage()); 15164 return; 15165 } 15166 } 15167 15168 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15169 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15170 systemApp = (ps.pkg.applicationInfo.flags & 15171 ApplicationInfo.FLAG_SYSTEM) != 0; 15172 } 15173 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15174 } 15175 15176 // Check whether the newly-scanned package wants to define an already-defined perm 15177 int N = pkg.permissions.size(); 15178 for (int i = N-1; i >= 0; i--) { 15179 PackageParser.Permission perm = pkg.permissions.get(i); 15180 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15181 if (bp != null) { 15182 // If the defining package is signed with our cert, it's okay. This 15183 // also includes the "updating the same package" case, of course. 15184 // "updating same package" could also involve key-rotation. 15185 final boolean sigsOk; 15186 if (bp.sourcePackage.equals(pkg.packageName) 15187 && (bp.packageSetting instanceof PackageSetting) 15188 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15189 scanFlags))) { 15190 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15191 } else { 15192 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15193 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15194 } 15195 if (!sigsOk) { 15196 // If the owning package is the system itself, we log but allow 15197 // install to proceed; we fail the install on all other permission 15198 // redefinitions. 15199 if (!bp.sourcePackage.equals("android")) { 15200 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15201 + pkg.packageName + " attempting to redeclare permission " 15202 + perm.info.name + " already owned by " + bp.sourcePackage); 15203 res.origPermission = perm.info.name; 15204 res.origPackage = bp.sourcePackage; 15205 return; 15206 } else { 15207 Slog.w(TAG, "Package " + pkg.packageName 15208 + " attempting to redeclare system permission " 15209 + perm.info.name + "; ignoring new declaration"); 15210 pkg.permissions.remove(i); 15211 } 15212 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 15213 // Prevent apps to change protection level to dangerous from any other 15214 // type as this would allow a privilege escalation where an app adds a 15215 // normal/signature permission in other app's group and later redefines 15216 // it as dangerous leading to the group auto-grant. 15217 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 15218 == PermissionInfo.PROTECTION_DANGEROUS) { 15219 if (bp != null && !bp.isRuntime()) { 15220 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 15221 + "non-runtime permission " + perm.info.name 15222 + " to runtime; keeping old protection level"); 15223 perm.info.protectionLevel = bp.protectionLevel; 15224 } 15225 } 15226 } 15227 } 15228 } 15229 } 15230 15231 if (systemApp) { 15232 if (onExternal) { 15233 // Abort update; system app can't be replaced with app on sdcard 15234 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15235 "Cannot install updates to system apps on sdcard"); 15236 return; 15237 } else if (ephemeral) { 15238 // Abort update; system app can't be replaced with an ephemeral app 15239 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15240 "Cannot update a system app with an ephemeral app"); 15241 return; 15242 } 15243 } 15244 15245 if (args.move != null) { 15246 // We did an in-place move, so dex is ready to roll 15247 scanFlags |= SCAN_NO_DEX; 15248 scanFlags |= SCAN_MOVE; 15249 15250 synchronized (mPackages) { 15251 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15252 if (ps == null) { 15253 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15254 "Missing settings for moved package " + pkgName); 15255 } 15256 15257 // We moved the entire application as-is, so bring over the 15258 // previously derived ABI information. 15259 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15260 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15261 } 15262 15263 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15264 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15265 scanFlags |= SCAN_NO_DEX; 15266 15267 try { 15268 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15269 args.abiOverride : pkg.cpuAbiOverride); 15270 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15271 true /* extract libs */); 15272 } catch (PackageManagerException pme) { 15273 Slog.e(TAG, "Error deriving application ABI", pme); 15274 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15275 return; 15276 } 15277 15278 // Shared libraries for the package need to be updated. 15279 synchronized (mPackages) { 15280 try { 15281 updateSharedLibrariesLPw(pkg, null); 15282 } catch (PackageManagerException e) { 15283 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15284 } 15285 } 15286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15287 // Do not run PackageDexOptimizer through the local performDexOpt 15288 // method because `pkg` may not be in `mPackages` yet. 15289 // 15290 // Also, don't fail application installs if the dexopt step fails. 15291 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15292 null /* instructionSets */, false /* checkProfiles */, 15293 getCompilerFilterForReason(REASON_INSTALL), 15294 getOrCreateCompilerPackageStats(pkg)); 15295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15296 15297 // Notify BackgroundDexOptService that the package has been changed. 15298 // If this is an update of a package which used to fail to compile, 15299 // BDOS will remove it from its blacklist. 15300 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15301 } 15302 15303 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15304 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15305 return; 15306 } 15307 15308 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15309 15310 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15311 "installPackageLI")) { 15312 if (replace) { 15313 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15314 installerPackageName, res); 15315 } else { 15316 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15317 args.user, installerPackageName, volumeUuid, res); 15318 } 15319 } 15320 synchronized (mPackages) { 15321 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15322 if (ps != null) { 15323 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15324 } 15325 15326 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15327 for (int i = 0; i < childCount; i++) { 15328 PackageParser.Package childPkg = pkg.childPackages.get(i); 15329 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15330 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15331 if (childPs != null) { 15332 childRes.newUsers = childPs.queryInstalledUsers( 15333 sUserManager.getUserIds(), true); 15334 } 15335 } 15336 } 15337 } 15338 15339 private void startIntentFilterVerifications(int userId, boolean replacing, 15340 PackageParser.Package pkg) { 15341 if (mIntentFilterVerifierComponent == null) { 15342 Slog.w(TAG, "No IntentFilter verification will not be done as " 15343 + "there is no IntentFilterVerifier available!"); 15344 return; 15345 } 15346 15347 final int verifierUid = getPackageUid( 15348 mIntentFilterVerifierComponent.getPackageName(), 15349 MATCH_DEBUG_TRIAGED_MISSING, 15350 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15351 15352 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15353 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15354 mHandler.sendMessage(msg); 15355 15356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15357 for (int i = 0; i < childCount; i++) { 15358 PackageParser.Package childPkg = pkg.childPackages.get(i); 15359 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15360 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15361 mHandler.sendMessage(msg); 15362 } 15363 } 15364 15365 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15366 PackageParser.Package pkg) { 15367 int size = pkg.activities.size(); 15368 if (size == 0) { 15369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15370 "No activity, so no need to verify any IntentFilter!"); 15371 return; 15372 } 15373 15374 final boolean hasDomainURLs = hasDomainURLs(pkg); 15375 if (!hasDomainURLs) { 15376 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15377 "No domain URLs, so no need to verify any IntentFilter!"); 15378 return; 15379 } 15380 15381 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15382 + " if any IntentFilter from the " + size 15383 + " Activities needs verification ..."); 15384 15385 int count = 0; 15386 final String packageName = pkg.packageName; 15387 15388 synchronized (mPackages) { 15389 // If this is a new install and we see that we've already run verification for this 15390 // package, we have nothing to do: it means the state was restored from backup. 15391 if (!replacing) { 15392 IntentFilterVerificationInfo ivi = 15393 mSettings.getIntentFilterVerificationLPr(packageName); 15394 if (ivi != null) { 15395 if (DEBUG_DOMAIN_VERIFICATION) { 15396 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15397 + ivi.getStatusString()); 15398 } 15399 return; 15400 } 15401 } 15402 15403 // If any filters need to be verified, then all need to be. 15404 boolean needToVerify = false; 15405 for (PackageParser.Activity a : pkg.activities) { 15406 for (ActivityIntentInfo filter : a.intents) { 15407 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15408 if (DEBUG_DOMAIN_VERIFICATION) { 15409 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15410 } 15411 needToVerify = true; 15412 break; 15413 } 15414 } 15415 } 15416 15417 if (needToVerify) { 15418 final int verificationId = mIntentFilterVerificationToken++; 15419 for (PackageParser.Activity a : pkg.activities) { 15420 for (ActivityIntentInfo filter : a.intents) { 15421 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15422 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15423 "Verification needed for IntentFilter:" + filter.toString()); 15424 mIntentFilterVerifier.addOneIntentFilterVerification( 15425 verifierUid, userId, verificationId, filter, packageName); 15426 count++; 15427 } 15428 } 15429 } 15430 } 15431 } 15432 15433 if (count > 0) { 15434 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15435 + " IntentFilter verification" + (count > 1 ? "s" : "") 15436 + " for userId:" + userId); 15437 mIntentFilterVerifier.startVerifications(userId); 15438 } else { 15439 if (DEBUG_DOMAIN_VERIFICATION) { 15440 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15441 } 15442 } 15443 } 15444 15445 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15446 final ComponentName cn = filter.activity.getComponentName(); 15447 final String packageName = cn.getPackageName(); 15448 15449 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15450 packageName); 15451 if (ivi == null) { 15452 return true; 15453 } 15454 int status = ivi.getStatus(); 15455 switch (status) { 15456 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15457 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15458 return true; 15459 15460 default: 15461 // Nothing to do 15462 return false; 15463 } 15464 } 15465 15466 private static boolean isMultiArch(ApplicationInfo info) { 15467 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15468 } 15469 15470 private static boolean isExternal(PackageParser.Package pkg) { 15471 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15472 } 15473 15474 private static boolean isExternal(PackageSetting ps) { 15475 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15476 } 15477 15478 private static boolean isEphemeral(PackageParser.Package pkg) { 15479 return pkg.applicationInfo.isEphemeralApp(); 15480 } 15481 15482 private static boolean isEphemeral(PackageSetting ps) { 15483 return ps.pkg != null && isEphemeral(ps.pkg); 15484 } 15485 15486 private static boolean isSystemApp(PackageParser.Package pkg) { 15487 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15488 } 15489 15490 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15491 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15492 } 15493 15494 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15495 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15496 } 15497 15498 private static boolean isSystemApp(PackageSetting ps) { 15499 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15500 } 15501 15502 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15503 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15504 } 15505 15506 private int packageFlagsToInstallFlags(PackageSetting ps) { 15507 int installFlags = 0; 15508 if (isEphemeral(ps)) { 15509 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15510 } 15511 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15512 // This existing package was an external ASEC install when we have 15513 // the external flag without a UUID 15514 installFlags |= PackageManager.INSTALL_EXTERNAL; 15515 } 15516 if (ps.isForwardLocked()) { 15517 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15518 } 15519 return installFlags; 15520 } 15521 15522 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15523 if (isExternal(pkg)) { 15524 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15525 return StorageManager.UUID_PRIMARY_PHYSICAL; 15526 } else { 15527 return pkg.volumeUuid; 15528 } 15529 } else { 15530 return StorageManager.UUID_PRIVATE_INTERNAL; 15531 } 15532 } 15533 15534 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15535 if (isExternal(pkg)) { 15536 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15537 return mSettings.getExternalVersion(); 15538 } else { 15539 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15540 } 15541 } else { 15542 return mSettings.getInternalVersion(); 15543 } 15544 } 15545 15546 private void deleteTempPackageFiles() { 15547 final FilenameFilter filter = new FilenameFilter() { 15548 public boolean accept(File dir, String name) { 15549 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15550 } 15551 }; 15552 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15553 file.delete(); 15554 } 15555 } 15556 15557 @Override 15558 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15559 int flags) { 15560 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15561 flags); 15562 } 15563 15564 @Override 15565 public void deletePackage(final String packageName, 15566 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15567 mContext.enforceCallingOrSelfPermission( 15568 android.Manifest.permission.DELETE_PACKAGES, null); 15569 Preconditions.checkNotNull(packageName); 15570 Preconditions.checkNotNull(observer); 15571 final int uid = Binder.getCallingUid(); 15572 if (!isOrphaned(packageName) 15573 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15574 try { 15575 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15576 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15577 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15578 observer.onUserActionRequired(intent); 15579 } catch (RemoteException re) { 15580 } 15581 return; 15582 } 15583 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15584 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15585 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15586 mContext.enforceCallingOrSelfPermission( 15587 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15588 "deletePackage for user " + userId); 15589 } 15590 15591 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15592 try { 15593 observer.onPackageDeleted(packageName, 15594 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15595 } catch (RemoteException re) { 15596 } 15597 return; 15598 } 15599 15600 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15601 try { 15602 observer.onPackageDeleted(packageName, 15603 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15604 } catch (RemoteException re) { 15605 } 15606 return; 15607 } 15608 15609 if (DEBUG_REMOVE) { 15610 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15611 + " deleteAllUsers: " + deleteAllUsers ); 15612 } 15613 // Queue up an async operation since the package deletion may take a little while. 15614 mHandler.post(new Runnable() { 15615 public void run() { 15616 mHandler.removeCallbacks(this); 15617 int returnCode; 15618 if (!deleteAllUsers) { 15619 returnCode = deletePackageX(packageName, userId, deleteFlags); 15620 } else { 15621 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15622 // If nobody is blocking uninstall, proceed with delete for all users 15623 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15624 returnCode = deletePackageX(packageName, userId, deleteFlags); 15625 } else { 15626 // Otherwise uninstall individually for users with blockUninstalls=false 15627 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15628 for (int userId : users) { 15629 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15630 returnCode = deletePackageX(packageName, userId, userFlags); 15631 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15632 Slog.w(TAG, "Package delete failed for user " + userId 15633 + ", returnCode " + returnCode); 15634 } 15635 } 15636 } 15637 // The app has only been marked uninstalled for certain users. 15638 // We still need to report that delete was blocked 15639 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15640 } 15641 } 15642 try { 15643 observer.onPackageDeleted(packageName, returnCode, null); 15644 } catch (RemoteException e) { 15645 Log.i(TAG, "Observer no longer exists."); 15646 } //end catch 15647 } //end run 15648 }); 15649 } 15650 15651 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15652 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15653 || callingUid == Process.SYSTEM_UID) { 15654 return true; 15655 } 15656 final int callingUserId = UserHandle.getUserId(callingUid); 15657 // If the caller installed the pkgName, then allow it to silently uninstall. 15658 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15659 return true; 15660 } 15661 15662 // Allow package verifier to silently uninstall. 15663 if (mRequiredVerifierPackage != null && 15664 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15665 return true; 15666 } 15667 15668 // Allow package uninstaller to silently uninstall. 15669 if (mRequiredUninstallerPackage != null && 15670 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15671 return true; 15672 } 15673 15674 // Allow storage manager to silently uninstall. 15675 if (mStorageManagerPackage != null && 15676 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15677 return true; 15678 } 15679 return false; 15680 } 15681 15682 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15683 int[] result = EMPTY_INT_ARRAY; 15684 for (int userId : userIds) { 15685 if (getBlockUninstallForUser(packageName, userId)) { 15686 result = ArrayUtils.appendInt(result, userId); 15687 } 15688 } 15689 return result; 15690 } 15691 15692 @Override 15693 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15694 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15695 } 15696 15697 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15698 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15699 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15700 try { 15701 if (dpm != null) { 15702 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15703 /* callingUserOnly =*/ false); 15704 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15705 : deviceOwnerComponentName.getPackageName(); 15706 // Does the package contains the device owner? 15707 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15708 // this check is probably not needed, since DO should be registered as a device 15709 // admin on some user too. (Original bug for this: b/17657954) 15710 if (packageName.equals(deviceOwnerPackageName)) { 15711 return true; 15712 } 15713 // Does it contain a device admin for any user? 15714 int[] users; 15715 if (userId == UserHandle.USER_ALL) { 15716 users = sUserManager.getUserIds(); 15717 } else { 15718 users = new int[]{userId}; 15719 } 15720 for (int i = 0; i < users.length; ++i) { 15721 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15722 return true; 15723 } 15724 } 15725 } 15726 } catch (RemoteException e) { 15727 } 15728 return false; 15729 } 15730 15731 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15732 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15733 } 15734 15735 /** 15736 * This method is an internal method that could be get invoked either 15737 * to delete an installed package or to clean up a failed installation. 15738 * After deleting an installed package, a broadcast is sent to notify any 15739 * listeners that the package has been removed. For cleaning up a failed 15740 * installation, the broadcast is not necessary since the package's 15741 * installation wouldn't have sent the initial broadcast either 15742 * The key steps in deleting a package are 15743 * deleting the package information in internal structures like mPackages, 15744 * deleting the packages base directories through installd 15745 * updating mSettings to reflect current status 15746 * persisting settings for later use 15747 * sending a broadcast if necessary 15748 */ 15749 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15750 final PackageRemovedInfo info = new PackageRemovedInfo(); 15751 final boolean res; 15752 15753 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15754 ? UserHandle.USER_ALL : userId; 15755 15756 if (isPackageDeviceAdmin(packageName, removeUser)) { 15757 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15758 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15759 } 15760 15761 PackageSetting uninstalledPs = null; 15762 15763 // for the uninstall-updates case and restricted profiles, remember the per- 15764 // user handle installed state 15765 int[] allUsers; 15766 synchronized (mPackages) { 15767 uninstalledPs = mSettings.mPackages.get(packageName); 15768 if (uninstalledPs == null) { 15769 Slog.w(TAG, "Not removing non-existent package " + packageName); 15770 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15771 } 15772 allUsers = sUserManager.getUserIds(); 15773 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15774 } 15775 15776 final int freezeUser; 15777 if (isUpdatedSystemApp(uninstalledPs) 15778 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15779 // We're downgrading a system app, which will apply to all users, so 15780 // freeze them all during the downgrade 15781 freezeUser = UserHandle.USER_ALL; 15782 } else { 15783 freezeUser = removeUser; 15784 } 15785 15786 synchronized (mInstallLock) { 15787 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15788 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15789 deleteFlags, "deletePackageX")) { 15790 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15791 deleteFlags | REMOVE_CHATTY, info, true, null); 15792 } 15793 synchronized (mPackages) { 15794 if (res) { 15795 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15796 } 15797 } 15798 } 15799 15800 if (res) { 15801 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15802 info.sendPackageRemovedBroadcasts(killApp); 15803 info.sendSystemPackageUpdatedBroadcasts(); 15804 info.sendSystemPackageAppearedBroadcasts(); 15805 } 15806 // Force a gc here. 15807 Runtime.getRuntime().gc(); 15808 // Delete the resources here after sending the broadcast to let 15809 // other processes clean up before deleting resources. 15810 if (info.args != null) { 15811 synchronized (mInstallLock) { 15812 info.args.doPostDeleteLI(true); 15813 } 15814 } 15815 15816 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15817 } 15818 15819 class PackageRemovedInfo { 15820 String removedPackage; 15821 int uid = -1; 15822 int removedAppId = -1; 15823 int[] origUsers; 15824 int[] removedUsers = null; 15825 boolean isRemovedPackageSystemUpdate = false; 15826 boolean isUpdate; 15827 boolean dataRemoved; 15828 boolean removedForAllUsers; 15829 // Clean up resources deleted packages. 15830 InstallArgs args = null; 15831 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15832 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15833 15834 void sendPackageRemovedBroadcasts(boolean killApp) { 15835 sendPackageRemovedBroadcastInternal(killApp); 15836 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15837 for (int i = 0; i < childCount; i++) { 15838 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15839 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15840 } 15841 } 15842 15843 void sendSystemPackageUpdatedBroadcasts() { 15844 if (isRemovedPackageSystemUpdate) { 15845 sendSystemPackageUpdatedBroadcastsInternal(); 15846 final int childCount = (removedChildPackages != null) 15847 ? removedChildPackages.size() : 0; 15848 for (int i = 0; i < childCount; i++) { 15849 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15850 if (childInfo.isRemovedPackageSystemUpdate) { 15851 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15852 } 15853 } 15854 } 15855 } 15856 15857 void sendSystemPackageAppearedBroadcasts() { 15858 final int packageCount = (appearedChildPackages != null) 15859 ? appearedChildPackages.size() : 0; 15860 for (int i = 0; i < packageCount; i++) { 15861 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15862 for (int userId : installedInfo.newUsers) { 15863 sendPackageAddedForUser(installedInfo.name, true, 15864 UserHandle.getAppId(installedInfo.uid), userId); 15865 } 15866 } 15867 } 15868 15869 private void sendSystemPackageUpdatedBroadcastsInternal() { 15870 Bundle extras = new Bundle(2); 15871 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15872 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15873 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15874 extras, 0, null, null, null); 15875 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15876 extras, 0, null, null, null); 15877 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15878 null, 0, removedPackage, null, null); 15879 } 15880 15881 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15882 Bundle extras = new Bundle(2); 15883 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15884 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15885 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15886 if (isUpdate || isRemovedPackageSystemUpdate) { 15887 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15888 } 15889 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15890 if (removedPackage != null) { 15891 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15892 extras, 0, null, null, removedUsers); 15893 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15894 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15895 removedPackage, extras, 0, null, null, removedUsers); 15896 } 15897 } 15898 if (removedAppId >= 0) { 15899 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15900 removedUsers); 15901 } 15902 } 15903 } 15904 15905 /* 15906 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15907 * flag is not set, the data directory is removed as well. 15908 * make sure this flag is set for partially installed apps. If not its meaningless to 15909 * delete a partially installed application. 15910 */ 15911 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15912 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15913 String packageName = ps.name; 15914 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15915 // Retrieve object to delete permissions for shared user later on 15916 final PackageParser.Package deletedPkg; 15917 final PackageSetting deletedPs; 15918 // reader 15919 synchronized (mPackages) { 15920 deletedPkg = mPackages.get(packageName); 15921 deletedPs = mSettings.mPackages.get(packageName); 15922 if (outInfo != null) { 15923 outInfo.removedPackage = packageName; 15924 outInfo.removedUsers = deletedPs != null 15925 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15926 : null; 15927 } 15928 } 15929 15930 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15931 15932 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15933 final PackageParser.Package resolvedPkg; 15934 if (deletedPkg != null) { 15935 resolvedPkg = deletedPkg; 15936 } else { 15937 // We don't have a parsed package when it lives on an ejected 15938 // adopted storage device, so fake something together 15939 resolvedPkg = new PackageParser.Package(ps.name); 15940 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15941 } 15942 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15943 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15944 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15945 if (outInfo != null) { 15946 outInfo.dataRemoved = true; 15947 } 15948 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15949 } 15950 15951 // writer 15952 synchronized (mPackages) { 15953 if (deletedPs != null) { 15954 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15955 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15956 clearDefaultBrowserIfNeeded(packageName); 15957 if (outInfo != null) { 15958 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15959 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15960 } 15961 updatePermissionsLPw(deletedPs.name, null, 0); 15962 if (deletedPs.sharedUser != null) { 15963 // Remove permissions associated with package. Since runtime 15964 // permissions are per user we have to kill the removed package 15965 // or packages running under the shared user of the removed 15966 // package if revoking the permissions requested only by the removed 15967 // package is successful and this causes a change in gids. 15968 for (int userId : UserManagerService.getInstance().getUserIds()) { 15969 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15970 userId); 15971 if (userIdToKill == UserHandle.USER_ALL 15972 || userIdToKill >= UserHandle.USER_SYSTEM) { 15973 // If gids changed for this user, kill all affected packages. 15974 mHandler.post(new Runnable() { 15975 @Override 15976 public void run() { 15977 // This has to happen with no lock held. 15978 killApplication(deletedPs.name, deletedPs.appId, 15979 KILL_APP_REASON_GIDS_CHANGED); 15980 } 15981 }); 15982 break; 15983 } 15984 } 15985 } 15986 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15987 } 15988 // make sure to preserve per-user disabled state if this removal was just 15989 // a downgrade of a system app to the factory package 15990 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15991 if (DEBUG_REMOVE) { 15992 Slog.d(TAG, "Propagating install state across downgrade"); 15993 } 15994 for (int userId : allUserHandles) { 15995 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15996 if (DEBUG_REMOVE) { 15997 Slog.d(TAG, " user " + userId + " => " + installed); 15998 } 15999 ps.setInstalled(installed, userId); 16000 } 16001 } 16002 } 16003 // can downgrade to reader 16004 if (writeSettings) { 16005 // Save settings now 16006 mSettings.writeLPr(); 16007 } 16008 } 16009 if (outInfo != null) { 16010 // A user ID was deleted here. Go through all users and remove it 16011 // from KeyStore. 16012 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16013 } 16014 } 16015 16016 static boolean locationIsPrivileged(File path) { 16017 try { 16018 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16019 .getCanonicalPath(); 16020 return path.getCanonicalPath().startsWith(privilegedAppDir); 16021 } catch (IOException e) { 16022 Slog.e(TAG, "Unable to access code path " + path); 16023 } 16024 return false; 16025 } 16026 16027 /* 16028 * Tries to delete system package. 16029 */ 16030 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16031 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16032 boolean writeSettings) { 16033 if (deletedPs.parentPackageName != null) { 16034 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16035 return false; 16036 } 16037 16038 final boolean applyUserRestrictions 16039 = (allUserHandles != null) && (outInfo.origUsers != null); 16040 final PackageSetting disabledPs; 16041 // Confirm if the system package has been updated 16042 // An updated system app can be deleted. This will also have to restore 16043 // the system pkg from system partition 16044 // reader 16045 synchronized (mPackages) { 16046 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16047 } 16048 16049 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16050 + " disabledPs=" + disabledPs); 16051 16052 if (disabledPs == null) { 16053 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16054 return false; 16055 } else if (DEBUG_REMOVE) { 16056 Slog.d(TAG, "Deleting system pkg from data partition"); 16057 } 16058 16059 if (DEBUG_REMOVE) { 16060 if (applyUserRestrictions) { 16061 Slog.d(TAG, "Remembering install states:"); 16062 for (int userId : allUserHandles) { 16063 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16064 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16065 } 16066 } 16067 } 16068 16069 // Delete the updated package 16070 outInfo.isRemovedPackageSystemUpdate = true; 16071 if (outInfo.removedChildPackages != null) { 16072 final int childCount = (deletedPs.childPackageNames != null) 16073 ? deletedPs.childPackageNames.size() : 0; 16074 for (int i = 0; i < childCount; i++) { 16075 String childPackageName = deletedPs.childPackageNames.get(i); 16076 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16077 .contains(childPackageName)) { 16078 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16079 childPackageName); 16080 if (childInfo != null) { 16081 childInfo.isRemovedPackageSystemUpdate = true; 16082 } 16083 } 16084 } 16085 } 16086 16087 if (disabledPs.versionCode < deletedPs.versionCode) { 16088 // Delete data for downgrades 16089 flags &= ~PackageManager.DELETE_KEEP_DATA; 16090 } else { 16091 // Preserve data by setting flag 16092 flags |= PackageManager.DELETE_KEEP_DATA; 16093 } 16094 16095 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16096 outInfo, writeSettings, disabledPs.pkg); 16097 if (!ret) { 16098 return false; 16099 } 16100 16101 // writer 16102 synchronized (mPackages) { 16103 // Reinstate the old system package 16104 enableSystemPackageLPw(disabledPs.pkg); 16105 // Remove any native libraries from the upgraded package. 16106 removeNativeBinariesLI(deletedPs); 16107 } 16108 16109 // Install the system package 16110 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16111 int parseFlags = mDefParseFlags 16112 | PackageParser.PARSE_MUST_BE_APK 16113 | PackageParser.PARSE_IS_SYSTEM 16114 | PackageParser.PARSE_IS_SYSTEM_DIR; 16115 if (locationIsPrivileged(disabledPs.codePath)) { 16116 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16117 } 16118 16119 final PackageParser.Package newPkg; 16120 try { 16121 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16122 } catch (PackageManagerException e) { 16123 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16124 + e.getMessage()); 16125 return false; 16126 } 16127 try { 16128 // update shared libraries for the newly re-installed system package 16129 updateSharedLibrariesLPw(newPkg, null); 16130 } catch (PackageManagerException e) { 16131 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16132 } 16133 16134 prepareAppDataAfterInstallLIF(newPkg); 16135 16136 // writer 16137 synchronized (mPackages) { 16138 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16139 16140 // Propagate the permissions state as we do not want to drop on the floor 16141 // runtime permissions. The update permissions method below will take 16142 // care of removing obsolete permissions and grant install permissions. 16143 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16144 updatePermissionsLPw(newPkg.packageName, newPkg, 16145 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16146 16147 if (applyUserRestrictions) { 16148 if (DEBUG_REMOVE) { 16149 Slog.d(TAG, "Propagating install state across reinstall"); 16150 } 16151 for (int userId : allUserHandles) { 16152 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16153 if (DEBUG_REMOVE) { 16154 Slog.d(TAG, " user " + userId + " => " + installed); 16155 } 16156 ps.setInstalled(installed, userId); 16157 16158 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16159 } 16160 // Regardless of writeSettings we need to ensure that this restriction 16161 // state propagation is persisted 16162 mSettings.writeAllUsersPackageRestrictionsLPr(); 16163 } 16164 // can downgrade to reader here 16165 if (writeSettings) { 16166 mSettings.writeLPr(); 16167 } 16168 } 16169 return true; 16170 } 16171 16172 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16173 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16174 PackageRemovedInfo outInfo, boolean writeSettings, 16175 PackageParser.Package replacingPackage) { 16176 synchronized (mPackages) { 16177 if (outInfo != null) { 16178 outInfo.uid = ps.appId; 16179 } 16180 16181 if (outInfo != null && outInfo.removedChildPackages != null) { 16182 final int childCount = (ps.childPackageNames != null) 16183 ? ps.childPackageNames.size() : 0; 16184 for (int i = 0; i < childCount; i++) { 16185 String childPackageName = ps.childPackageNames.get(i); 16186 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16187 if (childPs == null) { 16188 return false; 16189 } 16190 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16191 childPackageName); 16192 if (childInfo != null) { 16193 childInfo.uid = childPs.appId; 16194 } 16195 } 16196 } 16197 } 16198 16199 // Delete package data from internal structures and also remove data if flag is set 16200 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16201 16202 // Delete the child packages data 16203 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16204 for (int i = 0; i < childCount; i++) { 16205 PackageSetting childPs; 16206 synchronized (mPackages) { 16207 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16208 } 16209 if (childPs != null) { 16210 PackageRemovedInfo childOutInfo = (outInfo != null 16211 && outInfo.removedChildPackages != null) 16212 ? outInfo.removedChildPackages.get(childPs.name) : null; 16213 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16214 && (replacingPackage != null 16215 && !replacingPackage.hasChildPackage(childPs.name)) 16216 ? flags & ~DELETE_KEEP_DATA : flags; 16217 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16218 deleteFlags, writeSettings); 16219 } 16220 } 16221 16222 // Delete application code and resources only for parent packages 16223 if (ps.parentPackageName == null) { 16224 if (deleteCodeAndResources && (outInfo != null)) { 16225 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16226 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16227 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16228 } 16229 } 16230 16231 return true; 16232 } 16233 16234 @Override 16235 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16236 int userId) { 16237 mContext.enforceCallingOrSelfPermission( 16238 android.Manifest.permission.DELETE_PACKAGES, null); 16239 synchronized (mPackages) { 16240 PackageSetting ps = mSettings.mPackages.get(packageName); 16241 if (ps == null) { 16242 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16243 return false; 16244 } 16245 if (!ps.getInstalled(userId)) { 16246 // Can't block uninstall for an app that is not installed or enabled. 16247 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16248 return false; 16249 } 16250 ps.setBlockUninstall(blockUninstall, userId); 16251 mSettings.writePackageRestrictionsLPr(userId); 16252 } 16253 return true; 16254 } 16255 16256 @Override 16257 public boolean getBlockUninstallForUser(String packageName, int userId) { 16258 synchronized (mPackages) { 16259 PackageSetting ps = mSettings.mPackages.get(packageName); 16260 if (ps == null) { 16261 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16262 return false; 16263 } 16264 return ps.getBlockUninstall(userId); 16265 } 16266 } 16267 16268 @Override 16269 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16270 int callingUid = Binder.getCallingUid(); 16271 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16272 throw new SecurityException( 16273 "setRequiredForSystemUser can only be run by the system or root"); 16274 } 16275 synchronized (mPackages) { 16276 PackageSetting ps = mSettings.mPackages.get(packageName); 16277 if (ps == null) { 16278 Log.w(TAG, "Package doesn't exist: " + packageName); 16279 return false; 16280 } 16281 if (systemUserApp) { 16282 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16283 } else { 16284 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16285 } 16286 mSettings.writeLPr(); 16287 } 16288 return true; 16289 } 16290 16291 /* 16292 * This method handles package deletion in general 16293 */ 16294 private boolean deletePackageLIF(String packageName, UserHandle user, 16295 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16296 PackageRemovedInfo outInfo, boolean writeSettings, 16297 PackageParser.Package replacingPackage) { 16298 if (packageName == null) { 16299 Slog.w(TAG, "Attempt to delete null packageName."); 16300 return false; 16301 } 16302 16303 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16304 16305 PackageSetting ps; 16306 16307 synchronized (mPackages) { 16308 ps = mSettings.mPackages.get(packageName); 16309 if (ps == null) { 16310 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16311 return false; 16312 } 16313 16314 if (ps.parentPackageName != null && (!isSystemApp(ps) 16315 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16316 if (DEBUG_REMOVE) { 16317 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16318 + ((user == null) ? UserHandle.USER_ALL : user)); 16319 } 16320 final int removedUserId = (user != null) ? user.getIdentifier() 16321 : UserHandle.USER_ALL; 16322 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16323 return false; 16324 } 16325 markPackageUninstalledForUserLPw(ps, user); 16326 scheduleWritePackageRestrictionsLocked(user); 16327 return true; 16328 } 16329 } 16330 16331 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16332 && user.getIdentifier() != UserHandle.USER_ALL)) { 16333 // The caller is asking that the package only be deleted for a single 16334 // user. To do this, we just mark its uninstalled state and delete 16335 // its data. If this is a system app, we only allow this to happen if 16336 // they have set the special DELETE_SYSTEM_APP which requests different 16337 // semantics than normal for uninstalling system apps. 16338 markPackageUninstalledForUserLPw(ps, user); 16339 16340 if (!isSystemApp(ps)) { 16341 // Do not uninstall the APK if an app should be cached 16342 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16343 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16344 // Other user still have this package installed, so all 16345 // we need to do is clear this user's data and save that 16346 // it is uninstalled. 16347 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16348 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16349 return false; 16350 } 16351 scheduleWritePackageRestrictionsLocked(user); 16352 return true; 16353 } else { 16354 // We need to set it back to 'installed' so the uninstall 16355 // broadcasts will be sent correctly. 16356 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16357 ps.setInstalled(true, user.getIdentifier()); 16358 } 16359 } else { 16360 // This is a system app, so we assume that the 16361 // other users still have this package installed, so all 16362 // we need to do is clear this user's data and save that 16363 // it is uninstalled. 16364 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16365 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16366 return false; 16367 } 16368 scheduleWritePackageRestrictionsLocked(user); 16369 return true; 16370 } 16371 } 16372 16373 // If we are deleting a composite package for all users, keep track 16374 // of result for each child. 16375 if (ps.childPackageNames != null && outInfo != null) { 16376 synchronized (mPackages) { 16377 final int childCount = ps.childPackageNames.size(); 16378 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16379 for (int i = 0; i < childCount; i++) { 16380 String childPackageName = ps.childPackageNames.get(i); 16381 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16382 childInfo.removedPackage = childPackageName; 16383 outInfo.removedChildPackages.put(childPackageName, childInfo); 16384 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16385 if (childPs != null) { 16386 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16387 } 16388 } 16389 } 16390 } 16391 16392 boolean ret = false; 16393 if (isSystemApp(ps)) { 16394 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16395 // When an updated system application is deleted we delete the existing resources 16396 // as well and fall back to existing code in system partition 16397 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16398 } else { 16399 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16400 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16401 outInfo, writeSettings, replacingPackage); 16402 } 16403 16404 // Take a note whether we deleted the package for all users 16405 if (outInfo != null) { 16406 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16407 if (outInfo.removedChildPackages != null) { 16408 synchronized (mPackages) { 16409 final int childCount = outInfo.removedChildPackages.size(); 16410 for (int i = 0; i < childCount; i++) { 16411 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16412 if (childInfo != null) { 16413 childInfo.removedForAllUsers = mPackages.get( 16414 childInfo.removedPackage) == null; 16415 } 16416 } 16417 } 16418 } 16419 // If we uninstalled an update to a system app there may be some 16420 // child packages that appeared as they are declared in the system 16421 // app but were not declared in the update. 16422 if (isSystemApp(ps)) { 16423 synchronized (mPackages) { 16424 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16425 final int childCount = (updatedPs.childPackageNames != null) 16426 ? updatedPs.childPackageNames.size() : 0; 16427 for (int i = 0; i < childCount; i++) { 16428 String childPackageName = updatedPs.childPackageNames.get(i); 16429 if (outInfo.removedChildPackages == null 16430 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16431 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16432 if (childPs == null) { 16433 continue; 16434 } 16435 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16436 installRes.name = childPackageName; 16437 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16438 installRes.pkg = mPackages.get(childPackageName); 16439 installRes.uid = childPs.pkg.applicationInfo.uid; 16440 if (outInfo.appearedChildPackages == null) { 16441 outInfo.appearedChildPackages = new ArrayMap<>(); 16442 } 16443 outInfo.appearedChildPackages.put(childPackageName, installRes); 16444 } 16445 } 16446 } 16447 } 16448 } 16449 16450 return ret; 16451 } 16452 16453 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16454 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16455 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16456 for (int nextUserId : userIds) { 16457 if (DEBUG_REMOVE) { 16458 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16459 } 16460 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16461 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16462 false /*hidden*/, false /*suspended*/, null, null, null, 16463 false /*blockUninstall*/, 16464 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16465 } 16466 } 16467 16468 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16469 PackageRemovedInfo outInfo) { 16470 final PackageParser.Package pkg; 16471 synchronized (mPackages) { 16472 pkg = mPackages.get(ps.name); 16473 } 16474 16475 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16476 : new int[] {userId}; 16477 for (int nextUserId : userIds) { 16478 if (DEBUG_REMOVE) { 16479 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16480 + nextUserId); 16481 } 16482 16483 destroyAppDataLIF(pkg, userId, 16484 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16485 destroyAppProfilesLIF(pkg, userId); 16486 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16487 schedulePackageCleaning(ps.name, nextUserId, false); 16488 synchronized (mPackages) { 16489 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16490 scheduleWritePackageRestrictionsLocked(nextUserId); 16491 } 16492 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16493 } 16494 } 16495 16496 if (outInfo != null) { 16497 outInfo.removedPackage = ps.name; 16498 outInfo.removedAppId = ps.appId; 16499 outInfo.removedUsers = userIds; 16500 } 16501 16502 return true; 16503 } 16504 16505 private final class ClearStorageConnection implements ServiceConnection { 16506 IMediaContainerService mContainerService; 16507 16508 @Override 16509 public void onServiceConnected(ComponentName name, IBinder service) { 16510 synchronized (this) { 16511 mContainerService = IMediaContainerService.Stub.asInterface(service); 16512 notifyAll(); 16513 } 16514 } 16515 16516 @Override 16517 public void onServiceDisconnected(ComponentName name) { 16518 } 16519 } 16520 16521 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16522 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16523 16524 final boolean mounted; 16525 if (Environment.isExternalStorageEmulated()) { 16526 mounted = true; 16527 } else { 16528 final String status = Environment.getExternalStorageState(); 16529 16530 mounted = status.equals(Environment.MEDIA_MOUNTED) 16531 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16532 } 16533 16534 if (!mounted) { 16535 return; 16536 } 16537 16538 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16539 int[] users; 16540 if (userId == UserHandle.USER_ALL) { 16541 users = sUserManager.getUserIds(); 16542 } else { 16543 users = new int[] { userId }; 16544 } 16545 final ClearStorageConnection conn = new ClearStorageConnection(); 16546 if (mContext.bindServiceAsUser( 16547 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16548 try { 16549 for (int curUser : users) { 16550 long timeout = SystemClock.uptimeMillis() + 5000; 16551 synchronized (conn) { 16552 long now; 16553 while (conn.mContainerService == null && 16554 (now = SystemClock.uptimeMillis()) < timeout) { 16555 try { 16556 conn.wait(timeout - now); 16557 } catch (InterruptedException e) { 16558 } 16559 } 16560 } 16561 if (conn.mContainerService == null) { 16562 return; 16563 } 16564 16565 final UserEnvironment userEnv = new UserEnvironment(curUser); 16566 clearDirectory(conn.mContainerService, 16567 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16568 if (allData) { 16569 clearDirectory(conn.mContainerService, 16570 userEnv.buildExternalStorageAppDataDirs(packageName)); 16571 clearDirectory(conn.mContainerService, 16572 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16573 } 16574 } 16575 } finally { 16576 mContext.unbindService(conn); 16577 } 16578 } 16579 } 16580 16581 @Override 16582 public void clearApplicationProfileData(String packageName) { 16583 enforceSystemOrRoot("Only the system can clear all profile data"); 16584 16585 final PackageParser.Package pkg; 16586 synchronized (mPackages) { 16587 pkg = mPackages.get(packageName); 16588 } 16589 16590 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16591 synchronized (mInstallLock) { 16592 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16593 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16594 true /* removeBaseMarker */); 16595 } 16596 } 16597 } 16598 16599 @Override 16600 public void clearApplicationUserData(final String packageName, 16601 final IPackageDataObserver observer, final int userId) { 16602 mContext.enforceCallingOrSelfPermission( 16603 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16604 16605 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16606 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16607 16608 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16609 throw new SecurityException("Cannot clear data for a protected package: " 16610 + packageName); 16611 } 16612 // Queue up an async operation since the package deletion may take a little while. 16613 mHandler.post(new Runnable() { 16614 public void run() { 16615 mHandler.removeCallbacks(this); 16616 final boolean succeeded; 16617 try (PackageFreezer freezer = freezePackage(packageName, 16618 "clearApplicationUserData")) { 16619 synchronized (mInstallLock) { 16620 succeeded = clearApplicationUserDataLIF(packageName, userId); 16621 } 16622 clearExternalStorageDataSync(packageName, userId, true); 16623 } 16624 if (succeeded) { 16625 // invoke DeviceStorageMonitor's update method to clear any notifications 16626 DeviceStorageMonitorInternal dsm = LocalServices 16627 .getService(DeviceStorageMonitorInternal.class); 16628 if (dsm != null) { 16629 dsm.checkMemory(); 16630 } 16631 } 16632 if(observer != null) { 16633 try { 16634 observer.onRemoveCompleted(packageName, succeeded); 16635 } catch (RemoteException e) { 16636 Log.i(TAG, "Observer no longer exists."); 16637 } 16638 } //end if observer 16639 } //end run 16640 }); 16641 } 16642 16643 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16644 if (packageName == null) { 16645 Slog.w(TAG, "Attempt to delete null packageName."); 16646 return false; 16647 } 16648 16649 // Try finding details about the requested package 16650 PackageParser.Package pkg; 16651 synchronized (mPackages) { 16652 pkg = mPackages.get(packageName); 16653 if (pkg == null) { 16654 final PackageSetting ps = mSettings.mPackages.get(packageName); 16655 if (ps != null) { 16656 pkg = ps.pkg; 16657 } 16658 } 16659 16660 if (pkg == null) { 16661 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16662 return false; 16663 } 16664 16665 PackageSetting ps = (PackageSetting) pkg.mExtras; 16666 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16667 } 16668 16669 clearAppDataLIF(pkg, userId, 16670 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16671 16672 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16673 removeKeystoreDataIfNeeded(userId, appId); 16674 16675 UserManagerInternal umInternal = getUserManagerInternal(); 16676 final int flags; 16677 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16678 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16679 } else if (umInternal.isUserRunning(userId)) { 16680 flags = StorageManager.FLAG_STORAGE_DE; 16681 } else { 16682 flags = 0; 16683 } 16684 prepareAppDataContentsLIF(pkg, userId, flags); 16685 16686 return true; 16687 } 16688 16689 /** 16690 * Reverts user permission state changes (permissions and flags) in 16691 * all packages for a given user. 16692 * 16693 * @param userId The device user for which to do a reset. 16694 */ 16695 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16696 final int packageCount = mPackages.size(); 16697 for (int i = 0; i < packageCount; i++) { 16698 PackageParser.Package pkg = mPackages.valueAt(i); 16699 PackageSetting ps = (PackageSetting) pkg.mExtras; 16700 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16701 } 16702 } 16703 16704 private void resetNetworkPolicies(int userId) { 16705 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16706 } 16707 16708 /** 16709 * Reverts user permission state changes (permissions and flags). 16710 * 16711 * @param ps The package for which to reset. 16712 * @param userId The device user for which to do a reset. 16713 */ 16714 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16715 final PackageSetting ps, final int userId) { 16716 if (ps.pkg == null) { 16717 return; 16718 } 16719 16720 // These are flags that can change base on user actions. 16721 final int userSettableMask = FLAG_PERMISSION_USER_SET 16722 | FLAG_PERMISSION_USER_FIXED 16723 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16724 | FLAG_PERMISSION_REVIEW_REQUIRED; 16725 16726 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16727 | FLAG_PERMISSION_POLICY_FIXED; 16728 16729 boolean writeInstallPermissions = false; 16730 boolean writeRuntimePermissions = false; 16731 16732 final int permissionCount = ps.pkg.requestedPermissions.size(); 16733 for (int i = 0; i < permissionCount; i++) { 16734 String permission = ps.pkg.requestedPermissions.get(i); 16735 16736 BasePermission bp = mSettings.mPermissions.get(permission); 16737 if (bp == null) { 16738 continue; 16739 } 16740 16741 // If shared user we just reset the state to which only this app contributed. 16742 if (ps.sharedUser != null) { 16743 boolean used = false; 16744 final int packageCount = ps.sharedUser.packages.size(); 16745 for (int j = 0; j < packageCount; j++) { 16746 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16747 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16748 && pkg.pkg.requestedPermissions.contains(permission)) { 16749 used = true; 16750 break; 16751 } 16752 } 16753 if (used) { 16754 continue; 16755 } 16756 } 16757 16758 PermissionsState permissionsState = ps.getPermissionsState(); 16759 16760 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16761 16762 // Always clear the user settable flags. 16763 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16764 bp.name) != null; 16765 // If permission review is enabled and this is a legacy app, mark the 16766 // permission as requiring a review as this is the initial state. 16767 int flags = 0; 16768 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 16769 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16770 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16771 } 16772 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16773 if (hasInstallState) { 16774 writeInstallPermissions = true; 16775 } else { 16776 writeRuntimePermissions = true; 16777 } 16778 } 16779 16780 // Below is only runtime permission handling. 16781 if (!bp.isRuntime()) { 16782 continue; 16783 } 16784 16785 // Never clobber system or policy. 16786 if ((oldFlags & policyOrSystemFlags) != 0) { 16787 continue; 16788 } 16789 16790 // If this permission was granted by default, make sure it is. 16791 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16792 if (permissionsState.grantRuntimePermission(bp, userId) 16793 != PERMISSION_OPERATION_FAILURE) { 16794 writeRuntimePermissions = true; 16795 } 16796 // If permission review is enabled the permissions for a legacy apps 16797 // are represented as constantly granted runtime ones, so don't revoke. 16798 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16799 // Otherwise, reset the permission. 16800 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16801 switch (revokeResult) { 16802 case PERMISSION_OPERATION_SUCCESS: 16803 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16804 writeRuntimePermissions = true; 16805 final int appId = ps.appId; 16806 mHandler.post(new Runnable() { 16807 @Override 16808 public void run() { 16809 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16810 } 16811 }); 16812 } break; 16813 } 16814 } 16815 } 16816 16817 // Synchronously write as we are taking permissions away. 16818 if (writeRuntimePermissions) { 16819 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16820 } 16821 16822 // Synchronously write as we are taking permissions away. 16823 if (writeInstallPermissions) { 16824 mSettings.writeLPr(); 16825 } 16826 } 16827 16828 /** 16829 * Remove entries from the keystore daemon. Will only remove it if the 16830 * {@code appId} is valid. 16831 */ 16832 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16833 if (appId < 0) { 16834 return; 16835 } 16836 16837 final KeyStore keyStore = KeyStore.getInstance(); 16838 if (keyStore != null) { 16839 if (userId == UserHandle.USER_ALL) { 16840 for (final int individual : sUserManager.getUserIds()) { 16841 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16842 } 16843 } else { 16844 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16845 } 16846 } else { 16847 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16848 } 16849 } 16850 16851 @Override 16852 public void deleteApplicationCacheFiles(final String packageName, 16853 final IPackageDataObserver observer) { 16854 final int userId = UserHandle.getCallingUserId(); 16855 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16856 } 16857 16858 @Override 16859 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16860 final IPackageDataObserver observer) { 16861 mContext.enforceCallingOrSelfPermission( 16862 android.Manifest.permission.DELETE_CACHE_FILES, null); 16863 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16864 /* requireFullPermission= */ true, /* checkShell= */ false, 16865 "delete application cache files"); 16866 16867 final PackageParser.Package pkg; 16868 synchronized (mPackages) { 16869 pkg = mPackages.get(packageName); 16870 } 16871 16872 // Queue up an async operation since the package deletion may take a little while. 16873 mHandler.post(new Runnable() { 16874 public void run() { 16875 synchronized (mInstallLock) { 16876 final int flags = StorageManager.FLAG_STORAGE_DE 16877 | StorageManager.FLAG_STORAGE_CE; 16878 // We're only clearing cache files, so we don't care if the 16879 // app is unfrozen and still able to run 16880 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16881 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16882 } 16883 clearExternalStorageDataSync(packageName, userId, false); 16884 if (observer != null) { 16885 try { 16886 observer.onRemoveCompleted(packageName, true); 16887 } catch (RemoteException e) { 16888 Log.i(TAG, "Observer no longer exists."); 16889 } 16890 } 16891 } 16892 }); 16893 } 16894 16895 @Override 16896 public void getPackageSizeInfo(final String packageName, int userHandle, 16897 final IPackageStatsObserver observer) { 16898 mContext.enforceCallingOrSelfPermission( 16899 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16900 if (packageName == null) { 16901 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16902 } 16903 16904 PackageStats stats = new PackageStats(packageName, userHandle); 16905 16906 /* 16907 * Queue up an async operation since the package measurement may take a 16908 * little while. 16909 */ 16910 Message msg = mHandler.obtainMessage(INIT_COPY); 16911 msg.obj = new MeasureParams(stats, observer); 16912 mHandler.sendMessage(msg); 16913 } 16914 16915 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16916 final PackageSetting ps; 16917 synchronized (mPackages) { 16918 ps = mSettings.mPackages.get(packageName); 16919 if (ps == null) { 16920 Slog.w(TAG, "Failed to find settings for " + packageName); 16921 return false; 16922 } 16923 } 16924 try { 16925 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16926 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16927 ps.getCeDataInode(userId), ps.codePathString, stats); 16928 } catch (InstallerException e) { 16929 Slog.w(TAG, String.valueOf(e)); 16930 return false; 16931 } 16932 16933 // For now, ignore code size of packages on system partition 16934 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16935 stats.codeSize = 0; 16936 } 16937 16938 return true; 16939 } 16940 16941 private int getUidTargetSdkVersionLockedLPr(int uid) { 16942 Object obj = mSettings.getUserIdLPr(uid); 16943 if (obj instanceof SharedUserSetting) { 16944 final SharedUserSetting sus = (SharedUserSetting) obj; 16945 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16946 final Iterator<PackageSetting> it = sus.packages.iterator(); 16947 while (it.hasNext()) { 16948 final PackageSetting ps = it.next(); 16949 if (ps.pkg != null) { 16950 int v = ps.pkg.applicationInfo.targetSdkVersion; 16951 if (v < vers) vers = v; 16952 } 16953 } 16954 return vers; 16955 } else if (obj instanceof PackageSetting) { 16956 final PackageSetting ps = (PackageSetting) obj; 16957 if (ps.pkg != null) { 16958 return ps.pkg.applicationInfo.targetSdkVersion; 16959 } 16960 } 16961 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16962 } 16963 16964 @Override 16965 public void addPreferredActivity(IntentFilter filter, int match, 16966 ComponentName[] set, ComponentName activity, int userId) { 16967 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16968 "Adding preferred"); 16969 } 16970 16971 private void addPreferredActivityInternal(IntentFilter filter, int match, 16972 ComponentName[] set, ComponentName activity, boolean always, int userId, 16973 String opname) { 16974 // writer 16975 int callingUid = Binder.getCallingUid(); 16976 enforceCrossUserPermission(callingUid, userId, 16977 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16978 if (filter.countActions() == 0) { 16979 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16980 return; 16981 } 16982 synchronized (mPackages) { 16983 if (mContext.checkCallingOrSelfPermission( 16984 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16985 != PackageManager.PERMISSION_GRANTED) { 16986 if (getUidTargetSdkVersionLockedLPr(callingUid) 16987 < Build.VERSION_CODES.FROYO) { 16988 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16989 + callingUid); 16990 return; 16991 } 16992 mContext.enforceCallingOrSelfPermission( 16993 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16994 } 16995 16996 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16997 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16998 + userId + ":"); 16999 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17000 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17001 scheduleWritePackageRestrictionsLocked(userId); 17002 postPreferredActivityChangedBroadcast(userId); 17003 } 17004 } 17005 17006 private void postPreferredActivityChangedBroadcast(int userId) { 17007 mHandler.post(() -> { 17008 final IActivityManager am = ActivityManagerNative.getDefault(); 17009 if (am == null) { 17010 return; 17011 } 17012 17013 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17014 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17015 try { 17016 am.broadcastIntent(null, intent, null, null, 17017 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17018 null, false, false, userId); 17019 } catch (RemoteException e) { 17020 } 17021 }); 17022 } 17023 17024 @Override 17025 public void replacePreferredActivity(IntentFilter filter, int match, 17026 ComponentName[] set, ComponentName activity, int userId) { 17027 if (filter.countActions() != 1) { 17028 throw new IllegalArgumentException( 17029 "replacePreferredActivity expects filter to have only 1 action."); 17030 } 17031 if (filter.countDataAuthorities() != 0 17032 || filter.countDataPaths() != 0 17033 || filter.countDataSchemes() > 1 17034 || filter.countDataTypes() != 0) { 17035 throw new IllegalArgumentException( 17036 "replacePreferredActivity expects filter to have no data authorities, " + 17037 "paths, or types; and at most one scheme."); 17038 } 17039 17040 final int callingUid = Binder.getCallingUid(); 17041 enforceCrossUserPermission(callingUid, userId, 17042 true /* requireFullPermission */, false /* checkShell */, 17043 "replace preferred activity"); 17044 synchronized (mPackages) { 17045 if (mContext.checkCallingOrSelfPermission( 17046 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17047 != PackageManager.PERMISSION_GRANTED) { 17048 if (getUidTargetSdkVersionLockedLPr(callingUid) 17049 < Build.VERSION_CODES.FROYO) { 17050 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17051 + Binder.getCallingUid()); 17052 return; 17053 } 17054 mContext.enforceCallingOrSelfPermission( 17055 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17056 } 17057 17058 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17059 if (pir != null) { 17060 // Get all of the existing entries that exactly match this filter. 17061 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17062 if (existing != null && existing.size() == 1) { 17063 PreferredActivity cur = existing.get(0); 17064 if (DEBUG_PREFERRED) { 17065 Slog.i(TAG, "Checking replace of preferred:"); 17066 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17067 if (!cur.mPref.mAlways) { 17068 Slog.i(TAG, " -- CUR; not mAlways!"); 17069 } else { 17070 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17071 Slog.i(TAG, " -- CUR: mSet=" 17072 + Arrays.toString(cur.mPref.mSetComponents)); 17073 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17074 Slog.i(TAG, " -- NEW: mMatch=" 17075 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17076 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17077 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17078 } 17079 } 17080 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17081 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17082 && cur.mPref.sameSet(set)) { 17083 // Setting the preferred activity to what it happens to be already 17084 if (DEBUG_PREFERRED) { 17085 Slog.i(TAG, "Replacing with same preferred activity " 17086 + cur.mPref.mShortComponent + " for user " 17087 + userId + ":"); 17088 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17089 } 17090 return; 17091 } 17092 } 17093 17094 if (existing != null) { 17095 if (DEBUG_PREFERRED) { 17096 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17097 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17098 } 17099 for (int i = 0; i < existing.size(); i++) { 17100 PreferredActivity pa = existing.get(i); 17101 if (DEBUG_PREFERRED) { 17102 Slog.i(TAG, "Removing existing preferred activity " 17103 + pa.mPref.mComponent + ":"); 17104 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17105 } 17106 pir.removeFilter(pa); 17107 } 17108 } 17109 } 17110 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17111 "Replacing preferred"); 17112 } 17113 } 17114 17115 @Override 17116 public void clearPackagePreferredActivities(String packageName) { 17117 final int uid = Binder.getCallingUid(); 17118 // writer 17119 synchronized (mPackages) { 17120 PackageParser.Package pkg = mPackages.get(packageName); 17121 if (pkg == null || pkg.applicationInfo.uid != uid) { 17122 if (mContext.checkCallingOrSelfPermission( 17123 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17124 != PackageManager.PERMISSION_GRANTED) { 17125 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17126 < Build.VERSION_CODES.FROYO) { 17127 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17128 + Binder.getCallingUid()); 17129 return; 17130 } 17131 mContext.enforceCallingOrSelfPermission( 17132 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17133 } 17134 } 17135 17136 int user = UserHandle.getCallingUserId(); 17137 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17138 scheduleWritePackageRestrictionsLocked(user); 17139 } 17140 } 17141 } 17142 17143 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17144 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17145 ArrayList<PreferredActivity> removed = null; 17146 boolean changed = false; 17147 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17148 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17149 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17150 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17151 continue; 17152 } 17153 Iterator<PreferredActivity> it = pir.filterIterator(); 17154 while (it.hasNext()) { 17155 PreferredActivity pa = it.next(); 17156 // Mark entry for removal only if it matches the package name 17157 // and the entry is of type "always". 17158 if (packageName == null || 17159 (pa.mPref.mComponent.getPackageName().equals(packageName) 17160 && pa.mPref.mAlways)) { 17161 if (removed == null) { 17162 removed = new ArrayList<PreferredActivity>(); 17163 } 17164 removed.add(pa); 17165 } 17166 } 17167 if (removed != null) { 17168 for (int j=0; j<removed.size(); j++) { 17169 PreferredActivity pa = removed.get(j); 17170 pir.removeFilter(pa); 17171 } 17172 changed = true; 17173 } 17174 } 17175 if (changed) { 17176 postPreferredActivityChangedBroadcast(userId); 17177 } 17178 return changed; 17179 } 17180 17181 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17182 private void clearIntentFilterVerificationsLPw(int userId) { 17183 final int packageCount = mPackages.size(); 17184 for (int i = 0; i < packageCount; i++) { 17185 PackageParser.Package pkg = mPackages.valueAt(i); 17186 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17187 } 17188 } 17189 17190 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17191 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17192 if (userId == UserHandle.USER_ALL) { 17193 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17194 sUserManager.getUserIds())) { 17195 for (int oneUserId : sUserManager.getUserIds()) { 17196 scheduleWritePackageRestrictionsLocked(oneUserId); 17197 } 17198 } 17199 } else { 17200 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17201 scheduleWritePackageRestrictionsLocked(userId); 17202 } 17203 } 17204 } 17205 17206 void clearDefaultBrowserIfNeeded(String packageName) { 17207 for (int oneUserId : sUserManager.getUserIds()) { 17208 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17209 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17210 if (packageName.equals(defaultBrowserPackageName)) { 17211 setDefaultBrowserPackageName(null, oneUserId); 17212 } 17213 } 17214 } 17215 17216 @Override 17217 public void resetApplicationPreferences(int userId) { 17218 mContext.enforceCallingOrSelfPermission( 17219 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17220 final long identity = Binder.clearCallingIdentity(); 17221 // writer 17222 try { 17223 synchronized (mPackages) { 17224 clearPackagePreferredActivitiesLPw(null, userId); 17225 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17226 // TODO: We have to reset the default SMS and Phone. This requires 17227 // significant refactoring to keep all default apps in the package 17228 // manager (cleaner but more work) or have the services provide 17229 // callbacks to the package manager to request a default app reset. 17230 applyFactoryDefaultBrowserLPw(userId); 17231 clearIntentFilterVerificationsLPw(userId); 17232 primeDomainVerificationsLPw(userId); 17233 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17234 scheduleWritePackageRestrictionsLocked(userId); 17235 } 17236 resetNetworkPolicies(userId); 17237 } finally { 17238 Binder.restoreCallingIdentity(identity); 17239 } 17240 } 17241 17242 @Override 17243 public int getPreferredActivities(List<IntentFilter> outFilters, 17244 List<ComponentName> outActivities, String packageName) { 17245 17246 int num = 0; 17247 final int userId = UserHandle.getCallingUserId(); 17248 // reader 17249 synchronized (mPackages) { 17250 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17251 if (pir != null) { 17252 final Iterator<PreferredActivity> it = pir.filterIterator(); 17253 while (it.hasNext()) { 17254 final PreferredActivity pa = it.next(); 17255 if (packageName == null 17256 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17257 && pa.mPref.mAlways)) { 17258 if (outFilters != null) { 17259 outFilters.add(new IntentFilter(pa)); 17260 } 17261 if (outActivities != null) { 17262 outActivities.add(pa.mPref.mComponent); 17263 } 17264 } 17265 } 17266 } 17267 } 17268 17269 return num; 17270 } 17271 17272 @Override 17273 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17274 int userId) { 17275 int callingUid = Binder.getCallingUid(); 17276 if (callingUid != Process.SYSTEM_UID) { 17277 throw new SecurityException( 17278 "addPersistentPreferredActivity can only be run by the system"); 17279 } 17280 if (filter.countActions() == 0) { 17281 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17282 return; 17283 } 17284 synchronized (mPackages) { 17285 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17286 ":"); 17287 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17288 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17289 new PersistentPreferredActivity(filter, activity)); 17290 scheduleWritePackageRestrictionsLocked(userId); 17291 postPreferredActivityChangedBroadcast(userId); 17292 } 17293 } 17294 17295 @Override 17296 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17297 int callingUid = Binder.getCallingUid(); 17298 if (callingUid != Process.SYSTEM_UID) { 17299 throw new SecurityException( 17300 "clearPackagePersistentPreferredActivities can only be run by the system"); 17301 } 17302 ArrayList<PersistentPreferredActivity> removed = null; 17303 boolean changed = false; 17304 synchronized (mPackages) { 17305 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17306 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17307 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17308 .valueAt(i); 17309 if (userId != thisUserId) { 17310 continue; 17311 } 17312 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17313 while (it.hasNext()) { 17314 PersistentPreferredActivity ppa = it.next(); 17315 // Mark entry for removal only if it matches the package name. 17316 if (ppa.mComponent.getPackageName().equals(packageName)) { 17317 if (removed == null) { 17318 removed = new ArrayList<PersistentPreferredActivity>(); 17319 } 17320 removed.add(ppa); 17321 } 17322 } 17323 if (removed != null) { 17324 for (int j=0; j<removed.size(); j++) { 17325 PersistentPreferredActivity ppa = removed.get(j); 17326 ppir.removeFilter(ppa); 17327 } 17328 changed = true; 17329 } 17330 } 17331 17332 if (changed) { 17333 scheduleWritePackageRestrictionsLocked(userId); 17334 postPreferredActivityChangedBroadcast(userId); 17335 } 17336 } 17337 } 17338 17339 /** 17340 * Common machinery for picking apart a restored XML blob and passing 17341 * it to a caller-supplied functor to be applied to the running system. 17342 */ 17343 private void restoreFromXml(XmlPullParser parser, int userId, 17344 String expectedStartTag, BlobXmlRestorer functor) 17345 throws IOException, XmlPullParserException { 17346 int type; 17347 while ((type = parser.next()) != XmlPullParser.START_TAG 17348 && type != XmlPullParser.END_DOCUMENT) { 17349 } 17350 if (type != XmlPullParser.START_TAG) { 17351 // oops didn't find a start tag?! 17352 if (DEBUG_BACKUP) { 17353 Slog.e(TAG, "Didn't find start tag during restore"); 17354 } 17355 return; 17356 } 17357Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17358 // this is supposed to be TAG_PREFERRED_BACKUP 17359 if (!expectedStartTag.equals(parser.getName())) { 17360 if (DEBUG_BACKUP) { 17361 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17362 } 17363 return; 17364 } 17365 17366 // skip interfering stuff, then we're aligned with the backing implementation 17367 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17368Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17369 functor.apply(parser, userId); 17370 } 17371 17372 private interface BlobXmlRestorer { 17373 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17374 } 17375 17376 /** 17377 * Non-Binder method, support for the backup/restore mechanism: write the 17378 * full set of preferred activities in its canonical XML format. Returns the 17379 * XML output as a byte array, or null if there is none. 17380 */ 17381 @Override 17382 public byte[] getPreferredActivityBackup(int userId) { 17383 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17384 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17385 } 17386 17387 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17388 try { 17389 final XmlSerializer serializer = new FastXmlSerializer(); 17390 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17391 serializer.startDocument(null, true); 17392 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17393 17394 synchronized (mPackages) { 17395 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17396 } 17397 17398 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17399 serializer.endDocument(); 17400 serializer.flush(); 17401 } catch (Exception e) { 17402 if (DEBUG_BACKUP) { 17403 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17404 } 17405 return null; 17406 } 17407 17408 return dataStream.toByteArray(); 17409 } 17410 17411 @Override 17412 public void restorePreferredActivities(byte[] backup, int userId) { 17413 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17414 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17415 } 17416 17417 try { 17418 final XmlPullParser parser = Xml.newPullParser(); 17419 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17420 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17421 new BlobXmlRestorer() { 17422 @Override 17423 public void apply(XmlPullParser parser, int userId) 17424 throws XmlPullParserException, IOException { 17425 synchronized (mPackages) { 17426 mSettings.readPreferredActivitiesLPw(parser, userId); 17427 } 17428 } 17429 } ); 17430 } catch (Exception e) { 17431 if (DEBUG_BACKUP) { 17432 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17433 } 17434 } 17435 } 17436 17437 /** 17438 * Non-Binder method, support for the backup/restore mechanism: write the 17439 * default browser (etc) settings in its canonical XML format. Returns the default 17440 * browser XML representation as a byte array, or null if there is none. 17441 */ 17442 @Override 17443 public byte[] getDefaultAppsBackup(int userId) { 17444 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17445 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17446 } 17447 17448 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17449 try { 17450 final XmlSerializer serializer = new FastXmlSerializer(); 17451 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17452 serializer.startDocument(null, true); 17453 serializer.startTag(null, TAG_DEFAULT_APPS); 17454 17455 synchronized (mPackages) { 17456 mSettings.writeDefaultAppsLPr(serializer, userId); 17457 } 17458 17459 serializer.endTag(null, TAG_DEFAULT_APPS); 17460 serializer.endDocument(); 17461 serializer.flush(); 17462 } catch (Exception e) { 17463 if (DEBUG_BACKUP) { 17464 Slog.e(TAG, "Unable to write default apps for backup", e); 17465 } 17466 return null; 17467 } 17468 17469 return dataStream.toByteArray(); 17470 } 17471 17472 @Override 17473 public void restoreDefaultApps(byte[] backup, int userId) { 17474 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17475 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17476 } 17477 17478 try { 17479 final XmlPullParser parser = Xml.newPullParser(); 17480 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17481 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17482 new BlobXmlRestorer() { 17483 @Override 17484 public void apply(XmlPullParser parser, int userId) 17485 throws XmlPullParserException, IOException { 17486 synchronized (mPackages) { 17487 mSettings.readDefaultAppsLPw(parser, userId); 17488 } 17489 } 17490 } ); 17491 } catch (Exception e) { 17492 if (DEBUG_BACKUP) { 17493 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17494 } 17495 } 17496 } 17497 17498 @Override 17499 public byte[] getIntentFilterVerificationBackup(int userId) { 17500 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17501 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17502 } 17503 17504 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17505 try { 17506 final XmlSerializer serializer = new FastXmlSerializer(); 17507 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17508 serializer.startDocument(null, true); 17509 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17510 17511 synchronized (mPackages) { 17512 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17513 } 17514 17515 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17516 serializer.endDocument(); 17517 serializer.flush(); 17518 } catch (Exception e) { 17519 if (DEBUG_BACKUP) { 17520 Slog.e(TAG, "Unable to write default apps for backup", e); 17521 } 17522 return null; 17523 } 17524 17525 return dataStream.toByteArray(); 17526 } 17527 17528 @Override 17529 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17530 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17531 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17532 } 17533 17534 try { 17535 final XmlPullParser parser = Xml.newPullParser(); 17536 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17537 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17538 new BlobXmlRestorer() { 17539 @Override 17540 public void apply(XmlPullParser parser, int userId) 17541 throws XmlPullParserException, IOException { 17542 synchronized (mPackages) { 17543 mSettings.readAllDomainVerificationsLPr(parser, userId); 17544 mSettings.writeLPr(); 17545 } 17546 } 17547 } ); 17548 } catch (Exception e) { 17549 if (DEBUG_BACKUP) { 17550 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17551 } 17552 } 17553 } 17554 17555 @Override 17556 public byte[] getPermissionGrantBackup(int userId) { 17557 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17558 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17559 } 17560 17561 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17562 try { 17563 final XmlSerializer serializer = new FastXmlSerializer(); 17564 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17565 serializer.startDocument(null, true); 17566 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17567 17568 synchronized (mPackages) { 17569 serializeRuntimePermissionGrantsLPr(serializer, userId); 17570 } 17571 17572 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17573 serializer.endDocument(); 17574 serializer.flush(); 17575 } catch (Exception e) { 17576 if (DEBUG_BACKUP) { 17577 Slog.e(TAG, "Unable to write default apps for backup", e); 17578 } 17579 return null; 17580 } 17581 17582 return dataStream.toByteArray(); 17583 } 17584 17585 @Override 17586 public void restorePermissionGrants(byte[] backup, int userId) { 17587 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17588 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17589 } 17590 17591 try { 17592 final XmlPullParser parser = Xml.newPullParser(); 17593 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17594 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17595 new BlobXmlRestorer() { 17596 @Override 17597 public void apply(XmlPullParser parser, int userId) 17598 throws XmlPullParserException, IOException { 17599 synchronized (mPackages) { 17600 processRestoredPermissionGrantsLPr(parser, userId); 17601 } 17602 } 17603 } ); 17604 } catch (Exception e) { 17605 if (DEBUG_BACKUP) { 17606 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17607 } 17608 } 17609 } 17610 17611 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17612 throws IOException { 17613 serializer.startTag(null, TAG_ALL_GRANTS); 17614 17615 final int N = mSettings.mPackages.size(); 17616 for (int i = 0; i < N; i++) { 17617 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17618 boolean pkgGrantsKnown = false; 17619 17620 PermissionsState packagePerms = ps.getPermissionsState(); 17621 17622 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17623 final int grantFlags = state.getFlags(); 17624 // only look at grants that are not system/policy fixed 17625 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17626 final boolean isGranted = state.isGranted(); 17627 // And only back up the user-twiddled state bits 17628 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17629 final String packageName = mSettings.mPackages.keyAt(i); 17630 if (!pkgGrantsKnown) { 17631 serializer.startTag(null, TAG_GRANT); 17632 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17633 pkgGrantsKnown = true; 17634 } 17635 17636 final boolean userSet = 17637 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17638 final boolean userFixed = 17639 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17640 final boolean revoke = 17641 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17642 17643 serializer.startTag(null, TAG_PERMISSION); 17644 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17645 if (isGranted) { 17646 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17647 } 17648 if (userSet) { 17649 serializer.attribute(null, ATTR_USER_SET, "true"); 17650 } 17651 if (userFixed) { 17652 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17653 } 17654 if (revoke) { 17655 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17656 } 17657 serializer.endTag(null, TAG_PERMISSION); 17658 } 17659 } 17660 } 17661 17662 if (pkgGrantsKnown) { 17663 serializer.endTag(null, TAG_GRANT); 17664 } 17665 } 17666 17667 serializer.endTag(null, TAG_ALL_GRANTS); 17668 } 17669 17670 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17671 throws XmlPullParserException, IOException { 17672 String pkgName = null; 17673 int outerDepth = parser.getDepth(); 17674 int type; 17675 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17676 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17677 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17678 continue; 17679 } 17680 17681 final String tagName = parser.getName(); 17682 if (tagName.equals(TAG_GRANT)) { 17683 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17684 if (DEBUG_BACKUP) { 17685 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17686 } 17687 } else if (tagName.equals(TAG_PERMISSION)) { 17688 17689 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17690 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17691 17692 int newFlagSet = 0; 17693 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17694 newFlagSet |= FLAG_PERMISSION_USER_SET; 17695 } 17696 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17697 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17698 } 17699 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17700 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17701 } 17702 if (DEBUG_BACKUP) { 17703 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17704 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17705 } 17706 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17707 if (ps != null) { 17708 // Already installed so we apply the grant immediately 17709 if (DEBUG_BACKUP) { 17710 Slog.v(TAG, " + already installed; applying"); 17711 } 17712 PermissionsState perms = ps.getPermissionsState(); 17713 BasePermission bp = mSettings.mPermissions.get(permName); 17714 if (bp != null) { 17715 if (isGranted) { 17716 perms.grantRuntimePermission(bp, userId); 17717 } 17718 if (newFlagSet != 0) { 17719 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17720 } 17721 } 17722 } else { 17723 // Need to wait for post-restore install to apply the grant 17724 if (DEBUG_BACKUP) { 17725 Slog.v(TAG, " - not yet installed; saving for later"); 17726 } 17727 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17728 isGranted, newFlagSet, userId); 17729 } 17730 } else { 17731 PackageManagerService.reportSettingsProblem(Log.WARN, 17732 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17733 XmlUtils.skipCurrentTag(parser); 17734 } 17735 } 17736 17737 scheduleWriteSettingsLocked(); 17738 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17739 } 17740 17741 @Override 17742 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17743 int sourceUserId, int targetUserId, int flags) { 17744 mContext.enforceCallingOrSelfPermission( 17745 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17746 int callingUid = Binder.getCallingUid(); 17747 enforceOwnerRights(ownerPackage, callingUid); 17748 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17749 if (intentFilter.countActions() == 0) { 17750 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17751 return; 17752 } 17753 synchronized (mPackages) { 17754 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17755 ownerPackage, targetUserId, flags); 17756 CrossProfileIntentResolver resolver = 17757 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17758 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17759 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17760 if (existing != null) { 17761 int size = existing.size(); 17762 for (int i = 0; i < size; i++) { 17763 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17764 return; 17765 } 17766 } 17767 } 17768 resolver.addFilter(newFilter); 17769 scheduleWritePackageRestrictionsLocked(sourceUserId); 17770 } 17771 } 17772 17773 @Override 17774 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17775 mContext.enforceCallingOrSelfPermission( 17776 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17777 int callingUid = Binder.getCallingUid(); 17778 enforceOwnerRights(ownerPackage, callingUid); 17779 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17780 synchronized (mPackages) { 17781 CrossProfileIntentResolver resolver = 17782 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17783 ArraySet<CrossProfileIntentFilter> set = 17784 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17785 for (CrossProfileIntentFilter filter : set) { 17786 if (filter.getOwnerPackage().equals(ownerPackage)) { 17787 resolver.removeFilter(filter); 17788 } 17789 } 17790 scheduleWritePackageRestrictionsLocked(sourceUserId); 17791 } 17792 } 17793 17794 // Enforcing that callingUid is owning pkg on userId 17795 private void enforceOwnerRights(String pkg, int callingUid) { 17796 // The system owns everything. 17797 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17798 return; 17799 } 17800 int callingUserId = UserHandle.getUserId(callingUid); 17801 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17802 if (pi == null) { 17803 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17804 + callingUserId); 17805 } 17806 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17807 throw new SecurityException("Calling uid " + callingUid 17808 + " does not own package " + pkg); 17809 } 17810 } 17811 17812 @Override 17813 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17814 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17815 } 17816 17817 private Intent getHomeIntent() { 17818 Intent intent = new Intent(Intent.ACTION_MAIN); 17819 intent.addCategory(Intent.CATEGORY_HOME); 17820 intent.addCategory(Intent.CATEGORY_DEFAULT); 17821 return intent; 17822 } 17823 17824 private IntentFilter getHomeFilter() { 17825 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17826 filter.addCategory(Intent.CATEGORY_HOME); 17827 filter.addCategory(Intent.CATEGORY_DEFAULT); 17828 return filter; 17829 } 17830 17831 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17832 int userId) { 17833 Intent intent = getHomeIntent(); 17834 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17835 PackageManager.GET_META_DATA, userId); 17836 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17837 true, false, false, userId); 17838 17839 allHomeCandidates.clear(); 17840 if (list != null) { 17841 for (ResolveInfo ri : list) { 17842 allHomeCandidates.add(ri); 17843 } 17844 } 17845 return (preferred == null || preferred.activityInfo == null) 17846 ? null 17847 : new ComponentName(preferred.activityInfo.packageName, 17848 preferred.activityInfo.name); 17849 } 17850 17851 @Override 17852 public void setHomeActivity(ComponentName comp, int userId) { 17853 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17854 getHomeActivitiesAsUser(homeActivities, userId); 17855 17856 boolean found = false; 17857 17858 final int size = homeActivities.size(); 17859 final ComponentName[] set = new ComponentName[size]; 17860 for (int i = 0; i < size; i++) { 17861 final ResolveInfo candidate = homeActivities.get(i); 17862 final ActivityInfo info = candidate.activityInfo; 17863 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17864 set[i] = activityName; 17865 if (!found && activityName.equals(comp)) { 17866 found = true; 17867 } 17868 } 17869 if (!found) { 17870 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17871 + userId); 17872 } 17873 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17874 set, comp, userId); 17875 } 17876 17877 private @Nullable String getSetupWizardPackageName() { 17878 final Intent intent = new Intent(Intent.ACTION_MAIN); 17879 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17880 17881 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17882 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17883 | MATCH_DISABLED_COMPONENTS, 17884 UserHandle.myUserId()); 17885 if (matches.size() == 1) { 17886 return matches.get(0).getComponentInfo().packageName; 17887 } else { 17888 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17889 + ": matches=" + matches); 17890 return null; 17891 } 17892 } 17893 17894 private @Nullable String getStorageManagerPackageName() { 17895 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17896 17897 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17898 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17899 | MATCH_DISABLED_COMPONENTS, 17900 UserHandle.myUserId()); 17901 if (matches.size() == 1) { 17902 return matches.get(0).getComponentInfo().packageName; 17903 } else { 17904 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17905 + matches.size() + ": matches=" + matches); 17906 return null; 17907 } 17908 } 17909 17910 @Override 17911 public void setApplicationEnabledSetting(String appPackageName, 17912 int newState, int flags, int userId, String callingPackage) { 17913 if (!sUserManager.exists(userId)) return; 17914 if (callingPackage == null) { 17915 callingPackage = Integer.toString(Binder.getCallingUid()); 17916 } 17917 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17918 } 17919 17920 @Override 17921 public void setComponentEnabledSetting(ComponentName componentName, 17922 int newState, int flags, int userId) { 17923 if (!sUserManager.exists(userId)) return; 17924 setEnabledSetting(componentName.getPackageName(), 17925 componentName.getClassName(), newState, flags, userId, null); 17926 } 17927 17928 private void setEnabledSetting(final String packageName, String className, int newState, 17929 final int flags, int userId, String callingPackage) { 17930 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17931 || newState == COMPONENT_ENABLED_STATE_ENABLED 17932 || newState == COMPONENT_ENABLED_STATE_DISABLED 17933 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17934 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17935 throw new IllegalArgumentException("Invalid new component state: " 17936 + newState); 17937 } 17938 PackageSetting pkgSetting; 17939 final int uid = Binder.getCallingUid(); 17940 final int permission; 17941 if (uid == Process.SYSTEM_UID) { 17942 permission = PackageManager.PERMISSION_GRANTED; 17943 } else { 17944 permission = mContext.checkCallingOrSelfPermission( 17945 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17946 } 17947 enforceCrossUserPermission(uid, userId, 17948 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17949 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17950 boolean sendNow = false; 17951 boolean isApp = (className == null); 17952 String componentName = isApp ? packageName : className; 17953 int packageUid = -1; 17954 ArrayList<String> components; 17955 17956 // writer 17957 synchronized (mPackages) { 17958 pkgSetting = mSettings.mPackages.get(packageName); 17959 if (pkgSetting == null) { 17960 if (className == null) { 17961 throw new IllegalArgumentException("Unknown package: " + packageName); 17962 } 17963 throw new IllegalArgumentException( 17964 "Unknown component: " + packageName + "/" + className); 17965 } 17966 } 17967 17968 // Limit who can change which apps 17969 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17970 // Don't allow apps that don't have permission to modify other apps 17971 if (!allowedByPermission) { 17972 throw new SecurityException( 17973 "Permission Denial: attempt to change component state from pid=" 17974 + Binder.getCallingPid() 17975 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17976 } 17977 // Don't allow changing protected packages. 17978 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17979 throw new SecurityException("Cannot disable a protected package: " + packageName); 17980 } 17981 } 17982 17983 synchronized (mPackages) { 17984 if (uid == Process.SHELL_UID) { 17985 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17986 int oldState = pkgSetting.getEnabled(userId); 17987 if (className == null 17988 && 17989 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17990 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17991 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17992 && 17993 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17994 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17995 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17996 // ok 17997 } else { 17998 throw new SecurityException( 17999 "Shell cannot change component state for " + packageName + "/" 18000 + className + " to " + newState); 18001 } 18002 } 18003 if (className == null) { 18004 // We're dealing with an application/package level state change 18005 if (pkgSetting.getEnabled(userId) == newState) { 18006 // Nothing to do 18007 return; 18008 } 18009 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18010 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18011 // Don't care about who enables an app. 18012 callingPackage = null; 18013 } 18014 pkgSetting.setEnabled(newState, userId, callingPackage); 18015 // pkgSetting.pkg.mSetEnabled = newState; 18016 } else { 18017 // We're dealing with a component level state change 18018 // First, verify that this is a valid class name. 18019 PackageParser.Package pkg = pkgSetting.pkg; 18020 if (pkg == null || !pkg.hasComponentClassName(className)) { 18021 if (pkg != null && 18022 pkg.applicationInfo.targetSdkVersion >= 18023 Build.VERSION_CODES.JELLY_BEAN) { 18024 throw new IllegalArgumentException("Component class " + className 18025 + " does not exist in " + packageName); 18026 } else { 18027 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18028 + className + " does not exist in " + packageName); 18029 } 18030 } 18031 switch (newState) { 18032 case COMPONENT_ENABLED_STATE_ENABLED: 18033 if (!pkgSetting.enableComponentLPw(className, userId)) { 18034 return; 18035 } 18036 break; 18037 case COMPONENT_ENABLED_STATE_DISABLED: 18038 if (!pkgSetting.disableComponentLPw(className, userId)) { 18039 return; 18040 } 18041 break; 18042 case COMPONENT_ENABLED_STATE_DEFAULT: 18043 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18044 return; 18045 } 18046 break; 18047 default: 18048 Slog.e(TAG, "Invalid new component state: " + newState); 18049 return; 18050 } 18051 } 18052 scheduleWritePackageRestrictionsLocked(userId); 18053 components = mPendingBroadcasts.get(userId, packageName); 18054 final boolean newPackage = components == null; 18055 if (newPackage) { 18056 components = new ArrayList<String>(); 18057 } 18058 if (!components.contains(componentName)) { 18059 components.add(componentName); 18060 } 18061 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18062 sendNow = true; 18063 // Purge entry from pending broadcast list if another one exists already 18064 // since we are sending one right away. 18065 mPendingBroadcasts.remove(userId, packageName); 18066 } else { 18067 if (newPackage) { 18068 mPendingBroadcasts.put(userId, packageName, components); 18069 } 18070 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18071 // Schedule a message 18072 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18073 } 18074 } 18075 } 18076 18077 long callingId = Binder.clearCallingIdentity(); 18078 try { 18079 if (sendNow) { 18080 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18081 sendPackageChangedBroadcast(packageName, 18082 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18083 } 18084 } finally { 18085 Binder.restoreCallingIdentity(callingId); 18086 } 18087 } 18088 18089 @Override 18090 public void flushPackageRestrictionsAsUser(int userId) { 18091 if (!sUserManager.exists(userId)) { 18092 return; 18093 } 18094 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18095 false /* checkShell */, "flushPackageRestrictions"); 18096 synchronized (mPackages) { 18097 mSettings.writePackageRestrictionsLPr(userId); 18098 mDirtyUsers.remove(userId); 18099 if (mDirtyUsers.isEmpty()) { 18100 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18101 } 18102 } 18103 } 18104 18105 private void sendPackageChangedBroadcast(String packageName, 18106 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18107 if (DEBUG_INSTALL) 18108 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18109 + componentNames); 18110 Bundle extras = new Bundle(4); 18111 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18112 String nameList[] = new String[componentNames.size()]; 18113 componentNames.toArray(nameList); 18114 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18115 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18116 extras.putInt(Intent.EXTRA_UID, packageUid); 18117 // If this is not reporting a change of the overall package, then only send it 18118 // to registered receivers. We don't want to launch a swath of apps for every 18119 // little component state change. 18120 final int flags = !componentNames.contains(packageName) 18121 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18122 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18123 new int[] {UserHandle.getUserId(packageUid)}); 18124 } 18125 18126 @Override 18127 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18128 if (!sUserManager.exists(userId)) return; 18129 final int uid = Binder.getCallingUid(); 18130 final int permission = mContext.checkCallingOrSelfPermission( 18131 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18132 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18133 enforceCrossUserPermission(uid, userId, 18134 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18135 // writer 18136 synchronized (mPackages) { 18137 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18138 allowedByPermission, uid, userId)) { 18139 scheduleWritePackageRestrictionsLocked(userId); 18140 } 18141 } 18142 } 18143 18144 @Override 18145 public String getInstallerPackageName(String packageName) { 18146 // reader 18147 synchronized (mPackages) { 18148 return mSettings.getInstallerPackageNameLPr(packageName); 18149 } 18150 } 18151 18152 public boolean isOrphaned(String packageName) { 18153 // reader 18154 synchronized (mPackages) { 18155 return mSettings.isOrphaned(packageName); 18156 } 18157 } 18158 18159 @Override 18160 public int getApplicationEnabledSetting(String packageName, int userId) { 18161 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18162 int uid = Binder.getCallingUid(); 18163 enforceCrossUserPermission(uid, userId, 18164 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18165 // reader 18166 synchronized (mPackages) { 18167 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18168 } 18169 } 18170 18171 @Override 18172 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18173 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18174 int uid = Binder.getCallingUid(); 18175 enforceCrossUserPermission(uid, userId, 18176 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18177 // reader 18178 synchronized (mPackages) { 18179 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18180 } 18181 } 18182 18183 @Override 18184 public void enterSafeMode() { 18185 enforceSystemOrRoot("Only the system can request entering safe mode"); 18186 18187 if (!mSystemReady) { 18188 mSafeMode = true; 18189 } 18190 } 18191 18192 @Override 18193 public void systemReady() { 18194 mSystemReady = true; 18195 18196 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18197 // disabled after already being started. 18198 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18199 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18200 18201 // Read the compatibilty setting when the system is ready. 18202 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18203 mContext.getContentResolver(), 18204 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18205 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18206 if (DEBUG_SETTINGS) { 18207 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18208 } 18209 18210 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18211 18212 synchronized (mPackages) { 18213 // Verify that all of the preferred activity components actually 18214 // exist. It is possible for applications to be updated and at 18215 // that point remove a previously declared activity component that 18216 // had been set as a preferred activity. We try to clean this up 18217 // the next time we encounter that preferred activity, but it is 18218 // possible for the user flow to never be able to return to that 18219 // situation so here we do a sanity check to make sure we haven't 18220 // left any junk around. 18221 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18222 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18223 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18224 removed.clear(); 18225 for (PreferredActivity pa : pir.filterSet()) { 18226 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18227 removed.add(pa); 18228 } 18229 } 18230 if (removed.size() > 0) { 18231 for (int r=0; r<removed.size(); r++) { 18232 PreferredActivity pa = removed.get(r); 18233 Slog.w(TAG, "Removing dangling preferred activity: " 18234 + pa.mPref.mComponent); 18235 pir.removeFilter(pa); 18236 } 18237 mSettings.writePackageRestrictionsLPr( 18238 mSettings.mPreferredActivities.keyAt(i)); 18239 } 18240 } 18241 18242 for (int userId : UserManagerService.getInstance().getUserIds()) { 18243 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18244 grantPermissionsUserIds = ArrayUtils.appendInt( 18245 grantPermissionsUserIds, userId); 18246 } 18247 } 18248 } 18249 sUserManager.systemReady(); 18250 18251 // If we upgraded grant all default permissions before kicking off. 18252 for (int userId : grantPermissionsUserIds) { 18253 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18254 } 18255 18256 // If we did not grant default permissions, we preload from this the 18257 // default permission exceptions lazily to ensure we don't hit the 18258 // disk on a new user creation. 18259 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18260 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18261 } 18262 18263 // Kick off any messages waiting for system ready 18264 if (mPostSystemReadyMessages != null) { 18265 for (Message msg : mPostSystemReadyMessages) { 18266 msg.sendToTarget(); 18267 } 18268 mPostSystemReadyMessages = null; 18269 } 18270 18271 // Watch for external volumes that come and go over time 18272 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18273 storage.registerListener(mStorageListener); 18274 18275 mInstallerService.systemReady(); 18276 mPackageDexOptimizer.systemReady(); 18277 18278 MountServiceInternal mountServiceInternal = LocalServices.getService( 18279 MountServiceInternal.class); 18280 mountServiceInternal.addExternalStoragePolicy( 18281 new MountServiceInternal.ExternalStorageMountPolicy() { 18282 @Override 18283 public int getMountMode(int uid, String packageName) { 18284 if (Process.isIsolated(uid)) { 18285 return Zygote.MOUNT_EXTERNAL_NONE; 18286 } 18287 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18288 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18289 } 18290 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18291 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18292 } 18293 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18294 return Zygote.MOUNT_EXTERNAL_READ; 18295 } 18296 return Zygote.MOUNT_EXTERNAL_WRITE; 18297 } 18298 18299 @Override 18300 public boolean hasExternalStorage(int uid, String packageName) { 18301 return true; 18302 } 18303 }); 18304 18305 // Now that we're mostly running, clean up stale users and apps 18306 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18307 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18308 } 18309 18310 @Override 18311 public boolean isSafeMode() { 18312 return mSafeMode; 18313 } 18314 18315 @Override 18316 public boolean hasSystemUidErrors() { 18317 return mHasSystemUidErrors; 18318 } 18319 18320 static String arrayToString(int[] array) { 18321 StringBuffer buf = new StringBuffer(128); 18322 buf.append('['); 18323 if (array != null) { 18324 for (int i=0; i<array.length; i++) { 18325 if (i > 0) buf.append(", "); 18326 buf.append(array[i]); 18327 } 18328 } 18329 buf.append(']'); 18330 return buf.toString(); 18331 } 18332 18333 static class DumpState { 18334 public static final int DUMP_LIBS = 1 << 0; 18335 public static final int DUMP_FEATURES = 1 << 1; 18336 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18337 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18338 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18339 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18340 public static final int DUMP_PERMISSIONS = 1 << 6; 18341 public static final int DUMP_PACKAGES = 1 << 7; 18342 public static final int DUMP_SHARED_USERS = 1 << 8; 18343 public static final int DUMP_MESSAGES = 1 << 9; 18344 public static final int DUMP_PROVIDERS = 1 << 10; 18345 public static final int DUMP_VERIFIERS = 1 << 11; 18346 public static final int DUMP_PREFERRED = 1 << 12; 18347 public static final int DUMP_PREFERRED_XML = 1 << 13; 18348 public static final int DUMP_KEYSETS = 1 << 14; 18349 public static final int DUMP_VERSION = 1 << 15; 18350 public static final int DUMP_INSTALLS = 1 << 16; 18351 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18352 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18353 public static final int DUMP_FROZEN = 1 << 19; 18354 public static final int DUMP_DEXOPT = 1 << 20; 18355 public static final int DUMP_COMPILER_STATS = 1 << 21; 18356 18357 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18358 18359 private int mTypes; 18360 18361 private int mOptions; 18362 18363 private boolean mTitlePrinted; 18364 18365 private SharedUserSetting mSharedUser; 18366 18367 public boolean isDumping(int type) { 18368 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18369 return true; 18370 } 18371 18372 return (mTypes & type) != 0; 18373 } 18374 18375 public void setDump(int type) { 18376 mTypes |= type; 18377 } 18378 18379 public boolean isOptionEnabled(int option) { 18380 return (mOptions & option) != 0; 18381 } 18382 18383 public void setOptionEnabled(int option) { 18384 mOptions |= option; 18385 } 18386 18387 public boolean onTitlePrinted() { 18388 final boolean printed = mTitlePrinted; 18389 mTitlePrinted = true; 18390 return printed; 18391 } 18392 18393 public boolean getTitlePrinted() { 18394 return mTitlePrinted; 18395 } 18396 18397 public void setTitlePrinted(boolean enabled) { 18398 mTitlePrinted = enabled; 18399 } 18400 18401 public SharedUserSetting getSharedUser() { 18402 return mSharedUser; 18403 } 18404 18405 public void setSharedUser(SharedUserSetting user) { 18406 mSharedUser = user; 18407 } 18408 } 18409 18410 @Override 18411 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18412 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18413 (new PackageManagerShellCommand(this)).exec( 18414 this, in, out, err, args, resultReceiver); 18415 } 18416 18417 @Override 18418 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18419 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18420 != PackageManager.PERMISSION_GRANTED) { 18421 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18422 + Binder.getCallingPid() 18423 + ", uid=" + Binder.getCallingUid() 18424 + " without permission " 18425 + android.Manifest.permission.DUMP); 18426 return; 18427 } 18428 18429 DumpState dumpState = new DumpState(); 18430 boolean fullPreferred = false; 18431 boolean checkin = false; 18432 18433 String packageName = null; 18434 ArraySet<String> permissionNames = null; 18435 18436 int opti = 0; 18437 while (opti < args.length) { 18438 String opt = args[opti]; 18439 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18440 break; 18441 } 18442 opti++; 18443 18444 if ("-a".equals(opt)) { 18445 // Right now we only know how to print all. 18446 } else if ("-h".equals(opt)) { 18447 pw.println("Package manager dump options:"); 18448 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18449 pw.println(" --checkin: dump for a checkin"); 18450 pw.println(" -f: print details of intent filters"); 18451 pw.println(" -h: print this help"); 18452 pw.println(" cmd may be one of:"); 18453 pw.println(" l[ibraries]: list known shared libraries"); 18454 pw.println(" f[eatures]: list device features"); 18455 pw.println(" k[eysets]: print known keysets"); 18456 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18457 pw.println(" perm[issions]: dump permissions"); 18458 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18459 pw.println(" pref[erred]: print preferred package settings"); 18460 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18461 pw.println(" prov[iders]: dump content providers"); 18462 pw.println(" p[ackages]: dump installed packages"); 18463 pw.println(" s[hared-users]: dump shared user IDs"); 18464 pw.println(" m[essages]: print collected runtime messages"); 18465 pw.println(" v[erifiers]: print package verifier info"); 18466 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18467 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18468 pw.println(" version: print database version info"); 18469 pw.println(" write: write current settings now"); 18470 pw.println(" installs: details about install sessions"); 18471 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18472 pw.println(" dexopt: dump dexopt state"); 18473 pw.println(" compiler-stats: dump compiler statistics"); 18474 pw.println(" <package.name>: info about given package"); 18475 return; 18476 } else if ("--checkin".equals(opt)) { 18477 checkin = true; 18478 } else if ("-f".equals(opt)) { 18479 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18480 } else { 18481 pw.println("Unknown argument: " + opt + "; use -h for help"); 18482 } 18483 } 18484 18485 // Is the caller requesting to dump a particular piece of data? 18486 if (opti < args.length) { 18487 String cmd = args[opti]; 18488 opti++; 18489 // Is this a package name? 18490 if ("android".equals(cmd) || cmd.contains(".")) { 18491 packageName = cmd; 18492 // When dumping a single package, we always dump all of its 18493 // filter information since the amount of data will be reasonable. 18494 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18495 } else if ("check-permission".equals(cmd)) { 18496 if (opti >= args.length) { 18497 pw.println("Error: check-permission missing permission argument"); 18498 return; 18499 } 18500 String perm = args[opti]; 18501 opti++; 18502 if (opti >= args.length) { 18503 pw.println("Error: check-permission missing package argument"); 18504 return; 18505 } 18506 String pkg = args[opti]; 18507 opti++; 18508 int user = UserHandle.getUserId(Binder.getCallingUid()); 18509 if (opti < args.length) { 18510 try { 18511 user = Integer.parseInt(args[opti]); 18512 } catch (NumberFormatException e) { 18513 pw.println("Error: check-permission user argument is not a number: " 18514 + args[opti]); 18515 return; 18516 } 18517 } 18518 pw.println(checkPermission(perm, pkg, user)); 18519 return; 18520 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18521 dumpState.setDump(DumpState.DUMP_LIBS); 18522 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18523 dumpState.setDump(DumpState.DUMP_FEATURES); 18524 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18525 if (opti >= args.length) { 18526 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18527 | DumpState.DUMP_SERVICE_RESOLVERS 18528 | DumpState.DUMP_RECEIVER_RESOLVERS 18529 | DumpState.DUMP_CONTENT_RESOLVERS); 18530 } else { 18531 while (opti < args.length) { 18532 String name = args[opti]; 18533 if ("a".equals(name) || "activity".equals(name)) { 18534 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18535 } else if ("s".equals(name) || "service".equals(name)) { 18536 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18537 } else if ("r".equals(name) || "receiver".equals(name)) { 18538 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18539 } else if ("c".equals(name) || "content".equals(name)) { 18540 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18541 } else { 18542 pw.println("Error: unknown resolver table type: " + name); 18543 return; 18544 } 18545 opti++; 18546 } 18547 } 18548 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18549 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18550 } else if ("permission".equals(cmd)) { 18551 if (opti >= args.length) { 18552 pw.println("Error: permission requires permission name"); 18553 return; 18554 } 18555 permissionNames = new ArraySet<>(); 18556 while (opti < args.length) { 18557 permissionNames.add(args[opti]); 18558 opti++; 18559 } 18560 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18561 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18562 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18563 dumpState.setDump(DumpState.DUMP_PREFERRED); 18564 } else if ("preferred-xml".equals(cmd)) { 18565 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18566 if (opti < args.length && "--full".equals(args[opti])) { 18567 fullPreferred = true; 18568 opti++; 18569 } 18570 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18571 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18572 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18573 dumpState.setDump(DumpState.DUMP_PACKAGES); 18574 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18575 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18576 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18577 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18578 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18579 dumpState.setDump(DumpState.DUMP_MESSAGES); 18580 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18581 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18582 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18583 || "intent-filter-verifiers".equals(cmd)) { 18584 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18585 } else if ("version".equals(cmd)) { 18586 dumpState.setDump(DumpState.DUMP_VERSION); 18587 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18588 dumpState.setDump(DumpState.DUMP_KEYSETS); 18589 } else if ("installs".equals(cmd)) { 18590 dumpState.setDump(DumpState.DUMP_INSTALLS); 18591 } else if ("frozen".equals(cmd)) { 18592 dumpState.setDump(DumpState.DUMP_FROZEN); 18593 } else if ("dexopt".equals(cmd)) { 18594 dumpState.setDump(DumpState.DUMP_DEXOPT); 18595 } else if ("compiler-stats".equals(cmd)) { 18596 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18597 } else if ("write".equals(cmd)) { 18598 synchronized (mPackages) { 18599 mSettings.writeLPr(); 18600 pw.println("Settings written."); 18601 return; 18602 } 18603 } 18604 } 18605 18606 if (checkin) { 18607 pw.println("vers,1"); 18608 } 18609 18610 // reader 18611 synchronized (mPackages) { 18612 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18613 if (!checkin) { 18614 if (dumpState.onTitlePrinted()) 18615 pw.println(); 18616 pw.println("Database versions:"); 18617 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18618 } 18619 } 18620 18621 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18622 if (!checkin) { 18623 if (dumpState.onTitlePrinted()) 18624 pw.println(); 18625 pw.println("Verifiers:"); 18626 pw.print(" Required: "); 18627 pw.print(mRequiredVerifierPackage); 18628 pw.print(" (uid="); 18629 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18630 UserHandle.USER_SYSTEM)); 18631 pw.println(")"); 18632 } else if (mRequiredVerifierPackage != null) { 18633 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18634 pw.print(","); 18635 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18636 UserHandle.USER_SYSTEM)); 18637 } 18638 } 18639 18640 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18641 packageName == null) { 18642 if (mIntentFilterVerifierComponent != null) { 18643 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18644 if (!checkin) { 18645 if (dumpState.onTitlePrinted()) 18646 pw.println(); 18647 pw.println("Intent Filter Verifier:"); 18648 pw.print(" Using: "); 18649 pw.print(verifierPackageName); 18650 pw.print(" (uid="); 18651 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18652 UserHandle.USER_SYSTEM)); 18653 pw.println(")"); 18654 } else if (verifierPackageName != null) { 18655 pw.print("ifv,"); pw.print(verifierPackageName); 18656 pw.print(","); 18657 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18658 UserHandle.USER_SYSTEM)); 18659 } 18660 } else { 18661 pw.println(); 18662 pw.println("No Intent Filter Verifier available!"); 18663 } 18664 } 18665 18666 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18667 boolean printedHeader = false; 18668 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18669 while (it.hasNext()) { 18670 String name = it.next(); 18671 SharedLibraryEntry ent = mSharedLibraries.get(name); 18672 if (!checkin) { 18673 if (!printedHeader) { 18674 if (dumpState.onTitlePrinted()) 18675 pw.println(); 18676 pw.println("Libraries:"); 18677 printedHeader = true; 18678 } 18679 pw.print(" "); 18680 } else { 18681 pw.print("lib,"); 18682 } 18683 pw.print(name); 18684 if (!checkin) { 18685 pw.print(" -> "); 18686 } 18687 if (ent.path != null) { 18688 if (!checkin) { 18689 pw.print("(jar) "); 18690 pw.print(ent.path); 18691 } else { 18692 pw.print(",jar,"); 18693 pw.print(ent.path); 18694 } 18695 } else { 18696 if (!checkin) { 18697 pw.print("(apk) "); 18698 pw.print(ent.apk); 18699 } else { 18700 pw.print(",apk,"); 18701 pw.print(ent.apk); 18702 } 18703 } 18704 pw.println(); 18705 } 18706 } 18707 18708 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18709 if (dumpState.onTitlePrinted()) 18710 pw.println(); 18711 if (!checkin) { 18712 pw.println("Features:"); 18713 } 18714 18715 for (FeatureInfo feat : mAvailableFeatures.values()) { 18716 if (checkin) { 18717 pw.print("feat,"); 18718 pw.print(feat.name); 18719 pw.print(","); 18720 pw.println(feat.version); 18721 } else { 18722 pw.print(" "); 18723 pw.print(feat.name); 18724 if (feat.version > 0) { 18725 pw.print(" version="); 18726 pw.print(feat.version); 18727 } 18728 pw.println(); 18729 } 18730 } 18731 } 18732 18733 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18734 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18735 : "Activity Resolver Table:", " ", packageName, 18736 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18737 dumpState.setTitlePrinted(true); 18738 } 18739 } 18740 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18741 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18742 : "Receiver Resolver Table:", " ", packageName, 18743 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18744 dumpState.setTitlePrinted(true); 18745 } 18746 } 18747 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18748 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18749 : "Service Resolver Table:", " ", packageName, 18750 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18751 dumpState.setTitlePrinted(true); 18752 } 18753 } 18754 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18755 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18756 : "Provider Resolver Table:", " ", packageName, 18757 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18758 dumpState.setTitlePrinted(true); 18759 } 18760 } 18761 18762 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18763 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18764 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18765 int user = mSettings.mPreferredActivities.keyAt(i); 18766 if (pir.dump(pw, 18767 dumpState.getTitlePrinted() 18768 ? "\nPreferred Activities User " + user + ":" 18769 : "Preferred Activities User " + user + ":", " ", 18770 packageName, true, false)) { 18771 dumpState.setTitlePrinted(true); 18772 } 18773 } 18774 } 18775 18776 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18777 pw.flush(); 18778 FileOutputStream fout = new FileOutputStream(fd); 18779 BufferedOutputStream str = new BufferedOutputStream(fout); 18780 XmlSerializer serializer = new FastXmlSerializer(); 18781 try { 18782 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18783 serializer.startDocument(null, true); 18784 serializer.setFeature( 18785 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18786 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18787 serializer.endDocument(); 18788 serializer.flush(); 18789 } catch (IllegalArgumentException e) { 18790 pw.println("Failed writing: " + e); 18791 } catch (IllegalStateException e) { 18792 pw.println("Failed writing: " + e); 18793 } catch (IOException e) { 18794 pw.println("Failed writing: " + e); 18795 } 18796 } 18797 18798 if (!checkin 18799 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18800 && packageName == null) { 18801 pw.println(); 18802 int count = mSettings.mPackages.size(); 18803 if (count == 0) { 18804 pw.println("No applications!"); 18805 pw.println(); 18806 } else { 18807 final String prefix = " "; 18808 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18809 if (allPackageSettings.size() == 0) { 18810 pw.println("No domain preferred apps!"); 18811 pw.println(); 18812 } else { 18813 pw.println("App verification status:"); 18814 pw.println(); 18815 count = 0; 18816 for (PackageSetting ps : allPackageSettings) { 18817 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18818 if (ivi == null || ivi.getPackageName() == null) continue; 18819 pw.println(prefix + "Package: " + ivi.getPackageName()); 18820 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18821 pw.println(prefix + "Status: " + ivi.getStatusString()); 18822 pw.println(); 18823 count++; 18824 } 18825 if (count == 0) { 18826 pw.println(prefix + "No app verification established."); 18827 pw.println(); 18828 } 18829 for (int userId : sUserManager.getUserIds()) { 18830 pw.println("App linkages for user " + userId + ":"); 18831 pw.println(); 18832 count = 0; 18833 for (PackageSetting ps : allPackageSettings) { 18834 final long status = ps.getDomainVerificationStatusForUser(userId); 18835 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18836 continue; 18837 } 18838 pw.println(prefix + "Package: " + ps.name); 18839 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18840 String statusStr = IntentFilterVerificationInfo. 18841 getStatusStringFromValue(status); 18842 pw.println(prefix + "Status: " + statusStr); 18843 pw.println(); 18844 count++; 18845 } 18846 if (count == 0) { 18847 pw.println(prefix + "No configured app linkages."); 18848 pw.println(); 18849 } 18850 } 18851 } 18852 } 18853 } 18854 18855 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18856 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18857 if (packageName == null && permissionNames == null) { 18858 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18859 if (iperm == 0) { 18860 if (dumpState.onTitlePrinted()) 18861 pw.println(); 18862 pw.println("AppOp Permissions:"); 18863 } 18864 pw.print(" AppOp Permission "); 18865 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18866 pw.println(":"); 18867 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18868 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18869 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18870 } 18871 } 18872 } 18873 } 18874 18875 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18876 boolean printedSomething = false; 18877 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18878 if (packageName != null && !packageName.equals(p.info.packageName)) { 18879 continue; 18880 } 18881 if (!printedSomething) { 18882 if (dumpState.onTitlePrinted()) 18883 pw.println(); 18884 pw.println("Registered ContentProviders:"); 18885 printedSomething = true; 18886 } 18887 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18888 pw.print(" "); pw.println(p.toString()); 18889 } 18890 printedSomething = false; 18891 for (Map.Entry<String, PackageParser.Provider> entry : 18892 mProvidersByAuthority.entrySet()) { 18893 PackageParser.Provider p = entry.getValue(); 18894 if (packageName != null && !packageName.equals(p.info.packageName)) { 18895 continue; 18896 } 18897 if (!printedSomething) { 18898 if (dumpState.onTitlePrinted()) 18899 pw.println(); 18900 pw.println("ContentProvider Authorities:"); 18901 printedSomething = true; 18902 } 18903 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18904 pw.print(" "); pw.println(p.toString()); 18905 if (p.info != null && p.info.applicationInfo != null) { 18906 final String appInfo = p.info.applicationInfo.toString(); 18907 pw.print(" applicationInfo="); pw.println(appInfo); 18908 } 18909 } 18910 } 18911 18912 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18913 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18914 } 18915 18916 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18917 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18918 } 18919 18920 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18921 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18922 } 18923 18924 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18925 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18926 } 18927 18928 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18929 // XXX should handle packageName != null by dumping only install data that 18930 // the given package is involved with. 18931 if (dumpState.onTitlePrinted()) pw.println(); 18932 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18933 } 18934 18935 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18936 // XXX should handle packageName != null by dumping only install data that 18937 // the given package is involved with. 18938 if (dumpState.onTitlePrinted()) pw.println(); 18939 18940 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18941 ipw.println(); 18942 ipw.println("Frozen packages:"); 18943 ipw.increaseIndent(); 18944 if (mFrozenPackages.size() == 0) { 18945 ipw.println("(none)"); 18946 } else { 18947 for (int i = 0; i < mFrozenPackages.size(); i++) { 18948 ipw.println(mFrozenPackages.valueAt(i)); 18949 } 18950 } 18951 ipw.decreaseIndent(); 18952 } 18953 18954 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18955 if (dumpState.onTitlePrinted()) pw.println(); 18956 dumpDexoptStateLPr(pw, packageName); 18957 } 18958 18959 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18960 if (dumpState.onTitlePrinted()) pw.println(); 18961 dumpCompilerStatsLPr(pw, packageName); 18962 } 18963 18964 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18965 if (dumpState.onTitlePrinted()) pw.println(); 18966 mSettings.dumpReadMessagesLPr(pw, dumpState); 18967 18968 pw.println(); 18969 pw.println("Package warning messages:"); 18970 BufferedReader in = null; 18971 String line = null; 18972 try { 18973 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18974 while ((line = in.readLine()) != null) { 18975 if (line.contains("ignored: updated version")) continue; 18976 pw.println(line); 18977 } 18978 } catch (IOException ignored) { 18979 } finally { 18980 IoUtils.closeQuietly(in); 18981 } 18982 } 18983 18984 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18985 BufferedReader in = null; 18986 String line = null; 18987 try { 18988 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18989 while ((line = in.readLine()) != null) { 18990 if (line.contains("ignored: updated version")) continue; 18991 pw.print("msg,"); 18992 pw.println(line); 18993 } 18994 } catch (IOException ignored) { 18995 } finally { 18996 IoUtils.closeQuietly(in); 18997 } 18998 } 18999 } 19000 } 19001 19002 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19003 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19004 ipw.println(); 19005 ipw.println("Dexopt state:"); 19006 ipw.increaseIndent(); 19007 Collection<PackageParser.Package> packages = null; 19008 if (packageName != null) { 19009 PackageParser.Package targetPackage = mPackages.get(packageName); 19010 if (targetPackage != null) { 19011 packages = Collections.singletonList(targetPackage); 19012 } else { 19013 ipw.println("Unable to find package: " + packageName); 19014 return; 19015 } 19016 } else { 19017 packages = mPackages.values(); 19018 } 19019 19020 for (PackageParser.Package pkg : packages) { 19021 ipw.println("[" + pkg.packageName + "]"); 19022 ipw.increaseIndent(); 19023 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19024 ipw.decreaseIndent(); 19025 } 19026 } 19027 19028 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19029 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19030 ipw.println(); 19031 ipw.println("Compiler stats:"); 19032 ipw.increaseIndent(); 19033 Collection<PackageParser.Package> packages = null; 19034 if (packageName != null) { 19035 PackageParser.Package targetPackage = mPackages.get(packageName); 19036 if (targetPackage != null) { 19037 packages = Collections.singletonList(targetPackage); 19038 } else { 19039 ipw.println("Unable to find package: " + packageName); 19040 return; 19041 } 19042 } else { 19043 packages = mPackages.values(); 19044 } 19045 19046 for (PackageParser.Package pkg : packages) { 19047 ipw.println("[" + pkg.packageName + "]"); 19048 ipw.increaseIndent(); 19049 19050 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19051 if (stats == null) { 19052 ipw.println("(No recorded stats)"); 19053 } else { 19054 stats.dump(ipw); 19055 } 19056 ipw.decreaseIndent(); 19057 } 19058 } 19059 19060 private String dumpDomainString(String packageName) { 19061 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19062 .getList(); 19063 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19064 19065 ArraySet<String> result = new ArraySet<>(); 19066 if (iviList.size() > 0) { 19067 for (IntentFilterVerificationInfo ivi : iviList) { 19068 for (String host : ivi.getDomains()) { 19069 result.add(host); 19070 } 19071 } 19072 } 19073 if (filters != null && filters.size() > 0) { 19074 for (IntentFilter filter : filters) { 19075 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19076 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19077 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19078 result.addAll(filter.getHostsList()); 19079 } 19080 } 19081 } 19082 19083 StringBuilder sb = new StringBuilder(result.size() * 16); 19084 for (String domain : result) { 19085 if (sb.length() > 0) sb.append(" "); 19086 sb.append(domain); 19087 } 19088 return sb.toString(); 19089 } 19090 19091 // ------- apps on sdcard specific code ------- 19092 static final boolean DEBUG_SD_INSTALL = false; 19093 19094 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19095 19096 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19097 19098 private boolean mMediaMounted = false; 19099 19100 static String getEncryptKey() { 19101 try { 19102 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19103 SD_ENCRYPTION_KEYSTORE_NAME); 19104 if (sdEncKey == null) { 19105 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19106 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19107 if (sdEncKey == null) { 19108 Slog.e(TAG, "Failed to create encryption keys"); 19109 return null; 19110 } 19111 } 19112 return sdEncKey; 19113 } catch (NoSuchAlgorithmException nsae) { 19114 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19115 return null; 19116 } catch (IOException ioe) { 19117 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19118 return null; 19119 } 19120 } 19121 19122 /* 19123 * Update media status on PackageManager. 19124 */ 19125 @Override 19126 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19127 int callingUid = Binder.getCallingUid(); 19128 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19129 throw new SecurityException("Media status can only be updated by the system"); 19130 } 19131 // reader; this apparently protects mMediaMounted, but should probably 19132 // be a different lock in that case. 19133 synchronized (mPackages) { 19134 Log.i(TAG, "Updating external media status from " 19135 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19136 + (mediaStatus ? "mounted" : "unmounted")); 19137 if (DEBUG_SD_INSTALL) 19138 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19139 + ", mMediaMounted=" + mMediaMounted); 19140 if (mediaStatus == mMediaMounted) { 19141 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19142 : 0, -1); 19143 mHandler.sendMessage(msg); 19144 return; 19145 } 19146 mMediaMounted = mediaStatus; 19147 } 19148 // Queue up an async operation since the package installation may take a 19149 // little while. 19150 mHandler.post(new Runnable() { 19151 public void run() { 19152 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19153 } 19154 }); 19155 } 19156 19157 /** 19158 * Called by MountService when the initial ASECs to scan are available. 19159 * Should block until all the ASEC containers are finished being scanned. 19160 */ 19161 public void scanAvailableAsecs() { 19162 updateExternalMediaStatusInner(true, false, false); 19163 } 19164 19165 /* 19166 * Collect information of applications on external media, map them against 19167 * existing containers and update information based on current mount status. 19168 * Please note that we always have to report status if reportStatus has been 19169 * set to true especially when unloading packages. 19170 */ 19171 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19172 boolean externalStorage) { 19173 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19174 int[] uidArr = EmptyArray.INT; 19175 19176 final String[] list = PackageHelper.getSecureContainerList(); 19177 if (ArrayUtils.isEmpty(list)) { 19178 Log.i(TAG, "No secure containers found"); 19179 } else { 19180 // Process list of secure containers and categorize them 19181 // as active or stale based on their package internal state. 19182 19183 // reader 19184 synchronized (mPackages) { 19185 for (String cid : list) { 19186 // Leave stages untouched for now; installer service owns them 19187 if (PackageInstallerService.isStageName(cid)) continue; 19188 19189 if (DEBUG_SD_INSTALL) 19190 Log.i(TAG, "Processing container " + cid); 19191 String pkgName = getAsecPackageName(cid); 19192 if (pkgName == null) { 19193 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19194 continue; 19195 } 19196 if (DEBUG_SD_INSTALL) 19197 Log.i(TAG, "Looking for pkg : " + pkgName); 19198 19199 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19200 if (ps == null) { 19201 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19202 continue; 19203 } 19204 19205 /* 19206 * Skip packages that are not external if we're unmounting 19207 * external storage. 19208 */ 19209 if (externalStorage && !isMounted && !isExternal(ps)) { 19210 continue; 19211 } 19212 19213 final AsecInstallArgs args = new AsecInstallArgs(cid, 19214 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19215 // The package status is changed only if the code path 19216 // matches between settings and the container id. 19217 if (ps.codePathString != null 19218 && ps.codePathString.startsWith(args.getCodePath())) { 19219 if (DEBUG_SD_INSTALL) { 19220 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19221 + " at code path: " + ps.codePathString); 19222 } 19223 19224 // We do have a valid package installed on sdcard 19225 processCids.put(args, ps.codePathString); 19226 final int uid = ps.appId; 19227 if (uid != -1) { 19228 uidArr = ArrayUtils.appendInt(uidArr, uid); 19229 } 19230 } else { 19231 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19232 + ps.codePathString); 19233 } 19234 } 19235 } 19236 19237 Arrays.sort(uidArr); 19238 } 19239 19240 // Process packages with valid entries. 19241 if (isMounted) { 19242 if (DEBUG_SD_INSTALL) 19243 Log.i(TAG, "Loading packages"); 19244 loadMediaPackages(processCids, uidArr, externalStorage); 19245 startCleaningPackages(); 19246 mInstallerService.onSecureContainersAvailable(); 19247 } else { 19248 if (DEBUG_SD_INSTALL) 19249 Log.i(TAG, "Unloading packages"); 19250 unloadMediaPackages(processCids, uidArr, reportStatus); 19251 } 19252 } 19253 19254 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19255 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19256 final int size = infos.size(); 19257 final String[] packageNames = new String[size]; 19258 final int[] packageUids = new int[size]; 19259 for (int i = 0; i < size; i++) { 19260 final ApplicationInfo info = infos.get(i); 19261 packageNames[i] = info.packageName; 19262 packageUids[i] = info.uid; 19263 } 19264 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19265 finishedReceiver); 19266 } 19267 19268 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19269 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19270 sendResourcesChangedBroadcast(mediaStatus, replacing, 19271 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19272 } 19273 19274 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19275 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19276 int size = pkgList.length; 19277 if (size > 0) { 19278 // Send broadcasts here 19279 Bundle extras = new Bundle(); 19280 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19281 if (uidArr != null) { 19282 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19283 } 19284 if (replacing) { 19285 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19286 } 19287 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19288 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19289 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19290 } 19291 } 19292 19293 /* 19294 * Look at potentially valid container ids from processCids If package 19295 * information doesn't match the one on record or package scanning fails, 19296 * the cid is added to list of removeCids. We currently don't delete stale 19297 * containers. 19298 */ 19299 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19300 boolean externalStorage) { 19301 ArrayList<String> pkgList = new ArrayList<String>(); 19302 Set<AsecInstallArgs> keys = processCids.keySet(); 19303 19304 for (AsecInstallArgs args : keys) { 19305 String codePath = processCids.get(args); 19306 if (DEBUG_SD_INSTALL) 19307 Log.i(TAG, "Loading container : " + args.cid); 19308 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19309 try { 19310 // Make sure there are no container errors first. 19311 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19312 Slog.e(TAG, "Failed to mount cid : " + args.cid 19313 + " when installing from sdcard"); 19314 continue; 19315 } 19316 // Check code path here. 19317 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19318 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19319 + " does not match one in settings " + codePath); 19320 continue; 19321 } 19322 // Parse package 19323 int parseFlags = mDefParseFlags; 19324 if (args.isExternalAsec()) { 19325 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19326 } 19327 if (args.isFwdLocked()) { 19328 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19329 } 19330 19331 synchronized (mInstallLock) { 19332 PackageParser.Package pkg = null; 19333 try { 19334 // Sadly we don't know the package name yet to freeze it 19335 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19336 SCAN_IGNORE_FROZEN, 0, null); 19337 } catch (PackageManagerException e) { 19338 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19339 } 19340 // Scan the package 19341 if (pkg != null) { 19342 /* 19343 * TODO why is the lock being held? doPostInstall is 19344 * called in other places without the lock. This needs 19345 * to be straightened out. 19346 */ 19347 // writer 19348 synchronized (mPackages) { 19349 retCode = PackageManager.INSTALL_SUCCEEDED; 19350 pkgList.add(pkg.packageName); 19351 // Post process args 19352 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19353 pkg.applicationInfo.uid); 19354 } 19355 } else { 19356 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19357 } 19358 } 19359 19360 } finally { 19361 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19362 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19363 } 19364 } 19365 } 19366 // writer 19367 synchronized (mPackages) { 19368 // If the platform SDK has changed since the last time we booted, 19369 // we need to re-grant app permission to catch any new ones that 19370 // appear. This is really a hack, and means that apps can in some 19371 // cases get permissions that the user didn't initially explicitly 19372 // allow... it would be nice to have some better way to handle 19373 // this situation. 19374 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19375 : mSettings.getInternalVersion(); 19376 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19377 : StorageManager.UUID_PRIVATE_INTERNAL; 19378 19379 int updateFlags = UPDATE_PERMISSIONS_ALL; 19380 if (ver.sdkVersion != mSdkVersion) { 19381 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19382 + mSdkVersion + "; regranting permissions for external"); 19383 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19384 } 19385 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19386 19387 // Yay, everything is now upgraded 19388 ver.forceCurrent(); 19389 19390 // can downgrade to reader 19391 // Persist settings 19392 mSettings.writeLPr(); 19393 } 19394 // Send a broadcast to let everyone know we are done processing 19395 if (pkgList.size() > 0) { 19396 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19397 } 19398 } 19399 19400 /* 19401 * Utility method to unload a list of specified containers 19402 */ 19403 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19404 // Just unmount all valid containers. 19405 for (AsecInstallArgs arg : cidArgs) { 19406 synchronized (mInstallLock) { 19407 arg.doPostDeleteLI(false); 19408 } 19409 } 19410 } 19411 19412 /* 19413 * Unload packages mounted on external media. This involves deleting package 19414 * data from internal structures, sending broadcasts about disabled packages, 19415 * gc'ing to free up references, unmounting all secure containers 19416 * corresponding to packages on external media, and posting a 19417 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19418 * that we always have to post this message if status has been requested no 19419 * matter what. 19420 */ 19421 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19422 final boolean reportStatus) { 19423 if (DEBUG_SD_INSTALL) 19424 Log.i(TAG, "unloading media packages"); 19425 ArrayList<String> pkgList = new ArrayList<String>(); 19426 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19427 final Set<AsecInstallArgs> keys = processCids.keySet(); 19428 for (AsecInstallArgs args : keys) { 19429 String pkgName = args.getPackageName(); 19430 if (DEBUG_SD_INSTALL) 19431 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19432 // Delete package internally 19433 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19434 synchronized (mInstallLock) { 19435 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19436 final boolean res; 19437 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19438 "unloadMediaPackages")) { 19439 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19440 null); 19441 } 19442 if (res) { 19443 pkgList.add(pkgName); 19444 } else { 19445 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19446 failedList.add(args); 19447 } 19448 } 19449 } 19450 19451 // reader 19452 synchronized (mPackages) { 19453 // We didn't update the settings after removing each package; 19454 // write them now for all packages. 19455 mSettings.writeLPr(); 19456 } 19457 19458 // We have to absolutely send UPDATED_MEDIA_STATUS only 19459 // after confirming that all the receivers processed the ordered 19460 // broadcast when packages get disabled, force a gc to clean things up. 19461 // and unload all the containers. 19462 if (pkgList.size() > 0) { 19463 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19464 new IIntentReceiver.Stub() { 19465 public void performReceive(Intent intent, int resultCode, String data, 19466 Bundle extras, boolean ordered, boolean sticky, 19467 int sendingUser) throws RemoteException { 19468 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19469 reportStatus ? 1 : 0, 1, keys); 19470 mHandler.sendMessage(msg); 19471 } 19472 }); 19473 } else { 19474 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19475 keys); 19476 mHandler.sendMessage(msg); 19477 } 19478 } 19479 19480 private void loadPrivatePackages(final VolumeInfo vol) { 19481 mHandler.post(new Runnable() { 19482 @Override 19483 public void run() { 19484 loadPrivatePackagesInner(vol); 19485 } 19486 }); 19487 } 19488 19489 private void loadPrivatePackagesInner(VolumeInfo vol) { 19490 final String volumeUuid = vol.fsUuid; 19491 if (TextUtils.isEmpty(volumeUuid)) { 19492 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19493 return; 19494 } 19495 19496 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19497 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19498 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19499 19500 final VersionInfo ver; 19501 final List<PackageSetting> packages; 19502 synchronized (mPackages) { 19503 ver = mSettings.findOrCreateVersion(volumeUuid); 19504 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19505 } 19506 19507 for (PackageSetting ps : packages) { 19508 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19509 synchronized (mInstallLock) { 19510 final PackageParser.Package pkg; 19511 try { 19512 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19513 loaded.add(pkg.applicationInfo); 19514 19515 } catch (PackageManagerException e) { 19516 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19517 } 19518 19519 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19520 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19521 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19522 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19523 } 19524 } 19525 } 19526 19527 // Reconcile app data for all started/unlocked users 19528 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19529 final UserManager um = mContext.getSystemService(UserManager.class); 19530 UserManagerInternal umInternal = getUserManagerInternal(); 19531 for (UserInfo user : um.getUsers()) { 19532 final int flags; 19533 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19534 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19535 } else if (umInternal.isUserRunning(user.id)) { 19536 flags = StorageManager.FLAG_STORAGE_DE; 19537 } else { 19538 continue; 19539 } 19540 19541 try { 19542 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19543 synchronized (mInstallLock) { 19544 reconcileAppsDataLI(volumeUuid, user.id, flags); 19545 } 19546 } catch (IllegalStateException e) { 19547 // Device was probably ejected, and we'll process that event momentarily 19548 Slog.w(TAG, "Failed to prepare storage: " + e); 19549 } 19550 } 19551 19552 synchronized (mPackages) { 19553 int updateFlags = UPDATE_PERMISSIONS_ALL; 19554 if (ver.sdkVersion != mSdkVersion) { 19555 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19556 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19557 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19558 } 19559 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19560 19561 // Yay, everything is now upgraded 19562 ver.forceCurrent(); 19563 19564 mSettings.writeLPr(); 19565 } 19566 19567 for (PackageFreezer freezer : freezers) { 19568 freezer.close(); 19569 } 19570 19571 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19572 sendResourcesChangedBroadcast(true, false, loaded, null); 19573 } 19574 19575 private void unloadPrivatePackages(final VolumeInfo vol) { 19576 mHandler.post(new Runnable() { 19577 @Override 19578 public void run() { 19579 unloadPrivatePackagesInner(vol); 19580 } 19581 }); 19582 } 19583 19584 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19585 final String volumeUuid = vol.fsUuid; 19586 if (TextUtils.isEmpty(volumeUuid)) { 19587 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19588 return; 19589 } 19590 19591 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19592 synchronized (mInstallLock) { 19593 synchronized (mPackages) { 19594 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19595 for (PackageSetting ps : packages) { 19596 if (ps.pkg == null) continue; 19597 19598 final ApplicationInfo info = ps.pkg.applicationInfo; 19599 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19600 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19601 19602 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19603 "unloadPrivatePackagesInner")) { 19604 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19605 false, null)) { 19606 unloaded.add(info); 19607 } else { 19608 Slog.w(TAG, "Failed to unload " + ps.codePath); 19609 } 19610 } 19611 19612 // Try very hard to release any references to this package 19613 // so we don't risk the system server being killed due to 19614 // open FDs 19615 AttributeCache.instance().removePackage(ps.name); 19616 } 19617 19618 mSettings.writeLPr(); 19619 } 19620 } 19621 19622 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19623 sendResourcesChangedBroadcast(false, false, unloaded, null); 19624 19625 // Try very hard to release any references to this path so we don't risk 19626 // the system server being killed due to open FDs 19627 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19628 19629 for (int i = 0; i < 3; i++) { 19630 System.gc(); 19631 System.runFinalization(); 19632 } 19633 } 19634 19635 /** 19636 * Prepare storage areas for given user on all mounted devices. 19637 */ 19638 void prepareUserData(int userId, int userSerial, int flags) { 19639 synchronized (mInstallLock) { 19640 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19641 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19642 final String volumeUuid = vol.getFsUuid(); 19643 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19644 } 19645 } 19646 } 19647 19648 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19649 boolean allowRecover) { 19650 // Prepare storage and verify that serial numbers are consistent; if 19651 // there's a mismatch we need to destroy to avoid leaking data 19652 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19653 try { 19654 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19655 19656 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19657 UserManagerService.enforceSerialNumber( 19658 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19659 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19660 UserManagerService.enforceSerialNumber( 19661 Environment.getDataSystemDeDirectory(userId), userSerial); 19662 } 19663 } 19664 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19665 UserManagerService.enforceSerialNumber( 19666 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19667 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19668 UserManagerService.enforceSerialNumber( 19669 Environment.getDataSystemCeDirectory(userId), userSerial); 19670 } 19671 } 19672 19673 synchronized (mInstallLock) { 19674 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19675 } 19676 } catch (Exception e) { 19677 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19678 + " because we failed to prepare: " + e); 19679 destroyUserDataLI(volumeUuid, userId, 19680 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19681 19682 if (allowRecover) { 19683 // Try one last time; if we fail again we're really in trouble 19684 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19685 } 19686 } 19687 } 19688 19689 /** 19690 * Destroy storage areas for given user on all mounted devices. 19691 */ 19692 void destroyUserData(int userId, int flags) { 19693 synchronized (mInstallLock) { 19694 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19695 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19696 final String volumeUuid = vol.getFsUuid(); 19697 destroyUserDataLI(volumeUuid, userId, flags); 19698 } 19699 } 19700 } 19701 19702 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19703 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19704 try { 19705 // Clean up app data, profile data, and media data 19706 mInstaller.destroyUserData(volumeUuid, userId, flags); 19707 19708 // Clean up system data 19709 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19710 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19711 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19712 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19713 } 19714 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19715 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19716 } 19717 } 19718 19719 // Data with special labels is now gone, so finish the job 19720 storage.destroyUserStorage(volumeUuid, userId, flags); 19721 19722 } catch (Exception e) { 19723 logCriticalInfo(Log.WARN, 19724 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19725 } 19726 } 19727 19728 /** 19729 * Examine all users present on given mounted volume, and destroy data 19730 * belonging to users that are no longer valid, or whose user ID has been 19731 * recycled. 19732 */ 19733 private void reconcileUsers(String volumeUuid) { 19734 final List<File> files = new ArrayList<>(); 19735 Collections.addAll(files, FileUtils 19736 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19737 Collections.addAll(files, FileUtils 19738 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19739 Collections.addAll(files, FileUtils 19740 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19741 Collections.addAll(files, FileUtils 19742 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19743 for (File file : files) { 19744 if (!file.isDirectory()) continue; 19745 19746 final int userId; 19747 final UserInfo info; 19748 try { 19749 userId = Integer.parseInt(file.getName()); 19750 info = sUserManager.getUserInfo(userId); 19751 } catch (NumberFormatException e) { 19752 Slog.w(TAG, "Invalid user directory " + file); 19753 continue; 19754 } 19755 19756 boolean destroyUser = false; 19757 if (info == null) { 19758 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19759 + " because no matching user was found"); 19760 destroyUser = true; 19761 } else if (!mOnlyCore) { 19762 try { 19763 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19764 } catch (IOException e) { 19765 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19766 + " because we failed to enforce serial number: " + e); 19767 destroyUser = true; 19768 } 19769 } 19770 19771 if (destroyUser) { 19772 synchronized (mInstallLock) { 19773 destroyUserDataLI(volumeUuid, userId, 19774 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19775 } 19776 } 19777 } 19778 } 19779 19780 private void assertPackageKnown(String volumeUuid, String packageName) 19781 throws PackageManagerException { 19782 synchronized (mPackages) { 19783 // Normalize package name to handle renamed packages 19784 packageName = normalizePackageNameLPr(packageName); 19785 19786 final PackageSetting ps = mSettings.mPackages.get(packageName); 19787 if (ps == null) { 19788 throw new PackageManagerException("Package " + packageName + " is unknown"); 19789 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19790 throw new PackageManagerException( 19791 "Package " + packageName + " found on unknown volume " + volumeUuid 19792 + "; expected volume " + ps.volumeUuid); 19793 } 19794 } 19795 } 19796 19797 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19798 throws PackageManagerException { 19799 synchronized (mPackages) { 19800 // Normalize package name to handle renamed packages 19801 packageName = normalizePackageNameLPr(packageName); 19802 19803 final PackageSetting ps = mSettings.mPackages.get(packageName); 19804 if (ps == null) { 19805 throw new PackageManagerException("Package " + packageName + " is unknown"); 19806 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19807 throw new PackageManagerException( 19808 "Package " + packageName + " found on unknown volume " + volumeUuid 19809 + "; expected volume " + ps.volumeUuid); 19810 } else if (!ps.getInstalled(userId)) { 19811 throw new PackageManagerException( 19812 "Package " + packageName + " not installed for user " + userId); 19813 } 19814 } 19815 } 19816 19817 /** 19818 * Examine all apps present on given mounted volume, and destroy apps that 19819 * aren't expected, either due to uninstallation or reinstallation on 19820 * another volume. 19821 */ 19822 private void reconcileApps(String volumeUuid) { 19823 final File[] files = FileUtils 19824 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19825 for (File file : files) { 19826 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19827 && !PackageInstallerService.isStageName(file.getName()); 19828 if (!isPackage) { 19829 // Ignore entries which are not packages 19830 continue; 19831 } 19832 19833 try { 19834 final PackageLite pkg = PackageParser.parsePackageLite(file, 19835 PackageParser.PARSE_MUST_BE_APK); 19836 assertPackageKnown(volumeUuid, pkg.packageName); 19837 19838 } catch (PackageParserException | PackageManagerException e) { 19839 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19840 synchronized (mInstallLock) { 19841 removeCodePathLI(file); 19842 } 19843 } 19844 } 19845 } 19846 19847 /** 19848 * Reconcile all app data for the given user. 19849 * <p> 19850 * Verifies that directories exist and that ownership and labeling is 19851 * correct for all installed apps on all mounted volumes. 19852 */ 19853 void reconcileAppsData(int userId, int flags) { 19854 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19855 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19856 final String volumeUuid = vol.getFsUuid(); 19857 synchronized (mInstallLock) { 19858 reconcileAppsDataLI(volumeUuid, userId, flags); 19859 } 19860 } 19861 } 19862 19863 /** 19864 * Reconcile all app data on given mounted volume. 19865 * <p> 19866 * Destroys app data that isn't expected, either due to uninstallation or 19867 * reinstallation on another volume. 19868 * <p> 19869 * Verifies that directories exist and that ownership and labeling is 19870 * correct for all installed apps. 19871 */ 19872 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19873 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19874 + Integer.toHexString(flags)); 19875 19876 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19877 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19878 19879 // First look for stale data that doesn't belong, and check if things 19880 // have changed since we did our last restorecon 19881 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19882 if (StorageManager.isFileEncryptedNativeOrEmulated() 19883 && !StorageManager.isUserKeyUnlocked(userId)) { 19884 throw new RuntimeException( 19885 "Yikes, someone asked us to reconcile CE storage while " + userId 19886 + " was still locked; this would have caused massive data loss!"); 19887 } 19888 19889 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19890 for (File file : files) { 19891 final String packageName = file.getName(); 19892 try { 19893 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19894 } catch (PackageManagerException e) { 19895 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19896 try { 19897 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19898 StorageManager.FLAG_STORAGE_CE, 0); 19899 } catch (InstallerException e2) { 19900 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19901 } 19902 } 19903 } 19904 } 19905 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19906 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19907 for (File file : files) { 19908 final String packageName = file.getName(); 19909 try { 19910 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19911 } catch (PackageManagerException e) { 19912 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19913 try { 19914 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19915 StorageManager.FLAG_STORAGE_DE, 0); 19916 } catch (InstallerException e2) { 19917 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19918 } 19919 } 19920 } 19921 } 19922 19923 // Ensure that data directories are ready to roll for all packages 19924 // installed for this volume and user 19925 final List<PackageSetting> packages; 19926 synchronized (mPackages) { 19927 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19928 } 19929 int preparedCount = 0; 19930 for (PackageSetting ps : packages) { 19931 final String packageName = ps.name; 19932 if (ps.pkg == null) { 19933 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19934 // TODO: might be due to legacy ASEC apps; we should circle back 19935 // and reconcile again once they're scanned 19936 continue; 19937 } 19938 19939 if (ps.getInstalled(userId)) { 19940 prepareAppDataLIF(ps.pkg, userId, flags); 19941 19942 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19943 // We may have just shuffled around app data directories, so 19944 // prepare them one more time 19945 prepareAppDataLIF(ps.pkg, userId, flags); 19946 } 19947 19948 preparedCount++; 19949 } 19950 } 19951 19952 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19953 } 19954 19955 /** 19956 * Prepare app data for the given app just after it was installed or 19957 * upgraded. This method carefully only touches users that it's installed 19958 * for, and it forces a restorecon to handle any seinfo changes. 19959 * <p> 19960 * Verifies that directories exist and that ownership and labeling is 19961 * correct for all installed apps. If there is an ownership mismatch, it 19962 * will try recovering system apps by wiping data; third-party app data is 19963 * left intact. 19964 * <p> 19965 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19966 */ 19967 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19968 final PackageSetting ps; 19969 synchronized (mPackages) { 19970 ps = mSettings.mPackages.get(pkg.packageName); 19971 mSettings.writeKernelMappingLPr(ps); 19972 } 19973 19974 final UserManager um = mContext.getSystemService(UserManager.class); 19975 UserManagerInternal umInternal = getUserManagerInternal(); 19976 for (UserInfo user : um.getUsers()) { 19977 final int flags; 19978 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19979 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19980 } else if (umInternal.isUserRunning(user.id)) { 19981 flags = StorageManager.FLAG_STORAGE_DE; 19982 } else { 19983 continue; 19984 } 19985 19986 if (ps.getInstalled(user.id)) { 19987 // TODO: when user data is locked, mark that we're still dirty 19988 prepareAppDataLIF(pkg, user.id, flags); 19989 } 19990 } 19991 } 19992 19993 /** 19994 * Prepare app data for the given app. 19995 * <p> 19996 * Verifies that directories exist and that ownership and labeling is 19997 * correct for all installed apps. If there is an ownership mismatch, this 19998 * will try recovering system apps by wiping data; third-party app data is 19999 * left intact. 20000 */ 20001 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20002 if (pkg == null) { 20003 Slog.wtf(TAG, "Package was null!", new Throwable()); 20004 return; 20005 } 20006 prepareAppDataLeafLIF(pkg, userId, flags); 20007 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20008 for (int i = 0; i < childCount; i++) { 20009 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20010 } 20011 } 20012 20013 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20014 if (DEBUG_APP_DATA) { 20015 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20016 + Integer.toHexString(flags)); 20017 } 20018 20019 final String volumeUuid = pkg.volumeUuid; 20020 final String packageName = pkg.packageName; 20021 final ApplicationInfo app = pkg.applicationInfo; 20022 final int appId = UserHandle.getAppId(app.uid); 20023 20024 Preconditions.checkNotNull(app.seinfo); 20025 20026 try { 20027 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20028 appId, app.seinfo, app.targetSdkVersion); 20029 } catch (InstallerException e) { 20030 if (app.isSystemApp()) { 20031 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20032 + ", but trying to recover: " + e); 20033 destroyAppDataLeafLIF(pkg, userId, flags); 20034 try { 20035 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20036 appId, app.seinfo, app.targetSdkVersion); 20037 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20038 } catch (InstallerException e2) { 20039 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20040 } 20041 } else { 20042 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20043 } 20044 } 20045 20046 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20047 try { 20048 // CE storage is unlocked right now, so read out the inode and 20049 // remember for use later when it's locked 20050 // TODO: mark this structure as dirty so we persist it! 20051 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20052 StorageManager.FLAG_STORAGE_CE); 20053 synchronized (mPackages) { 20054 final PackageSetting ps = mSettings.mPackages.get(packageName); 20055 if (ps != null) { 20056 ps.setCeDataInode(ceDataInode, userId); 20057 } 20058 } 20059 } catch (InstallerException e) { 20060 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20061 } 20062 } 20063 20064 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20065 } 20066 20067 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20068 if (pkg == null) { 20069 Slog.wtf(TAG, "Package was null!", new Throwable()); 20070 return; 20071 } 20072 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20073 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20074 for (int i = 0; i < childCount; i++) { 20075 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20076 } 20077 } 20078 20079 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20080 final String volumeUuid = pkg.volumeUuid; 20081 final String packageName = pkg.packageName; 20082 final ApplicationInfo app = pkg.applicationInfo; 20083 20084 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20085 // Create a native library symlink only if we have native libraries 20086 // and if the native libraries are 32 bit libraries. We do not provide 20087 // this symlink for 64 bit libraries. 20088 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20089 final String nativeLibPath = app.nativeLibraryDir; 20090 try { 20091 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20092 nativeLibPath, userId); 20093 } catch (InstallerException e) { 20094 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20095 } 20096 } 20097 } 20098 } 20099 20100 /** 20101 * For system apps on non-FBE devices, this method migrates any existing 20102 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20103 * requested by the app. 20104 */ 20105 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20106 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20107 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20108 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20109 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20110 try { 20111 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20112 storageTarget); 20113 } catch (InstallerException e) { 20114 logCriticalInfo(Log.WARN, 20115 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20116 } 20117 return true; 20118 } else { 20119 return false; 20120 } 20121 } 20122 20123 public PackageFreezer freezePackage(String packageName, String killReason) { 20124 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20125 } 20126 20127 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20128 return new PackageFreezer(packageName, userId, killReason); 20129 } 20130 20131 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20132 String killReason) { 20133 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20134 } 20135 20136 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20137 String killReason) { 20138 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20139 return new PackageFreezer(); 20140 } else { 20141 return freezePackage(packageName, userId, killReason); 20142 } 20143 } 20144 20145 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20146 String killReason) { 20147 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20148 } 20149 20150 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20151 String killReason) { 20152 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20153 return new PackageFreezer(); 20154 } else { 20155 return freezePackage(packageName, userId, killReason); 20156 } 20157 } 20158 20159 /** 20160 * Class that freezes and kills the given package upon creation, and 20161 * unfreezes it upon closing. This is typically used when doing surgery on 20162 * app code/data to prevent the app from running while you're working. 20163 */ 20164 private class PackageFreezer implements AutoCloseable { 20165 private final String mPackageName; 20166 private final PackageFreezer[] mChildren; 20167 20168 private final boolean mWeFroze; 20169 20170 private final AtomicBoolean mClosed = new AtomicBoolean(); 20171 private final CloseGuard mCloseGuard = CloseGuard.get(); 20172 20173 /** 20174 * Create and return a stub freezer that doesn't actually do anything, 20175 * typically used when someone requested 20176 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20177 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20178 */ 20179 public PackageFreezer() { 20180 mPackageName = null; 20181 mChildren = null; 20182 mWeFroze = false; 20183 mCloseGuard.open("close"); 20184 } 20185 20186 public PackageFreezer(String packageName, int userId, String killReason) { 20187 synchronized (mPackages) { 20188 mPackageName = packageName; 20189 mWeFroze = mFrozenPackages.add(mPackageName); 20190 20191 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20192 if (ps != null) { 20193 killApplication(ps.name, ps.appId, userId, killReason); 20194 } 20195 20196 final PackageParser.Package p = mPackages.get(packageName); 20197 if (p != null && p.childPackages != null) { 20198 final int N = p.childPackages.size(); 20199 mChildren = new PackageFreezer[N]; 20200 for (int i = 0; i < N; i++) { 20201 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20202 userId, killReason); 20203 } 20204 } else { 20205 mChildren = null; 20206 } 20207 } 20208 mCloseGuard.open("close"); 20209 } 20210 20211 @Override 20212 protected void finalize() throws Throwable { 20213 try { 20214 mCloseGuard.warnIfOpen(); 20215 close(); 20216 } finally { 20217 super.finalize(); 20218 } 20219 } 20220 20221 @Override 20222 public void close() { 20223 mCloseGuard.close(); 20224 if (mClosed.compareAndSet(false, true)) { 20225 synchronized (mPackages) { 20226 if (mWeFroze) { 20227 mFrozenPackages.remove(mPackageName); 20228 } 20229 20230 if (mChildren != null) { 20231 for (PackageFreezer freezer : mChildren) { 20232 freezer.close(); 20233 } 20234 } 20235 } 20236 } 20237 } 20238 } 20239 20240 /** 20241 * Verify that given package is currently frozen. 20242 */ 20243 private void checkPackageFrozen(String packageName) { 20244 synchronized (mPackages) { 20245 if (!mFrozenPackages.contains(packageName)) { 20246 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20247 } 20248 } 20249 } 20250 20251 @Override 20252 public int movePackage(final String packageName, final String volumeUuid) { 20253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20254 20255 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20256 final int moveId = mNextMoveId.getAndIncrement(); 20257 mHandler.post(new Runnable() { 20258 @Override 20259 public void run() { 20260 try { 20261 movePackageInternal(packageName, volumeUuid, moveId, user); 20262 } catch (PackageManagerException e) { 20263 Slog.w(TAG, "Failed to move " + packageName, e); 20264 mMoveCallbacks.notifyStatusChanged(moveId, 20265 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20266 } 20267 } 20268 }); 20269 return moveId; 20270 } 20271 20272 private void movePackageInternal(final String packageName, final String volumeUuid, 20273 final int moveId, UserHandle user) throws PackageManagerException { 20274 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20275 final PackageManager pm = mContext.getPackageManager(); 20276 20277 final boolean currentAsec; 20278 final String currentVolumeUuid; 20279 final File codeFile; 20280 final String installerPackageName; 20281 final String packageAbiOverride; 20282 final int appId; 20283 final String seinfo; 20284 final String label; 20285 final int targetSdkVersion; 20286 final PackageFreezer freezer; 20287 final int[] installedUserIds; 20288 20289 // reader 20290 synchronized (mPackages) { 20291 final PackageParser.Package pkg = mPackages.get(packageName); 20292 final PackageSetting ps = mSettings.mPackages.get(packageName); 20293 if (pkg == null || ps == null) { 20294 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20295 } 20296 20297 if (pkg.applicationInfo.isSystemApp()) { 20298 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20299 "Cannot move system application"); 20300 } 20301 20302 if (pkg.applicationInfo.isExternalAsec()) { 20303 currentAsec = true; 20304 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20305 } else if (pkg.applicationInfo.isForwardLocked()) { 20306 currentAsec = true; 20307 currentVolumeUuid = "forward_locked"; 20308 } else { 20309 currentAsec = false; 20310 currentVolumeUuid = ps.volumeUuid; 20311 20312 final File probe = new File(pkg.codePath); 20313 final File probeOat = new File(probe, "oat"); 20314 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20315 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20316 "Move only supported for modern cluster style installs"); 20317 } 20318 } 20319 20320 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20321 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20322 "Package already moved to " + volumeUuid); 20323 } 20324 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20325 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20326 "Device admin cannot be moved"); 20327 } 20328 20329 if (mFrozenPackages.contains(packageName)) { 20330 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20331 "Failed to move already frozen package"); 20332 } 20333 20334 codeFile = new File(pkg.codePath); 20335 installerPackageName = ps.installerPackageName; 20336 packageAbiOverride = ps.cpuAbiOverrideString; 20337 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20338 seinfo = pkg.applicationInfo.seinfo; 20339 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20340 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20341 freezer = freezePackage(packageName, "movePackageInternal"); 20342 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20343 } 20344 20345 final Bundle extras = new Bundle(); 20346 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20347 extras.putString(Intent.EXTRA_TITLE, label); 20348 mMoveCallbacks.notifyCreated(moveId, extras); 20349 20350 int installFlags; 20351 final boolean moveCompleteApp; 20352 final File measurePath; 20353 20354 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20355 installFlags = INSTALL_INTERNAL; 20356 moveCompleteApp = !currentAsec; 20357 measurePath = Environment.getDataAppDirectory(volumeUuid); 20358 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20359 installFlags = INSTALL_EXTERNAL; 20360 moveCompleteApp = false; 20361 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20362 } else { 20363 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20364 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20365 || !volume.isMountedWritable()) { 20366 freezer.close(); 20367 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20368 "Move location not mounted private volume"); 20369 } 20370 20371 Preconditions.checkState(!currentAsec); 20372 20373 installFlags = INSTALL_INTERNAL; 20374 moveCompleteApp = true; 20375 measurePath = Environment.getDataAppDirectory(volumeUuid); 20376 } 20377 20378 final PackageStats stats = new PackageStats(null, -1); 20379 synchronized (mInstaller) { 20380 for (int userId : installedUserIds) { 20381 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20382 freezer.close(); 20383 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20384 "Failed to measure package size"); 20385 } 20386 } 20387 } 20388 20389 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20390 + stats.dataSize); 20391 20392 final long startFreeBytes = measurePath.getFreeSpace(); 20393 final long sizeBytes; 20394 if (moveCompleteApp) { 20395 sizeBytes = stats.codeSize + stats.dataSize; 20396 } else { 20397 sizeBytes = stats.codeSize; 20398 } 20399 20400 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20401 freezer.close(); 20402 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20403 "Not enough free space to move"); 20404 } 20405 20406 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20407 20408 final CountDownLatch installedLatch = new CountDownLatch(1); 20409 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20410 @Override 20411 public void onUserActionRequired(Intent intent) throws RemoteException { 20412 throw new IllegalStateException(); 20413 } 20414 20415 @Override 20416 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20417 Bundle extras) throws RemoteException { 20418 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20419 + PackageManager.installStatusToString(returnCode, msg)); 20420 20421 installedLatch.countDown(); 20422 freezer.close(); 20423 20424 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20425 switch (status) { 20426 case PackageInstaller.STATUS_SUCCESS: 20427 mMoveCallbacks.notifyStatusChanged(moveId, 20428 PackageManager.MOVE_SUCCEEDED); 20429 break; 20430 case PackageInstaller.STATUS_FAILURE_STORAGE: 20431 mMoveCallbacks.notifyStatusChanged(moveId, 20432 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20433 break; 20434 default: 20435 mMoveCallbacks.notifyStatusChanged(moveId, 20436 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20437 break; 20438 } 20439 } 20440 }; 20441 20442 final MoveInfo move; 20443 if (moveCompleteApp) { 20444 // Kick off a thread to report progress estimates 20445 new Thread() { 20446 @Override 20447 public void run() { 20448 while (true) { 20449 try { 20450 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20451 break; 20452 } 20453 } catch (InterruptedException ignored) { 20454 } 20455 20456 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20457 final int progress = 10 + (int) MathUtils.constrain( 20458 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20459 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20460 } 20461 } 20462 }.start(); 20463 20464 final String dataAppName = codeFile.getName(); 20465 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20466 dataAppName, appId, seinfo, targetSdkVersion); 20467 } else { 20468 move = null; 20469 } 20470 20471 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20472 20473 final Message msg = mHandler.obtainMessage(INIT_COPY); 20474 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20475 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20476 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20477 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20478 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20479 msg.obj = params; 20480 20481 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20482 System.identityHashCode(msg.obj)); 20483 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20484 System.identityHashCode(msg.obj)); 20485 20486 mHandler.sendMessage(msg); 20487 } 20488 20489 @Override 20490 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20491 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20492 20493 final int realMoveId = mNextMoveId.getAndIncrement(); 20494 final Bundle extras = new Bundle(); 20495 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20496 mMoveCallbacks.notifyCreated(realMoveId, extras); 20497 20498 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20499 @Override 20500 public void onCreated(int moveId, Bundle extras) { 20501 // Ignored 20502 } 20503 20504 @Override 20505 public void onStatusChanged(int moveId, int status, long estMillis) { 20506 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20507 } 20508 }; 20509 20510 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20511 storage.setPrimaryStorageUuid(volumeUuid, callback); 20512 return realMoveId; 20513 } 20514 20515 @Override 20516 public int getMoveStatus(int moveId) { 20517 mContext.enforceCallingOrSelfPermission( 20518 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20519 return mMoveCallbacks.mLastStatus.get(moveId); 20520 } 20521 20522 @Override 20523 public void registerMoveCallback(IPackageMoveObserver callback) { 20524 mContext.enforceCallingOrSelfPermission( 20525 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20526 mMoveCallbacks.register(callback); 20527 } 20528 20529 @Override 20530 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20531 mContext.enforceCallingOrSelfPermission( 20532 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20533 mMoveCallbacks.unregister(callback); 20534 } 20535 20536 @Override 20537 public boolean setInstallLocation(int loc) { 20538 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20539 null); 20540 if (getInstallLocation() == loc) { 20541 return true; 20542 } 20543 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20544 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20545 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20546 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20547 return true; 20548 } 20549 return false; 20550 } 20551 20552 @Override 20553 public int getInstallLocation() { 20554 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20555 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20556 PackageHelper.APP_INSTALL_AUTO); 20557 } 20558 20559 /** Called by UserManagerService */ 20560 void cleanUpUser(UserManagerService userManager, int userHandle) { 20561 synchronized (mPackages) { 20562 mDirtyUsers.remove(userHandle); 20563 mUserNeedsBadging.delete(userHandle); 20564 mSettings.removeUserLPw(userHandle); 20565 mPendingBroadcasts.remove(userHandle); 20566 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20567 removeUnusedPackagesLPw(userManager, userHandle); 20568 } 20569 } 20570 20571 /** 20572 * We're removing userHandle and would like to remove any downloaded packages 20573 * that are no longer in use by any other user. 20574 * @param userHandle the user being removed 20575 */ 20576 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20577 final boolean DEBUG_CLEAN_APKS = false; 20578 int [] users = userManager.getUserIds(); 20579 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20580 while (psit.hasNext()) { 20581 PackageSetting ps = psit.next(); 20582 if (ps.pkg == null) { 20583 continue; 20584 } 20585 final String packageName = ps.pkg.packageName; 20586 // Skip over if system app 20587 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20588 continue; 20589 } 20590 if (DEBUG_CLEAN_APKS) { 20591 Slog.i(TAG, "Checking package " + packageName); 20592 } 20593 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20594 if (keep) { 20595 if (DEBUG_CLEAN_APKS) { 20596 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20597 } 20598 } else { 20599 for (int i = 0; i < users.length; i++) { 20600 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20601 keep = true; 20602 if (DEBUG_CLEAN_APKS) { 20603 Slog.i(TAG, " Keeping package " + packageName + " for user " 20604 + users[i]); 20605 } 20606 break; 20607 } 20608 } 20609 } 20610 if (!keep) { 20611 if (DEBUG_CLEAN_APKS) { 20612 Slog.i(TAG, " Removing package " + packageName); 20613 } 20614 mHandler.post(new Runnable() { 20615 public void run() { 20616 deletePackageX(packageName, userHandle, 0); 20617 } //end run 20618 }); 20619 } 20620 } 20621 } 20622 20623 /** Called by UserManagerService */ 20624 void createNewUser(int userId) { 20625 synchronized (mInstallLock) { 20626 mSettings.createNewUserLI(this, mInstaller, userId); 20627 } 20628 synchronized (mPackages) { 20629 scheduleWritePackageRestrictionsLocked(userId); 20630 scheduleWritePackageListLocked(userId); 20631 applyFactoryDefaultBrowserLPw(userId); 20632 primeDomainVerificationsLPw(userId); 20633 } 20634 } 20635 20636 void onNewUserCreated(final int userId) { 20637 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20638 // If permission review for legacy apps is required, we represent 20639 // dagerous permissions for such apps as always granted runtime 20640 // permissions to keep per user flag state whether review is needed. 20641 // Hence, if a new user is added we have to propagate dangerous 20642 // permission grants for these legacy apps. 20643 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) { 20644 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20645 | UPDATE_PERMISSIONS_REPLACE_ALL); 20646 } 20647 } 20648 20649 @Override 20650 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20651 mContext.enforceCallingOrSelfPermission( 20652 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20653 "Only package verification agents can read the verifier device identity"); 20654 20655 synchronized (mPackages) { 20656 return mSettings.getVerifierDeviceIdentityLPw(); 20657 } 20658 } 20659 20660 @Override 20661 public void setPermissionEnforced(String permission, boolean enforced) { 20662 // TODO: Now that we no longer change GID for storage, this should to away. 20663 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20664 "setPermissionEnforced"); 20665 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20666 synchronized (mPackages) { 20667 if (mSettings.mReadExternalStorageEnforced == null 20668 || mSettings.mReadExternalStorageEnforced != enforced) { 20669 mSettings.mReadExternalStorageEnforced = enforced; 20670 mSettings.writeLPr(); 20671 } 20672 } 20673 // kill any non-foreground processes so we restart them and 20674 // grant/revoke the GID. 20675 final IActivityManager am = ActivityManagerNative.getDefault(); 20676 if (am != null) { 20677 final long token = Binder.clearCallingIdentity(); 20678 try { 20679 am.killProcessesBelowForeground("setPermissionEnforcement"); 20680 } catch (RemoteException e) { 20681 } finally { 20682 Binder.restoreCallingIdentity(token); 20683 } 20684 } 20685 } else { 20686 throw new IllegalArgumentException("No selective enforcement for " + permission); 20687 } 20688 } 20689 20690 @Override 20691 @Deprecated 20692 public boolean isPermissionEnforced(String permission) { 20693 return true; 20694 } 20695 20696 @Override 20697 public boolean isStorageLow() { 20698 final long token = Binder.clearCallingIdentity(); 20699 try { 20700 final DeviceStorageMonitorInternal 20701 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20702 if (dsm != null) { 20703 return dsm.isMemoryLow(); 20704 } else { 20705 return false; 20706 } 20707 } finally { 20708 Binder.restoreCallingIdentity(token); 20709 } 20710 } 20711 20712 @Override 20713 public IPackageInstaller getPackageInstaller() { 20714 return mInstallerService; 20715 } 20716 20717 private boolean userNeedsBadging(int userId) { 20718 int index = mUserNeedsBadging.indexOfKey(userId); 20719 if (index < 0) { 20720 final UserInfo userInfo; 20721 final long token = Binder.clearCallingIdentity(); 20722 try { 20723 userInfo = sUserManager.getUserInfo(userId); 20724 } finally { 20725 Binder.restoreCallingIdentity(token); 20726 } 20727 final boolean b; 20728 if (userInfo != null && userInfo.isManagedProfile()) { 20729 b = true; 20730 } else { 20731 b = false; 20732 } 20733 mUserNeedsBadging.put(userId, b); 20734 return b; 20735 } 20736 return mUserNeedsBadging.valueAt(index); 20737 } 20738 20739 @Override 20740 public KeySet getKeySetByAlias(String packageName, String alias) { 20741 if (packageName == null || alias == null) { 20742 return null; 20743 } 20744 synchronized(mPackages) { 20745 final PackageParser.Package pkg = mPackages.get(packageName); 20746 if (pkg == null) { 20747 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20748 throw new IllegalArgumentException("Unknown package: " + packageName); 20749 } 20750 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20751 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20752 } 20753 } 20754 20755 @Override 20756 public KeySet getSigningKeySet(String packageName) { 20757 if (packageName == null) { 20758 return null; 20759 } 20760 synchronized(mPackages) { 20761 final PackageParser.Package pkg = mPackages.get(packageName); 20762 if (pkg == null) { 20763 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20764 throw new IllegalArgumentException("Unknown package: " + packageName); 20765 } 20766 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20767 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20768 throw new SecurityException("May not access signing KeySet of other apps."); 20769 } 20770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20771 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20772 } 20773 } 20774 20775 @Override 20776 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20777 if (packageName == null || ks == null) { 20778 return false; 20779 } 20780 synchronized(mPackages) { 20781 final PackageParser.Package pkg = mPackages.get(packageName); 20782 if (pkg == null) { 20783 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20784 throw new IllegalArgumentException("Unknown package: " + packageName); 20785 } 20786 IBinder ksh = ks.getToken(); 20787 if (ksh instanceof KeySetHandle) { 20788 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20789 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20790 } 20791 return false; 20792 } 20793 } 20794 20795 @Override 20796 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20797 if (packageName == null || ks == null) { 20798 return false; 20799 } 20800 synchronized(mPackages) { 20801 final PackageParser.Package pkg = mPackages.get(packageName); 20802 if (pkg == null) { 20803 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20804 throw new IllegalArgumentException("Unknown package: " + packageName); 20805 } 20806 IBinder ksh = ks.getToken(); 20807 if (ksh instanceof KeySetHandle) { 20808 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20809 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20810 } 20811 return false; 20812 } 20813 } 20814 20815 private void deletePackageIfUnusedLPr(final String packageName) { 20816 PackageSetting ps = mSettings.mPackages.get(packageName); 20817 if (ps == null) { 20818 return; 20819 } 20820 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20821 // TODO Implement atomic delete if package is unused 20822 // It is currently possible that the package will be deleted even if it is installed 20823 // after this method returns. 20824 mHandler.post(new Runnable() { 20825 public void run() { 20826 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20827 } 20828 }); 20829 } 20830 } 20831 20832 /** 20833 * Check and throw if the given before/after packages would be considered a 20834 * downgrade. 20835 */ 20836 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20837 throws PackageManagerException { 20838 if (after.versionCode < before.mVersionCode) { 20839 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20840 "Update version code " + after.versionCode + " is older than current " 20841 + before.mVersionCode); 20842 } else if (after.versionCode == before.mVersionCode) { 20843 if (after.baseRevisionCode < before.baseRevisionCode) { 20844 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20845 "Update base revision code " + after.baseRevisionCode 20846 + " is older than current " + before.baseRevisionCode); 20847 } 20848 20849 if (!ArrayUtils.isEmpty(after.splitNames)) { 20850 for (int i = 0; i < after.splitNames.length; i++) { 20851 final String splitName = after.splitNames[i]; 20852 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20853 if (j != -1) { 20854 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20855 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20856 "Update split " + splitName + " revision code " 20857 + after.splitRevisionCodes[i] + " is older than current " 20858 + before.splitRevisionCodes[j]); 20859 } 20860 } 20861 } 20862 } 20863 } 20864 } 20865 20866 private static class MoveCallbacks extends Handler { 20867 private static final int MSG_CREATED = 1; 20868 private static final int MSG_STATUS_CHANGED = 2; 20869 20870 private final RemoteCallbackList<IPackageMoveObserver> 20871 mCallbacks = new RemoteCallbackList<>(); 20872 20873 private final SparseIntArray mLastStatus = new SparseIntArray(); 20874 20875 public MoveCallbacks(Looper looper) { 20876 super(looper); 20877 } 20878 20879 public void register(IPackageMoveObserver callback) { 20880 mCallbacks.register(callback); 20881 } 20882 20883 public void unregister(IPackageMoveObserver callback) { 20884 mCallbacks.unregister(callback); 20885 } 20886 20887 @Override 20888 public void handleMessage(Message msg) { 20889 final SomeArgs args = (SomeArgs) msg.obj; 20890 final int n = mCallbacks.beginBroadcast(); 20891 for (int i = 0; i < n; i++) { 20892 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20893 try { 20894 invokeCallback(callback, msg.what, args); 20895 } catch (RemoteException ignored) { 20896 } 20897 } 20898 mCallbacks.finishBroadcast(); 20899 args.recycle(); 20900 } 20901 20902 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20903 throws RemoteException { 20904 switch (what) { 20905 case MSG_CREATED: { 20906 callback.onCreated(args.argi1, (Bundle) args.arg2); 20907 break; 20908 } 20909 case MSG_STATUS_CHANGED: { 20910 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20911 break; 20912 } 20913 } 20914 } 20915 20916 private void notifyCreated(int moveId, Bundle extras) { 20917 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20918 20919 final SomeArgs args = SomeArgs.obtain(); 20920 args.argi1 = moveId; 20921 args.arg2 = extras; 20922 obtainMessage(MSG_CREATED, args).sendToTarget(); 20923 } 20924 20925 private void notifyStatusChanged(int moveId, int status) { 20926 notifyStatusChanged(moveId, status, -1); 20927 } 20928 20929 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20930 Slog.v(TAG, "Move " + moveId + " status " + status); 20931 20932 final SomeArgs args = SomeArgs.obtain(); 20933 args.argi1 = moveId; 20934 args.argi2 = status; 20935 args.arg3 = estMillis; 20936 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20937 20938 synchronized (mLastStatus) { 20939 mLastStatus.put(moveId, status); 20940 } 20941 } 20942 } 20943 20944 private final static class OnPermissionChangeListeners extends Handler { 20945 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20946 20947 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20948 new RemoteCallbackList<>(); 20949 20950 public OnPermissionChangeListeners(Looper looper) { 20951 super(looper); 20952 } 20953 20954 @Override 20955 public void handleMessage(Message msg) { 20956 switch (msg.what) { 20957 case MSG_ON_PERMISSIONS_CHANGED: { 20958 final int uid = msg.arg1; 20959 handleOnPermissionsChanged(uid); 20960 } break; 20961 } 20962 } 20963 20964 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20965 mPermissionListeners.register(listener); 20966 20967 } 20968 20969 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20970 mPermissionListeners.unregister(listener); 20971 } 20972 20973 public void onPermissionsChanged(int uid) { 20974 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20975 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20976 } 20977 } 20978 20979 private void handleOnPermissionsChanged(int uid) { 20980 final int count = mPermissionListeners.beginBroadcast(); 20981 try { 20982 for (int i = 0; i < count; i++) { 20983 IOnPermissionsChangeListener callback = mPermissionListeners 20984 .getBroadcastItem(i); 20985 try { 20986 callback.onPermissionsChanged(uid); 20987 } catch (RemoteException e) { 20988 Log.e(TAG, "Permission listener is dead", e); 20989 } 20990 } 20991 } finally { 20992 mPermissionListeners.finishBroadcast(); 20993 } 20994 } 20995 } 20996 20997 private class PackageManagerInternalImpl extends PackageManagerInternal { 20998 @Override 20999 public void setLocationPackagesProvider(PackagesProvider provider) { 21000 synchronized (mPackages) { 21001 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21002 } 21003 } 21004 21005 @Override 21006 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21007 synchronized (mPackages) { 21008 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21009 } 21010 } 21011 21012 @Override 21013 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21014 synchronized (mPackages) { 21015 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21016 } 21017 } 21018 21019 @Override 21020 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21021 synchronized (mPackages) { 21022 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21023 } 21024 } 21025 21026 @Override 21027 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21028 synchronized (mPackages) { 21029 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21030 } 21031 } 21032 21033 @Override 21034 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21035 synchronized (mPackages) { 21036 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21037 } 21038 } 21039 21040 @Override 21041 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21042 synchronized (mPackages) { 21043 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21044 packageName, userId); 21045 } 21046 } 21047 21048 @Override 21049 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21050 synchronized (mPackages) { 21051 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21052 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21053 packageName, userId); 21054 } 21055 } 21056 21057 @Override 21058 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21059 synchronized (mPackages) { 21060 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21061 packageName, userId); 21062 } 21063 } 21064 21065 @Override 21066 public void setKeepUninstalledPackages(final List<String> packageList) { 21067 Preconditions.checkNotNull(packageList); 21068 List<String> removedFromList = null; 21069 synchronized (mPackages) { 21070 if (mKeepUninstalledPackages != null) { 21071 final int packagesCount = mKeepUninstalledPackages.size(); 21072 for (int i = 0; i < packagesCount; i++) { 21073 String oldPackage = mKeepUninstalledPackages.get(i); 21074 if (packageList != null && packageList.contains(oldPackage)) { 21075 continue; 21076 } 21077 if (removedFromList == null) { 21078 removedFromList = new ArrayList<>(); 21079 } 21080 removedFromList.add(oldPackage); 21081 } 21082 } 21083 mKeepUninstalledPackages = new ArrayList<>(packageList); 21084 if (removedFromList != null) { 21085 final int removedCount = removedFromList.size(); 21086 for (int i = 0; i < removedCount; i++) { 21087 deletePackageIfUnusedLPr(removedFromList.get(i)); 21088 } 21089 } 21090 } 21091 } 21092 21093 @Override 21094 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21095 synchronized (mPackages) { 21096 // If we do not support permission review, done. 21097 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) { 21098 return false; 21099 } 21100 21101 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21102 if (packageSetting == null) { 21103 return false; 21104 } 21105 21106 // Permission review applies only to apps not supporting the new permission model. 21107 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21108 return false; 21109 } 21110 21111 // Legacy apps have the permission and get user consent on launch. 21112 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21113 return permissionsState.isPermissionReviewRequired(userId); 21114 } 21115 } 21116 21117 @Override 21118 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21119 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21120 } 21121 21122 @Override 21123 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21124 int userId) { 21125 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21126 } 21127 21128 @Override 21129 public void setDeviceAndProfileOwnerPackages( 21130 int deviceOwnerUserId, String deviceOwnerPackage, 21131 SparseArray<String> profileOwnerPackages) { 21132 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21133 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21134 } 21135 21136 @Override 21137 public boolean isPackageDataProtected(int userId, String packageName) { 21138 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21139 } 21140 21141 @Override 21142 public boolean wasPackageEverLaunched(String packageName, int userId) { 21143 synchronized (mPackages) { 21144 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21145 } 21146 } 21147 } 21148 21149 @Override 21150 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21151 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21152 synchronized (mPackages) { 21153 final long identity = Binder.clearCallingIdentity(); 21154 try { 21155 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21156 packageNames, userId); 21157 } finally { 21158 Binder.restoreCallingIdentity(identity); 21159 } 21160 } 21161 } 21162 21163 private static void enforceSystemOrPhoneCaller(String tag) { 21164 int callingUid = Binder.getCallingUid(); 21165 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21166 throw new SecurityException( 21167 "Cannot call " + tag + " from UID " + callingUid); 21168 } 21169 } 21170 21171 boolean isHistoricalPackageUsageAvailable() { 21172 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21173 } 21174 21175 /** 21176 * Return a <b>copy</b> of the collection of packages known to the package manager. 21177 * @return A copy of the values of mPackages. 21178 */ 21179 Collection<PackageParser.Package> getPackages() { 21180 synchronized (mPackages) { 21181 return new ArrayList<>(mPackages.values()); 21182 } 21183 } 21184 21185 /** 21186 * Logs process start information (including base APK hash) to the security log. 21187 * @hide 21188 */ 21189 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21190 String apkFile, int pid) { 21191 if (!SecurityLog.isLoggingEnabled()) { 21192 return; 21193 } 21194 Bundle data = new Bundle(); 21195 data.putLong("startTimestamp", System.currentTimeMillis()); 21196 data.putString("processName", processName); 21197 data.putInt("uid", uid); 21198 data.putString("seinfo", seinfo); 21199 data.putString("apkFile", apkFile); 21200 data.putInt("pid", pid); 21201 Message msg = mProcessLoggingHandler.obtainMessage( 21202 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21203 msg.setData(data); 21204 mProcessLoggingHandler.sendMessage(msg); 21205 } 21206 21207 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21208 return mCompilerStats.getPackageStats(pkgName); 21209 } 21210 21211 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21212 return getOrCreateCompilerPackageStats(pkg.packageName); 21213 } 21214 21215 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21216 return mCompilerStats.getOrCreatePackageStats(pkgName); 21217 } 21218 21219 public void deleteCompilerPackageStats(String pkgName) { 21220 mCompilerStats.deletePackageStats(pkgName); 21221 } 21222} 21223