PackageManagerService.java revision c24fa029bf9a2ee3c3657cb598e1595262ad2eeb
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_SKU_PROPERTY is set, search for runtime resource overlay APKs in 468 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in 469 * VENDOR_OVERLAY_DIR. 470 */ 471 private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku"; 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 private final PackageUsage mPackageUsage = new PackageUsage(); 1144 private final CompilerStats mCompilerStats = new CompilerStats(); 1145 1146 class PackageHandler extends Handler { 1147 private boolean mBound = false; 1148 final ArrayList<HandlerParams> mPendingInstalls = 1149 new ArrayList<HandlerParams>(); 1150 1151 private boolean connectToService() { 1152 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1153 " DefaultContainerService"); 1154 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1155 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1156 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1157 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1158 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1159 mBound = true; 1160 return true; 1161 } 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1163 return false; 1164 } 1165 1166 private void disconnectService() { 1167 mContainerService = null; 1168 mBound = false; 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1170 mContext.unbindService(mDefContainerConn); 1171 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1172 } 1173 1174 PackageHandler(Looper looper) { 1175 super(looper); 1176 } 1177 1178 public void handleMessage(Message msg) { 1179 try { 1180 doHandleMessage(msg); 1181 } finally { 1182 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1183 } 1184 } 1185 1186 void doHandleMessage(Message msg) { 1187 switch (msg.what) { 1188 case INIT_COPY: { 1189 HandlerParams params = (HandlerParams) msg.obj; 1190 int idx = mPendingInstalls.size(); 1191 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1192 // If a bind was already initiated we dont really 1193 // need to do anything. The pending install 1194 // will be processed later on. 1195 if (!mBound) { 1196 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1197 System.identityHashCode(mHandler)); 1198 // If this is the only one pending we might 1199 // have to bind to the service again. 1200 if (!connectToService()) { 1201 Slog.e(TAG, "Failed to bind to media container service"); 1202 params.serviceError(); 1203 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1204 System.identityHashCode(mHandler)); 1205 if (params.traceMethod != null) { 1206 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1207 params.traceCookie); 1208 } 1209 return; 1210 } else { 1211 // Once we bind to the service, the first 1212 // pending request will be processed. 1213 mPendingInstalls.add(idx, params); 1214 } 1215 } else { 1216 mPendingInstalls.add(idx, params); 1217 // Already bound to the service. Just make 1218 // sure we trigger off processing the first request. 1219 if (idx == 0) { 1220 mHandler.sendEmptyMessage(MCS_BOUND); 1221 } 1222 } 1223 break; 1224 } 1225 case MCS_BOUND: { 1226 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1227 if (msg.obj != null) { 1228 mContainerService = (IMediaContainerService) msg.obj; 1229 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1230 System.identityHashCode(mHandler)); 1231 } 1232 if (mContainerService == null) { 1233 if (!mBound) { 1234 // Something seriously wrong since we are not bound and we are not 1235 // waiting for connection. Bail out. 1236 Slog.e(TAG, "Cannot bind to media container service"); 1237 for (HandlerParams params : mPendingInstalls) { 1238 // Indicate service bind error 1239 params.serviceError(); 1240 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1241 System.identityHashCode(params)); 1242 if (params.traceMethod != null) { 1243 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1244 params.traceMethod, params.traceCookie); 1245 } 1246 return; 1247 } 1248 mPendingInstalls.clear(); 1249 } else { 1250 Slog.w(TAG, "Waiting to connect to media container service"); 1251 } 1252 } else if (mPendingInstalls.size() > 0) { 1253 HandlerParams params = mPendingInstalls.get(0); 1254 if (params != null) { 1255 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1256 System.identityHashCode(params)); 1257 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1258 if (params.startCopy()) { 1259 // We are done... look for more work or to 1260 // go idle. 1261 if (DEBUG_SD_INSTALL) Log.i(TAG, 1262 "Checking for more work or unbind..."); 1263 // Delete pending install 1264 if (mPendingInstalls.size() > 0) { 1265 mPendingInstalls.remove(0); 1266 } 1267 if (mPendingInstalls.size() == 0) { 1268 if (mBound) { 1269 if (DEBUG_SD_INSTALL) Log.i(TAG, 1270 "Posting delayed MCS_UNBIND"); 1271 removeMessages(MCS_UNBIND); 1272 Message ubmsg = obtainMessage(MCS_UNBIND); 1273 // Unbind after a little delay, to avoid 1274 // continual thrashing. 1275 sendMessageDelayed(ubmsg, 10000); 1276 } 1277 } else { 1278 // There are more pending requests in queue. 1279 // Just post MCS_BOUND message to trigger processing 1280 // of next pending install. 1281 if (DEBUG_SD_INSTALL) Log.i(TAG, 1282 "Posting MCS_BOUND for next work"); 1283 mHandler.sendEmptyMessage(MCS_BOUND); 1284 } 1285 } 1286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1287 } 1288 } else { 1289 // Should never happen ideally. 1290 Slog.w(TAG, "Empty queue"); 1291 } 1292 break; 1293 } 1294 case MCS_RECONNECT: { 1295 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1296 if (mPendingInstalls.size() > 0) { 1297 if (mBound) { 1298 disconnectService(); 1299 } 1300 if (!connectToService()) { 1301 Slog.e(TAG, "Failed to bind to media container service"); 1302 for (HandlerParams params : mPendingInstalls) { 1303 // Indicate service bind error 1304 params.serviceError(); 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1306 System.identityHashCode(params)); 1307 } 1308 mPendingInstalls.clear(); 1309 } 1310 } 1311 break; 1312 } 1313 case MCS_UNBIND: { 1314 // If there is no actual work left, then time to unbind. 1315 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1316 1317 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1318 if (mBound) { 1319 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1320 1321 disconnectService(); 1322 } 1323 } else if (mPendingInstalls.size() > 0) { 1324 // There are more pending requests in queue. 1325 // Just post MCS_BOUND message to trigger processing 1326 // of next pending install. 1327 mHandler.sendEmptyMessage(MCS_BOUND); 1328 } 1329 1330 break; 1331 } 1332 case MCS_GIVE_UP: { 1333 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1334 HandlerParams params = mPendingInstalls.remove(0); 1335 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1336 System.identityHashCode(params)); 1337 break; 1338 } 1339 case SEND_PENDING_BROADCAST: { 1340 String packages[]; 1341 ArrayList<String> components[]; 1342 int size = 0; 1343 int uids[]; 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1345 synchronized (mPackages) { 1346 if (mPendingBroadcasts == null) { 1347 return; 1348 } 1349 size = mPendingBroadcasts.size(); 1350 if (size <= 0) { 1351 // Nothing to be done. Just return 1352 return; 1353 } 1354 packages = new String[size]; 1355 components = new ArrayList[size]; 1356 uids = new int[size]; 1357 int i = 0; // filling out the above arrays 1358 1359 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1360 int packageUserId = mPendingBroadcasts.userIdAt(n); 1361 Iterator<Map.Entry<String, ArrayList<String>>> it 1362 = mPendingBroadcasts.packagesForUserId(packageUserId) 1363 .entrySet().iterator(); 1364 while (it.hasNext() && i < size) { 1365 Map.Entry<String, ArrayList<String>> ent = it.next(); 1366 packages[i] = ent.getKey(); 1367 components[i] = ent.getValue(); 1368 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1369 uids[i] = (ps != null) 1370 ? UserHandle.getUid(packageUserId, ps.appId) 1371 : -1; 1372 i++; 1373 } 1374 } 1375 size = i; 1376 mPendingBroadcasts.clear(); 1377 } 1378 // Send broadcasts 1379 for (int i = 0; i < size; i++) { 1380 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1381 } 1382 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1383 break; 1384 } 1385 case START_CLEANING_PACKAGE: { 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1387 final String packageName = (String)msg.obj; 1388 final int userId = msg.arg1; 1389 final boolean andCode = msg.arg2 != 0; 1390 synchronized (mPackages) { 1391 if (userId == UserHandle.USER_ALL) { 1392 int[] users = sUserManager.getUserIds(); 1393 for (int user : users) { 1394 mSettings.addPackageToCleanLPw( 1395 new PackageCleanItem(user, packageName, andCode)); 1396 } 1397 } else { 1398 mSettings.addPackageToCleanLPw( 1399 new PackageCleanItem(userId, packageName, andCode)); 1400 } 1401 } 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 startCleaningPackages(); 1404 } break; 1405 case POST_INSTALL: { 1406 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1407 1408 PostInstallData data = mRunningInstalls.get(msg.arg1); 1409 final boolean didRestore = (msg.arg2 != 0); 1410 mRunningInstalls.delete(msg.arg1); 1411 1412 if (data != null) { 1413 InstallArgs args = data.args; 1414 PackageInstalledInfo parentRes = data.res; 1415 1416 final boolean grantPermissions = (args.installFlags 1417 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1418 final boolean killApp = (args.installFlags 1419 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1420 final String[] grantedPermissions = args.installGrantPermissions; 1421 1422 // Handle the parent package 1423 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1424 grantedPermissions, didRestore, args.installerPackageName, 1425 args.observer); 1426 1427 // Handle the child packages 1428 final int childCount = (parentRes.addedChildPackages != null) 1429 ? parentRes.addedChildPackages.size() : 0; 1430 for (int i = 0; i < childCount; i++) { 1431 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1432 handlePackagePostInstall(childRes, grantPermissions, killApp, 1433 grantedPermissions, false, args.installerPackageName, 1434 args.observer); 1435 } 1436 1437 // Log tracing if needed 1438 if (args.traceMethod != null) { 1439 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1440 args.traceCookie); 1441 } 1442 } else { 1443 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1444 } 1445 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1447 } break; 1448 case UPDATED_MEDIA_STATUS: { 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1450 boolean reportStatus = msg.arg1 == 1; 1451 boolean doGc = msg.arg2 == 1; 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1453 if (doGc) { 1454 // Force a gc to clear up stale containers. 1455 Runtime.getRuntime().gc(); 1456 } 1457 if (msg.obj != null) { 1458 @SuppressWarnings("unchecked") 1459 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1461 // Unload containers 1462 unloadAllContainers(args); 1463 } 1464 if (reportStatus) { 1465 try { 1466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1467 PackageHelper.getMountService().finishMediaUpdate(); 1468 } catch (RemoteException e) { 1469 Log.e(TAG, "MountService not running?"); 1470 } 1471 } 1472 } break; 1473 case WRITE_SETTINGS: { 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1475 synchronized (mPackages) { 1476 removeMessages(WRITE_SETTINGS); 1477 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1478 mSettings.writeLPr(); 1479 mDirtyUsers.clear(); 1480 } 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1482 } break; 1483 case WRITE_PACKAGE_RESTRICTIONS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1487 for (int userId : mDirtyUsers) { 1488 mSettings.writePackageRestrictionsLPr(userId); 1489 } 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case WRITE_PACKAGE_LIST: { 1495 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1496 synchronized (mPackages) { 1497 removeMessages(WRITE_PACKAGE_LIST); 1498 mSettings.writePackageListLPr(msg.arg1); 1499 } 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1501 } break; 1502 case CHECK_PENDING_VERIFICATION: { 1503 final int verificationId = msg.arg1; 1504 final PackageVerificationState state = mPendingVerification.get(verificationId); 1505 1506 if ((state != null) && !state.timeoutExtended()) { 1507 final InstallArgs args = state.getInstallArgs(); 1508 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1509 1510 Slog.i(TAG, "Verification timed out for " + originUri); 1511 mPendingVerification.remove(verificationId); 1512 1513 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1514 1515 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1516 Slog.i(TAG, "Continuing with installation of " + originUri); 1517 state.setVerifierResponse(Binder.getCallingUid(), 1518 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1519 broadcastPackageVerified(verificationId, originUri, 1520 PackageManager.VERIFICATION_ALLOW, 1521 state.getInstallArgs().getUser()); 1522 try { 1523 ret = args.copyApk(mContainerService, true); 1524 } catch (RemoteException e) { 1525 Slog.e(TAG, "Could not contact the ContainerService"); 1526 } 1527 } else { 1528 broadcastPackageVerified(verificationId, originUri, 1529 PackageManager.VERIFICATION_REJECT, 1530 state.getInstallArgs().getUser()); 1531 } 1532 1533 Trace.asyncTraceEnd( 1534 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1535 1536 processPendingInstall(args, ret); 1537 mHandler.sendEmptyMessage(MCS_UNBIND); 1538 } 1539 break; 1540 } 1541 case PACKAGE_VERIFIED: { 1542 final int verificationId = msg.arg1; 1543 1544 final PackageVerificationState state = mPendingVerification.get(verificationId); 1545 if (state == null) { 1546 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1547 break; 1548 } 1549 1550 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1551 1552 state.setVerifierResponse(response.callerUid, response.code); 1553 1554 if (state.isVerificationComplete()) { 1555 mPendingVerification.remove(verificationId); 1556 1557 final InstallArgs args = state.getInstallArgs(); 1558 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1559 1560 int ret; 1561 if (state.isInstallAllowed()) { 1562 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1563 broadcastPackageVerified(verificationId, originUri, 1564 response.code, state.getInstallArgs().getUser()); 1565 try { 1566 ret = args.copyApk(mContainerService, true); 1567 } catch (RemoteException e) { 1568 Slog.e(TAG, "Could not contact the ContainerService"); 1569 } 1570 } else { 1571 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1572 } 1573 1574 Trace.asyncTraceEnd( 1575 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1576 1577 processPendingInstall(args, ret); 1578 mHandler.sendEmptyMessage(MCS_UNBIND); 1579 } 1580 1581 break; 1582 } 1583 case START_INTENT_FILTER_VERIFICATIONS: { 1584 IFVerificationParams params = (IFVerificationParams) msg.obj; 1585 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1586 params.replacing, params.pkg); 1587 break; 1588 } 1589 case INTENT_FILTER_VERIFIED: { 1590 final int verificationId = msg.arg1; 1591 1592 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1593 verificationId); 1594 if (state == null) { 1595 Slog.w(TAG, "Invalid IntentFilter verification token " 1596 + verificationId + " received"); 1597 break; 1598 } 1599 1600 final int userId = state.getUserId(); 1601 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1603 "Processing IntentFilter verification with token:" 1604 + verificationId + " and userId:" + userId); 1605 1606 final IntentFilterVerificationResponse response = 1607 (IntentFilterVerificationResponse) msg.obj; 1608 1609 state.setVerifierResponse(response.callerUid, response.code); 1610 1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1612 "IntentFilter verification with token:" + verificationId 1613 + " and userId:" + userId 1614 + " is settings verifier response with response code:" 1615 + response.code); 1616 1617 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1619 + response.getFailedDomainsString()); 1620 } 1621 1622 if (state.isVerificationComplete()) { 1623 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1624 } else { 1625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1626 "IntentFilter verification with token:" + verificationId 1627 + " was not said to be complete"); 1628 } 1629 1630 break; 1631 } 1632 } 1633 } 1634 } 1635 1636 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1637 boolean killApp, String[] grantedPermissions, 1638 boolean launchedForRestore, String installerPackage, 1639 IPackageInstallObserver2 installObserver) { 1640 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1641 // Send the removed broadcasts 1642 if (res.removedInfo != null) { 1643 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1644 } 1645 1646 // Now that we successfully installed the package, grant runtime 1647 // permissions if requested before broadcasting the install. 1648 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1649 >= Build.VERSION_CODES.M) { 1650 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1651 } 1652 1653 final boolean update = res.removedInfo != null 1654 && res.removedInfo.removedPackage != null; 1655 1656 // If this is the first time we have child packages for a disabled privileged 1657 // app that had no children, we grant requested runtime permissions to the new 1658 // children if the parent on the system image had them already granted. 1659 if (res.pkg.parentPackage != null) { 1660 synchronized (mPackages) { 1661 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1662 } 1663 } 1664 1665 synchronized (mPackages) { 1666 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1667 } 1668 1669 final String packageName = res.pkg.applicationInfo.packageName; 1670 Bundle extras = new Bundle(1); 1671 extras.putInt(Intent.EXTRA_UID, res.uid); 1672 1673 // Determine the set of users who are adding this package for 1674 // the first time vs. those who are seeing an update. 1675 int[] firstUsers = EMPTY_INT_ARRAY; 1676 int[] updateUsers = EMPTY_INT_ARRAY; 1677 if (res.origUsers == null || res.origUsers.length == 0) { 1678 firstUsers = res.newUsers; 1679 } else { 1680 for (int newUser : res.newUsers) { 1681 boolean isNew = true; 1682 for (int origUser : res.origUsers) { 1683 if (origUser == newUser) { 1684 isNew = false; 1685 break; 1686 } 1687 } 1688 if (isNew) { 1689 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1690 } else { 1691 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1692 } 1693 } 1694 } 1695 1696 // Send installed broadcasts if the install/update is not ephemeral 1697 if (!isEphemeral(res.pkg)) { 1698 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1699 1700 // Send added for users that see the package for the first time 1701 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1702 extras, 0 /*flags*/, null /*targetPackage*/, 1703 null /*finishedReceiver*/, firstUsers); 1704 1705 // Send added for users that don't see the package for the first time 1706 if (update) { 1707 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1708 } 1709 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1710 extras, 0 /*flags*/, null /*targetPackage*/, 1711 null /*finishedReceiver*/, updateUsers); 1712 1713 // Send replaced for users that don't see the package for the first time 1714 if (update) { 1715 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1716 packageName, extras, 0 /*flags*/, 1717 null /*targetPackage*/, null /*finishedReceiver*/, 1718 updateUsers); 1719 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1720 null /*package*/, null /*extras*/, 0 /*flags*/, 1721 packageName /*targetPackage*/, 1722 null /*finishedReceiver*/, updateUsers); 1723 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1724 // First-install and we did a restore, so we're responsible for the 1725 // first-launch broadcast. 1726 if (DEBUG_BACKUP) { 1727 Slog.i(TAG, "Post-restore of " + packageName 1728 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1729 } 1730 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1731 } 1732 1733 // Send broadcast package appeared if forward locked/external for all users 1734 // treat asec-hosted packages like removable media on upgrade 1735 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1736 if (DEBUG_INSTALL) { 1737 Slog.i(TAG, "upgrading pkg " + res.pkg 1738 + " is ASEC-hosted -> AVAILABLE"); 1739 } 1740 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1741 ArrayList<String> pkgList = new ArrayList<>(1); 1742 pkgList.add(packageName); 1743 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1744 } 1745 } 1746 1747 // Work that needs to happen on first install within each user 1748 if (firstUsers != null && firstUsers.length > 0) { 1749 synchronized (mPackages) { 1750 for (int userId : firstUsers) { 1751 // If this app is a browser and it's newly-installed for some 1752 // users, clear any default-browser state in those users. The 1753 // app's nature doesn't depend on the user, so we can just check 1754 // its browser nature in any user and generalize. 1755 if (packageIsBrowser(packageName, userId)) { 1756 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1757 } 1758 1759 // We may also need to apply pending (restored) runtime 1760 // permission grants within these users. 1761 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1762 } 1763 } 1764 } 1765 1766 // Log current value of "unknown sources" setting 1767 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1768 getUnknownSourcesSettings()); 1769 1770 // Force a gc to clear up things 1771 Runtime.getRuntime().gc(); 1772 1773 // Remove the replaced package's older resources safely now 1774 // We delete after a gc for applications on sdcard. 1775 if (res.removedInfo != null && res.removedInfo.args != null) { 1776 synchronized (mInstallLock) { 1777 res.removedInfo.args.doPostDeleteLI(true); 1778 } 1779 } 1780 } 1781 1782 // If someone is watching installs - notify them 1783 if (installObserver != null) { 1784 try { 1785 Bundle extras = extrasForInstallResult(res); 1786 installObserver.onPackageInstalled(res.name, res.returnCode, 1787 res.returnMsg, extras); 1788 } catch (RemoteException e) { 1789 Slog.i(TAG, "Observer no longer exists."); 1790 } 1791 } 1792 } 1793 1794 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1795 PackageParser.Package pkg) { 1796 if (pkg.parentPackage == null) { 1797 return; 1798 } 1799 if (pkg.requestedPermissions == null) { 1800 return; 1801 } 1802 final PackageSetting disabledSysParentPs = mSettings 1803 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1804 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1805 || !disabledSysParentPs.isPrivileged() 1806 || (disabledSysParentPs.childPackageNames != null 1807 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1808 return; 1809 } 1810 final int[] allUserIds = sUserManager.getUserIds(); 1811 final int permCount = pkg.requestedPermissions.size(); 1812 for (int i = 0; i < permCount; i++) { 1813 String permission = pkg.requestedPermissions.get(i); 1814 BasePermission bp = mSettings.mPermissions.get(permission); 1815 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1816 continue; 1817 } 1818 for (int userId : allUserIds) { 1819 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1820 permission, userId)) { 1821 grantRuntimePermission(pkg.packageName, permission, userId); 1822 } 1823 } 1824 } 1825 } 1826 1827 private StorageEventListener mStorageListener = new StorageEventListener() { 1828 @Override 1829 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1830 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1831 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1832 final String volumeUuid = vol.getFsUuid(); 1833 1834 // Clean up any users or apps that were removed or recreated 1835 // while this volume was missing 1836 reconcileUsers(volumeUuid); 1837 reconcileApps(volumeUuid); 1838 1839 // Clean up any install sessions that expired or were 1840 // cancelled while this volume was missing 1841 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1842 1843 loadPrivatePackages(vol); 1844 1845 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1846 unloadPrivatePackages(vol); 1847 } 1848 } 1849 1850 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1851 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1852 updateExternalMediaStatus(true, false); 1853 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1854 updateExternalMediaStatus(false, false); 1855 } 1856 } 1857 } 1858 1859 @Override 1860 public void onVolumeForgotten(String fsUuid) { 1861 if (TextUtils.isEmpty(fsUuid)) { 1862 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1863 return; 1864 } 1865 1866 // Remove any apps installed on the forgotten volume 1867 synchronized (mPackages) { 1868 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1869 for (PackageSetting ps : packages) { 1870 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1871 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1872 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1873 } 1874 1875 mSettings.onVolumeForgotten(fsUuid); 1876 mSettings.writeLPr(); 1877 } 1878 } 1879 }; 1880 1881 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1882 String[] grantedPermissions) { 1883 for (int userId : userIds) { 1884 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1885 } 1886 1887 // We could have touched GID membership, so flush out packages.list 1888 synchronized (mPackages) { 1889 mSettings.writePackageListLPr(); 1890 } 1891 } 1892 1893 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1894 String[] grantedPermissions) { 1895 SettingBase sb = (SettingBase) pkg.mExtras; 1896 if (sb == null) { 1897 return; 1898 } 1899 1900 PermissionsState permissionsState = sb.getPermissionsState(); 1901 1902 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1903 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1904 1905 for (String permission : pkg.requestedPermissions) { 1906 final BasePermission bp; 1907 synchronized (mPackages) { 1908 bp = mSettings.mPermissions.get(permission); 1909 } 1910 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1911 && (grantedPermissions == null 1912 || ArrayUtils.contains(grantedPermissions, permission))) { 1913 final int flags = permissionsState.getPermissionFlags(permission, userId); 1914 // Installer cannot change immutable permissions. 1915 if ((flags & immutableFlags) == 0) { 1916 grantRuntimePermission(pkg.packageName, permission, userId); 1917 } 1918 } 1919 } 1920 } 1921 1922 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1923 Bundle extras = null; 1924 switch (res.returnCode) { 1925 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1926 extras = new Bundle(); 1927 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1928 res.origPermission); 1929 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1930 res.origPackage); 1931 break; 1932 } 1933 case PackageManager.INSTALL_SUCCEEDED: { 1934 extras = new Bundle(); 1935 extras.putBoolean(Intent.EXTRA_REPLACING, 1936 res.removedInfo != null && res.removedInfo.removedPackage != null); 1937 break; 1938 } 1939 } 1940 return extras; 1941 } 1942 1943 void scheduleWriteSettingsLocked() { 1944 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1945 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1946 } 1947 } 1948 1949 void scheduleWritePackageListLocked(int userId) { 1950 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1951 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1952 msg.arg1 = userId; 1953 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1954 } 1955 } 1956 1957 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1958 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1959 scheduleWritePackageRestrictionsLocked(userId); 1960 } 1961 1962 void scheduleWritePackageRestrictionsLocked(int userId) { 1963 final int[] userIds = (userId == UserHandle.USER_ALL) 1964 ? sUserManager.getUserIds() : new int[]{userId}; 1965 for (int nextUserId : userIds) { 1966 if (!sUserManager.exists(nextUserId)) return; 1967 mDirtyUsers.add(nextUserId); 1968 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1969 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1970 } 1971 } 1972 } 1973 1974 public static PackageManagerService main(Context context, Installer installer, 1975 boolean factoryTest, boolean onlyCore) { 1976 // Self-check for initial settings. 1977 PackageManagerServiceCompilerMapping.checkProperties(); 1978 1979 PackageManagerService m = new PackageManagerService(context, installer, 1980 factoryTest, onlyCore); 1981 m.enableSystemUserPackages(); 1982 ServiceManager.addService("package", m); 1983 return m; 1984 } 1985 1986 private void enableSystemUserPackages() { 1987 if (!UserManager.isSplitSystemUser()) { 1988 return; 1989 } 1990 // For system user, enable apps based on the following conditions: 1991 // - app is whitelisted or belong to one of these groups: 1992 // -- system app which has no launcher icons 1993 // -- system app which has INTERACT_ACROSS_USERS permission 1994 // -- system IME app 1995 // - app is not in the blacklist 1996 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1997 Set<String> enableApps = new ArraySet<>(); 1998 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1999 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2000 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2001 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2002 enableApps.addAll(wlApps); 2003 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2004 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2005 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2006 enableApps.removeAll(blApps); 2007 Log.i(TAG, "Applications installed for system user: " + enableApps); 2008 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2009 UserHandle.SYSTEM); 2010 final int allAppsSize = allAps.size(); 2011 synchronized (mPackages) { 2012 for (int i = 0; i < allAppsSize; i++) { 2013 String pName = allAps.get(i); 2014 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2015 // Should not happen, but we shouldn't be failing if it does 2016 if (pkgSetting == null) { 2017 continue; 2018 } 2019 boolean install = enableApps.contains(pName); 2020 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2021 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2022 + " for system user"); 2023 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2024 } 2025 } 2026 } 2027 } 2028 2029 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2030 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2031 Context.DISPLAY_SERVICE); 2032 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2033 } 2034 2035 /** 2036 * Requests that files preopted on a secondary system partition be copied to the data partition 2037 * if possible. Note that the actual copying of the files is accomplished by init for security 2038 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2039 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2040 */ 2041 private static void requestCopyPreoptedFiles() { 2042 final int WAIT_TIME_MS = 100; 2043 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2044 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2045 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2046 // We will wait for up to 100 seconds. 2047 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2048 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2049 try { 2050 Thread.sleep(WAIT_TIME_MS); 2051 } catch (InterruptedException e) { 2052 // Do nothing 2053 } 2054 if (SystemClock.uptimeMillis() > timeEnd) { 2055 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2056 Slog.wtf(TAG, "cppreopt did not finish!"); 2057 break; 2058 } 2059 } 2060 } 2061 } 2062 2063 public PackageManagerService(Context context, Installer installer, 2064 boolean factoryTest, boolean onlyCore) { 2065 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2066 SystemClock.uptimeMillis()); 2067 2068 if (mSdkVersion <= 0) { 2069 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2070 } 2071 2072 mContext = context; 2073 mFactoryTest = factoryTest; 2074 mOnlyCore = onlyCore; 2075 mMetrics = new DisplayMetrics(); 2076 mSettings = new Settings(mPackages); 2077 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2078 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2079 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2080 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2081 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2082 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2083 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2084 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2085 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2086 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2087 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2088 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2089 2090 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2091 if (separateProcesses != null && separateProcesses.length() > 0) { 2092 if ("*".equals(separateProcesses)) { 2093 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2094 mSeparateProcesses = null; 2095 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2096 } else { 2097 mDefParseFlags = 0; 2098 mSeparateProcesses = separateProcesses.split(","); 2099 Slog.w(TAG, "Running with debug.separate_processes: " 2100 + separateProcesses); 2101 } 2102 } else { 2103 mDefParseFlags = 0; 2104 mSeparateProcesses = null; 2105 } 2106 2107 mInstaller = installer; 2108 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2109 "*dexopt*"); 2110 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2111 2112 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2113 FgThread.get().getLooper()); 2114 2115 getDefaultDisplayMetrics(context, mMetrics); 2116 2117 SystemConfig systemConfig = SystemConfig.getInstance(); 2118 mGlobalGids = systemConfig.getGlobalGids(); 2119 mSystemPermissions = systemConfig.getSystemPermissions(); 2120 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2121 2122 mProtectedPackages = new ProtectedPackages(mContext); 2123 2124 synchronized (mInstallLock) { 2125 // writer 2126 synchronized (mPackages) { 2127 mHandlerThread = new ServiceThread(TAG, 2128 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2129 mHandlerThread.start(); 2130 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2131 mProcessLoggingHandler = new ProcessLoggingHandler(); 2132 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2133 2134 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2135 2136 File dataDir = Environment.getDataDirectory(); 2137 mAppInstallDir = new File(dataDir, "app"); 2138 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2139 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2140 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2141 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2142 2143 sUserManager = new UserManagerService(context, this, mPackages); 2144 2145 // Propagate permission configuration in to package manager. 2146 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2147 = systemConfig.getPermissions(); 2148 for (int i=0; i<permConfig.size(); i++) { 2149 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2150 BasePermission bp = mSettings.mPermissions.get(perm.name); 2151 if (bp == null) { 2152 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2153 mSettings.mPermissions.put(perm.name, bp); 2154 } 2155 if (perm.gids != null) { 2156 bp.setGids(perm.gids, perm.perUser); 2157 } 2158 } 2159 2160 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2161 for (int i=0; i<libConfig.size(); i++) { 2162 mSharedLibraries.put(libConfig.keyAt(i), 2163 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2164 } 2165 2166 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2167 2168 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2169 2170 if (mFirstBoot) { 2171 requestCopyPreoptedFiles(); 2172 } 2173 2174 String customResolverActivity = Resources.getSystem().getString( 2175 R.string.config_customResolverActivity); 2176 if (TextUtils.isEmpty(customResolverActivity)) { 2177 customResolverActivity = null; 2178 } else { 2179 mCustomResolverComponentName = ComponentName.unflattenFromString( 2180 customResolverActivity); 2181 } 2182 2183 long startTime = SystemClock.uptimeMillis(); 2184 2185 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2186 startTime); 2187 2188 // Set flag to monitor and not change apk file paths when 2189 // scanning install directories. 2190 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2191 2192 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2193 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2194 2195 if (bootClassPath == null) { 2196 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2197 } 2198 2199 if (systemServerClassPath == null) { 2200 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2201 } 2202 2203 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2204 final String[] dexCodeInstructionSets = 2205 getDexCodeInstructionSets( 2206 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2207 2208 /** 2209 * Ensure all external libraries have had dexopt run on them. 2210 */ 2211 if (mSharedLibraries.size() > 0) { 2212 // NOTE: For now, we're compiling these system "shared libraries" 2213 // (and framework jars) into all available architectures. It's possible 2214 // to compile them only when we come across an app that uses them (there's 2215 // already logic for that in scanPackageLI) but that adds some complexity. 2216 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2217 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2218 final String lib = libEntry.path; 2219 if (lib == null) { 2220 continue; 2221 } 2222 2223 try { 2224 // Shared libraries do not have profiles so we perform a full 2225 // AOT compilation (if needed). 2226 int dexoptNeeded = DexFile.getDexOptNeeded( 2227 lib, dexCodeInstructionSet, 2228 getCompilerFilterForReason(REASON_SHARED_APK), 2229 false /* newProfile */); 2230 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2231 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2232 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2233 getCompilerFilterForReason(REASON_SHARED_APK), 2234 StorageManager.UUID_PRIVATE_INTERNAL, 2235 SKIP_SHARED_LIBRARY_CHECK); 2236 } 2237 } catch (FileNotFoundException e) { 2238 Slog.w(TAG, "Library not found: " + lib); 2239 } catch (IOException | InstallerException e) { 2240 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2241 + e.getMessage()); 2242 } 2243 } 2244 } 2245 } 2246 2247 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2248 2249 final VersionInfo ver = mSettings.getInternalVersion(); 2250 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2251 2252 // when upgrading from pre-M, promote system app permissions from install to runtime 2253 mPromoteSystemApps = 2254 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2255 2256 // When upgrading from pre-N, we need to handle package extraction like first boot, 2257 // as there is no profiling data available. 2258 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2259 2260 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2261 2262 // save off the names of pre-existing system packages prior to scanning; we don't 2263 // want to automatically grant runtime permissions for new system apps 2264 if (mPromoteSystemApps) { 2265 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2266 while (pkgSettingIter.hasNext()) { 2267 PackageSetting ps = pkgSettingIter.next(); 2268 if (isSystemApp(ps)) { 2269 mExistingSystemPackages.add(ps.name); 2270 } 2271 } 2272 } 2273 2274 // Collect vendor overlay packages. 2275 // (Do this before scanning any apps.) 2276 // For security and version matching reason, only consider 2277 // overlay packages if they reside in the right directory. 2278 File vendorOverlayDir; 2279 String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY); 2280 if (!overlaySkuDir.isEmpty()) { 2281 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir); 2282 } else { 2283 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2284 } 2285 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2286 | PackageParser.PARSE_IS_SYSTEM 2287 | PackageParser.PARSE_IS_SYSTEM_DIR 2288 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2289 2290 // Find base frameworks (resource packages without code). 2291 scanDirTracedLI(frameworkDir, mDefParseFlags 2292 | PackageParser.PARSE_IS_SYSTEM 2293 | PackageParser.PARSE_IS_SYSTEM_DIR 2294 | PackageParser.PARSE_IS_PRIVILEGED, 2295 scanFlags | SCAN_NO_DEX, 0); 2296 2297 // Collected privileged system packages. 2298 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2299 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2300 | PackageParser.PARSE_IS_SYSTEM 2301 | PackageParser.PARSE_IS_SYSTEM_DIR 2302 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2303 2304 // Collect ordinary system packages. 2305 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2306 scanDirTracedLI(systemAppDir, mDefParseFlags 2307 | PackageParser.PARSE_IS_SYSTEM 2308 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2309 2310 // Collect all vendor packages. 2311 File vendorAppDir = new File("/vendor/app"); 2312 try { 2313 vendorAppDir = vendorAppDir.getCanonicalFile(); 2314 } catch (IOException e) { 2315 // failed to look up canonical path, continue with original one 2316 } 2317 scanDirTracedLI(vendorAppDir, mDefParseFlags 2318 | PackageParser.PARSE_IS_SYSTEM 2319 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2320 2321 // Collect all OEM packages. 2322 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2323 scanDirTracedLI(oemAppDir, mDefParseFlags 2324 | PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2326 2327 // Prune any system packages that no longer exist. 2328 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2329 if (!mOnlyCore) { 2330 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2331 while (psit.hasNext()) { 2332 PackageSetting ps = psit.next(); 2333 2334 /* 2335 * If this is not a system app, it can't be a 2336 * disable system app. 2337 */ 2338 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2339 continue; 2340 } 2341 2342 /* 2343 * If the package is scanned, it's not erased. 2344 */ 2345 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2346 if (scannedPkg != null) { 2347 /* 2348 * If the system app is both scanned and in the 2349 * disabled packages list, then it must have been 2350 * added via OTA. Remove it from the currently 2351 * scanned package so the previously user-installed 2352 * application can be scanned. 2353 */ 2354 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2355 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2356 + ps.name + "; removing system app. Last known codePath=" 2357 + ps.codePathString + ", installStatus=" + ps.installStatus 2358 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2359 + scannedPkg.mVersionCode); 2360 removePackageLI(scannedPkg, true); 2361 mExpectingBetter.put(ps.name, ps.codePath); 2362 } 2363 2364 continue; 2365 } 2366 2367 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2368 psit.remove(); 2369 logCriticalInfo(Log.WARN, "System package " + ps.name 2370 + " no longer exists; it's data will be wiped"); 2371 // Actual deletion of code and data will be handled by later 2372 // reconciliation step 2373 } else { 2374 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2375 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2376 possiblyDeletedUpdatedSystemApps.add(ps.name); 2377 } 2378 } 2379 } 2380 } 2381 2382 //look for any incomplete package installations 2383 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2384 for (int i = 0; i < deletePkgsList.size(); i++) { 2385 // Actual deletion of code and data will be handled by later 2386 // reconciliation step 2387 final String packageName = deletePkgsList.get(i).name; 2388 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2389 synchronized (mPackages) { 2390 mSettings.removePackageLPw(packageName); 2391 } 2392 } 2393 2394 //delete tmp files 2395 deleteTempPackageFiles(); 2396 2397 // Remove any shared userIDs that have no associated packages 2398 mSettings.pruneSharedUsersLPw(); 2399 2400 if (!mOnlyCore) { 2401 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2402 SystemClock.uptimeMillis()); 2403 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2404 2405 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2406 | PackageParser.PARSE_FORWARD_LOCK, 2407 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2408 2409 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2410 | PackageParser.PARSE_IS_EPHEMERAL, 2411 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2412 2413 /** 2414 * Remove disable package settings for any updated system 2415 * apps that were removed via an OTA. If they're not a 2416 * previously-updated app, remove them completely. 2417 * Otherwise, just revoke their system-level permissions. 2418 */ 2419 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2420 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2421 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2422 2423 String msg; 2424 if (deletedPkg == null) { 2425 msg = "Updated system package " + deletedAppName 2426 + " no longer exists; it's data will be wiped"; 2427 // Actual deletion of code and data will be handled by later 2428 // reconciliation step 2429 } else { 2430 msg = "Updated system app + " + deletedAppName 2431 + " no longer present; removing system privileges for " 2432 + deletedAppName; 2433 2434 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2435 2436 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2437 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2438 } 2439 logCriticalInfo(Log.WARN, msg); 2440 } 2441 2442 /** 2443 * Make sure all system apps that we expected to appear on 2444 * the userdata partition actually showed up. If they never 2445 * appeared, crawl back and revive the system version. 2446 */ 2447 for (int i = 0; i < mExpectingBetter.size(); i++) { 2448 final String packageName = mExpectingBetter.keyAt(i); 2449 if (!mPackages.containsKey(packageName)) { 2450 final File scanFile = mExpectingBetter.valueAt(i); 2451 2452 logCriticalInfo(Log.WARN, "Expected better " + packageName 2453 + " but never showed up; reverting to system"); 2454 2455 int reparseFlags = mDefParseFlags; 2456 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2457 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2458 | PackageParser.PARSE_IS_SYSTEM_DIR 2459 | PackageParser.PARSE_IS_PRIVILEGED; 2460 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2461 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR; 2463 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2464 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2465 | PackageParser.PARSE_IS_SYSTEM_DIR; 2466 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2467 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2468 | PackageParser.PARSE_IS_SYSTEM_DIR; 2469 } else { 2470 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2471 continue; 2472 } 2473 2474 mSettings.enableSystemPackageLPw(packageName); 2475 2476 try { 2477 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2478 } catch (PackageManagerException e) { 2479 Slog.e(TAG, "Failed to parse original system package: " 2480 + e.getMessage()); 2481 } 2482 } 2483 } 2484 } 2485 mExpectingBetter.clear(); 2486 2487 // Resolve the storage manager. 2488 mStorageManagerPackage = getStorageManagerPackageName(); 2489 2490 // Resolve protected action filters. Only the setup wizard is allowed to 2491 // have a high priority filter for these actions. 2492 mSetupWizardPackage = getSetupWizardPackageName(); 2493 if (mProtectedFilters.size() > 0) { 2494 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2495 Slog.i(TAG, "No setup wizard;" 2496 + " All protected intents capped to priority 0"); 2497 } 2498 for (ActivityIntentInfo filter : mProtectedFilters) { 2499 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2500 if (DEBUG_FILTERS) { 2501 Slog.i(TAG, "Found setup wizard;" 2502 + " allow priority " + filter.getPriority() + ";" 2503 + " package: " + filter.activity.info.packageName 2504 + " activity: " + filter.activity.className 2505 + " priority: " + filter.getPriority()); 2506 } 2507 // skip setup wizard; allow it to keep the high priority filter 2508 continue; 2509 } 2510 Slog.w(TAG, "Protected action; cap priority to 0;" 2511 + " package: " + filter.activity.info.packageName 2512 + " activity: " + filter.activity.className 2513 + " origPrio: " + filter.getPriority()); 2514 filter.setPriority(0); 2515 } 2516 } 2517 mDeferProtectedFilters = false; 2518 mProtectedFilters.clear(); 2519 2520 // Now that we know all of the shared libraries, update all clients to have 2521 // the correct library paths. 2522 updateAllSharedLibrariesLPw(); 2523 2524 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2525 // NOTE: We ignore potential failures here during a system scan (like 2526 // the rest of the commands above) because there's precious little we 2527 // can do about it. A settings error is reported, though. 2528 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2529 false /* boot complete */); 2530 } 2531 2532 // Now that we know all the packages we are keeping, 2533 // read and update their last usage times. 2534 mPackageUsage.read(mPackages); 2535 mCompilerStats.read(); 2536 2537 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2538 SystemClock.uptimeMillis()); 2539 Slog.i(TAG, "Time to scan packages: " 2540 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2541 + " seconds"); 2542 2543 // If the platform SDK has changed since the last time we booted, 2544 // we need to re-grant app permission to catch any new ones that 2545 // appear. This is really a hack, and means that apps can in some 2546 // cases get permissions that the user didn't initially explicitly 2547 // allow... it would be nice to have some better way to handle 2548 // this situation. 2549 int updateFlags = UPDATE_PERMISSIONS_ALL; 2550 if (ver.sdkVersion != mSdkVersion) { 2551 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2552 + mSdkVersion + "; regranting permissions for internal storage"); 2553 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2554 } 2555 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2556 ver.sdkVersion = mSdkVersion; 2557 2558 // If this is the first boot or an update from pre-M, and it is a normal 2559 // boot, then we need to initialize the default preferred apps across 2560 // all defined users. 2561 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2562 for (UserInfo user : sUserManager.getUsers(true)) { 2563 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2564 applyFactoryDefaultBrowserLPw(user.id); 2565 primeDomainVerificationsLPw(user.id); 2566 } 2567 } 2568 2569 // Prepare storage for system user really early during boot, 2570 // since core system apps like SettingsProvider and SystemUI 2571 // can't wait for user to start 2572 final int storageFlags; 2573 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2574 storageFlags = StorageManager.FLAG_STORAGE_DE; 2575 } else { 2576 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2577 } 2578 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2579 storageFlags); 2580 2581 // If this is first boot after an OTA, and a normal boot, then 2582 // we need to clear code cache directories. 2583 // Note that we do *not* clear the application profiles. These remain valid 2584 // across OTAs and are used to drive profile verification (post OTA) and 2585 // profile compilation (without waiting to collect a fresh set of profiles). 2586 if (mIsUpgrade && !onlyCore) { 2587 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2588 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2589 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2590 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2591 // No apps are running this early, so no need to freeze 2592 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2593 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2594 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2595 } 2596 } 2597 ver.fingerprint = Build.FINGERPRINT; 2598 } 2599 2600 checkDefaultBrowser(); 2601 2602 // clear only after permissions and other defaults have been updated 2603 mExistingSystemPackages.clear(); 2604 mPromoteSystemApps = false; 2605 2606 // All the changes are done during package scanning. 2607 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2608 2609 // can downgrade to reader 2610 mSettings.writeLPr(); 2611 2612 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2613 // early on (before the package manager declares itself as early) because other 2614 // components in the system server might ask for package contexts for these apps. 2615 // 2616 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2617 // (i.e, that the data partition is unavailable). 2618 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2619 long start = System.nanoTime(); 2620 List<PackageParser.Package> coreApps = new ArrayList<>(); 2621 for (PackageParser.Package pkg : mPackages.values()) { 2622 if (pkg.coreApp) { 2623 coreApps.add(pkg); 2624 } 2625 } 2626 2627 int[] stats = performDexOptUpgrade(coreApps, false, 2628 getCompilerFilterForReason(REASON_CORE_APP)); 2629 2630 final int elapsedTimeSeconds = 2631 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2632 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2633 2634 if (DEBUG_DEXOPT) { 2635 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2636 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2637 } 2638 2639 2640 // TODO: Should we log these stats to tron too ? 2641 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2642 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2643 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2644 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2645 } 2646 2647 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2648 SystemClock.uptimeMillis()); 2649 2650 if (!mOnlyCore) { 2651 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2652 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2653 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2654 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2655 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2656 mIntentFilterVerifierComponent); 2657 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2658 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2659 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2660 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2661 } else { 2662 mRequiredVerifierPackage = null; 2663 mRequiredInstallerPackage = null; 2664 mRequiredUninstallerPackage = null; 2665 mIntentFilterVerifierComponent = null; 2666 mIntentFilterVerifier = null; 2667 mServicesSystemSharedLibraryPackageName = null; 2668 mSharedSystemSharedLibraryPackageName = null; 2669 } 2670 2671 mInstallerService = new PackageInstallerService(context, this); 2672 2673 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2674 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2675 // both the installer and resolver must be present to enable ephemeral 2676 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2677 if (DEBUG_EPHEMERAL) { 2678 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2679 + " installer:" + ephemeralInstallerComponent); 2680 } 2681 mEphemeralResolverComponent = ephemeralResolverComponent; 2682 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2683 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2684 mEphemeralResolverConnection = 2685 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2686 } else { 2687 if (DEBUG_EPHEMERAL) { 2688 final String missingComponent = 2689 (ephemeralResolverComponent == null) 2690 ? (ephemeralInstallerComponent == null) 2691 ? "resolver and installer" 2692 : "resolver" 2693 : "installer"; 2694 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2695 } 2696 mEphemeralResolverComponent = null; 2697 mEphemeralInstallerComponent = null; 2698 mEphemeralResolverConnection = null; 2699 } 2700 2701 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2702 } // synchronized (mPackages) 2703 } // synchronized (mInstallLock) 2704 2705 // Now after opening every single application zip, make sure they 2706 // are all flushed. Not really needed, but keeps things nice and 2707 // tidy. 2708 Runtime.getRuntime().gc(); 2709 2710 // The initial scanning above does many calls into installd while 2711 // holding the mPackages lock, but we're mostly interested in yelling 2712 // once we have a booted system. 2713 mInstaller.setWarnIfHeld(mPackages); 2714 2715 // Expose private service for system components to use. 2716 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2717 } 2718 2719 @Override 2720 public boolean isFirstBoot() { 2721 return mFirstBoot; 2722 } 2723 2724 @Override 2725 public boolean isOnlyCoreApps() { 2726 return mOnlyCore; 2727 } 2728 2729 @Override 2730 public boolean isUpgrade() { 2731 return mIsUpgrade; 2732 } 2733 2734 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2735 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2736 2737 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2738 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2739 UserHandle.USER_SYSTEM); 2740 if (matches.size() == 1) { 2741 return matches.get(0).getComponentInfo().packageName; 2742 } else if (matches.size() == 0) { 2743 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2744 return null; 2745 } 2746 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2747 } 2748 2749 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2750 synchronized (mPackages) { 2751 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2752 if (libraryEntry == null) { 2753 throw new IllegalStateException("Missing required shared library:" + libraryName); 2754 } 2755 return libraryEntry.apk; 2756 } 2757 } 2758 2759 private @NonNull String getRequiredInstallerLPr() { 2760 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2761 intent.addCategory(Intent.CATEGORY_DEFAULT); 2762 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2763 2764 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2765 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2766 UserHandle.USER_SYSTEM); 2767 if (matches.size() == 1) { 2768 ResolveInfo resolveInfo = matches.get(0); 2769 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2770 throw new RuntimeException("The installer must be a privileged app"); 2771 } 2772 return matches.get(0).getComponentInfo().packageName; 2773 } else { 2774 throw new RuntimeException("There must be exactly one installer; found " + matches); 2775 } 2776 } 2777 2778 private @NonNull String getRequiredUninstallerLPr() { 2779 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2780 intent.addCategory(Intent.CATEGORY_DEFAULT); 2781 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2782 2783 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2784 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2785 UserHandle.USER_SYSTEM); 2786 if (resolveInfo == null || 2787 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2788 throw new RuntimeException("There must be exactly one uninstaller; found " 2789 + resolveInfo); 2790 } 2791 return resolveInfo.getComponentInfo().packageName; 2792 } 2793 2794 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2795 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2796 2797 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2798 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2799 UserHandle.USER_SYSTEM); 2800 ResolveInfo best = null; 2801 final int N = matches.size(); 2802 for (int i = 0; i < N; i++) { 2803 final ResolveInfo cur = matches.get(i); 2804 final String packageName = cur.getComponentInfo().packageName; 2805 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2806 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2807 continue; 2808 } 2809 2810 if (best == null || cur.priority > best.priority) { 2811 best = cur; 2812 } 2813 } 2814 2815 if (best != null) { 2816 return best.getComponentInfo().getComponentName(); 2817 } else { 2818 throw new RuntimeException("There must be at least one intent filter verifier"); 2819 } 2820 } 2821 2822 private @Nullable ComponentName getEphemeralResolverLPr() { 2823 final String[] packageArray = 2824 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2825 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2826 if (DEBUG_EPHEMERAL) { 2827 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2828 } 2829 return null; 2830 } 2831 2832 final int resolveFlags = 2833 MATCH_DIRECT_BOOT_AWARE 2834 | MATCH_DIRECT_BOOT_UNAWARE 2835 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2836 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2837 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2838 resolveFlags, UserHandle.USER_SYSTEM); 2839 2840 final int N = resolvers.size(); 2841 if (N == 0) { 2842 if (DEBUG_EPHEMERAL) { 2843 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2844 } 2845 return null; 2846 } 2847 2848 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2849 for (int i = 0; i < N; i++) { 2850 final ResolveInfo info = resolvers.get(i); 2851 2852 if (info.serviceInfo == null) { 2853 continue; 2854 } 2855 2856 final String packageName = info.serviceInfo.packageName; 2857 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2858 if (DEBUG_EPHEMERAL) { 2859 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2860 + " pkg: " + packageName + ", info:" + info); 2861 } 2862 continue; 2863 } 2864 2865 if (DEBUG_EPHEMERAL) { 2866 Slog.v(TAG, "Ephemeral resolver found;" 2867 + " pkg: " + packageName + ", info:" + info); 2868 } 2869 return new ComponentName(packageName, info.serviceInfo.name); 2870 } 2871 if (DEBUG_EPHEMERAL) { 2872 Slog.v(TAG, "Ephemeral resolver NOT found"); 2873 } 2874 return null; 2875 } 2876 2877 private @Nullable ComponentName getEphemeralInstallerLPr() { 2878 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2879 intent.addCategory(Intent.CATEGORY_DEFAULT); 2880 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2881 2882 final int resolveFlags = 2883 MATCH_DIRECT_BOOT_AWARE 2884 | MATCH_DIRECT_BOOT_UNAWARE 2885 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2886 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2887 resolveFlags, UserHandle.USER_SYSTEM); 2888 if (matches.size() == 0) { 2889 return null; 2890 } else if (matches.size() == 1) { 2891 return matches.get(0).getComponentInfo().getComponentName(); 2892 } else { 2893 throw new RuntimeException( 2894 "There must be at most one ephemeral installer; found " + matches); 2895 } 2896 } 2897 2898 private void primeDomainVerificationsLPw(int userId) { 2899 if (DEBUG_DOMAIN_VERIFICATION) { 2900 Slog.d(TAG, "Priming domain verifications in user " + userId); 2901 } 2902 2903 SystemConfig systemConfig = SystemConfig.getInstance(); 2904 ArraySet<String> packages = systemConfig.getLinkedApps(); 2905 ArraySet<String> domains = new ArraySet<String>(); 2906 2907 for (String packageName : packages) { 2908 PackageParser.Package pkg = mPackages.get(packageName); 2909 if (pkg != null) { 2910 if (!pkg.isSystemApp()) { 2911 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2912 continue; 2913 } 2914 2915 domains.clear(); 2916 for (PackageParser.Activity a : pkg.activities) { 2917 for (ActivityIntentInfo filter : a.intents) { 2918 if (hasValidDomains(filter)) { 2919 domains.addAll(filter.getHostsList()); 2920 } 2921 } 2922 } 2923 2924 if (domains.size() > 0) { 2925 if (DEBUG_DOMAIN_VERIFICATION) { 2926 Slog.v(TAG, " + " + packageName); 2927 } 2928 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2929 // state w.r.t. the formal app-linkage "no verification attempted" state; 2930 // and then 'always' in the per-user state actually used for intent resolution. 2931 final IntentFilterVerificationInfo ivi; 2932 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2933 new ArrayList<String>(domains)); 2934 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2935 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2936 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2937 } else { 2938 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2939 + "' does not handle web links"); 2940 } 2941 } else { 2942 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2943 } 2944 } 2945 2946 scheduleWritePackageRestrictionsLocked(userId); 2947 scheduleWriteSettingsLocked(); 2948 } 2949 2950 private void applyFactoryDefaultBrowserLPw(int userId) { 2951 // The default browser app's package name is stored in a string resource, 2952 // with a product-specific overlay used for vendor customization. 2953 String browserPkg = mContext.getResources().getString( 2954 com.android.internal.R.string.default_browser); 2955 if (!TextUtils.isEmpty(browserPkg)) { 2956 // non-empty string => required to be a known package 2957 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2958 if (ps == null) { 2959 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2960 browserPkg = null; 2961 } else { 2962 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2963 } 2964 } 2965 2966 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2967 // default. If there's more than one, just leave everything alone. 2968 if (browserPkg == null) { 2969 calculateDefaultBrowserLPw(userId); 2970 } 2971 } 2972 2973 private void calculateDefaultBrowserLPw(int userId) { 2974 List<String> allBrowsers = resolveAllBrowserApps(userId); 2975 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2976 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2977 } 2978 2979 private List<String> resolveAllBrowserApps(int userId) { 2980 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2981 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2982 PackageManager.MATCH_ALL, userId); 2983 2984 final int count = list.size(); 2985 List<String> result = new ArrayList<String>(count); 2986 for (int i=0; i<count; i++) { 2987 ResolveInfo info = list.get(i); 2988 if (info.activityInfo == null 2989 || !info.handleAllWebDataURI 2990 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2991 || result.contains(info.activityInfo.packageName)) { 2992 continue; 2993 } 2994 result.add(info.activityInfo.packageName); 2995 } 2996 2997 return result; 2998 } 2999 3000 private boolean packageIsBrowser(String packageName, int userId) { 3001 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3002 PackageManager.MATCH_ALL, userId); 3003 final int N = list.size(); 3004 for (int i = 0; i < N; i++) { 3005 ResolveInfo info = list.get(i); 3006 if (packageName.equals(info.activityInfo.packageName)) { 3007 return true; 3008 } 3009 } 3010 return false; 3011 } 3012 3013 private void checkDefaultBrowser() { 3014 final int myUserId = UserHandle.myUserId(); 3015 final String packageName = getDefaultBrowserPackageName(myUserId); 3016 if (packageName != null) { 3017 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3018 if (info == null) { 3019 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3020 synchronized (mPackages) { 3021 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3022 } 3023 } 3024 } 3025 } 3026 3027 @Override 3028 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3029 throws RemoteException { 3030 try { 3031 return super.onTransact(code, data, reply, flags); 3032 } catch (RuntimeException e) { 3033 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3034 Slog.wtf(TAG, "Package Manager Crash", e); 3035 } 3036 throw e; 3037 } 3038 } 3039 3040 static int[] appendInts(int[] cur, int[] add) { 3041 if (add == null) return cur; 3042 if (cur == null) return add; 3043 final int N = add.length; 3044 for (int i=0; i<N; i++) { 3045 cur = appendInt(cur, add[i]); 3046 } 3047 return cur; 3048 } 3049 3050 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3051 if (!sUserManager.exists(userId)) return null; 3052 if (ps == null) { 3053 return null; 3054 } 3055 final PackageParser.Package p = ps.pkg; 3056 if (p == null) { 3057 return null; 3058 } 3059 3060 final PermissionsState permissionsState = ps.getPermissionsState(); 3061 3062 // Compute GIDs only if requested 3063 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3064 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3065 // Compute granted permissions only if package has requested permissions 3066 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3067 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3068 final PackageUserState state = ps.readUserState(userId); 3069 3070 return PackageParser.generatePackageInfo(p, gids, flags, 3071 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3072 } 3073 3074 @Override 3075 public void checkPackageStartable(String packageName, int userId) { 3076 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3077 3078 synchronized (mPackages) { 3079 final PackageSetting ps = mSettings.mPackages.get(packageName); 3080 if (ps == null) { 3081 throw new SecurityException("Package " + packageName + " was not found!"); 3082 } 3083 3084 if (!ps.getInstalled(userId)) { 3085 throw new SecurityException( 3086 "Package " + packageName + " was not installed for user " + userId + "!"); 3087 } 3088 3089 if (mSafeMode && !ps.isSystem()) { 3090 throw new SecurityException("Package " + packageName + " not a system app!"); 3091 } 3092 3093 if (mFrozenPackages.contains(packageName)) { 3094 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3095 } 3096 3097 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3098 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3099 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3100 } 3101 } 3102 } 3103 3104 @Override 3105 public boolean isPackageAvailable(String packageName, int userId) { 3106 if (!sUserManager.exists(userId)) return false; 3107 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3108 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3109 synchronized (mPackages) { 3110 PackageParser.Package p = mPackages.get(packageName); 3111 if (p != null) { 3112 final PackageSetting ps = (PackageSetting) p.mExtras; 3113 if (ps != null) { 3114 final PackageUserState state = ps.readUserState(userId); 3115 if (state != null) { 3116 return PackageParser.isAvailable(state); 3117 } 3118 } 3119 } 3120 } 3121 return false; 3122 } 3123 3124 @Override 3125 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3126 if (!sUserManager.exists(userId)) return null; 3127 flags = updateFlagsForPackage(flags, userId, packageName); 3128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3129 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3130 // reader 3131 synchronized (mPackages) { 3132 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3133 PackageParser.Package p = null; 3134 if (matchFactoryOnly) { 3135 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3136 if (ps != null) { 3137 return generatePackageInfo(ps, flags, userId); 3138 } 3139 } 3140 if (p == null) { 3141 p = mPackages.get(packageName); 3142 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3143 return null; 3144 } 3145 } 3146 if (DEBUG_PACKAGE_INFO) 3147 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3148 if (p != null) { 3149 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3150 } 3151 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3152 final PackageSetting ps = mSettings.mPackages.get(packageName); 3153 return generatePackageInfo(ps, flags, userId); 3154 } 3155 } 3156 return null; 3157 } 3158 3159 @Override 3160 public String[] currentToCanonicalPackageNames(String[] names) { 3161 String[] out = new String[names.length]; 3162 // reader 3163 synchronized (mPackages) { 3164 for (int i=names.length-1; i>=0; i--) { 3165 PackageSetting ps = mSettings.mPackages.get(names[i]); 3166 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3167 } 3168 } 3169 return out; 3170 } 3171 3172 @Override 3173 public String[] canonicalToCurrentPackageNames(String[] names) { 3174 String[] out = new String[names.length]; 3175 // reader 3176 synchronized (mPackages) { 3177 for (int i=names.length-1; i>=0; i--) { 3178 String cur = mSettings.mRenamedPackages.get(names[i]); 3179 out[i] = cur != null ? cur : names[i]; 3180 } 3181 } 3182 return out; 3183 } 3184 3185 @Override 3186 public int getPackageUid(String packageName, int flags, int userId) { 3187 if (!sUserManager.exists(userId)) return -1; 3188 flags = updateFlagsForPackage(flags, userId, packageName); 3189 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3190 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3191 3192 // reader 3193 synchronized (mPackages) { 3194 final PackageParser.Package p = mPackages.get(packageName); 3195 if (p != null && p.isMatch(flags)) { 3196 return UserHandle.getUid(userId, p.applicationInfo.uid); 3197 } 3198 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3199 final PackageSetting ps = mSettings.mPackages.get(packageName); 3200 if (ps != null && ps.isMatch(flags)) { 3201 return UserHandle.getUid(userId, ps.appId); 3202 } 3203 } 3204 } 3205 3206 return -1; 3207 } 3208 3209 @Override 3210 public int[] getPackageGids(String packageName, int flags, int userId) { 3211 if (!sUserManager.exists(userId)) return null; 3212 flags = updateFlagsForPackage(flags, userId, packageName); 3213 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3214 false /* requireFullPermission */, false /* checkShell */, 3215 "getPackageGids"); 3216 3217 // reader 3218 synchronized (mPackages) { 3219 final PackageParser.Package p = mPackages.get(packageName); 3220 if (p != null && p.isMatch(flags)) { 3221 PackageSetting ps = (PackageSetting) p.mExtras; 3222 return ps.getPermissionsState().computeGids(userId); 3223 } 3224 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3225 final PackageSetting ps = mSettings.mPackages.get(packageName); 3226 if (ps != null && ps.isMatch(flags)) { 3227 return ps.getPermissionsState().computeGids(userId); 3228 } 3229 } 3230 } 3231 3232 return null; 3233 } 3234 3235 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3236 if (bp.perm != null) { 3237 return PackageParser.generatePermissionInfo(bp.perm, flags); 3238 } 3239 PermissionInfo pi = new PermissionInfo(); 3240 pi.name = bp.name; 3241 pi.packageName = bp.sourcePackage; 3242 pi.nonLocalizedLabel = bp.name; 3243 pi.protectionLevel = bp.protectionLevel; 3244 return pi; 3245 } 3246 3247 @Override 3248 public PermissionInfo getPermissionInfo(String name, int flags) { 3249 // reader 3250 synchronized (mPackages) { 3251 final BasePermission p = mSettings.mPermissions.get(name); 3252 if (p != null) { 3253 return generatePermissionInfo(p, flags); 3254 } 3255 return null; 3256 } 3257 } 3258 3259 @Override 3260 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3261 int flags) { 3262 // reader 3263 synchronized (mPackages) { 3264 if (group != null && !mPermissionGroups.containsKey(group)) { 3265 // This is thrown as NameNotFoundException 3266 return null; 3267 } 3268 3269 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3270 for (BasePermission p : mSettings.mPermissions.values()) { 3271 if (group == null) { 3272 if (p.perm == null || p.perm.info.group == null) { 3273 out.add(generatePermissionInfo(p, flags)); 3274 } 3275 } else { 3276 if (p.perm != null && group.equals(p.perm.info.group)) { 3277 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3278 } 3279 } 3280 } 3281 return new ParceledListSlice<>(out); 3282 } 3283 } 3284 3285 @Override 3286 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3287 // reader 3288 synchronized (mPackages) { 3289 return PackageParser.generatePermissionGroupInfo( 3290 mPermissionGroups.get(name), flags); 3291 } 3292 } 3293 3294 @Override 3295 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3296 // reader 3297 synchronized (mPackages) { 3298 final int N = mPermissionGroups.size(); 3299 ArrayList<PermissionGroupInfo> out 3300 = new ArrayList<PermissionGroupInfo>(N); 3301 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3302 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3303 } 3304 return new ParceledListSlice<>(out); 3305 } 3306 } 3307 3308 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3309 int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 PackageSetting ps = mSettings.mPackages.get(packageName); 3312 if (ps != null) { 3313 if (ps.pkg == null) { 3314 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3315 if (pInfo != null) { 3316 return pInfo.applicationInfo; 3317 } 3318 return null; 3319 } 3320 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3321 ps.readUserState(userId), userId); 3322 } 3323 return null; 3324 } 3325 3326 @Override 3327 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3328 if (!sUserManager.exists(userId)) return null; 3329 flags = updateFlagsForApplication(flags, userId, packageName); 3330 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3331 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3332 // writer 3333 synchronized (mPackages) { 3334 PackageParser.Package p = mPackages.get(packageName); 3335 if (DEBUG_PACKAGE_INFO) Log.v( 3336 TAG, "getApplicationInfo " + packageName 3337 + ": " + p); 3338 if (p != null) { 3339 PackageSetting ps = mSettings.mPackages.get(packageName); 3340 if (ps == null) return null; 3341 // Note: isEnabledLP() does not apply here - always return info 3342 return PackageParser.generateApplicationInfo( 3343 p, flags, ps.readUserState(userId), userId); 3344 } 3345 if ("android".equals(packageName)||"system".equals(packageName)) { 3346 return mAndroidApplication; 3347 } 3348 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3349 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3350 } 3351 } 3352 return null; 3353 } 3354 3355 @Override 3356 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3357 final IPackageDataObserver observer) { 3358 mContext.enforceCallingOrSelfPermission( 3359 android.Manifest.permission.CLEAR_APP_CACHE, null); 3360 // Queue up an async operation since clearing cache may take a little while. 3361 mHandler.post(new Runnable() { 3362 public void run() { 3363 mHandler.removeCallbacks(this); 3364 boolean success = true; 3365 synchronized (mInstallLock) { 3366 try { 3367 mInstaller.freeCache(volumeUuid, freeStorageSize); 3368 } catch (InstallerException e) { 3369 Slog.w(TAG, "Couldn't clear application caches: " + e); 3370 success = false; 3371 } 3372 } 3373 if (observer != null) { 3374 try { 3375 observer.onRemoveCompleted(null, success); 3376 } catch (RemoteException e) { 3377 Slog.w(TAG, "RemoveException when invoking call back"); 3378 } 3379 } 3380 } 3381 }); 3382 } 3383 3384 @Override 3385 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3386 final IntentSender pi) { 3387 mContext.enforceCallingOrSelfPermission( 3388 android.Manifest.permission.CLEAR_APP_CACHE, null); 3389 // Queue up an async operation since clearing cache may take a little while. 3390 mHandler.post(new Runnable() { 3391 public void run() { 3392 mHandler.removeCallbacks(this); 3393 boolean success = true; 3394 synchronized (mInstallLock) { 3395 try { 3396 mInstaller.freeCache(volumeUuid, freeStorageSize); 3397 } catch (InstallerException e) { 3398 Slog.w(TAG, "Couldn't clear application caches: " + e); 3399 success = false; 3400 } 3401 } 3402 if(pi != null) { 3403 try { 3404 // Callback via pending intent 3405 int code = success ? 1 : 0; 3406 pi.sendIntent(null, code, null, 3407 null, null); 3408 } catch (SendIntentException e1) { 3409 Slog.i(TAG, "Failed to send pending intent"); 3410 } 3411 } 3412 } 3413 }); 3414 } 3415 3416 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3417 synchronized (mInstallLock) { 3418 try { 3419 mInstaller.freeCache(volumeUuid, freeStorageSize); 3420 } catch (InstallerException e) { 3421 throw new IOException("Failed to free enough space", e); 3422 } 3423 } 3424 } 3425 3426 /** 3427 * Update given flags based on encryption status of current user. 3428 */ 3429 private int updateFlags(int flags, int userId) { 3430 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3431 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3432 // Caller expressed an explicit opinion about what encryption 3433 // aware/unaware components they want to see, so fall through and 3434 // give them what they want 3435 } else { 3436 // Caller expressed no opinion, so match based on user state 3437 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3438 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3439 } else { 3440 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3441 } 3442 } 3443 return flags; 3444 } 3445 3446 private UserManagerInternal getUserManagerInternal() { 3447 if (mUserManagerInternal == null) { 3448 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3449 } 3450 return mUserManagerInternal; 3451 } 3452 3453 /** 3454 * Update given flags when being used to request {@link PackageInfo}. 3455 */ 3456 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3457 boolean triaged = true; 3458 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3459 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3460 // Caller is asking for component details, so they'd better be 3461 // asking for specific encryption matching behavior, or be triaged 3462 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3463 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3464 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3465 triaged = false; 3466 } 3467 } 3468 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3469 | PackageManager.MATCH_SYSTEM_ONLY 3470 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3471 triaged = false; 3472 } 3473 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3474 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3475 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3476 } 3477 return updateFlags(flags, userId); 3478 } 3479 3480 /** 3481 * Update given flags when being used to request {@link ApplicationInfo}. 3482 */ 3483 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3484 return updateFlagsForPackage(flags, userId, cookie); 3485 } 3486 3487 /** 3488 * Update given flags when being used to request {@link ComponentInfo}. 3489 */ 3490 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3491 if (cookie instanceof Intent) { 3492 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3493 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3494 } 3495 } 3496 3497 boolean triaged = true; 3498 // Caller is asking for component details, so they'd better be 3499 // asking for specific encryption matching behavior, or be triaged 3500 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3501 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3502 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3503 triaged = false; 3504 } 3505 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3506 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3507 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3508 } 3509 3510 return updateFlags(flags, userId); 3511 } 3512 3513 /** 3514 * Update given flags when being used to request {@link ResolveInfo}. 3515 */ 3516 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3517 // Safe mode means we shouldn't match any third-party components 3518 if (mSafeMode) { 3519 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3520 } 3521 3522 return updateFlagsForComponent(flags, userId, cookie); 3523 } 3524 3525 @Override 3526 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3527 if (!sUserManager.exists(userId)) return null; 3528 flags = updateFlagsForComponent(flags, userId, component); 3529 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3530 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3531 synchronized (mPackages) { 3532 PackageParser.Activity a = mActivities.mActivities.get(component); 3533 3534 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3535 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3536 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3537 if (ps == null) return null; 3538 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3539 userId); 3540 } 3541 if (mResolveComponentName.equals(component)) { 3542 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3543 new PackageUserState(), userId); 3544 } 3545 } 3546 return null; 3547 } 3548 3549 @Override 3550 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3551 String resolvedType) { 3552 synchronized (mPackages) { 3553 if (component.equals(mResolveComponentName)) { 3554 // The resolver supports EVERYTHING! 3555 return true; 3556 } 3557 PackageParser.Activity a = mActivities.mActivities.get(component); 3558 if (a == null) { 3559 return false; 3560 } 3561 for (int i=0; i<a.intents.size(); i++) { 3562 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3563 intent.getData(), intent.getCategories(), TAG) >= 0) { 3564 return true; 3565 } 3566 } 3567 return false; 3568 } 3569 } 3570 3571 @Override 3572 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3573 if (!sUserManager.exists(userId)) return null; 3574 flags = updateFlagsForComponent(flags, userId, component); 3575 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3576 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3577 synchronized (mPackages) { 3578 PackageParser.Activity a = mReceivers.mActivities.get(component); 3579 if (DEBUG_PACKAGE_INFO) Log.v( 3580 TAG, "getReceiverInfo " + component + ": " + a); 3581 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3582 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3583 if (ps == null) return null; 3584 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3585 userId); 3586 } 3587 } 3588 return null; 3589 } 3590 3591 @Override 3592 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3593 if (!sUserManager.exists(userId)) return null; 3594 flags = updateFlagsForComponent(flags, userId, component); 3595 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3596 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3597 synchronized (mPackages) { 3598 PackageParser.Service s = mServices.mServices.get(component); 3599 if (DEBUG_PACKAGE_INFO) Log.v( 3600 TAG, "getServiceInfo " + component + ": " + s); 3601 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3602 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3603 if (ps == null) return null; 3604 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3605 userId); 3606 } 3607 } 3608 return null; 3609 } 3610 3611 @Override 3612 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3613 if (!sUserManager.exists(userId)) return null; 3614 flags = updateFlagsForComponent(flags, userId, component); 3615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3616 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3617 synchronized (mPackages) { 3618 PackageParser.Provider p = mProviders.mProviders.get(component); 3619 if (DEBUG_PACKAGE_INFO) Log.v( 3620 TAG, "getProviderInfo " + component + ": " + p); 3621 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3622 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3623 if (ps == null) return null; 3624 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3625 userId); 3626 } 3627 } 3628 return null; 3629 } 3630 3631 @Override 3632 public String[] getSystemSharedLibraryNames() { 3633 Set<String> libSet; 3634 synchronized (mPackages) { 3635 libSet = mSharedLibraries.keySet(); 3636 int size = libSet.size(); 3637 if (size > 0) { 3638 String[] libs = new String[size]; 3639 libSet.toArray(libs); 3640 return libs; 3641 } 3642 } 3643 return null; 3644 } 3645 3646 @Override 3647 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3648 synchronized (mPackages) { 3649 return mServicesSystemSharedLibraryPackageName; 3650 } 3651 } 3652 3653 @Override 3654 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3655 synchronized (mPackages) { 3656 return mSharedSystemSharedLibraryPackageName; 3657 } 3658 } 3659 3660 @Override 3661 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3662 synchronized (mPackages) { 3663 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3664 3665 final FeatureInfo fi = new FeatureInfo(); 3666 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3667 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3668 res.add(fi); 3669 3670 return new ParceledListSlice<>(res); 3671 } 3672 } 3673 3674 @Override 3675 public boolean hasSystemFeature(String name, int version) { 3676 synchronized (mPackages) { 3677 final FeatureInfo feat = mAvailableFeatures.get(name); 3678 if (feat == null) { 3679 return false; 3680 } else { 3681 return feat.version >= version; 3682 } 3683 } 3684 } 3685 3686 @Override 3687 public int checkPermission(String permName, String pkgName, int userId) { 3688 if (!sUserManager.exists(userId)) { 3689 return PackageManager.PERMISSION_DENIED; 3690 } 3691 3692 synchronized (mPackages) { 3693 final PackageParser.Package p = mPackages.get(pkgName); 3694 if (p != null && p.mExtras != null) { 3695 final PackageSetting ps = (PackageSetting) p.mExtras; 3696 final PermissionsState permissionsState = ps.getPermissionsState(); 3697 if (permissionsState.hasPermission(permName, userId)) { 3698 return PackageManager.PERMISSION_GRANTED; 3699 } 3700 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3701 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3702 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3703 return PackageManager.PERMISSION_GRANTED; 3704 } 3705 } 3706 } 3707 3708 return PackageManager.PERMISSION_DENIED; 3709 } 3710 3711 @Override 3712 public int checkUidPermission(String permName, int uid) { 3713 final int userId = UserHandle.getUserId(uid); 3714 3715 if (!sUserManager.exists(userId)) { 3716 return PackageManager.PERMISSION_DENIED; 3717 } 3718 3719 synchronized (mPackages) { 3720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3721 if (obj != null) { 3722 final SettingBase ps = (SettingBase) obj; 3723 final PermissionsState permissionsState = ps.getPermissionsState(); 3724 if (permissionsState.hasPermission(permName, userId)) { 3725 return PackageManager.PERMISSION_GRANTED; 3726 } 3727 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3728 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3729 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3730 return PackageManager.PERMISSION_GRANTED; 3731 } 3732 } else { 3733 ArraySet<String> perms = mSystemPermissions.get(uid); 3734 if (perms != null) { 3735 if (perms.contains(permName)) { 3736 return PackageManager.PERMISSION_GRANTED; 3737 } 3738 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3739 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3740 return PackageManager.PERMISSION_GRANTED; 3741 } 3742 } 3743 } 3744 } 3745 3746 return PackageManager.PERMISSION_DENIED; 3747 } 3748 3749 @Override 3750 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3751 if (UserHandle.getCallingUserId() != userId) { 3752 mContext.enforceCallingPermission( 3753 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3754 "isPermissionRevokedByPolicy for user " + userId); 3755 } 3756 3757 if (checkPermission(permission, packageName, userId) 3758 == PackageManager.PERMISSION_GRANTED) { 3759 return false; 3760 } 3761 3762 final long identity = Binder.clearCallingIdentity(); 3763 try { 3764 final int flags = getPermissionFlags(permission, packageName, userId); 3765 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3766 } finally { 3767 Binder.restoreCallingIdentity(identity); 3768 } 3769 } 3770 3771 @Override 3772 public String getPermissionControllerPackageName() { 3773 synchronized (mPackages) { 3774 return mRequiredInstallerPackage; 3775 } 3776 } 3777 3778 /** 3779 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3780 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3781 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3782 * @param message the message to log on security exception 3783 */ 3784 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3785 boolean checkShell, String message) { 3786 if (userId < 0) { 3787 throw new IllegalArgumentException("Invalid userId " + userId); 3788 } 3789 if (checkShell) { 3790 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3791 } 3792 if (userId == UserHandle.getUserId(callingUid)) return; 3793 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3794 if (requireFullPermission) { 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3797 } else { 3798 try { 3799 mContext.enforceCallingOrSelfPermission( 3800 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3801 } catch (SecurityException se) { 3802 mContext.enforceCallingOrSelfPermission( 3803 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3804 } 3805 } 3806 } 3807 } 3808 3809 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3810 if (callingUid == Process.SHELL_UID) { 3811 if (userHandle >= 0 3812 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3813 throw new SecurityException("Shell does not have permission to access user " 3814 + userHandle); 3815 } else if (userHandle < 0) { 3816 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3817 + Debug.getCallers(3)); 3818 } 3819 } 3820 } 3821 3822 private BasePermission findPermissionTreeLP(String permName) { 3823 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3824 if (permName.startsWith(bp.name) && 3825 permName.length() > bp.name.length() && 3826 permName.charAt(bp.name.length()) == '.') { 3827 return bp; 3828 } 3829 } 3830 return null; 3831 } 3832 3833 private BasePermission checkPermissionTreeLP(String permName) { 3834 if (permName != null) { 3835 BasePermission bp = findPermissionTreeLP(permName); 3836 if (bp != null) { 3837 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3838 return bp; 3839 } 3840 throw new SecurityException("Calling uid " 3841 + Binder.getCallingUid() 3842 + " is not allowed to add to permission tree " 3843 + bp.name + " owned by uid " + bp.uid); 3844 } 3845 } 3846 throw new SecurityException("No permission tree found for " + permName); 3847 } 3848 3849 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3850 if (s1 == null) { 3851 return s2 == null; 3852 } 3853 if (s2 == null) { 3854 return false; 3855 } 3856 if (s1.getClass() != s2.getClass()) { 3857 return false; 3858 } 3859 return s1.equals(s2); 3860 } 3861 3862 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3863 if (pi1.icon != pi2.icon) return false; 3864 if (pi1.logo != pi2.logo) return false; 3865 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3866 if (!compareStrings(pi1.name, pi2.name)) return false; 3867 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3868 // We'll take care of setting this one. 3869 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3870 // These are not currently stored in settings. 3871 //if (!compareStrings(pi1.group, pi2.group)) return false; 3872 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3873 //if (pi1.labelRes != pi2.labelRes) return false; 3874 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3875 return true; 3876 } 3877 3878 int permissionInfoFootprint(PermissionInfo info) { 3879 int size = info.name.length(); 3880 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3881 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3882 return size; 3883 } 3884 3885 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3886 int size = 0; 3887 for (BasePermission perm : mSettings.mPermissions.values()) { 3888 if (perm.uid == tree.uid) { 3889 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3890 } 3891 } 3892 return size; 3893 } 3894 3895 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3896 // We calculate the max size of permissions defined by this uid and throw 3897 // if that plus the size of 'info' would exceed our stated maximum. 3898 if (tree.uid != Process.SYSTEM_UID) { 3899 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3900 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3901 throw new SecurityException("Permission tree size cap exceeded"); 3902 } 3903 } 3904 } 3905 3906 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3907 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3908 throw new SecurityException("Label must be specified in permission"); 3909 } 3910 BasePermission tree = checkPermissionTreeLP(info.name); 3911 BasePermission bp = mSettings.mPermissions.get(info.name); 3912 boolean added = bp == null; 3913 boolean changed = true; 3914 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3915 if (added) { 3916 enforcePermissionCapLocked(info, tree); 3917 bp = new BasePermission(info.name, tree.sourcePackage, 3918 BasePermission.TYPE_DYNAMIC); 3919 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3920 throw new SecurityException( 3921 "Not allowed to modify non-dynamic permission " 3922 + info.name); 3923 } else { 3924 if (bp.protectionLevel == fixedLevel 3925 && bp.perm.owner.equals(tree.perm.owner) 3926 && bp.uid == tree.uid 3927 && comparePermissionInfos(bp.perm.info, info)) { 3928 changed = false; 3929 } 3930 } 3931 bp.protectionLevel = fixedLevel; 3932 info = new PermissionInfo(info); 3933 info.protectionLevel = fixedLevel; 3934 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3935 bp.perm.info.packageName = tree.perm.info.packageName; 3936 bp.uid = tree.uid; 3937 if (added) { 3938 mSettings.mPermissions.put(info.name, bp); 3939 } 3940 if (changed) { 3941 if (!async) { 3942 mSettings.writeLPr(); 3943 } else { 3944 scheduleWriteSettingsLocked(); 3945 } 3946 } 3947 return added; 3948 } 3949 3950 @Override 3951 public boolean addPermission(PermissionInfo info) { 3952 synchronized (mPackages) { 3953 return addPermissionLocked(info, false); 3954 } 3955 } 3956 3957 @Override 3958 public boolean addPermissionAsync(PermissionInfo info) { 3959 synchronized (mPackages) { 3960 return addPermissionLocked(info, true); 3961 } 3962 } 3963 3964 @Override 3965 public void removePermission(String name) { 3966 synchronized (mPackages) { 3967 checkPermissionTreeLP(name); 3968 BasePermission bp = mSettings.mPermissions.get(name); 3969 if (bp != null) { 3970 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3971 throw new SecurityException( 3972 "Not allowed to modify non-dynamic permission " 3973 + name); 3974 } 3975 mSettings.mPermissions.remove(name); 3976 mSettings.writeLPr(); 3977 } 3978 } 3979 } 3980 3981 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3982 BasePermission bp) { 3983 int index = pkg.requestedPermissions.indexOf(bp.name); 3984 if (index == -1) { 3985 throw new SecurityException("Package " + pkg.packageName 3986 + " has not requested permission " + bp.name); 3987 } 3988 if (!bp.isRuntime() && !bp.isDevelopment()) { 3989 throw new SecurityException("Permission " + bp.name 3990 + " is not a changeable permission type"); 3991 } 3992 } 3993 3994 @Override 3995 public void grantRuntimePermission(String packageName, String name, final int userId) { 3996 if (!sUserManager.exists(userId)) { 3997 Log.e(TAG, "No such user:" + userId); 3998 return; 3999 } 4000 4001 mContext.enforceCallingOrSelfPermission( 4002 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4003 "grantRuntimePermission"); 4004 4005 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4006 true /* requireFullPermission */, true /* checkShell */, 4007 "grantRuntimePermission"); 4008 4009 final int uid; 4010 final SettingBase sb; 4011 4012 synchronized (mPackages) { 4013 final PackageParser.Package pkg = mPackages.get(packageName); 4014 if (pkg == null) { 4015 throw new IllegalArgumentException("Unknown package: " + packageName); 4016 } 4017 4018 final BasePermission bp = mSettings.mPermissions.get(name); 4019 if (bp == null) { 4020 throw new IllegalArgumentException("Unknown permission: " + name); 4021 } 4022 4023 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4024 4025 // If a permission review is required for legacy apps we represent 4026 // their permissions as always granted runtime ones since we need 4027 // to keep the review required permission flag per user while an 4028 // install permission's state is shared across all users. 4029 if (Build.PERMISSIONS_REVIEW_REQUIRED 4030 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4031 && bp.isRuntime()) { 4032 return; 4033 } 4034 4035 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4036 sb = (SettingBase) pkg.mExtras; 4037 if (sb == null) { 4038 throw new IllegalArgumentException("Unknown package: " + packageName); 4039 } 4040 4041 final PermissionsState permissionsState = sb.getPermissionsState(); 4042 4043 final int flags = permissionsState.getPermissionFlags(name, userId); 4044 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4045 throw new SecurityException("Cannot grant system fixed permission " 4046 + name + " for package " + packageName); 4047 } 4048 4049 if (bp.isDevelopment()) { 4050 // Development permissions must be handled specially, since they are not 4051 // normal runtime permissions. For now they apply to all users. 4052 if (permissionsState.grantInstallPermission(bp) != 4053 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4054 scheduleWriteSettingsLocked(); 4055 } 4056 return; 4057 } 4058 4059 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4060 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4061 return; 4062 } 4063 4064 final int result = permissionsState.grantRuntimePermission(bp, userId); 4065 switch (result) { 4066 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4067 return; 4068 } 4069 4070 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4071 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4072 mHandler.post(new Runnable() { 4073 @Override 4074 public void run() { 4075 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4076 } 4077 }); 4078 } 4079 break; 4080 } 4081 4082 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4083 4084 // Not critical if that is lost - app has to request again. 4085 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4086 } 4087 4088 // Only need to do this if user is initialized. Otherwise it's a new user 4089 // and there are no processes running as the user yet and there's no need 4090 // to make an expensive call to remount processes for the changed permissions. 4091 if (READ_EXTERNAL_STORAGE.equals(name) 4092 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4093 final long token = Binder.clearCallingIdentity(); 4094 try { 4095 if (sUserManager.isInitialized(userId)) { 4096 MountServiceInternal mountServiceInternal = LocalServices.getService( 4097 MountServiceInternal.class); 4098 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4099 } 4100 } finally { 4101 Binder.restoreCallingIdentity(token); 4102 } 4103 } 4104 } 4105 4106 @Override 4107 public void revokeRuntimePermission(String packageName, String name, int userId) { 4108 if (!sUserManager.exists(userId)) { 4109 Log.e(TAG, "No such user:" + userId); 4110 return; 4111 } 4112 4113 mContext.enforceCallingOrSelfPermission( 4114 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4115 "revokeRuntimePermission"); 4116 4117 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4118 true /* requireFullPermission */, true /* checkShell */, 4119 "revokeRuntimePermission"); 4120 4121 final int appId; 4122 4123 synchronized (mPackages) { 4124 final PackageParser.Package pkg = mPackages.get(packageName); 4125 if (pkg == null) { 4126 throw new IllegalArgumentException("Unknown package: " + packageName); 4127 } 4128 4129 final BasePermission bp = mSettings.mPermissions.get(name); 4130 if (bp == null) { 4131 throw new IllegalArgumentException("Unknown permission: " + name); 4132 } 4133 4134 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4135 4136 // If a permission review is required for legacy apps we represent 4137 // their permissions as always granted runtime ones since we need 4138 // to keep the review required permission flag per user while an 4139 // install permission's state is shared across all users. 4140 if (Build.PERMISSIONS_REVIEW_REQUIRED 4141 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4142 && bp.isRuntime()) { 4143 return; 4144 } 4145 4146 SettingBase sb = (SettingBase) pkg.mExtras; 4147 if (sb == null) { 4148 throw new IllegalArgumentException("Unknown package: " + packageName); 4149 } 4150 4151 final PermissionsState permissionsState = sb.getPermissionsState(); 4152 4153 final int flags = permissionsState.getPermissionFlags(name, userId); 4154 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4155 throw new SecurityException("Cannot revoke system fixed permission " 4156 + name + " for package " + packageName); 4157 } 4158 4159 if (bp.isDevelopment()) { 4160 // Development permissions must be handled specially, since they are not 4161 // normal runtime permissions. For now they apply to all users. 4162 if (permissionsState.revokeInstallPermission(bp) != 4163 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4164 scheduleWriteSettingsLocked(); 4165 } 4166 return; 4167 } 4168 4169 if (permissionsState.revokeRuntimePermission(bp, userId) == 4170 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4171 return; 4172 } 4173 4174 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4175 4176 // Critical, after this call app should never have the permission. 4177 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4178 4179 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4180 } 4181 4182 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4183 } 4184 4185 @Override 4186 public void resetRuntimePermissions() { 4187 mContext.enforceCallingOrSelfPermission( 4188 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4189 "revokeRuntimePermission"); 4190 4191 int callingUid = Binder.getCallingUid(); 4192 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4193 mContext.enforceCallingOrSelfPermission( 4194 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4195 "resetRuntimePermissions"); 4196 } 4197 4198 synchronized (mPackages) { 4199 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4200 for (int userId : UserManagerService.getInstance().getUserIds()) { 4201 final int packageCount = mPackages.size(); 4202 for (int i = 0; i < packageCount; i++) { 4203 PackageParser.Package pkg = mPackages.valueAt(i); 4204 if (!(pkg.mExtras instanceof PackageSetting)) { 4205 continue; 4206 } 4207 PackageSetting ps = (PackageSetting) pkg.mExtras; 4208 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4209 } 4210 } 4211 } 4212 } 4213 4214 @Override 4215 public int getPermissionFlags(String name, String packageName, int userId) { 4216 if (!sUserManager.exists(userId)) { 4217 return 0; 4218 } 4219 4220 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4221 4222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4223 true /* requireFullPermission */, false /* checkShell */, 4224 "getPermissionFlags"); 4225 4226 synchronized (mPackages) { 4227 final PackageParser.Package pkg = mPackages.get(packageName); 4228 if (pkg == null) { 4229 return 0; 4230 } 4231 4232 final BasePermission bp = mSettings.mPermissions.get(name); 4233 if (bp == null) { 4234 return 0; 4235 } 4236 4237 SettingBase sb = (SettingBase) pkg.mExtras; 4238 if (sb == null) { 4239 return 0; 4240 } 4241 4242 PermissionsState permissionsState = sb.getPermissionsState(); 4243 return permissionsState.getPermissionFlags(name, userId); 4244 } 4245 } 4246 4247 @Override 4248 public void updatePermissionFlags(String name, String packageName, int flagMask, 4249 int flagValues, int userId) { 4250 if (!sUserManager.exists(userId)) { 4251 return; 4252 } 4253 4254 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4255 4256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4257 true /* requireFullPermission */, true /* checkShell */, 4258 "updatePermissionFlags"); 4259 4260 // Only the system can change these flags and nothing else. 4261 if (getCallingUid() != Process.SYSTEM_UID) { 4262 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4263 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4264 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4265 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4266 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4267 } 4268 4269 synchronized (mPackages) { 4270 final PackageParser.Package pkg = mPackages.get(packageName); 4271 if (pkg == null) { 4272 throw new IllegalArgumentException("Unknown package: " + packageName); 4273 } 4274 4275 final BasePermission bp = mSettings.mPermissions.get(name); 4276 if (bp == null) { 4277 throw new IllegalArgumentException("Unknown permission: " + name); 4278 } 4279 4280 SettingBase sb = (SettingBase) pkg.mExtras; 4281 if (sb == null) { 4282 throw new IllegalArgumentException("Unknown package: " + packageName); 4283 } 4284 4285 PermissionsState permissionsState = sb.getPermissionsState(); 4286 4287 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4288 4289 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4290 // Install and runtime permissions are stored in different places, 4291 // so figure out what permission changed and persist the change. 4292 if (permissionsState.getInstallPermissionState(name) != null) { 4293 scheduleWriteSettingsLocked(); 4294 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4295 || hadState) { 4296 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4297 } 4298 } 4299 } 4300 } 4301 4302 /** 4303 * Update the permission flags for all packages and runtime permissions of a user in order 4304 * to allow device or profile owner to remove POLICY_FIXED. 4305 */ 4306 @Override 4307 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4308 if (!sUserManager.exists(userId)) { 4309 return; 4310 } 4311 4312 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4313 4314 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4315 true /* requireFullPermission */, true /* checkShell */, 4316 "updatePermissionFlagsForAllApps"); 4317 4318 // Only the system can change system fixed flags. 4319 if (getCallingUid() != Process.SYSTEM_UID) { 4320 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4321 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4322 } 4323 4324 synchronized (mPackages) { 4325 boolean changed = false; 4326 final int packageCount = mPackages.size(); 4327 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4328 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4329 SettingBase sb = (SettingBase) pkg.mExtras; 4330 if (sb == null) { 4331 continue; 4332 } 4333 PermissionsState permissionsState = sb.getPermissionsState(); 4334 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4335 userId, flagMask, flagValues); 4336 } 4337 if (changed) { 4338 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4339 } 4340 } 4341 } 4342 4343 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4344 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4345 != PackageManager.PERMISSION_GRANTED 4346 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4347 != PackageManager.PERMISSION_GRANTED) { 4348 throw new SecurityException(message + " requires " 4349 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4350 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4351 } 4352 } 4353 4354 @Override 4355 public boolean shouldShowRequestPermissionRationale(String permissionName, 4356 String packageName, int userId) { 4357 if (UserHandle.getCallingUserId() != userId) { 4358 mContext.enforceCallingPermission( 4359 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4360 "canShowRequestPermissionRationale for user " + userId); 4361 } 4362 4363 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4364 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4365 return false; 4366 } 4367 4368 if (checkPermission(permissionName, packageName, userId) 4369 == PackageManager.PERMISSION_GRANTED) { 4370 return false; 4371 } 4372 4373 final int flags; 4374 4375 final long identity = Binder.clearCallingIdentity(); 4376 try { 4377 flags = getPermissionFlags(permissionName, 4378 packageName, userId); 4379 } finally { 4380 Binder.restoreCallingIdentity(identity); 4381 } 4382 4383 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4384 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4385 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4386 4387 if ((flags & fixedFlags) != 0) { 4388 return false; 4389 } 4390 4391 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4392 } 4393 4394 @Override 4395 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4396 mContext.enforceCallingOrSelfPermission( 4397 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4398 "addOnPermissionsChangeListener"); 4399 4400 synchronized (mPackages) { 4401 mOnPermissionChangeListeners.addListenerLocked(listener); 4402 } 4403 } 4404 4405 @Override 4406 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4407 synchronized (mPackages) { 4408 mOnPermissionChangeListeners.removeListenerLocked(listener); 4409 } 4410 } 4411 4412 @Override 4413 public boolean isProtectedBroadcast(String actionName) { 4414 synchronized (mPackages) { 4415 if (mProtectedBroadcasts.contains(actionName)) { 4416 return true; 4417 } else if (actionName != null) { 4418 // TODO: remove these terrible hacks 4419 if (actionName.startsWith("android.net.netmon.lingerExpired") 4420 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4421 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4422 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4423 return true; 4424 } 4425 } 4426 } 4427 return false; 4428 } 4429 4430 @Override 4431 public int checkSignatures(String pkg1, String pkg2) { 4432 synchronized (mPackages) { 4433 final PackageParser.Package p1 = mPackages.get(pkg1); 4434 final PackageParser.Package p2 = mPackages.get(pkg2); 4435 if (p1 == null || p1.mExtras == null 4436 || p2 == null || p2.mExtras == null) { 4437 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4438 } 4439 return compareSignatures(p1.mSignatures, p2.mSignatures); 4440 } 4441 } 4442 4443 @Override 4444 public int checkUidSignatures(int uid1, int uid2) { 4445 // Map to base uids. 4446 uid1 = UserHandle.getAppId(uid1); 4447 uid2 = UserHandle.getAppId(uid2); 4448 // reader 4449 synchronized (mPackages) { 4450 Signature[] s1; 4451 Signature[] s2; 4452 Object obj = mSettings.getUserIdLPr(uid1); 4453 if (obj != null) { 4454 if (obj instanceof SharedUserSetting) { 4455 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4456 } else if (obj instanceof PackageSetting) { 4457 s1 = ((PackageSetting)obj).signatures.mSignatures; 4458 } else { 4459 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4460 } 4461 } else { 4462 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4463 } 4464 obj = mSettings.getUserIdLPr(uid2); 4465 if (obj != null) { 4466 if (obj instanceof SharedUserSetting) { 4467 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4468 } else if (obj instanceof PackageSetting) { 4469 s2 = ((PackageSetting)obj).signatures.mSignatures; 4470 } else { 4471 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4472 } 4473 } else { 4474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4475 } 4476 return compareSignatures(s1, s2); 4477 } 4478 } 4479 4480 /** 4481 * This method should typically only be used when granting or revoking 4482 * permissions, since the app may immediately restart after this call. 4483 * <p> 4484 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4485 * guard your work against the app being relaunched. 4486 */ 4487 private void killUid(int appId, int userId, String reason) { 4488 final long identity = Binder.clearCallingIdentity(); 4489 try { 4490 IActivityManager am = ActivityManagerNative.getDefault(); 4491 if (am != null) { 4492 try { 4493 am.killUid(appId, userId, reason); 4494 } catch (RemoteException e) { 4495 /* ignore - same process */ 4496 } 4497 } 4498 } finally { 4499 Binder.restoreCallingIdentity(identity); 4500 } 4501 } 4502 4503 /** 4504 * Compares two sets of signatures. Returns: 4505 * <br /> 4506 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4507 * <br /> 4508 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4509 * <br /> 4510 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4511 * <br /> 4512 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4513 * <br /> 4514 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4515 */ 4516 static int compareSignatures(Signature[] s1, Signature[] s2) { 4517 if (s1 == null) { 4518 return s2 == null 4519 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4520 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4521 } 4522 4523 if (s2 == null) { 4524 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4525 } 4526 4527 if (s1.length != s2.length) { 4528 return PackageManager.SIGNATURE_NO_MATCH; 4529 } 4530 4531 // Since both signature sets are of size 1, we can compare without HashSets. 4532 if (s1.length == 1) { 4533 return s1[0].equals(s2[0]) ? 4534 PackageManager.SIGNATURE_MATCH : 4535 PackageManager.SIGNATURE_NO_MATCH; 4536 } 4537 4538 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4539 for (Signature sig : s1) { 4540 set1.add(sig); 4541 } 4542 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4543 for (Signature sig : s2) { 4544 set2.add(sig); 4545 } 4546 // Make sure s2 contains all signatures in s1. 4547 if (set1.equals(set2)) { 4548 return PackageManager.SIGNATURE_MATCH; 4549 } 4550 return PackageManager.SIGNATURE_NO_MATCH; 4551 } 4552 4553 /** 4554 * If the database version for this type of package (internal storage or 4555 * external storage) is less than the version where package signatures 4556 * were updated, return true. 4557 */ 4558 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4559 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4560 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4561 } 4562 4563 /** 4564 * Used for backward compatibility to make sure any packages with 4565 * certificate chains get upgraded to the new style. {@code existingSigs} 4566 * will be in the old format (since they were stored on disk from before the 4567 * system upgrade) and {@code scannedSigs} will be in the newer format. 4568 */ 4569 private int compareSignaturesCompat(PackageSignatures existingSigs, 4570 PackageParser.Package scannedPkg) { 4571 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4572 return PackageManager.SIGNATURE_NO_MATCH; 4573 } 4574 4575 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4576 for (Signature sig : existingSigs.mSignatures) { 4577 existingSet.add(sig); 4578 } 4579 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4580 for (Signature sig : scannedPkg.mSignatures) { 4581 try { 4582 Signature[] chainSignatures = sig.getChainSignatures(); 4583 for (Signature chainSig : chainSignatures) { 4584 scannedCompatSet.add(chainSig); 4585 } 4586 } catch (CertificateEncodingException e) { 4587 scannedCompatSet.add(sig); 4588 } 4589 } 4590 /* 4591 * Make sure the expanded scanned set contains all signatures in the 4592 * existing one. 4593 */ 4594 if (scannedCompatSet.equals(existingSet)) { 4595 // Migrate the old signatures to the new scheme. 4596 existingSigs.assignSignatures(scannedPkg.mSignatures); 4597 // The new KeySets will be re-added later in the scanning process. 4598 synchronized (mPackages) { 4599 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4600 } 4601 return PackageManager.SIGNATURE_MATCH; 4602 } 4603 return PackageManager.SIGNATURE_NO_MATCH; 4604 } 4605 4606 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4607 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4608 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4609 } 4610 4611 private int compareSignaturesRecover(PackageSignatures existingSigs, 4612 PackageParser.Package scannedPkg) { 4613 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4614 return PackageManager.SIGNATURE_NO_MATCH; 4615 } 4616 4617 String msg = null; 4618 try { 4619 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4620 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4621 + scannedPkg.packageName); 4622 return PackageManager.SIGNATURE_MATCH; 4623 } 4624 } catch (CertificateException e) { 4625 msg = e.getMessage(); 4626 } 4627 4628 logCriticalInfo(Log.INFO, 4629 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4630 return PackageManager.SIGNATURE_NO_MATCH; 4631 } 4632 4633 @Override 4634 public List<String> getAllPackages() { 4635 synchronized (mPackages) { 4636 return new ArrayList<String>(mPackages.keySet()); 4637 } 4638 } 4639 4640 @Override 4641 public String[] getPackagesForUid(int uid) { 4642 final int userId = UserHandle.getUserId(uid); 4643 uid = UserHandle.getAppId(uid); 4644 // reader 4645 synchronized (mPackages) { 4646 Object obj = mSettings.getUserIdLPr(uid); 4647 if (obj instanceof SharedUserSetting) { 4648 final SharedUserSetting sus = (SharedUserSetting) obj; 4649 final int N = sus.packages.size(); 4650 String[] res = new String[N]; 4651 final Iterator<PackageSetting> it = sus.packages.iterator(); 4652 int i = 0; 4653 while (it.hasNext()) { 4654 PackageSetting ps = it.next(); 4655 if (ps.getInstalled(userId)) { 4656 res[i++] = ps.name; 4657 } else { 4658 res = ArrayUtils.removeElement(String.class, res, res[i]); 4659 } 4660 } 4661 return res; 4662 } else if (obj instanceof PackageSetting) { 4663 final PackageSetting ps = (PackageSetting) obj; 4664 return new String[] { ps.name }; 4665 } 4666 } 4667 return null; 4668 } 4669 4670 @Override 4671 public String getNameForUid(int uid) { 4672 // reader 4673 synchronized (mPackages) { 4674 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4675 if (obj instanceof SharedUserSetting) { 4676 final SharedUserSetting sus = (SharedUserSetting) obj; 4677 return sus.name + ":" + sus.userId; 4678 } else if (obj instanceof PackageSetting) { 4679 final PackageSetting ps = (PackageSetting) obj; 4680 return ps.name; 4681 } 4682 } 4683 return null; 4684 } 4685 4686 @Override 4687 public int getUidForSharedUser(String sharedUserName) { 4688 if(sharedUserName == null) { 4689 return -1; 4690 } 4691 // reader 4692 synchronized (mPackages) { 4693 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4694 if (suid == null) { 4695 return -1; 4696 } 4697 return suid.userId; 4698 } 4699 } 4700 4701 @Override 4702 public int getFlagsForUid(int uid) { 4703 synchronized (mPackages) { 4704 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4705 if (obj instanceof SharedUserSetting) { 4706 final SharedUserSetting sus = (SharedUserSetting) obj; 4707 return sus.pkgFlags; 4708 } else if (obj instanceof PackageSetting) { 4709 final PackageSetting ps = (PackageSetting) obj; 4710 return ps.pkgFlags; 4711 } 4712 } 4713 return 0; 4714 } 4715 4716 @Override 4717 public int getPrivateFlagsForUid(int uid) { 4718 synchronized (mPackages) { 4719 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4720 if (obj instanceof SharedUserSetting) { 4721 final SharedUserSetting sus = (SharedUserSetting) obj; 4722 return sus.pkgPrivateFlags; 4723 } else if (obj instanceof PackageSetting) { 4724 final PackageSetting ps = (PackageSetting) obj; 4725 return ps.pkgPrivateFlags; 4726 } 4727 } 4728 return 0; 4729 } 4730 4731 @Override 4732 public boolean isUidPrivileged(int uid) { 4733 uid = UserHandle.getAppId(uid); 4734 // reader 4735 synchronized (mPackages) { 4736 Object obj = mSettings.getUserIdLPr(uid); 4737 if (obj instanceof SharedUserSetting) { 4738 final SharedUserSetting sus = (SharedUserSetting) obj; 4739 final Iterator<PackageSetting> it = sus.packages.iterator(); 4740 while (it.hasNext()) { 4741 if (it.next().isPrivileged()) { 4742 return true; 4743 } 4744 } 4745 } else if (obj instanceof PackageSetting) { 4746 final PackageSetting ps = (PackageSetting) obj; 4747 return ps.isPrivileged(); 4748 } 4749 } 4750 return false; 4751 } 4752 4753 @Override 4754 public String[] getAppOpPermissionPackages(String permissionName) { 4755 synchronized (mPackages) { 4756 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4757 if (pkgs == null) { 4758 return null; 4759 } 4760 return pkgs.toArray(new String[pkgs.size()]); 4761 } 4762 } 4763 4764 @Override 4765 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4766 int flags, int userId) { 4767 try { 4768 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4769 4770 if (!sUserManager.exists(userId)) return null; 4771 flags = updateFlagsForResolve(flags, userId, intent); 4772 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4773 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4774 4775 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4776 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4777 flags, userId); 4778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4779 4780 final ResolveInfo bestChoice = 4781 chooseBestActivity(intent, resolvedType, flags, query, userId); 4782 return bestChoice; 4783 } finally { 4784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4785 } 4786 } 4787 4788 @Override 4789 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4790 IntentFilter filter, int match, ComponentName activity) { 4791 final int userId = UserHandle.getCallingUserId(); 4792 if (DEBUG_PREFERRED) { 4793 Log.v(TAG, "setLastChosenActivity intent=" + intent 4794 + " resolvedType=" + resolvedType 4795 + " flags=" + flags 4796 + " filter=" + filter 4797 + " match=" + match 4798 + " activity=" + activity); 4799 filter.dump(new PrintStreamPrinter(System.out), " "); 4800 } 4801 intent.setComponent(null); 4802 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4803 userId); 4804 // Find any earlier preferred or last chosen entries and nuke them 4805 findPreferredActivity(intent, resolvedType, 4806 flags, query, 0, false, true, false, userId); 4807 // Add the new activity as the last chosen for this filter 4808 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4809 "Setting last chosen"); 4810 } 4811 4812 @Override 4813 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4814 final int userId = UserHandle.getCallingUserId(); 4815 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4816 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4817 userId); 4818 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4819 false, false, false, userId); 4820 } 4821 4822 private boolean isEphemeralDisabled() { 4823 // ephemeral apps have been disabled across the board 4824 if (DISABLE_EPHEMERAL_APPS) { 4825 return true; 4826 } 4827 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4828 if (!mSystemReady) { 4829 return true; 4830 } 4831 // we can't get a content resolver until the system is ready; these checks must happen last 4832 final ContentResolver resolver = mContext.getContentResolver(); 4833 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4834 return true; 4835 } 4836 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4837 } 4838 4839 private boolean isEphemeralAllowed( 4840 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4841 boolean skipPackageCheck) { 4842 // Short circuit and return early if possible. 4843 if (isEphemeralDisabled()) { 4844 return false; 4845 } 4846 final int callingUser = UserHandle.getCallingUserId(); 4847 if (callingUser != UserHandle.USER_SYSTEM) { 4848 return false; 4849 } 4850 if (mEphemeralResolverConnection == null) { 4851 return false; 4852 } 4853 if (intent.getComponent() != null) { 4854 return false; 4855 } 4856 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4857 return false; 4858 } 4859 if (!skipPackageCheck && intent.getPackage() != null) { 4860 return false; 4861 } 4862 final boolean isWebUri = hasWebURI(intent); 4863 if (!isWebUri || intent.getData().getHost() == null) { 4864 return false; 4865 } 4866 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4867 synchronized (mPackages) { 4868 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4869 for (int n = 0; n < count; n++) { 4870 ResolveInfo info = resolvedActivities.get(n); 4871 String packageName = info.activityInfo.packageName; 4872 PackageSetting ps = mSettings.mPackages.get(packageName); 4873 if (ps != null) { 4874 // Try to get the status from User settings first 4875 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4876 int status = (int) (packedStatus >> 32); 4877 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4878 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4879 if (DEBUG_EPHEMERAL) { 4880 Slog.v(TAG, "DENY ephemeral apps;" 4881 + " pkg: " + packageName + ", status: " + status); 4882 } 4883 return false; 4884 } 4885 } 4886 } 4887 } 4888 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4889 return true; 4890 } 4891 4892 private static EphemeralResolveInfo getEphemeralResolveInfo( 4893 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4894 String resolvedType, int userId, String packageName) { 4895 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4896 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4897 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4898 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4899 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4900 ephemeralPrefixCount); 4901 final int[] shaPrefix = digest.getDigestPrefix(); 4902 final byte[][] digestBytes = digest.getDigestBytes(); 4903 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4904 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4905 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4906 // No hash prefix match; there are no ephemeral apps for this domain. 4907 return null; 4908 } 4909 4910 // Go in reverse order so we match the narrowest scope first. 4911 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4912 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4913 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4914 continue; 4915 } 4916 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4917 // No filters; this should never happen. 4918 if (filters.isEmpty()) { 4919 continue; 4920 } 4921 if (packageName != null 4922 && !packageName.equals(ephemeralApplication.getPackageName())) { 4923 continue; 4924 } 4925 // We have a domain match; resolve the filters to see if anything matches. 4926 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4927 for (int j = filters.size() - 1; j >= 0; --j) { 4928 final EphemeralResolveIntentInfo intentInfo = 4929 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4930 ephemeralResolver.addFilter(intentInfo); 4931 } 4932 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4933 intent, resolvedType, false /*defaultOnly*/, userId); 4934 if (!matchedResolveInfoList.isEmpty()) { 4935 return matchedResolveInfoList.get(0); 4936 } 4937 } 4938 } 4939 // Hash or filter mis-match; no ephemeral apps for this domain. 4940 return null; 4941 } 4942 4943 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4944 int flags, List<ResolveInfo> query, int userId) { 4945 if (query != null) { 4946 final int N = query.size(); 4947 if (N == 1) { 4948 return query.get(0); 4949 } else if (N > 1) { 4950 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4951 // If there is more than one activity with the same priority, 4952 // then let the user decide between them. 4953 ResolveInfo r0 = query.get(0); 4954 ResolveInfo r1 = query.get(1); 4955 if (DEBUG_INTENT_MATCHING || debug) { 4956 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4957 + r1.activityInfo.name + "=" + r1.priority); 4958 } 4959 // If the first activity has a higher priority, or a different 4960 // default, then it is always desirable to pick it. 4961 if (r0.priority != r1.priority 4962 || r0.preferredOrder != r1.preferredOrder 4963 || r0.isDefault != r1.isDefault) { 4964 return query.get(0); 4965 } 4966 // If we have saved a preference for a preferred activity for 4967 // this Intent, use that. 4968 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4969 flags, query, r0.priority, true, false, debug, userId); 4970 if (ri != null) { 4971 return ri; 4972 } 4973 ri = new ResolveInfo(mResolveInfo); 4974 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4975 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4976 // If all of the options come from the same package, show the application's 4977 // label and icon instead of the generic resolver's. 4978 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4979 // and then throw away the ResolveInfo itself, meaning that the caller loses 4980 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4981 // a fallback for this case; we only set the target package's resources on 4982 // the ResolveInfo, not the ActivityInfo. 4983 final String intentPackage = intent.getPackage(); 4984 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4985 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4986 ri.resolvePackageName = intentPackage; 4987 if (userNeedsBadging(userId)) { 4988 ri.noResourceId = true; 4989 } else { 4990 ri.icon = appi.icon; 4991 } 4992 ri.iconResourceId = appi.icon; 4993 ri.labelRes = appi.labelRes; 4994 } 4995 ri.activityInfo.applicationInfo = new ApplicationInfo( 4996 ri.activityInfo.applicationInfo); 4997 if (userId != 0) { 4998 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4999 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5000 } 5001 // Make sure that the resolver is displayable in car mode 5002 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5003 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5004 return ri; 5005 } 5006 } 5007 return null; 5008 } 5009 5010 /** 5011 * Return true if the given list is not empty and all of its contents have 5012 * an activityInfo with the given package name. 5013 */ 5014 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5015 if (ArrayUtils.isEmpty(list)) { 5016 return false; 5017 } 5018 for (int i = 0, N = list.size(); i < N; i++) { 5019 final ResolveInfo ri = list.get(i); 5020 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5021 if (ai == null || !packageName.equals(ai.packageName)) { 5022 return false; 5023 } 5024 } 5025 return true; 5026 } 5027 5028 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5029 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5030 final int N = query.size(); 5031 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5032 .get(userId); 5033 // Get the list of persistent preferred activities that handle the intent 5034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5035 List<PersistentPreferredActivity> pprefs = ppir != null 5036 ? ppir.queryIntent(intent, resolvedType, 5037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5038 : null; 5039 if (pprefs != null && pprefs.size() > 0) { 5040 final int M = pprefs.size(); 5041 for (int i=0; i<M; i++) { 5042 final PersistentPreferredActivity ppa = pprefs.get(i); 5043 if (DEBUG_PREFERRED || debug) { 5044 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5045 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5046 + "\n component=" + ppa.mComponent); 5047 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5048 } 5049 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5050 flags | MATCH_DISABLED_COMPONENTS, userId); 5051 if (DEBUG_PREFERRED || debug) { 5052 Slog.v(TAG, "Found persistent preferred activity:"); 5053 if (ai != null) { 5054 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5055 } else { 5056 Slog.v(TAG, " null"); 5057 } 5058 } 5059 if (ai == null) { 5060 // This previously registered persistent preferred activity 5061 // component is no longer known. Ignore it and do NOT remove it. 5062 continue; 5063 } 5064 for (int j=0; j<N; j++) { 5065 final ResolveInfo ri = query.get(j); 5066 if (!ri.activityInfo.applicationInfo.packageName 5067 .equals(ai.applicationInfo.packageName)) { 5068 continue; 5069 } 5070 if (!ri.activityInfo.name.equals(ai.name)) { 5071 continue; 5072 } 5073 // Found a persistent preference that can handle the intent. 5074 if (DEBUG_PREFERRED || debug) { 5075 Slog.v(TAG, "Returning persistent preferred activity: " + 5076 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5077 } 5078 return ri; 5079 } 5080 } 5081 } 5082 return null; 5083 } 5084 5085 // TODO: handle preferred activities missing while user has amnesia 5086 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5087 List<ResolveInfo> query, int priority, boolean always, 5088 boolean removeMatches, boolean debug, int userId) { 5089 if (!sUserManager.exists(userId)) return null; 5090 flags = updateFlagsForResolve(flags, userId, intent); 5091 // writer 5092 synchronized (mPackages) { 5093 if (intent.getSelector() != null) { 5094 intent = intent.getSelector(); 5095 } 5096 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5097 5098 // Try to find a matching persistent preferred activity. 5099 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5100 debug, userId); 5101 5102 // If a persistent preferred activity matched, use it. 5103 if (pri != null) { 5104 return pri; 5105 } 5106 5107 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5108 // Get the list of preferred activities that handle the intent 5109 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5110 List<PreferredActivity> prefs = pir != null 5111 ? pir.queryIntent(intent, resolvedType, 5112 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5113 : null; 5114 if (prefs != null && prefs.size() > 0) { 5115 boolean changed = false; 5116 try { 5117 // First figure out how good the original match set is. 5118 // We will only allow preferred activities that came 5119 // from the same match quality. 5120 int match = 0; 5121 5122 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5123 5124 final int N = query.size(); 5125 for (int j=0; j<N; j++) { 5126 final ResolveInfo ri = query.get(j); 5127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5128 + ": 0x" + Integer.toHexString(match)); 5129 if (ri.match > match) { 5130 match = ri.match; 5131 } 5132 } 5133 5134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5135 + Integer.toHexString(match)); 5136 5137 match &= IntentFilter.MATCH_CATEGORY_MASK; 5138 final int M = prefs.size(); 5139 for (int i=0; i<M; i++) { 5140 final PreferredActivity pa = prefs.get(i); 5141 if (DEBUG_PREFERRED || debug) { 5142 Slog.v(TAG, "Checking PreferredActivity ds=" 5143 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5144 + "\n component=" + pa.mPref.mComponent); 5145 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5146 } 5147 if (pa.mPref.mMatch != match) { 5148 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5149 + Integer.toHexString(pa.mPref.mMatch)); 5150 continue; 5151 } 5152 // If it's not an "always" type preferred activity and that's what we're 5153 // looking for, skip it. 5154 if (always && !pa.mPref.mAlways) { 5155 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5156 continue; 5157 } 5158 final ActivityInfo ai = getActivityInfo( 5159 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5160 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5161 userId); 5162 if (DEBUG_PREFERRED || debug) { 5163 Slog.v(TAG, "Found preferred activity:"); 5164 if (ai != null) { 5165 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5166 } else { 5167 Slog.v(TAG, " null"); 5168 } 5169 } 5170 if (ai == null) { 5171 // This previously registered preferred activity 5172 // component is no longer known. Most likely an update 5173 // to the app was installed and in the new version this 5174 // component no longer exists. Clean it up by removing 5175 // it from the preferred activities list, and skip it. 5176 Slog.w(TAG, "Removing dangling preferred activity: " 5177 + pa.mPref.mComponent); 5178 pir.removeFilter(pa); 5179 changed = true; 5180 continue; 5181 } 5182 for (int j=0; j<N; j++) { 5183 final ResolveInfo ri = query.get(j); 5184 if (!ri.activityInfo.applicationInfo.packageName 5185 .equals(ai.applicationInfo.packageName)) { 5186 continue; 5187 } 5188 if (!ri.activityInfo.name.equals(ai.name)) { 5189 continue; 5190 } 5191 5192 if (removeMatches) { 5193 pir.removeFilter(pa); 5194 changed = true; 5195 if (DEBUG_PREFERRED) { 5196 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5197 } 5198 break; 5199 } 5200 5201 // Okay we found a previously set preferred or last chosen app. 5202 // If the result set is different from when this 5203 // was created, we need to clear it and re-ask the 5204 // user their preference, if we're looking for an "always" type entry. 5205 if (always && !pa.mPref.sameSet(query)) { 5206 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5207 + intent + " type " + resolvedType); 5208 if (DEBUG_PREFERRED) { 5209 Slog.v(TAG, "Removing preferred activity since set changed " 5210 + pa.mPref.mComponent); 5211 } 5212 pir.removeFilter(pa); 5213 // Re-add the filter as a "last chosen" entry (!always) 5214 PreferredActivity lastChosen = new PreferredActivity( 5215 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5216 pir.addFilter(lastChosen); 5217 changed = true; 5218 return null; 5219 } 5220 5221 // Yay! Either the set matched or we're looking for the last chosen 5222 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5223 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5224 return ri; 5225 } 5226 } 5227 } finally { 5228 if (changed) { 5229 if (DEBUG_PREFERRED) { 5230 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5231 } 5232 scheduleWritePackageRestrictionsLocked(userId); 5233 } 5234 } 5235 } 5236 } 5237 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5238 return null; 5239 } 5240 5241 /* 5242 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5243 */ 5244 @Override 5245 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5246 int targetUserId) { 5247 mContext.enforceCallingOrSelfPermission( 5248 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5249 List<CrossProfileIntentFilter> matches = 5250 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5251 if (matches != null) { 5252 int size = matches.size(); 5253 for (int i = 0; i < size; i++) { 5254 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5255 } 5256 } 5257 if (hasWebURI(intent)) { 5258 // cross-profile app linking works only towards the parent. 5259 final UserInfo parent = getProfileParent(sourceUserId); 5260 synchronized(mPackages) { 5261 int flags = updateFlagsForResolve(0, parent.id, intent); 5262 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5263 intent, resolvedType, flags, sourceUserId, parent.id); 5264 return xpDomainInfo != null; 5265 } 5266 } 5267 return false; 5268 } 5269 5270 private UserInfo getProfileParent(int userId) { 5271 final long identity = Binder.clearCallingIdentity(); 5272 try { 5273 return sUserManager.getProfileParent(userId); 5274 } finally { 5275 Binder.restoreCallingIdentity(identity); 5276 } 5277 } 5278 5279 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5280 String resolvedType, int userId) { 5281 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5282 if (resolver != null) { 5283 return resolver.queryIntent(intent, resolvedType, false, userId); 5284 } 5285 return null; 5286 } 5287 5288 @Override 5289 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5290 String resolvedType, int flags, int userId) { 5291 try { 5292 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5293 5294 return new ParceledListSlice<>( 5295 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5296 } finally { 5297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5298 } 5299 } 5300 5301 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5302 String resolvedType, int flags, int userId) { 5303 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5304 flags = updateFlagsForResolve(flags, userId, intent); 5305 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5306 false /* requireFullPermission */, false /* checkShell */, 5307 "query intent activities"); 5308 ComponentName comp = intent.getComponent(); 5309 if (comp == null) { 5310 if (intent.getSelector() != null) { 5311 intent = intent.getSelector(); 5312 comp = intent.getComponent(); 5313 } 5314 } 5315 5316 if (comp != null) { 5317 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5318 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5319 if (ai != null) { 5320 final ResolveInfo ri = new ResolveInfo(); 5321 ri.activityInfo = ai; 5322 list.add(ri); 5323 } 5324 return list; 5325 } 5326 5327 // reader 5328 boolean sortResult = false; 5329 boolean addEphemeral = false; 5330 boolean matchEphemeralPackage = false; 5331 List<ResolveInfo> result; 5332 final String pkgName = intent.getPackage(); 5333 synchronized (mPackages) { 5334 if (pkgName == null) { 5335 List<CrossProfileIntentFilter> matchingFilters = 5336 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5337 // Check for results that need to skip the current profile. 5338 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5339 resolvedType, flags, userId); 5340 if (xpResolveInfo != null) { 5341 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5342 xpResult.add(xpResolveInfo); 5343 return filterIfNotSystemUser(xpResult, userId); 5344 } 5345 5346 // Check for results in the current profile. 5347 result = filterIfNotSystemUser(mActivities.queryIntent( 5348 intent, resolvedType, flags, userId), userId); 5349 addEphemeral = 5350 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5351 5352 // Check for cross profile results. 5353 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5354 xpResolveInfo = queryCrossProfileIntents( 5355 matchingFilters, intent, resolvedType, flags, userId, 5356 hasNonNegativePriorityResult); 5357 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5358 boolean isVisibleToUser = filterIfNotSystemUser( 5359 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5360 if (isVisibleToUser) { 5361 result.add(xpResolveInfo); 5362 sortResult = true; 5363 } 5364 } 5365 if (hasWebURI(intent)) { 5366 CrossProfileDomainInfo xpDomainInfo = null; 5367 final UserInfo parent = getProfileParent(userId); 5368 if (parent != null) { 5369 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5370 flags, userId, parent.id); 5371 } 5372 if (xpDomainInfo != null) { 5373 if (xpResolveInfo != null) { 5374 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5375 // in the result. 5376 result.remove(xpResolveInfo); 5377 } 5378 if (result.size() == 0 && !addEphemeral) { 5379 result.add(xpDomainInfo.resolveInfo); 5380 return result; 5381 } 5382 } 5383 if (result.size() > 1 || addEphemeral) { 5384 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5385 intent, flags, result, xpDomainInfo, userId); 5386 sortResult = true; 5387 } 5388 } 5389 } else { 5390 final PackageParser.Package pkg = mPackages.get(pkgName); 5391 if (pkg != null) { 5392 result = filterIfNotSystemUser( 5393 mActivities.queryIntentForPackage( 5394 intent, resolvedType, flags, pkg.activities, userId), 5395 userId); 5396 } else { 5397 // the caller wants to resolve for a particular package; however, there 5398 // were no installed results, so, try to find an ephemeral result 5399 addEphemeral = isEphemeralAllowed( 5400 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5401 matchEphemeralPackage = true; 5402 result = new ArrayList<ResolveInfo>(); 5403 } 5404 } 5405 } 5406 if (addEphemeral) { 5407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5408 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5409 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5410 matchEphemeralPackage ? pkgName : null); 5411 if (ai != null) { 5412 if (DEBUG_EPHEMERAL) { 5413 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5414 } 5415 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5416 ephemeralInstaller.ephemeralResolveInfo = ai; 5417 // make sure this resolver is the default 5418 ephemeralInstaller.isDefault = true; 5419 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5420 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5421 // add a non-generic filter 5422 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5423 ephemeralInstaller.filter.addDataPath( 5424 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5425 result.add(ephemeralInstaller); 5426 } 5427 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5428 } 5429 if (sortResult) { 5430 Collections.sort(result, mResolvePrioritySorter); 5431 } 5432 return result; 5433 } 5434 5435 private static class CrossProfileDomainInfo { 5436 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5437 ResolveInfo resolveInfo; 5438 /* Best domain verification status of the activities found in the other profile */ 5439 int bestDomainVerificationStatus; 5440 } 5441 5442 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5443 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5444 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5445 sourceUserId)) { 5446 return null; 5447 } 5448 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5449 resolvedType, flags, parentUserId); 5450 5451 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5452 return null; 5453 } 5454 CrossProfileDomainInfo result = null; 5455 int size = resultTargetUser.size(); 5456 for (int i = 0; i < size; i++) { 5457 ResolveInfo riTargetUser = resultTargetUser.get(i); 5458 // Intent filter verification is only for filters that specify a host. So don't return 5459 // those that handle all web uris. 5460 if (riTargetUser.handleAllWebDataURI) { 5461 continue; 5462 } 5463 String packageName = riTargetUser.activityInfo.packageName; 5464 PackageSetting ps = mSettings.mPackages.get(packageName); 5465 if (ps == null) { 5466 continue; 5467 } 5468 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5469 int status = (int)(verificationState >> 32); 5470 if (result == null) { 5471 result = new CrossProfileDomainInfo(); 5472 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5473 sourceUserId, parentUserId); 5474 result.bestDomainVerificationStatus = status; 5475 } else { 5476 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5477 result.bestDomainVerificationStatus); 5478 } 5479 } 5480 // Don't consider matches with status NEVER across profiles. 5481 if (result != null && result.bestDomainVerificationStatus 5482 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5483 return null; 5484 } 5485 return result; 5486 } 5487 5488 /** 5489 * Verification statuses are ordered from the worse to the best, except for 5490 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5491 */ 5492 private int bestDomainVerificationStatus(int status1, int status2) { 5493 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5494 return status2; 5495 } 5496 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5497 return status1; 5498 } 5499 return (int) MathUtils.max(status1, status2); 5500 } 5501 5502 private boolean isUserEnabled(int userId) { 5503 long callingId = Binder.clearCallingIdentity(); 5504 try { 5505 UserInfo userInfo = sUserManager.getUserInfo(userId); 5506 return userInfo != null && userInfo.isEnabled(); 5507 } finally { 5508 Binder.restoreCallingIdentity(callingId); 5509 } 5510 } 5511 5512 /** 5513 * Filter out activities with systemUserOnly flag set, when current user is not System. 5514 * 5515 * @return filtered list 5516 */ 5517 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5518 if (userId == UserHandle.USER_SYSTEM) { 5519 return resolveInfos; 5520 } 5521 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5522 ResolveInfo info = resolveInfos.get(i); 5523 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5524 resolveInfos.remove(i); 5525 } 5526 } 5527 return resolveInfos; 5528 } 5529 5530 /** 5531 * @param resolveInfos list of resolve infos in descending priority order 5532 * @return if the list contains a resolve info with non-negative priority 5533 */ 5534 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5535 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5536 } 5537 5538 private static boolean hasWebURI(Intent intent) { 5539 if (intent.getData() == null) { 5540 return false; 5541 } 5542 final String scheme = intent.getScheme(); 5543 if (TextUtils.isEmpty(scheme)) { 5544 return false; 5545 } 5546 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5547 } 5548 5549 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5550 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5551 int userId) { 5552 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5553 5554 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5555 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5556 candidates.size()); 5557 } 5558 5559 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5560 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5561 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5562 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5563 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5564 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5565 5566 synchronized (mPackages) { 5567 final int count = candidates.size(); 5568 // First, try to use linked apps. Partition the candidates into four lists: 5569 // one for the final results, one for the "do not use ever", one for "undefined status" 5570 // and finally one for "browser app type". 5571 for (int n=0; n<count; n++) { 5572 ResolveInfo info = candidates.get(n); 5573 String packageName = info.activityInfo.packageName; 5574 PackageSetting ps = mSettings.mPackages.get(packageName); 5575 if (ps != null) { 5576 // Add to the special match all list (Browser use case) 5577 if (info.handleAllWebDataURI) { 5578 matchAllList.add(info); 5579 continue; 5580 } 5581 // Try to get the status from User settings first 5582 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5583 int status = (int)(packedStatus >> 32); 5584 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5585 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5586 if (DEBUG_DOMAIN_VERIFICATION) { 5587 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5588 + " : linkgen=" + linkGeneration); 5589 } 5590 // Use link-enabled generation as preferredOrder, i.e. 5591 // prefer newly-enabled over earlier-enabled. 5592 info.preferredOrder = linkGeneration; 5593 alwaysList.add(info); 5594 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5595 if (DEBUG_DOMAIN_VERIFICATION) { 5596 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5597 } 5598 neverList.add(info); 5599 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5600 if (DEBUG_DOMAIN_VERIFICATION) { 5601 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5602 } 5603 alwaysAskList.add(info); 5604 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5605 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5606 if (DEBUG_DOMAIN_VERIFICATION) { 5607 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5608 } 5609 undefinedList.add(info); 5610 } 5611 } 5612 } 5613 5614 // We'll want to include browser possibilities in a few cases 5615 boolean includeBrowser = false; 5616 5617 // First try to add the "always" resolution(s) for the current user, if any 5618 if (alwaysList.size() > 0) { 5619 result.addAll(alwaysList); 5620 } else { 5621 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5622 result.addAll(undefinedList); 5623 // Maybe add one for the other profile. 5624 if (xpDomainInfo != null && ( 5625 xpDomainInfo.bestDomainVerificationStatus 5626 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5627 result.add(xpDomainInfo.resolveInfo); 5628 } 5629 includeBrowser = true; 5630 } 5631 5632 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5633 // If there were 'always' entries their preferred order has been set, so we also 5634 // back that off to make the alternatives equivalent 5635 if (alwaysAskList.size() > 0) { 5636 for (ResolveInfo i : result) { 5637 i.preferredOrder = 0; 5638 } 5639 result.addAll(alwaysAskList); 5640 includeBrowser = true; 5641 } 5642 5643 if (includeBrowser) { 5644 // Also add browsers (all of them or only the default one) 5645 if (DEBUG_DOMAIN_VERIFICATION) { 5646 Slog.v(TAG, " ...including browsers in candidate set"); 5647 } 5648 if ((matchFlags & MATCH_ALL) != 0) { 5649 result.addAll(matchAllList); 5650 } else { 5651 // Browser/generic handling case. If there's a default browser, go straight 5652 // to that (but only if there is no other higher-priority match). 5653 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5654 int maxMatchPrio = 0; 5655 ResolveInfo defaultBrowserMatch = null; 5656 final int numCandidates = matchAllList.size(); 5657 for (int n = 0; n < numCandidates; n++) { 5658 ResolveInfo info = matchAllList.get(n); 5659 // track the highest overall match priority... 5660 if (info.priority > maxMatchPrio) { 5661 maxMatchPrio = info.priority; 5662 } 5663 // ...and the highest-priority default browser match 5664 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5665 if (defaultBrowserMatch == null 5666 || (defaultBrowserMatch.priority < info.priority)) { 5667 if (debug) { 5668 Slog.v(TAG, "Considering default browser match " + info); 5669 } 5670 defaultBrowserMatch = info; 5671 } 5672 } 5673 } 5674 if (defaultBrowserMatch != null 5675 && defaultBrowserMatch.priority >= maxMatchPrio 5676 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5677 { 5678 if (debug) { 5679 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5680 } 5681 result.add(defaultBrowserMatch); 5682 } else { 5683 result.addAll(matchAllList); 5684 } 5685 } 5686 5687 // If there is nothing selected, add all candidates and remove the ones that the user 5688 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5689 if (result.size() == 0) { 5690 result.addAll(candidates); 5691 result.removeAll(neverList); 5692 } 5693 } 5694 } 5695 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5696 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5697 result.size()); 5698 for (ResolveInfo info : result) { 5699 Slog.v(TAG, " + " + info.activityInfo); 5700 } 5701 } 5702 return result; 5703 } 5704 5705 // Returns a packed value as a long: 5706 // 5707 // high 'int'-sized word: link status: undefined/ask/never/always. 5708 // low 'int'-sized word: relative priority among 'always' results. 5709 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5710 long result = ps.getDomainVerificationStatusForUser(userId); 5711 // if none available, get the master status 5712 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5713 if (ps.getIntentFilterVerificationInfo() != null) { 5714 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5715 } 5716 } 5717 return result; 5718 } 5719 5720 private ResolveInfo querySkipCurrentProfileIntents( 5721 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5722 int flags, int sourceUserId) { 5723 if (matchingFilters != null) { 5724 int size = matchingFilters.size(); 5725 for (int i = 0; i < size; i ++) { 5726 CrossProfileIntentFilter filter = matchingFilters.get(i); 5727 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5728 // Checking if there are activities in the target user that can handle the 5729 // intent. 5730 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5731 resolvedType, flags, sourceUserId); 5732 if (resolveInfo != null) { 5733 return resolveInfo; 5734 } 5735 } 5736 } 5737 } 5738 return null; 5739 } 5740 5741 // Return matching ResolveInfo in target user if any. 5742 private ResolveInfo queryCrossProfileIntents( 5743 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5744 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5745 if (matchingFilters != null) { 5746 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5747 // match the same intent. For performance reasons, it is better not to 5748 // run queryIntent twice for the same userId 5749 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5750 int size = matchingFilters.size(); 5751 for (int i = 0; i < size; i++) { 5752 CrossProfileIntentFilter filter = matchingFilters.get(i); 5753 int targetUserId = filter.getTargetUserId(); 5754 boolean skipCurrentProfile = 5755 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5756 boolean skipCurrentProfileIfNoMatchFound = 5757 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5758 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5759 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5760 // Checking if there are activities in the target user that can handle the 5761 // intent. 5762 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5763 resolvedType, flags, sourceUserId); 5764 if (resolveInfo != null) return resolveInfo; 5765 alreadyTriedUserIds.put(targetUserId, true); 5766 } 5767 } 5768 } 5769 return null; 5770 } 5771 5772 /** 5773 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5774 * will forward the intent to the filter's target user. 5775 * Otherwise, returns null. 5776 */ 5777 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5778 String resolvedType, int flags, int sourceUserId) { 5779 int targetUserId = filter.getTargetUserId(); 5780 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5781 resolvedType, flags, targetUserId); 5782 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5783 // If all the matches in the target profile are suspended, return null. 5784 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5785 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5786 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5787 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5788 targetUserId); 5789 } 5790 } 5791 } 5792 return null; 5793 } 5794 5795 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5796 int sourceUserId, int targetUserId) { 5797 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5798 long ident = Binder.clearCallingIdentity(); 5799 boolean targetIsProfile; 5800 try { 5801 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5802 } finally { 5803 Binder.restoreCallingIdentity(ident); 5804 } 5805 String className; 5806 if (targetIsProfile) { 5807 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5808 } else { 5809 className = FORWARD_INTENT_TO_PARENT; 5810 } 5811 ComponentName forwardingActivityComponentName = new ComponentName( 5812 mAndroidApplication.packageName, className); 5813 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5814 sourceUserId); 5815 if (!targetIsProfile) { 5816 forwardingActivityInfo.showUserIcon = targetUserId; 5817 forwardingResolveInfo.noResourceId = true; 5818 } 5819 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5820 forwardingResolveInfo.priority = 0; 5821 forwardingResolveInfo.preferredOrder = 0; 5822 forwardingResolveInfo.match = 0; 5823 forwardingResolveInfo.isDefault = true; 5824 forwardingResolveInfo.filter = filter; 5825 forwardingResolveInfo.targetUserId = targetUserId; 5826 return forwardingResolveInfo; 5827 } 5828 5829 @Override 5830 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5831 Intent[] specifics, String[] specificTypes, Intent intent, 5832 String resolvedType, int flags, int userId) { 5833 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5834 specificTypes, intent, resolvedType, flags, userId)); 5835 } 5836 5837 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5838 Intent[] specifics, String[] specificTypes, Intent intent, 5839 String resolvedType, int flags, int userId) { 5840 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5841 flags = updateFlagsForResolve(flags, userId, intent); 5842 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5843 false /* requireFullPermission */, false /* checkShell */, 5844 "query intent activity options"); 5845 final String resultsAction = intent.getAction(); 5846 5847 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5848 | PackageManager.GET_RESOLVED_FILTER, userId); 5849 5850 if (DEBUG_INTENT_MATCHING) { 5851 Log.v(TAG, "Query " + intent + ": " + results); 5852 } 5853 5854 int specificsPos = 0; 5855 int N; 5856 5857 // todo: note that the algorithm used here is O(N^2). This 5858 // isn't a problem in our current environment, but if we start running 5859 // into situations where we have more than 5 or 10 matches then this 5860 // should probably be changed to something smarter... 5861 5862 // First we go through and resolve each of the specific items 5863 // that were supplied, taking care of removing any corresponding 5864 // duplicate items in the generic resolve list. 5865 if (specifics != null) { 5866 for (int i=0; i<specifics.length; i++) { 5867 final Intent sintent = specifics[i]; 5868 if (sintent == null) { 5869 continue; 5870 } 5871 5872 if (DEBUG_INTENT_MATCHING) { 5873 Log.v(TAG, "Specific #" + i + ": " + sintent); 5874 } 5875 5876 String action = sintent.getAction(); 5877 if (resultsAction != null && resultsAction.equals(action)) { 5878 // If this action was explicitly requested, then don't 5879 // remove things that have it. 5880 action = null; 5881 } 5882 5883 ResolveInfo ri = null; 5884 ActivityInfo ai = null; 5885 5886 ComponentName comp = sintent.getComponent(); 5887 if (comp == null) { 5888 ri = resolveIntent( 5889 sintent, 5890 specificTypes != null ? specificTypes[i] : null, 5891 flags, userId); 5892 if (ri == null) { 5893 continue; 5894 } 5895 if (ri == mResolveInfo) { 5896 // ACK! Must do something better with this. 5897 } 5898 ai = ri.activityInfo; 5899 comp = new ComponentName(ai.applicationInfo.packageName, 5900 ai.name); 5901 } else { 5902 ai = getActivityInfo(comp, flags, userId); 5903 if (ai == null) { 5904 continue; 5905 } 5906 } 5907 5908 // Look for any generic query activities that are duplicates 5909 // of this specific one, and remove them from the results. 5910 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5911 N = results.size(); 5912 int j; 5913 for (j=specificsPos; j<N; j++) { 5914 ResolveInfo sri = results.get(j); 5915 if ((sri.activityInfo.name.equals(comp.getClassName()) 5916 && sri.activityInfo.applicationInfo.packageName.equals( 5917 comp.getPackageName())) 5918 || (action != null && sri.filter.matchAction(action))) { 5919 results.remove(j); 5920 if (DEBUG_INTENT_MATCHING) Log.v( 5921 TAG, "Removing duplicate item from " + j 5922 + " due to specific " + specificsPos); 5923 if (ri == null) { 5924 ri = sri; 5925 } 5926 j--; 5927 N--; 5928 } 5929 } 5930 5931 // Add this specific item to its proper place. 5932 if (ri == null) { 5933 ri = new ResolveInfo(); 5934 ri.activityInfo = ai; 5935 } 5936 results.add(specificsPos, ri); 5937 ri.specificIndex = i; 5938 specificsPos++; 5939 } 5940 } 5941 5942 // Now we go through the remaining generic results and remove any 5943 // duplicate actions that are found here. 5944 N = results.size(); 5945 for (int i=specificsPos; i<N-1; i++) { 5946 final ResolveInfo rii = results.get(i); 5947 if (rii.filter == null) { 5948 continue; 5949 } 5950 5951 // Iterate over all of the actions of this result's intent 5952 // filter... typically this should be just one. 5953 final Iterator<String> it = rii.filter.actionsIterator(); 5954 if (it == null) { 5955 continue; 5956 } 5957 while (it.hasNext()) { 5958 final String action = it.next(); 5959 if (resultsAction != null && resultsAction.equals(action)) { 5960 // If this action was explicitly requested, then don't 5961 // remove things that have it. 5962 continue; 5963 } 5964 for (int j=i+1; j<N; j++) { 5965 final ResolveInfo rij = results.get(j); 5966 if (rij.filter != null && rij.filter.hasAction(action)) { 5967 results.remove(j); 5968 if (DEBUG_INTENT_MATCHING) Log.v( 5969 TAG, "Removing duplicate item from " + j 5970 + " due to action " + action + " at " + i); 5971 j--; 5972 N--; 5973 } 5974 } 5975 } 5976 5977 // If the caller didn't request filter information, drop it now 5978 // so we don't have to marshall/unmarshall it. 5979 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5980 rii.filter = null; 5981 } 5982 } 5983 5984 // Filter out the caller activity if so requested. 5985 if (caller != null) { 5986 N = results.size(); 5987 for (int i=0; i<N; i++) { 5988 ActivityInfo ainfo = results.get(i).activityInfo; 5989 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5990 && caller.getClassName().equals(ainfo.name)) { 5991 results.remove(i); 5992 break; 5993 } 5994 } 5995 } 5996 5997 // If the caller didn't request filter information, 5998 // drop them now so we don't have to 5999 // marshall/unmarshall it. 6000 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6001 N = results.size(); 6002 for (int i=0; i<N; i++) { 6003 results.get(i).filter = null; 6004 } 6005 } 6006 6007 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6008 return results; 6009 } 6010 6011 @Override 6012 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6013 String resolvedType, int flags, int userId) { 6014 return new ParceledListSlice<>( 6015 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6016 } 6017 6018 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6019 String resolvedType, int flags, int userId) { 6020 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6021 flags = updateFlagsForResolve(flags, userId, intent); 6022 ComponentName comp = intent.getComponent(); 6023 if (comp == null) { 6024 if (intent.getSelector() != null) { 6025 intent = intent.getSelector(); 6026 comp = intent.getComponent(); 6027 } 6028 } 6029 if (comp != null) { 6030 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6031 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6032 if (ai != null) { 6033 ResolveInfo ri = new ResolveInfo(); 6034 ri.activityInfo = ai; 6035 list.add(ri); 6036 } 6037 return list; 6038 } 6039 6040 // reader 6041 synchronized (mPackages) { 6042 String pkgName = intent.getPackage(); 6043 if (pkgName == null) { 6044 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6045 } 6046 final PackageParser.Package pkg = mPackages.get(pkgName); 6047 if (pkg != null) { 6048 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6049 userId); 6050 } 6051 return Collections.emptyList(); 6052 } 6053 } 6054 6055 @Override 6056 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6057 if (!sUserManager.exists(userId)) return null; 6058 flags = updateFlagsForResolve(flags, userId, intent); 6059 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6060 if (query != null) { 6061 if (query.size() >= 1) { 6062 // If there is more than one service with the same priority, 6063 // just arbitrarily pick the first one. 6064 return query.get(0); 6065 } 6066 } 6067 return null; 6068 } 6069 6070 @Override 6071 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6072 String resolvedType, int flags, int userId) { 6073 return new ParceledListSlice<>( 6074 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6075 } 6076 6077 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6078 String resolvedType, int flags, int userId) { 6079 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6080 flags = updateFlagsForResolve(flags, userId, intent); 6081 ComponentName comp = intent.getComponent(); 6082 if (comp == null) { 6083 if (intent.getSelector() != null) { 6084 intent = intent.getSelector(); 6085 comp = intent.getComponent(); 6086 } 6087 } 6088 if (comp != null) { 6089 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6090 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6091 if (si != null) { 6092 final ResolveInfo ri = new ResolveInfo(); 6093 ri.serviceInfo = si; 6094 list.add(ri); 6095 } 6096 return list; 6097 } 6098 6099 // reader 6100 synchronized (mPackages) { 6101 String pkgName = intent.getPackage(); 6102 if (pkgName == null) { 6103 return mServices.queryIntent(intent, resolvedType, flags, userId); 6104 } 6105 final PackageParser.Package pkg = mPackages.get(pkgName); 6106 if (pkg != null) { 6107 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6108 userId); 6109 } 6110 return Collections.emptyList(); 6111 } 6112 } 6113 6114 @Override 6115 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6116 String resolvedType, int flags, int userId) { 6117 return new ParceledListSlice<>( 6118 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6119 } 6120 6121 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6122 Intent intent, String resolvedType, int flags, int userId) { 6123 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6124 flags = updateFlagsForResolve(flags, userId, intent); 6125 ComponentName comp = intent.getComponent(); 6126 if (comp == null) { 6127 if (intent.getSelector() != null) { 6128 intent = intent.getSelector(); 6129 comp = intent.getComponent(); 6130 } 6131 } 6132 if (comp != null) { 6133 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6134 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6135 if (pi != null) { 6136 final ResolveInfo ri = new ResolveInfo(); 6137 ri.providerInfo = pi; 6138 list.add(ri); 6139 } 6140 return list; 6141 } 6142 6143 // reader 6144 synchronized (mPackages) { 6145 String pkgName = intent.getPackage(); 6146 if (pkgName == null) { 6147 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6148 } 6149 final PackageParser.Package pkg = mPackages.get(pkgName); 6150 if (pkg != null) { 6151 return mProviders.queryIntentForPackage( 6152 intent, resolvedType, flags, pkg.providers, userId); 6153 } 6154 return Collections.emptyList(); 6155 } 6156 } 6157 6158 @Override 6159 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6160 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6161 flags = updateFlagsForPackage(flags, userId, null); 6162 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6164 true /* requireFullPermission */, false /* checkShell */, 6165 "get installed packages"); 6166 6167 // writer 6168 synchronized (mPackages) { 6169 ArrayList<PackageInfo> list; 6170 if (listUninstalled) { 6171 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6172 for (PackageSetting ps : mSettings.mPackages.values()) { 6173 final PackageInfo pi; 6174 if (ps.pkg != null) { 6175 pi = generatePackageInfo(ps, flags, userId); 6176 } else { 6177 pi = generatePackageInfo(ps, flags, userId); 6178 } 6179 if (pi != null) { 6180 list.add(pi); 6181 } 6182 } 6183 } else { 6184 list = new ArrayList<PackageInfo>(mPackages.size()); 6185 for (PackageParser.Package p : mPackages.values()) { 6186 final PackageInfo pi = 6187 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6188 if (pi != null) { 6189 list.add(pi); 6190 } 6191 } 6192 } 6193 6194 return new ParceledListSlice<PackageInfo>(list); 6195 } 6196 } 6197 6198 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6199 String[] permissions, boolean[] tmp, int flags, int userId) { 6200 int numMatch = 0; 6201 final PermissionsState permissionsState = ps.getPermissionsState(); 6202 for (int i=0; i<permissions.length; i++) { 6203 final String permission = permissions[i]; 6204 if (permissionsState.hasPermission(permission, userId)) { 6205 tmp[i] = true; 6206 numMatch++; 6207 } else { 6208 tmp[i] = false; 6209 } 6210 } 6211 if (numMatch == 0) { 6212 return; 6213 } 6214 final PackageInfo pi; 6215 if (ps.pkg != null) { 6216 pi = generatePackageInfo(ps, flags, userId); 6217 } else { 6218 pi = generatePackageInfo(ps, flags, userId); 6219 } 6220 // The above might return null in cases of uninstalled apps or install-state 6221 // skew across users/profiles. 6222 if (pi != null) { 6223 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6224 if (numMatch == permissions.length) { 6225 pi.requestedPermissions = permissions; 6226 } else { 6227 pi.requestedPermissions = new String[numMatch]; 6228 numMatch = 0; 6229 for (int i=0; i<permissions.length; i++) { 6230 if (tmp[i]) { 6231 pi.requestedPermissions[numMatch] = permissions[i]; 6232 numMatch++; 6233 } 6234 } 6235 } 6236 } 6237 list.add(pi); 6238 } 6239 } 6240 6241 @Override 6242 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6243 String[] permissions, int flags, int userId) { 6244 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6245 flags = updateFlagsForPackage(flags, userId, permissions); 6246 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6247 6248 // writer 6249 synchronized (mPackages) { 6250 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6251 boolean[] tmpBools = new boolean[permissions.length]; 6252 if (listUninstalled) { 6253 for (PackageSetting ps : mSettings.mPackages.values()) { 6254 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6255 } 6256 } else { 6257 for (PackageParser.Package pkg : mPackages.values()) { 6258 PackageSetting ps = (PackageSetting)pkg.mExtras; 6259 if (ps != null) { 6260 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6261 userId); 6262 } 6263 } 6264 } 6265 6266 return new ParceledListSlice<PackageInfo>(list); 6267 } 6268 } 6269 6270 @Override 6271 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6272 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6273 flags = updateFlagsForApplication(flags, userId, null); 6274 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6275 6276 // writer 6277 synchronized (mPackages) { 6278 ArrayList<ApplicationInfo> list; 6279 if (listUninstalled) { 6280 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6281 for (PackageSetting ps : mSettings.mPackages.values()) { 6282 ApplicationInfo ai; 6283 if (ps.pkg != null) { 6284 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6285 ps.readUserState(userId), userId); 6286 } else { 6287 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6288 } 6289 if (ai != null) { 6290 list.add(ai); 6291 } 6292 } 6293 } else { 6294 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6295 for (PackageParser.Package p : mPackages.values()) { 6296 if (p.mExtras != null) { 6297 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6298 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6299 if (ai != null) { 6300 list.add(ai); 6301 } 6302 } 6303 } 6304 } 6305 6306 return new ParceledListSlice<ApplicationInfo>(list); 6307 } 6308 } 6309 6310 @Override 6311 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6312 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6313 return null; 6314 } 6315 6316 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6317 "getEphemeralApplications"); 6318 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6319 true /* requireFullPermission */, false /* checkShell */, 6320 "getEphemeralApplications"); 6321 synchronized (mPackages) { 6322 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6323 .getEphemeralApplicationsLPw(userId); 6324 if (ephemeralApps != null) { 6325 return new ParceledListSlice<>(ephemeralApps); 6326 } 6327 } 6328 return null; 6329 } 6330 6331 @Override 6332 public boolean isEphemeralApplication(String packageName, int userId) { 6333 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6334 true /* requireFullPermission */, false /* checkShell */, 6335 "isEphemeral"); 6336 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6337 return false; 6338 } 6339 6340 if (!isCallerSameApp(packageName)) { 6341 return false; 6342 } 6343 synchronized (mPackages) { 6344 PackageParser.Package pkg = mPackages.get(packageName); 6345 if (pkg != null) { 6346 return pkg.applicationInfo.isEphemeralApp(); 6347 } 6348 } 6349 return false; 6350 } 6351 6352 @Override 6353 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6354 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6355 return null; 6356 } 6357 6358 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6359 true /* requireFullPermission */, false /* checkShell */, 6360 "getCookie"); 6361 if (!isCallerSameApp(packageName)) { 6362 return null; 6363 } 6364 synchronized (mPackages) { 6365 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6366 packageName, userId); 6367 } 6368 } 6369 6370 @Override 6371 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6372 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6373 return true; 6374 } 6375 6376 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6377 true /* requireFullPermission */, true /* checkShell */, 6378 "setCookie"); 6379 if (!isCallerSameApp(packageName)) { 6380 return false; 6381 } 6382 synchronized (mPackages) { 6383 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6384 packageName, cookie, userId); 6385 } 6386 } 6387 6388 @Override 6389 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6390 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6391 return null; 6392 } 6393 6394 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6395 "getEphemeralApplicationIcon"); 6396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6397 true /* requireFullPermission */, false /* checkShell */, 6398 "getEphemeralApplicationIcon"); 6399 synchronized (mPackages) { 6400 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6401 packageName, userId); 6402 } 6403 } 6404 6405 private boolean isCallerSameApp(String packageName) { 6406 PackageParser.Package pkg = mPackages.get(packageName); 6407 return pkg != null 6408 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6409 } 6410 6411 @Override 6412 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6413 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6414 } 6415 6416 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6417 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6418 6419 // reader 6420 synchronized (mPackages) { 6421 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6422 final int userId = UserHandle.getCallingUserId(); 6423 while (i.hasNext()) { 6424 final PackageParser.Package p = i.next(); 6425 if (p.applicationInfo == null) continue; 6426 6427 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6428 && !p.applicationInfo.isDirectBootAware(); 6429 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6430 && p.applicationInfo.isDirectBootAware(); 6431 6432 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6433 && (!mSafeMode || isSystemApp(p)) 6434 && (matchesUnaware || matchesAware)) { 6435 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6436 if (ps != null) { 6437 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6438 ps.readUserState(userId), userId); 6439 if (ai != null) { 6440 finalList.add(ai); 6441 } 6442 } 6443 } 6444 } 6445 } 6446 6447 return finalList; 6448 } 6449 6450 @Override 6451 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6452 if (!sUserManager.exists(userId)) return null; 6453 flags = updateFlagsForComponent(flags, userId, name); 6454 // reader 6455 synchronized (mPackages) { 6456 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6457 PackageSetting ps = provider != null 6458 ? mSettings.mPackages.get(provider.owner.packageName) 6459 : null; 6460 return ps != null 6461 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6462 ? PackageParser.generateProviderInfo(provider, flags, 6463 ps.readUserState(userId), userId) 6464 : null; 6465 } 6466 } 6467 6468 /** 6469 * @deprecated 6470 */ 6471 @Deprecated 6472 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6473 // reader 6474 synchronized (mPackages) { 6475 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6476 .entrySet().iterator(); 6477 final int userId = UserHandle.getCallingUserId(); 6478 while (i.hasNext()) { 6479 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6480 PackageParser.Provider p = entry.getValue(); 6481 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6482 6483 if (ps != null && p.syncable 6484 && (!mSafeMode || (p.info.applicationInfo.flags 6485 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6486 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6487 ps.readUserState(userId), userId); 6488 if (info != null) { 6489 outNames.add(entry.getKey()); 6490 outInfo.add(info); 6491 } 6492 } 6493 } 6494 } 6495 } 6496 6497 @Override 6498 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6499 int uid, int flags) { 6500 final int userId = processName != null ? UserHandle.getUserId(uid) 6501 : UserHandle.getCallingUserId(); 6502 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6503 flags = updateFlagsForComponent(flags, userId, processName); 6504 6505 ArrayList<ProviderInfo> finalList = null; 6506 // reader 6507 synchronized (mPackages) { 6508 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6509 while (i.hasNext()) { 6510 final PackageParser.Provider p = i.next(); 6511 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6512 if (ps != null && p.info.authority != null 6513 && (processName == null 6514 || (p.info.processName.equals(processName) 6515 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6516 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6517 if (finalList == null) { 6518 finalList = new ArrayList<ProviderInfo>(3); 6519 } 6520 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6521 ps.readUserState(userId), userId); 6522 if (info != null) { 6523 finalList.add(info); 6524 } 6525 } 6526 } 6527 } 6528 6529 if (finalList != null) { 6530 Collections.sort(finalList, mProviderInitOrderSorter); 6531 return new ParceledListSlice<ProviderInfo>(finalList); 6532 } 6533 6534 return ParceledListSlice.emptyList(); 6535 } 6536 6537 @Override 6538 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6539 // reader 6540 synchronized (mPackages) { 6541 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6542 return PackageParser.generateInstrumentationInfo(i, flags); 6543 } 6544 } 6545 6546 @Override 6547 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6548 String targetPackage, int flags) { 6549 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6550 } 6551 6552 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6553 int flags) { 6554 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6555 6556 // reader 6557 synchronized (mPackages) { 6558 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6559 while (i.hasNext()) { 6560 final PackageParser.Instrumentation p = i.next(); 6561 if (targetPackage == null 6562 || targetPackage.equals(p.info.targetPackage)) { 6563 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6564 flags); 6565 if (ii != null) { 6566 finalList.add(ii); 6567 } 6568 } 6569 } 6570 } 6571 6572 return finalList; 6573 } 6574 6575 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6576 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6577 if (overlays == null) { 6578 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6579 return; 6580 } 6581 for (PackageParser.Package opkg : overlays.values()) { 6582 // Not much to do if idmap fails: we already logged the error 6583 // and we certainly don't want to abort installation of pkg simply 6584 // because an overlay didn't fit properly. For these reasons, 6585 // ignore the return value of createIdmapForPackagePairLI. 6586 createIdmapForPackagePairLI(pkg, opkg); 6587 } 6588 } 6589 6590 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6591 PackageParser.Package opkg) { 6592 if (!opkg.mTrustedOverlay) { 6593 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6594 opkg.baseCodePath + ": overlay not trusted"); 6595 return false; 6596 } 6597 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6598 if (overlaySet == null) { 6599 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6600 opkg.baseCodePath + " but target package has no known overlays"); 6601 return false; 6602 } 6603 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6604 // TODO: generate idmap for split APKs 6605 try { 6606 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6607 } catch (InstallerException e) { 6608 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6609 + opkg.baseCodePath); 6610 return false; 6611 } 6612 PackageParser.Package[] overlayArray = 6613 overlaySet.values().toArray(new PackageParser.Package[0]); 6614 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6615 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6616 return p1.mOverlayPriority - p2.mOverlayPriority; 6617 } 6618 }; 6619 Arrays.sort(overlayArray, cmp); 6620 6621 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6622 int i = 0; 6623 for (PackageParser.Package p : overlayArray) { 6624 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6625 } 6626 return true; 6627 } 6628 6629 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6631 try { 6632 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6633 } finally { 6634 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6635 } 6636 } 6637 6638 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6639 final File[] files = dir.listFiles(); 6640 if (ArrayUtils.isEmpty(files)) { 6641 Log.d(TAG, "No files in app dir " + dir); 6642 return; 6643 } 6644 6645 if (DEBUG_PACKAGE_SCANNING) { 6646 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6647 + " flags=0x" + Integer.toHexString(parseFlags)); 6648 } 6649 6650 for (File file : files) { 6651 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6652 && !PackageInstallerService.isStageName(file.getName()); 6653 if (!isPackage) { 6654 // Ignore entries which are not packages 6655 continue; 6656 } 6657 try { 6658 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6659 scanFlags, currentTime, null); 6660 } catch (PackageManagerException e) { 6661 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6662 6663 // Delete invalid userdata apps 6664 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6665 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6666 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6667 removeCodePathLI(file); 6668 } 6669 } 6670 } 6671 } 6672 6673 private static File getSettingsProblemFile() { 6674 File dataDir = Environment.getDataDirectory(); 6675 File systemDir = new File(dataDir, "system"); 6676 File fname = new File(systemDir, "uiderrors.txt"); 6677 return fname; 6678 } 6679 6680 static void reportSettingsProblem(int priority, String msg) { 6681 logCriticalInfo(priority, msg); 6682 } 6683 6684 static void logCriticalInfo(int priority, String msg) { 6685 Slog.println(priority, TAG, msg); 6686 EventLogTags.writePmCriticalInfo(msg); 6687 try { 6688 File fname = getSettingsProblemFile(); 6689 FileOutputStream out = new FileOutputStream(fname, true); 6690 PrintWriter pw = new FastPrintWriter(out); 6691 SimpleDateFormat formatter = new SimpleDateFormat(); 6692 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6693 pw.println(dateString + ": " + msg); 6694 pw.close(); 6695 FileUtils.setPermissions( 6696 fname.toString(), 6697 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6698 -1, -1); 6699 } catch (java.io.IOException e) { 6700 } 6701 } 6702 6703 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6704 if (srcFile.isDirectory()) { 6705 final File baseFile = new File(pkg.baseCodePath); 6706 long maxModifiedTime = baseFile.lastModified(); 6707 if (pkg.splitCodePaths != null) { 6708 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6709 final File splitFile = new File(pkg.splitCodePaths[i]); 6710 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6711 } 6712 } 6713 return maxModifiedTime; 6714 } 6715 return srcFile.lastModified(); 6716 } 6717 6718 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6719 final int policyFlags) throws PackageManagerException { 6720 // When upgrading from pre-N MR1, verify the package time stamp using the package 6721 // directory and not the APK file. 6722 final long lastModifiedTime = mIsPreNMR1Upgrade 6723 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6724 if (ps != null 6725 && ps.codePath.equals(srcFile) 6726 && ps.timeStamp == lastModifiedTime 6727 && !isCompatSignatureUpdateNeeded(pkg) 6728 && !isRecoverSignatureUpdateNeeded(pkg)) { 6729 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6730 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6731 ArraySet<PublicKey> signingKs; 6732 synchronized (mPackages) { 6733 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6734 } 6735 if (ps.signatures.mSignatures != null 6736 && ps.signatures.mSignatures.length != 0 6737 && signingKs != null) { 6738 // Optimization: reuse the existing cached certificates 6739 // if the package appears to be unchanged. 6740 pkg.mSignatures = ps.signatures.mSignatures; 6741 pkg.mSigningKeys = signingKs; 6742 return; 6743 } 6744 6745 Slog.w(TAG, "PackageSetting for " + ps.name 6746 + " is missing signatures. Collecting certs again to recover them."); 6747 } else { 6748 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6749 } 6750 6751 try { 6752 PackageParser.collectCertificates(pkg, policyFlags); 6753 } catch (PackageParserException e) { 6754 throw PackageManagerException.from(e); 6755 } 6756 } 6757 6758 /** 6759 * Traces a package scan. 6760 * @see #scanPackageLI(File, int, int, long, UserHandle) 6761 */ 6762 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6763 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6764 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6765 try { 6766 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6767 } finally { 6768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6769 } 6770 } 6771 6772 /** 6773 * Scans a package and returns the newly parsed package. 6774 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6775 */ 6776 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6777 long currentTime, UserHandle user) throws PackageManagerException { 6778 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6779 PackageParser pp = new PackageParser(); 6780 pp.setSeparateProcesses(mSeparateProcesses); 6781 pp.setOnlyCoreApps(mOnlyCore); 6782 pp.setDisplayMetrics(mMetrics); 6783 6784 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6785 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6786 } 6787 6788 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6789 final PackageParser.Package pkg; 6790 try { 6791 pkg = pp.parsePackage(scanFile, parseFlags); 6792 } catch (PackageParserException e) { 6793 throw PackageManagerException.from(e); 6794 } finally { 6795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6796 } 6797 6798 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6799 } 6800 6801 /** 6802 * Scans a package and returns the newly parsed package. 6803 * @throws PackageManagerException on a parse error. 6804 */ 6805 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6806 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6807 throws PackageManagerException { 6808 // If the package has children and this is the first dive in the function 6809 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6810 // packages (parent and children) would be successfully scanned before the 6811 // actual scan since scanning mutates internal state and we want to atomically 6812 // install the package and its children. 6813 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6814 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6815 scanFlags |= SCAN_CHECK_ONLY; 6816 } 6817 } else { 6818 scanFlags &= ~SCAN_CHECK_ONLY; 6819 } 6820 6821 // Scan the parent 6822 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6823 scanFlags, currentTime, user); 6824 6825 // Scan the children 6826 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6827 for (int i = 0; i < childCount; i++) { 6828 PackageParser.Package childPackage = pkg.childPackages.get(i); 6829 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6830 currentTime, user); 6831 } 6832 6833 6834 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6835 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6836 } 6837 6838 return scannedPkg; 6839 } 6840 6841 /** 6842 * Scans a package and returns the newly parsed package. 6843 * @throws PackageManagerException on a parse error. 6844 */ 6845 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6846 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6847 throws PackageManagerException { 6848 PackageSetting ps = null; 6849 PackageSetting updatedPkg; 6850 // reader 6851 synchronized (mPackages) { 6852 // Look to see if we already know about this package. 6853 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6854 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6855 // This package has been renamed to its original name. Let's 6856 // use that. 6857 ps = mSettings.peekPackageLPr(oldName); 6858 } 6859 // If there was no original package, see one for the real package name. 6860 if (ps == null) { 6861 ps = mSettings.peekPackageLPr(pkg.packageName); 6862 } 6863 // Check to see if this package could be hiding/updating a system 6864 // package. Must look for it either under the original or real 6865 // package name depending on our state. 6866 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6867 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6868 6869 // If this is a package we don't know about on the system partition, we 6870 // may need to remove disabled child packages on the system partition 6871 // or may need to not add child packages if the parent apk is updated 6872 // on the data partition and no longer defines this child package. 6873 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6874 // If this is a parent package for an updated system app and this system 6875 // app got an OTA update which no longer defines some of the child packages 6876 // we have to prune them from the disabled system packages. 6877 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6878 if (disabledPs != null) { 6879 final int scannedChildCount = (pkg.childPackages != null) 6880 ? pkg.childPackages.size() : 0; 6881 final int disabledChildCount = disabledPs.childPackageNames != null 6882 ? disabledPs.childPackageNames.size() : 0; 6883 for (int i = 0; i < disabledChildCount; i++) { 6884 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6885 boolean disabledPackageAvailable = false; 6886 for (int j = 0; j < scannedChildCount; j++) { 6887 PackageParser.Package childPkg = pkg.childPackages.get(j); 6888 if (childPkg.packageName.equals(disabledChildPackageName)) { 6889 disabledPackageAvailable = true; 6890 break; 6891 } 6892 } 6893 if (!disabledPackageAvailable) { 6894 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6895 } 6896 } 6897 } 6898 } 6899 } 6900 6901 boolean updatedPkgBetter = false; 6902 // First check if this is a system package that may involve an update 6903 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6904 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6905 // it needs to drop FLAG_PRIVILEGED. 6906 if (locationIsPrivileged(scanFile)) { 6907 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6908 } else { 6909 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6910 } 6911 6912 if (ps != null && !ps.codePath.equals(scanFile)) { 6913 // The path has changed from what was last scanned... check the 6914 // version of the new path against what we have stored to determine 6915 // what to do. 6916 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6917 if (pkg.mVersionCode <= ps.versionCode) { 6918 // The system package has been updated and the code path does not match 6919 // Ignore entry. Skip it. 6920 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6921 + " ignored: updated version " + ps.versionCode 6922 + " better than this " + pkg.mVersionCode); 6923 if (!updatedPkg.codePath.equals(scanFile)) { 6924 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6925 + ps.name + " changing from " + updatedPkg.codePathString 6926 + " to " + scanFile); 6927 updatedPkg.codePath = scanFile; 6928 updatedPkg.codePathString = scanFile.toString(); 6929 updatedPkg.resourcePath = scanFile; 6930 updatedPkg.resourcePathString = scanFile.toString(); 6931 } 6932 updatedPkg.pkg = pkg; 6933 updatedPkg.versionCode = pkg.mVersionCode; 6934 6935 // Update the disabled system child packages to point to the package too. 6936 final int childCount = updatedPkg.childPackageNames != null 6937 ? updatedPkg.childPackageNames.size() : 0; 6938 for (int i = 0; i < childCount; i++) { 6939 String childPackageName = updatedPkg.childPackageNames.get(i); 6940 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6941 childPackageName); 6942 if (updatedChildPkg != null) { 6943 updatedChildPkg.pkg = pkg; 6944 updatedChildPkg.versionCode = pkg.mVersionCode; 6945 } 6946 } 6947 6948 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6949 + scanFile + " ignored: updated version " + ps.versionCode 6950 + " better than this " + pkg.mVersionCode); 6951 } else { 6952 // The current app on the system partition is better than 6953 // what we have updated to on the data partition; switch 6954 // back to the system partition version. 6955 // At this point, its safely assumed that package installation for 6956 // apps in system partition will go through. If not there won't be a working 6957 // version of the app 6958 // writer 6959 synchronized (mPackages) { 6960 // Just remove the loaded entries from package lists. 6961 mPackages.remove(ps.name); 6962 } 6963 6964 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6965 + " reverting from " + ps.codePathString 6966 + ": new version " + pkg.mVersionCode 6967 + " better than installed " + ps.versionCode); 6968 6969 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6970 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6971 synchronized (mInstallLock) { 6972 args.cleanUpResourcesLI(); 6973 } 6974 synchronized (mPackages) { 6975 mSettings.enableSystemPackageLPw(ps.name); 6976 } 6977 updatedPkgBetter = true; 6978 } 6979 } 6980 } 6981 6982 if (updatedPkg != null) { 6983 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6984 // initially 6985 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6986 6987 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6988 // flag set initially 6989 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6990 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6991 } 6992 } 6993 6994 // Verify certificates against what was last scanned 6995 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6996 6997 /* 6998 * A new system app appeared, but we already had a non-system one of the 6999 * same name installed earlier. 7000 */ 7001 boolean shouldHideSystemApp = false; 7002 if (updatedPkg == null && ps != null 7003 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7004 /* 7005 * Check to make sure the signatures match first. If they don't, 7006 * wipe the installed application and its data. 7007 */ 7008 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7009 != PackageManager.SIGNATURE_MATCH) { 7010 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7011 + " signatures don't match existing userdata copy; removing"); 7012 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7013 "scanPackageInternalLI")) { 7014 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7015 } 7016 ps = null; 7017 } else { 7018 /* 7019 * If the newly-added system app is an older version than the 7020 * already installed version, hide it. It will be scanned later 7021 * and re-added like an update. 7022 */ 7023 if (pkg.mVersionCode <= ps.versionCode) { 7024 shouldHideSystemApp = true; 7025 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7026 + " but new version " + pkg.mVersionCode + " better than installed " 7027 + ps.versionCode + "; hiding system"); 7028 } else { 7029 /* 7030 * The newly found system app is a newer version that the 7031 * one previously installed. Simply remove the 7032 * already-installed application and replace it with our own 7033 * while keeping the application data. 7034 */ 7035 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7036 + " reverting from " + ps.codePathString + ": new version " 7037 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7038 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7039 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7040 synchronized (mInstallLock) { 7041 args.cleanUpResourcesLI(); 7042 } 7043 } 7044 } 7045 } 7046 7047 // The apk is forward locked (not public) if its code and resources 7048 // are kept in different files. (except for app in either system or 7049 // vendor path). 7050 // TODO grab this value from PackageSettings 7051 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7052 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7053 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7054 } 7055 } 7056 7057 // TODO: extend to support forward-locked splits 7058 String resourcePath = null; 7059 String baseResourcePath = null; 7060 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7061 if (ps != null && ps.resourcePathString != null) { 7062 resourcePath = ps.resourcePathString; 7063 baseResourcePath = ps.resourcePathString; 7064 } else { 7065 // Should not happen at all. Just log an error. 7066 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7067 } 7068 } else { 7069 resourcePath = pkg.codePath; 7070 baseResourcePath = pkg.baseCodePath; 7071 } 7072 7073 // Set application objects path explicitly. 7074 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7075 pkg.setApplicationInfoCodePath(pkg.codePath); 7076 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7077 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7078 pkg.setApplicationInfoResourcePath(resourcePath); 7079 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7080 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7081 7082 // Note that we invoke the following method only if we are about to unpack an application 7083 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7084 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7085 7086 /* 7087 * If the system app should be overridden by a previously installed 7088 * data, hide the system app now and let the /data/app scan pick it up 7089 * again. 7090 */ 7091 if (shouldHideSystemApp) { 7092 synchronized (mPackages) { 7093 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7094 } 7095 } 7096 7097 return scannedPkg; 7098 } 7099 7100 private static String fixProcessName(String defProcessName, 7101 String processName, int uid) { 7102 if (processName == null) { 7103 return defProcessName; 7104 } 7105 return processName; 7106 } 7107 7108 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7109 throws PackageManagerException { 7110 if (pkgSetting.signatures.mSignatures != null) { 7111 // Already existing package. Make sure signatures match 7112 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7113 == PackageManager.SIGNATURE_MATCH; 7114 if (!match) { 7115 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7116 == PackageManager.SIGNATURE_MATCH; 7117 } 7118 if (!match) { 7119 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7120 == PackageManager.SIGNATURE_MATCH; 7121 } 7122 if (!match) { 7123 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7124 + pkg.packageName + " signatures do not match the " 7125 + "previously installed version; ignoring!"); 7126 } 7127 } 7128 7129 // Check for shared user signatures 7130 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7131 // Already existing package. Make sure signatures match 7132 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7133 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7134 if (!match) { 7135 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7136 == PackageManager.SIGNATURE_MATCH; 7137 } 7138 if (!match) { 7139 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7140 == PackageManager.SIGNATURE_MATCH; 7141 } 7142 if (!match) { 7143 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7144 "Package " + pkg.packageName 7145 + " has no signatures that match those in shared user " 7146 + pkgSetting.sharedUser.name + "; ignoring!"); 7147 } 7148 } 7149 } 7150 7151 /** 7152 * Enforces that only the system UID or root's UID can call a method exposed 7153 * via Binder. 7154 * 7155 * @param message used as message if SecurityException is thrown 7156 * @throws SecurityException if the caller is not system or root 7157 */ 7158 private static final void enforceSystemOrRoot(String message) { 7159 final int uid = Binder.getCallingUid(); 7160 if (uid != Process.SYSTEM_UID && uid != 0) { 7161 throw new SecurityException(message); 7162 } 7163 } 7164 7165 @Override 7166 public void performFstrimIfNeeded() { 7167 enforceSystemOrRoot("Only the system can request fstrim"); 7168 7169 // Before everything else, see whether we need to fstrim. 7170 try { 7171 IMountService ms = PackageHelper.getMountService(); 7172 if (ms != null) { 7173 boolean doTrim = false; 7174 final long interval = android.provider.Settings.Global.getLong( 7175 mContext.getContentResolver(), 7176 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7177 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7178 if (interval > 0) { 7179 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7180 if (timeSinceLast > interval) { 7181 doTrim = true; 7182 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7183 + "; running immediately"); 7184 } 7185 } 7186 if (doTrim) { 7187 final boolean dexOptDialogShown; 7188 synchronized (mPackages) { 7189 dexOptDialogShown = mDexOptDialogShown; 7190 } 7191 if (!isFirstBoot() && dexOptDialogShown) { 7192 try { 7193 ActivityManagerNative.getDefault().showBootMessage( 7194 mContext.getResources().getString( 7195 R.string.android_upgrading_fstrim), true); 7196 } catch (RemoteException e) { 7197 } 7198 } 7199 ms.runMaintenance(); 7200 } 7201 } else { 7202 Slog.e(TAG, "Mount service unavailable!"); 7203 } 7204 } catch (RemoteException e) { 7205 // Can't happen; MountService is local 7206 } 7207 } 7208 7209 @Override 7210 public void updatePackagesIfNeeded() { 7211 enforceSystemOrRoot("Only the system can request package update"); 7212 7213 // We need to re-extract after an OTA. 7214 boolean causeUpgrade = isUpgrade(); 7215 7216 // First boot or factory reset. 7217 // Note: we also handle devices that are upgrading to N right now as if it is their 7218 // first boot, as they do not have profile data. 7219 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7220 7221 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7222 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7223 7224 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7225 return; 7226 } 7227 7228 List<PackageParser.Package> pkgs; 7229 synchronized (mPackages) { 7230 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7231 } 7232 7233 final long startTime = System.nanoTime(); 7234 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7235 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7236 7237 final int elapsedTimeSeconds = 7238 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7239 7240 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7241 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7242 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7243 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7244 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7245 } 7246 7247 /** 7248 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7249 * containing statistics about the invocation. The array consists of three elements, 7250 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7251 * and {@code numberOfPackagesFailed}. 7252 */ 7253 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7254 String compilerFilter) { 7255 7256 int numberOfPackagesVisited = 0; 7257 int numberOfPackagesOptimized = 0; 7258 int numberOfPackagesSkipped = 0; 7259 int numberOfPackagesFailed = 0; 7260 final int numberOfPackagesToDexopt = pkgs.size(); 7261 7262 for (PackageParser.Package pkg : pkgs) { 7263 numberOfPackagesVisited++; 7264 7265 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7266 if (DEBUG_DEXOPT) { 7267 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7268 } 7269 numberOfPackagesSkipped++; 7270 continue; 7271 } 7272 7273 if (DEBUG_DEXOPT) { 7274 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7275 numberOfPackagesToDexopt + ": " + pkg.packageName); 7276 } 7277 7278 if (showDialog) { 7279 try { 7280 ActivityManagerNative.getDefault().showBootMessage( 7281 mContext.getResources().getString(R.string.android_upgrading_apk, 7282 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7283 } catch (RemoteException e) { 7284 } 7285 synchronized (mPackages) { 7286 mDexOptDialogShown = true; 7287 } 7288 } 7289 7290 // If the OTA updates a system app which was previously preopted to a non-preopted state 7291 // the app might end up being verified at runtime. That's because by default the apps 7292 // are verify-profile but for preopted apps there's no profile. 7293 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7294 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7295 // filter (by default interpret-only). 7296 // Note that at this stage unused apps are already filtered. 7297 if (isSystemApp(pkg) && 7298 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7299 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7300 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7301 } 7302 7303 // If the OTA updates a system app which was previously preopted to a non-preopted state 7304 // the app might end up being verified at runtime. That's because by default the apps 7305 // are verify-profile but for preopted apps there's no profile. 7306 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7307 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7308 // filter (by default interpret-only). 7309 // Note that at this stage unused apps are already filtered. 7310 if (isSystemApp(pkg) && 7311 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7312 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7313 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7314 } 7315 7316 // checkProfiles is false to avoid merging profiles during boot which 7317 // might interfere with background compilation (b/28612421). 7318 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7319 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7320 // trade-off worth doing to save boot time work. 7321 int dexOptStatus = performDexOptTraced(pkg.packageName, 7322 false /* checkProfiles */, 7323 compilerFilter, 7324 false /* force */); 7325 switch (dexOptStatus) { 7326 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7327 numberOfPackagesOptimized++; 7328 break; 7329 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7330 numberOfPackagesSkipped++; 7331 break; 7332 case PackageDexOptimizer.DEX_OPT_FAILED: 7333 numberOfPackagesFailed++; 7334 break; 7335 default: 7336 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7337 break; 7338 } 7339 } 7340 7341 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7342 numberOfPackagesFailed }; 7343 } 7344 7345 @Override 7346 public void notifyPackageUse(String packageName, int reason) { 7347 synchronized (mPackages) { 7348 PackageParser.Package p = mPackages.get(packageName); 7349 if (p == null) { 7350 return; 7351 } 7352 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7353 } 7354 } 7355 7356 // TODO: this is not used nor needed. Delete it. 7357 @Override 7358 public boolean performDexOptIfNeeded(String packageName) { 7359 int dexOptStatus = performDexOptTraced(packageName, 7360 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7361 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7362 } 7363 7364 @Override 7365 public boolean performDexOpt(String packageName, 7366 boolean checkProfiles, int compileReason, boolean force) { 7367 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7368 getCompilerFilterForReason(compileReason), force); 7369 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7370 } 7371 7372 @Override 7373 public boolean performDexOptMode(String packageName, 7374 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7375 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7376 targetCompilerFilter, force); 7377 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7378 } 7379 7380 private int performDexOptTraced(String packageName, 7381 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7383 try { 7384 return performDexOptInternal(packageName, checkProfiles, 7385 targetCompilerFilter, force); 7386 } finally { 7387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7388 } 7389 } 7390 7391 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7392 // if the package can now be considered up to date for the given filter. 7393 private int performDexOptInternal(String packageName, 7394 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7395 PackageParser.Package p; 7396 synchronized (mPackages) { 7397 p = mPackages.get(packageName); 7398 if (p == null) { 7399 // Package could not be found. Report failure. 7400 return PackageDexOptimizer.DEX_OPT_FAILED; 7401 } 7402 mPackageUsage.maybeWriteAsync(mPackages); 7403 mCompilerStats.maybeWriteAsync(); 7404 } 7405 long callingId = Binder.clearCallingIdentity(); 7406 try { 7407 synchronized (mInstallLock) { 7408 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7409 targetCompilerFilter, force); 7410 } 7411 } finally { 7412 Binder.restoreCallingIdentity(callingId); 7413 } 7414 } 7415 7416 public ArraySet<String> getOptimizablePackages() { 7417 ArraySet<String> pkgs = new ArraySet<String>(); 7418 synchronized (mPackages) { 7419 for (PackageParser.Package p : mPackages.values()) { 7420 if (PackageDexOptimizer.canOptimizePackage(p)) { 7421 pkgs.add(p.packageName); 7422 } 7423 } 7424 } 7425 return pkgs; 7426 } 7427 7428 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7429 boolean checkProfiles, String targetCompilerFilter, 7430 boolean force) { 7431 // Select the dex optimizer based on the force parameter. 7432 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7433 // allocate an object here. 7434 PackageDexOptimizer pdo = force 7435 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7436 : mPackageDexOptimizer; 7437 7438 // Optimize all dependencies first. Note: we ignore the return value and march on 7439 // on errors. 7440 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7441 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7442 if (!deps.isEmpty()) { 7443 for (PackageParser.Package depPackage : deps) { 7444 // TODO: Analyze and investigate if we (should) profile libraries. 7445 // Currently this will do a full compilation of the library by default. 7446 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7447 false /* checkProfiles */, 7448 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7449 getOrCreateCompilerPackageStats(depPackage)); 7450 } 7451 } 7452 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7453 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7454 } 7455 7456 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7457 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7458 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7459 Set<String> collectedNames = new HashSet<>(); 7460 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7461 7462 retValue.remove(p); 7463 7464 return retValue; 7465 } else { 7466 return Collections.emptyList(); 7467 } 7468 } 7469 7470 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7471 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7472 if (!collectedNames.contains(p.packageName)) { 7473 collectedNames.add(p.packageName); 7474 collected.add(p); 7475 7476 if (p.usesLibraries != null) { 7477 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7478 } 7479 if (p.usesOptionalLibraries != null) { 7480 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7481 collectedNames); 7482 } 7483 } 7484 } 7485 7486 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7487 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7488 for (String libName : libs) { 7489 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7490 if (libPkg != null) { 7491 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7492 } 7493 } 7494 } 7495 7496 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7497 synchronized (mPackages) { 7498 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7499 if (lib != null && lib.apk != null) { 7500 return mPackages.get(lib.apk); 7501 } 7502 } 7503 return null; 7504 } 7505 7506 public void shutdown() { 7507 mPackageUsage.writeNow(mPackages); 7508 mCompilerStats.writeNow(); 7509 } 7510 7511 @Override 7512 public void dumpProfiles(String packageName) { 7513 PackageParser.Package pkg; 7514 synchronized (mPackages) { 7515 pkg = mPackages.get(packageName); 7516 if (pkg == null) { 7517 throw new IllegalArgumentException("Unknown package: " + packageName); 7518 } 7519 } 7520 /* Only the shell, root, or the app user should be able to dump profiles. */ 7521 int callingUid = Binder.getCallingUid(); 7522 if (callingUid != Process.SHELL_UID && 7523 callingUid != Process.ROOT_UID && 7524 callingUid != pkg.applicationInfo.uid) { 7525 throw new SecurityException("dumpProfiles"); 7526 } 7527 7528 synchronized (mInstallLock) { 7529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7530 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7531 try { 7532 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7533 String codePaths = TextUtils.join(";", allCodePaths); 7534 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7535 } catch (InstallerException e) { 7536 Slog.w(TAG, "Failed to dump profiles", e); 7537 } 7538 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7539 } 7540 } 7541 7542 @Override 7543 public void forceDexOpt(String packageName) { 7544 enforceSystemOrRoot("forceDexOpt"); 7545 7546 PackageParser.Package pkg; 7547 synchronized (mPackages) { 7548 pkg = mPackages.get(packageName); 7549 if (pkg == null) { 7550 throw new IllegalArgumentException("Unknown package: " + packageName); 7551 } 7552 } 7553 7554 synchronized (mInstallLock) { 7555 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7556 7557 // Whoever is calling forceDexOpt wants a fully compiled package. 7558 // Don't use profiles since that may cause compilation to be skipped. 7559 final int res = performDexOptInternalWithDependenciesLI(pkg, 7560 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7561 true /* force */); 7562 7563 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7564 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7565 throw new IllegalStateException("Failed to dexopt: " + res); 7566 } 7567 } 7568 } 7569 7570 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7571 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7572 Slog.w(TAG, "Unable to update from " + oldPkg.name 7573 + " to " + newPkg.packageName 7574 + ": old package not in system partition"); 7575 return false; 7576 } else if (mPackages.get(oldPkg.name) != null) { 7577 Slog.w(TAG, "Unable to update from " + oldPkg.name 7578 + " to " + newPkg.packageName 7579 + ": old package still exists"); 7580 return false; 7581 } 7582 return true; 7583 } 7584 7585 void removeCodePathLI(File codePath) { 7586 if (codePath.isDirectory()) { 7587 try { 7588 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7589 } catch (InstallerException e) { 7590 Slog.w(TAG, "Failed to remove code path", e); 7591 } 7592 } else { 7593 codePath.delete(); 7594 } 7595 } 7596 7597 private int[] resolveUserIds(int userId) { 7598 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7599 } 7600 7601 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7602 if (pkg == null) { 7603 Slog.wtf(TAG, "Package was null!", new Throwable()); 7604 return; 7605 } 7606 clearAppDataLeafLIF(pkg, userId, flags); 7607 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7608 for (int i = 0; i < childCount; i++) { 7609 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7610 } 7611 } 7612 7613 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7614 final PackageSetting ps; 7615 synchronized (mPackages) { 7616 ps = mSettings.mPackages.get(pkg.packageName); 7617 } 7618 for (int realUserId : resolveUserIds(userId)) { 7619 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7620 try { 7621 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7622 ceDataInode); 7623 } catch (InstallerException e) { 7624 Slog.w(TAG, String.valueOf(e)); 7625 } 7626 } 7627 } 7628 7629 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7630 if (pkg == null) { 7631 Slog.wtf(TAG, "Package was null!", new Throwable()); 7632 return; 7633 } 7634 destroyAppDataLeafLIF(pkg, userId, flags); 7635 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7636 for (int i = 0; i < childCount; i++) { 7637 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7638 } 7639 } 7640 7641 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7642 final PackageSetting ps; 7643 synchronized (mPackages) { 7644 ps = mSettings.mPackages.get(pkg.packageName); 7645 } 7646 for (int realUserId : resolveUserIds(userId)) { 7647 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7648 try { 7649 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7650 ceDataInode); 7651 } catch (InstallerException e) { 7652 Slog.w(TAG, String.valueOf(e)); 7653 } 7654 } 7655 } 7656 7657 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7658 if (pkg == null) { 7659 Slog.wtf(TAG, "Package was null!", new Throwable()); 7660 return; 7661 } 7662 destroyAppProfilesLeafLIF(pkg); 7663 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7665 for (int i = 0; i < childCount; i++) { 7666 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7667 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7668 true /* removeBaseMarker */); 7669 } 7670 } 7671 7672 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7673 boolean removeBaseMarker) { 7674 if (pkg.isForwardLocked()) { 7675 return; 7676 } 7677 7678 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7679 try { 7680 path = PackageManagerServiceUtils.realpath(new File(path)); 7681 } catch (IOException e) { 7682 // TODO: Should we return early here ? 7683 Slog.w(TAG, "Failed to get canonical path", e); 7684 continue; 7685 } 7686 7687 final String useMarker = path.replace('/', '@'); 7688 for (int realUserId : resolveUserIds(userId)) { 7689 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7690 if (removeBaseMarker) { 7691 File foreignUseMark = new File(profileDir, useMarker); 7692 if (foreignUseMark.exists()) { 7693 if (!foreignUseMark.delete()) { 7694 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7695 + pkg.packageName); 7696 } 7697 } 7698 } 7699 7700 File[] markers = profileDir.listFiles(); 7701 if (markers != null) { 7702 final String searchString = "@" + pkg.packageName + "@"; 7703 // We also delete all markers that contain the package name we're 7704 // uninstalling. These are associated with secondary dex-files belonging 7705 // to the package. Reconstructing the path of these dex files is messy 7706 // in general. 7707 for (File marker : markers) { 7708 if (marker.getName().indexOf(searchString) > 0) { 7709 if (!marker.delete()) { 7710 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7711 + pkg.packageName); 7712 } 7713 } 7714 } 7715 } 7716 } 7717 } 7718 } 7719 7720 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7721 try { 7722 mInstaller.destroyAppProfiles(pkg.packageName); 7723 } catch (InstallerException e) { 7724 Slog.w(TAG, String.valueOf(e)); 7725 } 7726 } 7727 7728 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7729 if (pkg == null) { 7730 Slog.wtf(TAG, "Package was null!", new Throwable()); 7731 return; 7732 } 7733 clearAppProfilesLeafLIF(pkg); 7734 // We don't remove the base foreign use marker when clearing profiles because 7735 // we will rename it when the app is updated. Unlike the actual profile contents, 7736 // the foreign use marker is good across installs. 7737 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7738 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7739 for (int i = 0; i < childCount; i++) { 7740 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7741 } 7742 } 7743 7744 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7745 try { 7746 mInstaller.clearAppProfiles(pkg.packageName); 7747 } catch (InstallerException e) { 7748 Slog.w(TAG, String.valueOf(e)); 7749 } 7750 } 7751 7752 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7753 long lastUpdateTime) { 7754 // Set parent install/update time 7755 PackageSetting ps = (PackageSetting) pkg.mExtras; 7756 if (ps != null) { 7757 ps.firstInstallTime = firstInstallTime; 7758 ps.lastUpdateTime = lastUpdateTime; 7759 } 7760 // Set children install/update time 7761 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7762 for (int i = 0; i < childCount; i++) { 7763 PackageParser.Package childPkg = pkg.childPackages.get(i); 7764 ps = (PackageSetting) childPkg.mExtras; 7765 if (ps != null) { 7766 ps.firstInstallTime = firstInstallTime; 7767 ps.lastUpdateTime = lastUpdateTime; 7768 } 7769 } 7770 } 7771 7772 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7773 PackageParser.Package changingLib) { 7774 if (file.path != null) { 7775 usesLibraryFiles.add(file.path); 7776 return; 7777 } 7778 PackageParser.Package p = mPackages.get(file.apk); 7779 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7780 // If we are doing this while in the middle of updating a library apk, 7781 // then we need to make sure to use that new apk for determining the 7782 // dependencies here. (We haven't yet finished committing the new apk 7783 // to the package manager state.) 7784 if (p == null || p.packageName.equals(changingLib.packageName)) { 7785 p = changingLib; 7786 } 7787 } 7788 if (p != null) { 7789 usesLibraryFiles.addAll(p.getAllCodePaths()); 7790 } 7791 } 7792 7793 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7794 PackageParser.Package changingLib) throws PackageManagerException { 7795 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7796 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7797 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7798 for (int i=0; i<N; i++) { 7799 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7800 if (file == null) { 7801 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7802 "Package " + pkg.packageName + " requires unavailable shared library " 7803 + pkg.usesLibraries.get(i) + "; failing!"); 7804 } 7805 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7806 } 7807 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7808 for (int i=0; i<N; i++) { 7809 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7810 if (file == null) { 7811 Slog.w(TAG, "Package " + pkg.packageName 7812 + " desires unavailable shared library " 7813 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7814 } else { 7815 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7816 } 7817 } 7818 N = usesLibraryFiles.size(); 7819 if (N > 0) { 7820 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7821 } else { 7822 pkg.usesLibraryFiles = null; 7823 } 7824 } 7825 } 7826 7827 private static boolean hasString(List<String> list, List<String> which) { 7828 if (list == null) { 7829 return false; 7830 } 7831 for (int i=list.size()-1; i>=0; i--) { 7832 for (int j=which.size()-1; j>=0; j--) { 7833 if (which.get(j).equals(list.get(i))) { 7834 return true; 7835 } 7836 } 7837 } 7838 return false; 7839 } 7840 7841 private void updateAllSharedLibrariesLPw() { 7842 for (PackageParser.Package pkg : mPackages.values()) { 7843 try { 7844 updateSharedLibrariesLPw(pkg, null); 7845 } catch (PackageManagerException e) { 7846 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7847 } 7848 } 7849 } 7850 7851 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7852 PackageParser.Package changingPkg) { 7853 ArrayList<PackageParser.Package> res = null; 7854 for (PackageParser.Package pkg : mPackages.values()) { 7855 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7856 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7857 if (res == null) { 7858 res = new ArrayList<PackageParser.Package>(); 7859 } 7860 res.add(pkg); 7861 try { 7862 updateSharedLibrariesLPw(pkg, changingPkg); 7863 } catch (PackageManagerException e) { 7864 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7865 } 7866 } 7867 } 7868 return res; 7869 } 7870 7871 /** 7872 * Derive the value of the {@code cpuAbiOverride} based on the provided 7873 * value and an optional stored value from the package settings. 7874 */ 7875 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7876 String cpuAbiOverride = null; 7877 7878 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7879 cpuAbiOverride = null; 7880 } else if (abiOverride != null) { 7881 cpuAbiOverride = abiOverride; 7882 } else if (settings != null) { 7883 cpuAbiOverride = settings.cpuAbiOverrideString; 7884 } 7885 7886 return cpuAbiOverride; 7887 } 7888 7889 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7890 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7891 throws PackageManagerException { 7892 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7893 // If the package has children and this is the first dive in the function 7894 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7895 // whether all packages (parent and children) would be successfully scanned 7896 // before the actual scan since scanning mutates internal state and we want 7897 // to atomically install the package and its children. 7898 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7899 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7900 scanFlags |= SCAN_CHECK_ONLY; 7901 } 7902 } else { 7903 scanFlags &= ~SCAN_CHECK_ONLY; 7904 } 7905 7906 final PackageParser.Package scannedPkg; 7907 try { 7908 // Scan the parent 7909 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7910 // Scan the children 7911 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7912 for (int i = 0; i < childCount; i++) { 7913 PackageParser.Package childPkg = pkg.childPackages.get(i); 7914 scanPackageLI(childPkg, policyFlags, 7915 scanFlags, currentTime, user); 7916 } 7917 } finally { 7918 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7919 } 7920 7921 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7922 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7923 } 7924 7925 return scannedPkg; 7926 } 7927 7928 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7929 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7930 boolean success = false; 7931 try { 7932 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7933 currentTime, user); 7934 success = true; 7935 return res; 7936 } finally { 7937 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7938 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7939 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7940 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7941 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7942 } 7943 } 7944 } 7945 7946 /** 7947 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7948 */ 7949 private static boolean apkHasCode(String fileName) { 7950 StrictJarFile jarFile = null; 7951 try { 7952 jarFile = new StrictJarFile(fileName, 7953 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7954 return jarFile.findEntry("classes.dex") != null; 7955 } catch (IOException ignore) { 7956 } finally { 7957 try { 7958 if (jarFile != null) { 7959 jarFile.close(); 7960 } 7961 } catch (IOException ignore) {} 7962 } 7963 return false; 7964 } 7965 7966 /** 7967 * Enforces code policy for the package. This ensures that if an APK has 7968 * declared hasCode="true" in its manifest that the APK actually contains 7969 * code. 7970 * 7971 * @throws PackageManagerException If bytecode could not be found when it should exist 7972 */ 7973 private static void enforceCodePolicy(PackageParser.Package pkg) 7974 throws PackageManagerException { 7975 final boolean shouldHaveCode = 7976 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7977 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7978 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7979 "Package " + pkg.baseCodePath + " code is missing"); 7980 } 7981 7982 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7983 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7984 final boolean splitShouldHaveCode = 7985 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7986 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7987 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7988 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7989 } 7990 } 7991 } 7992 } 7993 7994 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7995 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7996 throws PackageManagerException { 7997 final File scanFile = new File(pkg.codePath); 7998 if (pkg.applicationInfo.getCodePath() == null || 7999 pkg.applicationInfo.getResourcePath() == null) { 8000 // Bail out. The resource and code paths haven't been set. 8001 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8002 "Code and resource paths haven't been set correctly"); 8003 } 8004 8005 // Apply policy 8006 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8007 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8008 if (pkg.applicationInfo.isDirectBootAware()) { 8009 // we're direct boot aware; set for all components 8010 for (PackageParser.Service s : pkg.services) { 8011 s.info.encryptionAware = s.info.directBootAware = true; 8012 } 8013 for (PackageParser.Provider p : pkg.providers) { 8014 p.info.encryptionAware = p.info.directBootAware = true; 8015 } 8016 for (PackageParser.Activity a : pkg.activities) { 8017 a.info.encryptionAware = a.info.directBootAware = true; 8018 } 8019 for (PackageParser.Activity r : pkg.receivers) { 8020 r.info.encryptionAware = r.info.directBootAware = true; 8021 } 8022 } 8023 } else { 8024 // Only allow system apps to be flagged as core apps. 8025 pkg.coreApp = false; 8026 // clear flags not applicable to regular apps 8027 pkg.applicationInfo.privateFlags &= 8028 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8029 pkg.applicationInfo.privateFlags &= 8030 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8031 } 8032 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8033 8034 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8035 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8036 } 8037 8038 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8039 enforceCodePolicy(pkg); 8040 } 8041 8042 if (mCustomResolverComponentName != null && 8043 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8044 setUpCustomResolverActivity(pkg); 8045 } 8046 8047 if (pkg.packageName.equals("android")) { 8048 synchronized (mPackages) { 8049 if (mAndroidApplication != null) { 8050 Slog.w(TAG, "*************************************************"); 8051 Slog.w(TAG, "Core android package being redefined. Skipping."); 8052 Slog.w(TAG, " file=" + scanFile); 8053 Slog.w(TAG, "*************************************************"); 8054 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8055 "Core android package being redefined. Skipping."); 8056 } 8057 8058 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8059 // Set up information for our fall-back user intent resolution activity. 8060 mPlatformPackage = pkg; 8061 pkg.mVersionCode = mSdkVersion; 8062 mAndroidApplication = pkg.applicationInfo; 8063 8064 if (!mResolverReplaced) { 8065 mResolveActivity.applicationInfo = mAndroidApplication; 8066 mResolveActivity.name = ResolverActivity.class.getName(); 8067 mResolveActivity.packageName = mAndroidApplication.packageName; 8068 mResolveActivity.processName = "system:ui"; 8069 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8070 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8071 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8072 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8073 mResolveActivity.exported = true; 8074 mResolveActivity.enabled = true; 8075 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8076 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8077 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8078 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8079 | ActivityInfo.CONFIG_ORIENTATION 8080 | ActivityInfo.CONFIG_KEYBOARD 8081 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8082 mResolveInfo.activityInfo = mResolveActivity; 8083 mResolveInfo.priority = 0; 8084 mResolveInfo.preferredOrder = 0; 8085 mResolveInfo.match = 0; 8086 mResolveComponentName = new ComponentName( 8087 mAndroidApplication.packageName, mResolveActivity.name); 8088 } 8089 } 8090 } 8091 } 8092 8093 if (DEBUG_PACKAGE_SCANNING) { 8094 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8095 Log.d(TAG, "Scanning package " + pkg.packageName); 8096 } 8097 8098 synchronized (mPackages) { 8099 if (mPackages.containsKey(pkg.packageName) 8100 || mSharedLibraries.containsKey(pkg.packageName)) { 8101 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8102 "Application package " + pkg.packageName 8103 + " already installed. Skipping duplicate."); 8104 } 8105 8106 // If we're only installing presumed-existing packages, require that the 8107 // scanned APK is both already known and at the path previously established 8108 // for it. Previously unknown packages we pick up normally, but if we have an 8109 // a priori expectation about this package's install presence, enforce it. 8110 // With a singular exception for new system packages. When an OTA contains 8111 // a new system package, we allow the codepath to change from a system location 8112 // to the user-installed location. If we don't allow this change, any newer, 8113 // user-installed version of the application will be ignored. 8114 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8115 if (mExpectingBetter.containsKey(pkg.packageName)) { 8116 logCriticalInfo(Log.WARN, 8117 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8118 } else { 8119 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8120 if (known != null) { 8121 if (DEBUG_PACKAGE_SCANNING) { 8122 Log.d(TAG, "Examining " + pkg.codePath 8123 + " and requiring known paths " + known.codePathString 8124 + " & " + known.resourcePathString); 8125 } 8126 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8127 || !pkg.applicationInfo.getResourcePath().equals( 8128 known.resourcePathString)) { 8129 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8130 "Application package " + pkg.packageName 8131 + " found at " + pkg.applicationInfo.getCodePath() 8132 + " but expected at " + known.codePathString 8133 + "; ignoring."); 8134 } 8135 } 8136 } 8137 } 8138 } 8139 8140 // Initialize package source and resource directories 8141 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8142 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8143 8144 SharedUserSetting suid = null; 8145 PackageSetting pkgSetting = null; 8146 8147 if (!isSystemApp(pkg)) { 8148 // Only system apps can use these features. 8149 pkg.mOriginalPackages = null; 8150 pkg.mRealPackage = null; 8151 pkg.mAdoptPermissions = null; 8152 } 8153 8154 // Getting the package setting may have a side-effect, so if we 8155 // are only checking if scan would succeed, stash a copy of the 8156 // old setting to restore at the end. 8157 PackageSetting nonMutatedPs = null; 8158 8159 // writer 8160 synchronized (mPackages) { 8161 if (pkg.mSharedUserId != null) { 8162 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8163 if (suid == null) { 8164 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8165 "Creating application package " + pkg.packageName 8166 + " for shared user failed"); 8167 } 8168 if (DEBUG_PACKAGE_SCANNING) { 8169 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8170 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8171 + "): packages=" + suid.packages); 8172 } 8173 } 8174 8175 // Check if we are renaming from an original package name. 8176 PackageSetting origPackage = null; 8177 String realName = null; 8178 if (pkg.mOriginalPackages != null) { 8179 // This package may need to be renamed to a previously 8180 // installed name. Let's check on that... 8181 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8182 if (pkg.mOriginalPackages.contains(renamed)) { 8183 // This package had originally been installed as the 8184 // original name, and we have already taken care of 8185 // transitioning to the new one. Just update the new 8186 // one to continue using the old name. 8187 realName = pkg.mRealPackage; 8188 if (!pkg.packageName.equals(renamed)) { 8189 // Callers into this function may have already taken 8190 // care of renaming the package; only do it here if 8191 // it is not already done. 8192 pkg.setPackageName(renamed); 8193 } 8194 8195 } else { 8196 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8197 if ((origPackage = mSettings.peekPackageLPr( 8198 pkg.mOriginalPackages.get(i))) != null) { 8199 // We do have the package already installed under its 8200 // original name... should we use it? 8201 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8202 // New package is not compatible with original. 8203 origPackage = null; 8204 continue; 8205 } else if (origPackage.sharedUser != null) { 8206 // Make sure uid is compatible between packages. 8207 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8208 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8209 + " to " + pkg.packageName + ": old uid " 8210 + origPackage.sharedUser.name 8211 + " differs from " + pkg.mSharedUserId); 8212 origPackage = null; 8213 continue; 8214 } 8215 // TODO: Add case when shared user id is added [b/28144775] 8216 } else { 8217 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8218 + pkg.packageName + " to old name " + origPackage.name); 8219 } 8220 break; 8221 } 8222 } 8223 } 8224 } 8225 8226 if (mTransferedPackages.contains(pkg.packageName)) { 8227 Slog.w(TAG, "Package " + pkg.packageName 8228 + " was transferred to another, but its .apk remains"); 8229 } 8230 8231 // See comments in nonMutatedPs declaration 8232 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8233 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8234 if (foundPs != null) { 8235 nonMutatedPs = new PackageSetting(foundPs); 8236 } 8237 } 8238 8239 // Just create the setting, don't add it yet. For already existing packages 8240 // the PkgSetting exists already and doesn't have to be created. 8241 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8242 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8243 pkg.applicationInfo.primaryCpuAbi, 8244 pkg.applicationInfo.secondaryCpuAbi, 8245 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8246 user, false); 8247 if (pkgSetting == null) { 8248 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8249 "Creating application package " + pkg.packageName + " failed"); 8250 } 8251 8252 if (pkgSetting.origPackage != null) { 8253 // If we are first transitioning from an original package, 8254 // fix up the new package's name now. We need to do this after 8255 // looking up the package under its new name, so getPackageLP 8256 // can take care of fiddling things correctly. 8257 pkg.setPackageName(origPackage.name); 8258 8259 // File a report about this. 8260 String msg = "New package " + pkgSetting.realName 8261 + " renamed to replace old package " + pkgSetting.name; 8262 reportSettingsProblem(Log.WARN, msg); 8263 8264 // Make a note of it. 8265 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8266 mTransferedPackages.add(origPackage.name); 8267 } 8268 8269 // No longer need to retain this. 8270 pkgSetting.origPackage = null; 8271 } 8272 8273 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8274 // Make a note of it. 8275 mTransferedPackages.add(pkg.packageName); 8276 } 8277 8278 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8279 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8280 } 8281 8282 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8283 // Check all shared libraries and map to their actual file path. 8284 // We only do this here for apps not on a system dir, because those 8285 // are the only ones that can fail an install due to this. We 8286 // will take care of the system apps by updating all of their 8287 // library paths after the scan is done. 8288 updateSharedLibrariesLPw(pkg, null); 8289 } 8290 8291 if (mFoundPolicyFile) { 8292 SELinuxMMAC.assignSeinfoValue(pkg); 8293 } 8294 8295 pkg.applicationInfo.uid = pkgSetting.appId; 8296 pkg.mExtras = pkgSetting; 8297 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8298 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8299 // We just determined the app is signed correctly, so bring 8300 // over the latest parsed certs. 8301 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8302 } else { 8303 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8304 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8305 "Package " + pkg.packageName + " upgrade keys do not match the " 8306 + "previously installed version"); 8307 } else { 8308 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8309 String msg = "System package " + pkg.packageName 8310 + " signature changed; retaining data."; 8311 reportSettingsProblem(Log.WARN, msg); 8312 } 8313 } 8314 } else { 8315 try { 8316 verifySignaturesLP(pkgSetting, pkg); 8317 // We just determined the app is signed correctly, so bring 8318 // over the latest parsed certs. 8319 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8320 } catch (PackageManagerException e) { 8321 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8322 throw e; 8323 } 8324 // The signature has changed, but this package is in the system 8325 // image... let's recover! 8326 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8327 // However... if this package is part of a shared user, but it 8328 // doesn't match the signature of the shared user, let's fail. 8329 // What this means is that you can't change the signatures 8330 // associated with an overall shared user, which doesn't seem all 8331 // that unreasonable. 8332 if (pkgSetting.sharedUser != null) { 8333 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8334 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8335 throw new PackageManagerException( 8336 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8337 "Signature mismatch for shared user: " 8338 + pkgSetting.sharedUser); 8339 } 8340 } 8341 // File a report about this. 8342 String msg = "System package " + pkg.packageName 8343 + " signature changed; retaining data."; 8344 reportSettingsProblem(Log.WARN, msg); 8345 } 8346 } 8347 // Verify that this new package doesn't have any content providers 8348 // that conflict with existing packages. Only do this if the 8349 // package isn't already installed, since we don't want to break 8350 // things that are installed. 8351 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8352 final int N = pkg.providers.size(); 8353 int i; 8354 for (i=0; i<N; i++) { 8355 PackageParser.Provider p = pkg.providers.get(i); 8356 if (p.info.authority != null) { 8357 String names[] = p.info.authority.split(";"); 8358 for (int j = 0; j < names.length; j++) { 8359 if (mProvidersByAuthority.containsKey(names[j])) { 8360 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8361 final String otherPackageName = 8362 ((other != null && other.getComponentName() != null) ? 8363 other.getComponentName().getPackageName() : "?"); 8364 throw new PackageManagerException( 8365 INSTALL_FAILED_CONFLICTING_PROVIDER, 8366 "Can't install because provider name " + names[j] 8367 + " (in package " + pkg.applicationInfo.packageName 8368 + ") is already used by " + otherPackageName); 8369 } 8370 } 8371 } 8372 } 8373 } 8374 8375 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8376 // This package wants to adopt ownership of permissions from 8377 // another package. 8378 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8379 final String origName = pkg.mAdoptPermissions.get(i); 8380 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8381 if (orig != null) { 8382 if (verifyPackageUpdateLPr(orig, pkg)) { 8383 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8384 + pkg.packageName); 8385 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8386 } 8387 } 8388 } 8389 } 8390 } 8391 8392 final String pkgName = pkg.packageName; 8393 8394 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8395 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8396 pkg.applicationInfo.processName = fixProcessName( 8397 pkg.applicationInfo.packageName, 8398 pkg.applicationInfo.processName, 8399 pkg.applicationInfo.uid); 8400 8401 if (pkg != mPlatformPackage) { 8402 // Get all of our default paths setup 8403 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8404 } 8405 8406 final String path = scanFile.getPath(); 8407 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8408 8409 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8410 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8411 8412 // Some system apps still use directory structure for native libraries 8413 // in which case we might end up not detecting abi solely based on apk 8414 // structure. Try to detect abi based on directory structure. 8415 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8416 pkg.applicationInfo.primaryCpuAbi == null) { 8417 setBundledAppAbisAndRoots(pkg, pkgSetting); 8418 setNativeLibraryPaths(pkg); 8419 } 8420 8421 } else { 8422 if ((scanFlags & SCAN_MOVE) != 0) { 8423 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8424 // but we already have this packages package info in the PackageSetting. We just 8425 // use that and derive the native library path based on the new codepath. 8426 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8427 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8428 } 8429 8430 // Set native library paths again. For moves, the path will be updated based on the 8431 // ABIs we've determined above. For non-moves, the path will be updated based on the 8432 // ABIs we determined during compilation, but the path will depend on the final 8433 // package path (after the rename away from the stage path). 8434 setNativeLibraryPaths(pkg); 8435 } 8436 8437 // This is a special case for the "system" package, where the ABI is 8438 // dictated by the zygote configuration (and init.rc). We should keep track 8439 // of this ABI so that we can deal with "normal" applications that run under 8440 // the same UID correctly. 8441 if (mPlatformPackage == pkg) { 8442 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8443 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8444 } 8445 8446 // If there's a mismatch between the abi-override in the package setting 8447 // and the abiOverride specified for the install. Warn about this because we 8448 // would've already compiled the app without taking the package setting into 8449 // account. 8450 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8451 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8452 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8453 " for package " + pkg.packageName); 8454 } 8455 } 8456 8457 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8458 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8459 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8460 8461 // Copy the derived override back to the parsed package, so that we can 8462 // update the package settings accordingly. 8463 pkg.cpuAbiOverride = cpuAbiOverride; 8464 8465 if (DEBUG_ABI_SELECTION) { 8466 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8467 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8468 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8469 } 8470 8471 // Push the derived path down into PackageSettings so we know what to 8472 // clean up at uninstall time. 8473 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8474 8475 if (DEBUG_ABI_SELECTION) { 8476 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8477 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8478 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8479 } 8480 8481 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8482 // We don't do this here during boot because we can do it all 8483 // at once after scanning all existing packages. 8484 // 8485 // We also do this *before* we perform dexopt on this package, so that 8486 // we can avoid redundant dexopts, and also to make sure we've got the 8487 // code and package path correct. 8488 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8489 pkg, true /* boot complete */); 8490 } 8491 8492 if (mFactoryTest && pkg.requestedPermissions.contains( 8493 android.Manifest.permission.FACTORY_TEST)) { 8494 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8495 } 8496 8497 if (isSystemApp(pkg)) { 8498 pkgSetting.isOrphaned = true; 8499 } 8500 8501 ArrayList<PackageParser.Package> clientLibPkgs = null; 8502 8503 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8504 if (nonMutatedPs != null) { 8505 synchronized (mPackages) { 8506 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8507 } 8508 } 8509 return pkg; 8510 } 8511 8512 // Only privileged apps and updated privileged apps can add child packages. 8513 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8514 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8515 throw new PackageManagerException("Only privileged apps and updated " 8516 + "privileged apps can add child packages. Ignoring package " 8517 + pkg.packageName); 8518 } 8519 final int childCount = pkg.childPackages.size(); 8520 for (int i = 0; i < childCount; i++) { 8521 PackageParser.Package childPkg = pkg.childPackages.get(i); 8522 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8523 childPkg.packageName)) { 8524 throw new PackageManagerException("Cannot override a child package of " 8525 + "another disabled system app. Ignoring package " + pkg.packageName); 8526 } 8527 } 8528 } 8529 8530 // writer 8531 synchronized (mPackages) { 8532 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8533 // Only system apps can add new shared libraries. 8534 if (pkg.libraryNames != null) { 8535 for (int i=0; i<pkg.libraryNames.size(); i++) { 8536 String name = pkg.libraryNames.get(i); 8537 boolean allowed = false; 8538 if (pkg.isUpdatedSystemApp()) { 8539 // New library entries can only be added through the 8540 // system image. This is important to get rid of a lot 8541 // of nasty edge cases: for example if we allowed a non- 8542 // system update of the app to add a library, then uninstalling 8543 // the update would make the library go away, and assumptions 8544 // we made such as through app install filtering would now 8545 // have allowed apps on the device which aren't compatible 8546 // with it. Better to just have the restriction here, be 8547 // conservative, and create many fewer cases that can negatively 8548 // impact the user experience. 8549 final PackageSetting sysPs = mSettings 8550 .getDisabledSystemPkgLPr(pkg.packageName); 8551 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8552 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8553 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8554 allowed = true; 8555 break; 8556 } 8557 } 8558 } 8559 } else { 8560 allowed = true; 8561 } 8562 if (allowed) { 8563 if (!mSharedLibraries.containsKey(name)) { 8564 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8565 } else if (!name.equals(pkg.packageName)) { 8566 Slog.w(TAG, "Package " + pkg.packageName + " library " 8567 + name + " already exists; skipping"); 8568 } 8569 } else { 8570 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8571 + name + " that is not declared on system image; skipping"); 8572 } 8573 } 8574 if ((scanFlags & SCAN_BOOTING) == 0) { 8575 // If we are not booting, we need to update any applications 8576 // that are clients of our shared library. If we are booting, 8577 // this will all be done once the scan is complete. 8578 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8579 } 8580 } 8581 } 8582 } 8583 8584 if ((scanFlags & SCAN_BOOTING) != 0) { 8585 // No apps can run during boot scan, so they don't need to be frozen 8586 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8587 // Caller asked to not kill app, so it's probably not frozen 8588 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8589 // Caller asked us to ignore frozen check for some reason; they 8590 // probably didn't know the package name 8591 } else { 8592 // We're doing major surgery on this package, so it better be frozen 8593 // right now to keep it from launching 8594 checkPackageFrozen(pkgName); 8595 } 8596 8597 // Also need to kill any apps that are dependent on the library. 8598 if (clientLibPkgs != null) { 8599 for (int i=0; i<clientLibPkgs.size(); i++) { 8600 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8601 killApplication(clientPkg.applicationInfo.packageName, 8602 clientPkg.applicationInfo.uid, "update lib"); 8603 } 8604 } 8605 8606 // Make sure we're not adding any bogus keyset info 8607 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8608 ksms.assertScannedPackageValid(pkg); 8609 8610 // writer 8611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8612 8613 boolean createIdmapFailed = false; 8614 synchronized (mPackages) { 8615 // We don't expect installation to fail beyond this point 8616 8617 if (pkgSetting.pkg != null) { 8618 // Note that |user| might be null during the initial boot scan. If a codePath 8619 // for an app has changed during a boot scan, it's due to an app update that's 8620 // part of the system partition and marker changes must be applied to all users. 8621 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8622 (user != null) ? user : UserHandle.ALL); 8623 } 8624 8625 // Add the new setting to mSettings 8626 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8627 // Add the new setting to mPackages 8628 mPackages.put(pkg.applicationInfo.packageName, pkg); 8629 // Make sure we don't accidentally delete its data. 8630 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8631 while (iter.hasNext()) { 8632 PackageCleanItem item = iter.next(); 8633 if (pkgName.equals(item.packageName)) { 8634 iter.remove(); 8635 } 8636 } 8637 8638 // Take care of first install / last update times. 8639 if (currentTime != 0) { 8640 if (pkgSetting.firstInstallTime == 0) { 8641 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8642 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8643 pkgSetting.lastUpdateTime = currentTime; 8644 } 8645 } else if (pkgSetting.firstInstallTime == 0) { 8646 // We need *something*. Take time time stamp of the file. 8647 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8648 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8649 if (scanFileTime != pkgSetting.timeStamp) { 8650 // A package on the system image has changed; consider this 8651 // to be an update. 8652 pkgSetting.lastUpdateTime = scanFileTime; 8653 } 8654 } 8655 8656 // Add the package's KeySets to the global KeySetManagerService 8657 ksms.addScannedPackageLPw(pkg); 8658 8659 int N = pkg.providers.size(); 8660 StringBuilder r = null; 8661 int i; 8662 for (i=0; i<N; i++) { 8663 PackageParser.Provider p = pkg.providers.get(i); 8664 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8665 p.info.processName, pkg.applicationInfo.uid); 8666 mProviders.addProvider(p); 8667 p.syncable = p.info.isSyncable; 8668 if (p.info.authority != null) { 8669 String names[] = p.info.authority.split(";"); 8670 p.info.authority = null; 8671 for (int j = 0; j < names.length; j++) { 8672 if (j == 1 && p.syncable) { 8673 // We only want the first authority for a provider to possibly be 8674 // syncable, so if we already added this provider using a different 8675 // authority clear the syncable flag. We copy the provider before 8676 // changing it because the mProviders object contains a reference 8677 // to a provider that we don't want to change. 8678 // Only do this for the second authority since the resulting provider 8679 // object can be the same for all future authorities for this provider. 8680 p = new PackageParser.Provider(p); 8681 p.syncable = false; 8682 } 8683 if (!mProvidersByAuthority.containsKey(names[j])) { 8684 mProvidersByAuthority.put(names[j], p); 8685 if (p.info.authority == null) { 8686 p.info.authority = names[j]; 8687 } else { 8688 p.info.authority = p.info.authority + ";" + names[j]; 8689 } 8690 if (DEBUG_PACKAGE_SCANNING) { 8691 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8692 Log.d(TAG, "Registered content provider: " + names[j] 8693 + ", className = " + p.info.name + ", isSyncable = " 8694 + p.info.isSyncable); 8695 } 8696 } else { 8697 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8698 Slog.w(TAG, "Skipping provider name " + names[j] + 8699 " (in package " + pkg.applicationInfo.packageName + 8700 "): name already used by " 8701 + ((other != null && other.getComponentName() != null) 8702 ? other.getComponentName().getPackageName() : "?")); 8703 } 8704 } 8705 } 8706 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8707 if (r == null) { 8708 r = new StringBuilder(256); 8709 } else { 8710 r.append(' '); 8711 } 8712 r.append(p.info.name); 8713 } 8714 } 8715 if (r != null) { 8716 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8717 } 8718 8719 N = pkg.services.size(); 8720 r = null; 8721 for (i=0; i<N; i++) { 8722 PackageParser.Service s = pkg.services.get(i); 8723 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8724 s.info.processName, pkg.applicationInfo.uid); 8725 mServices.addService(s); 8726 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8727 if (r == null) { 8728 r = new StringBuilder(256); 8729 } else { 8730 r.append(' '); 8731 } 8732 r.append(s.info.name); 8733 } 8734 } 8735 if (r != null) { 8736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8737 } 8738 8739 N = pkg.receivers.size(); 8740 r = null; 8741 for (i=0; i<N; i++) { 8742 PackageParser.Activity a = pkg.receivers.get(i); 8743 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8744 a.info.processName, pkg.applicationInfo.uid); 8745 mReceivers.addActivity(a, "receiver"); 8746 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8747 if (r == null) { 8748 r = new StringBuilder(256); 8749 } else { 8750 r.append(' '); 8751 } 8752 r.append(a.info.name); 8753 } 8754 } 8755 if (r != null) { 8756 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8757 } 8758 8759 N = pkg.activities.size(); 8760 r = null; 8761 for (i=0; i<N; i++) { 8762 PackageParser.Activity a = pkg.activities.get(i); 8763 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8764 a.info.processName, pkg.applicationInfo.uid); 8765 mActivities.addActivity(a, "activity"); 8766 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8767 if (r == null) { 8768 r = new StringBuilder(256); 8769 } else { 8770 r.append(' '); 8771 } 8772 r.append(a.info.name); 8773 } 8774 } 8775 if (r != null) { 8776 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8777 } 8778 8779 N = pkg.permissionGroups.size(); 8780 r = null; 8781 for (i=0; i<N; i++) { 8782 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8783 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8784 final String curPackageName = cur == null ? null : cur.info.packageName; 8785 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8786 if (cur == null || isPackageUpdate) { 8787 mPermissionGroups.put(pg.info.name, pg); 8788 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8789 if (r == null) { 8790 r = new StringBuilder(256); 8791 } else { 8792 r.append(' '); 8793 } 8794 if (isPackageUpdate) { 8795 r.append("UPD:"); 8796 } 8797 r.append(pg.info.name); 8798 } 8799 } else { 8800 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8801 + pg.info.packageName + " ignored: original from " 8802 + cur.info.packageName); 8803 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8804 if (r == null) { 8805 r = new StringBuilder(256); 8806 } else { 8807 r.append(' '); 8808 } 8809 r.append("DUP:"); 8810 r.append(pg.info.name); 8811 } 8812 } 8813 } 8814 if (r != null) { 8815 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8816 } 8817 8818 N = pkg.permissions.size(); 8819 r = null; 8820 for (i=0; i<N; i++) { 8821 PackageParser.Permission p = pkg.permissions.get(i); 8822 8823 // Assume by default that we did not install this permission into the system. 8824 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8825 8826 // Now that permission groups have a special meaning, we ignore permission 8827 // groups for legacy apps to prevent unexpected behavior. In particular, 8828 // permissions for one app being granted to someone just becase they happen 8829 // to be in a group defined by another app (before this had no implications). 8830 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8831 p.group = mPermissionGroups.get(p.info.group); 8832 // Warn for a permission in an unknown group. 8833 if (p.info.group != null && p.group == null) { 8834 Slog.w(TAG, "Permission " + p.info.name + " from package " 8835 + p.info.packageName + " in an unknown group " + p.info.group); 8836 } 8837 } 8838 8839 ArrayMap<String, BasePermission> permissionMap = 8840 p.tree ? mSettings.mPermissionTrees 8841 : mSettings.mPermissions; 8842 BasePermission bp = permissionMap.get(p.info.name); 8843 8844 // Allow system apps to redefine non-system permissions 8845 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8846 final boolean currentOwnerIsSystem = (bp.perm != null 8847 && isSystemApp(bp.perm.owner)); 8848 if (isSystemApp(p.owner)) { 8849 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8850 // It's a built-in permission and no owner, take ownership now 8851 bp.packageSetting = pkgSetting; 8852 bp.perm = p; 8853 bp.uid = pkg.applicationInfo.uid; 8854 bp.sourcePackage = p.info.packageName; 8855 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8856 } else if (!currentOwnerIsSystem) { 8857 String msg = "New decl " + p.owner + " of permission " 8858 + p.info.name + " is system; overriding " + bp.sourcePackage; 8859 reportSettingsProblem(Log.WARN, msg); 8860 bp = null; 8861 } 8862 } 8863 } 8864 8865 if (bp == null) { 8866 bp = new BasePermission(p.info.name, p.info.packageName, 8867 BasePermission.TYPE_NORMAL); 8868 permissionMap.put(p.info.name, bp); 8869 } 8870 8871 if (bp.perm == null) { 8872 if (bp.sourcePackage == null 8873 || bp.sourcePackage.equals(p.info.packageName)) { 8874 BasePermission tree = findPermissionTreeLP(p.info.name); 8875 if (tree == null 8876 || tree.sourcePackage.equals(p.info.packageName)) { 8877 bp.packageSetting = pkgSetting; 8878 bp.perm = p; 8879 bp.uid = pkg.applicationInfo.uid; 8880 bp.sourcePackage = p.info.packageName; 8881 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8882 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8883 if (r == null) { 8884 r = new StringBuilder(256); 8885 } else { 8886 r.append(' '); 8887 } 8888 r.append(p.info.name); 8889 } 8890 } else { 8891 Slog.w(TAG, "Permission " + p.info.name + " from package " 8892 + p.info.packageName + " ignored: base tree " 8893 + tree.name + " is from package " 8894 + tree.sourcePackage); 8895 } 8896 } else { 8897 Slog.w(TAG, "Permission " + p.info.name + " from package " 8898 + p.info.packageName + " ignored: original from " 8899 + bp.sourcePackage); 8900 } 8901 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8902 if (r == null) { 8903 r = new StringBuilder(256); 8904 } else { 8905 r.append(' '); 8906 } 8907 r.append("DUP:"); 8908 r.append(p.info.name); 8909 } 8910 if (bp.perm == p) { 8911 bp.protectionLevel = p.info.protectionLevel; 8912 } 8913 } 8914 8915 if (r != null) { 8916 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8917 } 8918 8919 N = pkg.instrumentation.size(); 8920 r = null; 8921 for (i=0; i<N; i++) { 8922 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8923 a.info.packageName = pkg.applicationInfo.packageName; 8924 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8925 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8926 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8927 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8928 a.info.dataDir = pkg.applicationInfo.dataDir; 8929 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8930 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8931 8932 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8933 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8934 mInstrumentation.put(a.getComponentName(), a); 8935 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8936 if (r == null) { 8937 r = new StringBuilder(256); 8938 } else { 8939 r.append(' '); 8940 } 8941 r.append(a.info.name); 8942 } 8943 } 8944 if (r != null) { 8945 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8946 } 8947 8948 if (pkg.protectedBroadcasts != null) { 8949 N = pkg.protectedBroadcasts.size(); 8950 for (i=0; i<N; i++) { 8951 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8952 } 8953 } 8954 8955 pkgSetting.setTimeStamp(scanFileTime); 8956 8957 // Create idmap files for pairs of (packages, overlay packages). 8958 // Note: "android", ie framework-res.apk, is handled by native layers. 8959 if (pkg.mOverlayTarget != null) { 8960 // This is an overlay package. 8961 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8962 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8963 mOverlays.put(pkg.mOverlayTarget, 8964 new ArrayMap<String, PackageParser.Package>()); 8965 } 8966 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8967 map.put(pkg.packageName, pkg); 8968 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8969 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8970 createIdmapFailed = true; 8971 } 8972 } 8973 } else if (mOverlays.containsKey(pkg.packageName) && 8974 !pkg.packageName.equals("android")) { 8975 // This is a regular package, with one or more known overlay packages. 8976 createIdmapsForPackageLI(pkg); 8977 } 8978 } 8979 8980 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8981 8982 if (createIdmapFailed) { 8983 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8984 "scanPackageLI failed to createIdmap"); 8985 } 8986 return pkg; 8987 } 8988 8989 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8990 PackageParser.Package update, UserHandle user) { 8991 if (existing.applicationInfo == null || update.applicationInfo == null) { 8992 // This isn't due to an app installation. 8993 return; 8994 } 8995 8996 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8997 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8998 8999 // The codePath hasn't changed, so there's nothing for us to do. 9000 if (Objects.equals(oldCodePath, newCodePath)) { 9001 return; 9002 } 9003 9004 File canonicalNewCodePath; 9005 try { 9006 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9007 } catch (IOException e) { 9008 Slog.w(TAG, "Failed to get canonical path.", e); 9009 return; 9010 } 9011 9012 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9013 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9014 // that the last component of the path (i.e, the name) doesn't need canonicalization 9015 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9016 // but may change in the future. Hopefully this function won't exist at that point. 9017 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9018 oldCodePath.getName()); 9019 9020 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9021 // with "@". 9022 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9023 if (!oldMarkerPrefix.endsWith("@")) { 9024 oldMarkerPrefix += "@"; 9025 } 9026 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9027 if (!newMarkerPrefix.endsWith("@")) { 9028 newMarkerPrefix += "@"; 9029 } 9030 9031 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9032 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9033 for (String updatedPath : updatedPaths) { 9034 String updatedPathName = new File(updatedPath).getName(); 9035 markerSuffixes.add(updatedPathName.replace('/', '@')); 9036 } 9037 9038 for (int userId : resolveUserIds(user.getIdentifier())) { 9039 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9040 9041 for (String markerSuffix : markerSuffixes) { 9042 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9043 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9044 if (oldForeignUseMark.exists()) { 9045 try { 9046 Os.rename(oldForeignUseMark.getAbsolutePath(), 9047 newForeignUseMark.getAbsolutePath()); 9048 } catch (ErrnoException e) { 9049 Slog.w(TAG, "Failed to rename foreign use marker", e); 9050 oldForeignUseMark.delete(); 9051 } 9052 } 9053 } 9054 } 9055 } 9056 9057 /** 9058 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9059 * is derived purely on the basis of the contents of {@code scanFile} and 9060 * {@code cpuAbiOverride}. 9061 * 9062 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9063 */ 9064 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9065 String cpuAbiOverride, boolean extractLibs) 9066 throws PackageManagerException { 9067 // TODO: We can probably be smarter about this stuff. For installed apps, 9068 // we can calculate this information at install time once and for all. For 9069 // system apps, we can probably assume that this information doesn't change 9070 // after the first boot scan. As things stand, we do lots of unnecessary work. 9071 9072 // Give ourselves some initial paths; we'll come back for another 9073 // pass once we've determined ABI below. 9074 setNativeLibraryPaths(pkg); 9075 9076 // We would never need to extract libs for forward-locked and external packages, 9077 // since the container service will do it for us. We shouldn't attempt to 9078 // extract libs from system app when it was not updated. 9079 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9080 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9081 extractLibs = false; 9082 } 9083 9084 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9085 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9086 9087 NativeLibraryHelper.Handle handle = null; 9088 try { 9089 handle = NativeLibraryHelper.Handle.create(pkg); 9090 // TODO(multiArch): This can be null for apps that didn't go through the 9091 // usual installation process. We can calculate it again, like we 9092 // do during install time. 9093 // 9094 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9095 // unnecessary. 9096 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9097 9098 // Null out the abis so that they can be recalculated. 9099 pkg.applicationInfo.primaryCpuAbi = null; 9100 pkg.applicationInfo.secondaryCpuAbi = null; 9101 if (isMultiArch(pkg.applicationInfo)) { 9102 // Warn if we've set an abiOverride for multi-lib packages.. 9103 // By definition, we need to copy both 32 and 64 bit libraries for 9104 // such packages. 9105 if (pkg.cpuAbiOverride != null 9106 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9107 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9108 } 9109 9110 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9111 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9112 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9113 if (extractLibs) { 9114 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9115 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9116 useIsaSpecificSubdirs); 9117 } else { 9118 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9119 } 9120 } 9121 9122 maybeThrowExceptionForMultiArchCopy( 9123 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9124 9125 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9126 if (extractLibs) { 9127 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9128 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9129 useIsaSpecificSubdirs); 9130 } else { 9131 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9132 } 9133 } 9134 9135 maybeThrowExceptionForMultiArchCopy( 9136 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9137 9138 if (abi64 >= 0) { 9139 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9140 } 9141 9142 if (abi32 >= 0) { 9143 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9144 if (abi64 >= 0) { 9145 if (pkg.use32bitAbi) { 9146 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9147 pkg.applicationInfo.primaryCpuAbi = abi; 9148 } else { 9149 pkg.applicationInfo.secondaryCpuAbi = abi; 9150 } 9151 } else { 9152 pkg.applicationInfo.primaryCpuAbi = abi; 9153 } 9154 } 9155 9156 } else { 9157 String[] abiList = (cpuAbiOverride != null) ? 9158 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9159 9160 // Enable gross and lame hacks for apps that are built with old 9161 // SDK tools. We must scan their APKs for renderscript bitcode and 9162 // not launch them if it's present. Don't bother checking on devices 9163 // that don't have 64 bit support. 9164 boolean needsRenderScriptOverride = false; 9165 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9166 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9167 abiList = Build.SUPPORTED_32_BIT_ABIS; 9168 needsRenderScriptOverride = true; 9169 } 9170 9171 final int copyRet; 9172 if (extractLibs) { 9173 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9174 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9175 } else { 9176 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9177 } 9178 9179 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9180 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9181 "Error unpackaging native libs for app, errorCode=" + copyRet); 9182 } 9183 9184 if (copyRet >= 0) { 9185 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9186 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9187 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9188 } else if (needsRenderScriptOverride) { 9189 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9190 } 9191 } 9192 } catch (IOException ioe) { 9193 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9194 } finally { 9195 IoUtils.closeQuietly(handle); 9196 } 9197 9198 // Now that we've calculated the ABIs and determined if it's an internal app, 9199 // we will go ahead and populate the nativeLibraryPath. 9200 setNativeLibraryPaths(pkg); 9201 } 9202 9203 /** 9204 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9205 * i.e, so that all packages can be run inside a single process if required. 9206 * 9207 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9208 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9209 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9210 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9211 * updating a package that belongs to a shared user. 9212 * 9213 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9214 * adds unnecessary complexity. 9215 */ 9216 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9217 PackageParser.Package scannedPackage, boolean bootComplete) { 9218 String requiredInstructionSet = null; 9219 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9220 requiredInstructionSet = VMRuntime.getInstructionSet( 9221 scannedPackage.applicationInfo.primaryCpuAbi); 9222 } 9223 9224 PackageSetting requirer = null; 9225 for (PackageSetting ps : packagesForUser) { 9226 // If packagesForUser contains scannedPackage, we skip it. This will happen 9227 // when scannedPackage is an update of an existing package. Without this check, 9228 // we will never be able to change the ABI of any package belonging to a shared 9229 // user, even if it's compatible with other packages. 9230 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9231 if (ps.primaryCpuAbiString == null) { 9232 continue; 9233 } 9234 9235 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9236 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9237 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9238 // this but there's not much we can do. 9239 String errorMessage = "Instruction set mismatch, " 9240 + ((requirer == null) ? "[caller]" : requirer) 9241 + " requires " + requiredInstructionSet + " whereas " + ps 9242 + " requires " + instructionSet; 9243 Slog.w(TAG, errorMessage); 9244 } 9245 9246 if (requiredInstructionSet == null) { 9247 requiredInstructionSet = instructionSet; 9248 requirer = ps; 9249 } 9250 } 9251 } 9252 9253 if (requiredInstructionSet != null) { 9254 String adjustedAbi; 9255 if (requirer != null) { 9256 // requirer != null implies that either scannedPackage was null or that scannedPackage 9257 // did not require an ABI, in which case we have to adjust scannedPackage to match 9258 // the ABI of the set (which is the same as requirer's ABI) 9259 adjustedAbi = requirer.primaryCpuAbiString; 9260 if (scannedPackage != null) { 9261 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9262 } 9263 } else { 9264 // requirer == null implies that we're updating all ABIs in the set to 9265 // match scannedPackage. 9266 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9267 } 9268 9269 for (PackageSetting ps : packagesForUser) { 9270 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9271 if (ps.primaryCpuAbiString != null) { 9272 continue; 9273 } 9274 9275 ps.primaryCpuAbiString = adjustedAbi; 9276 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9277 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9278 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9279 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9280 + " (requirer=" 9281 + (requirer == null ? "null" : requirer.pkg.packageName) 9282 + ", scannedPackage=" 9283 + (scannedPackage != null ? scannedPackage.packageName : "null") 9284 + ")"); 9285 try { 9286 mInstaller.rmdex(ps.codePathString, 9287 getDexCodeInstructionSet(getPreferredInstructionSet())); 9288 } catch (InstallerException ignored) { 9289 } 9290 } 9291 } 9292 } 9293 } 9294 } 9295 9296 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9297 synchronized (mPackages) { 9298 mResolverReplaced = true; 9299 // Set up information for custom user intent resolution activity. 9300 mResolveActivity.applicationInfo = pkg.applicationInfo; 9301 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9302 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9303 mResolveActivity.processName = pkg.applicationInfo.packageName; 9304 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9305 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9306 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9307 mResolveActivity.theme = 0; 9308 mResolveActivity.exported = true; 9309 mResolveActivity.enabled = true; 9310 mResolveInfo.activityInfo = mResolveActivity; 9311 mResolveInfo.priority = 0; 9312 mResolveInfo.preferredOrder = 0; 9313 mResolveInfo.match = 0; 9314 mResolveComponentName = mCustomResolverComponentName; 9315 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9316 mResolveComponentName); 9317 } 9318 } 9319 9320 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9321 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9322 9323 // Set up information for ephemeral installer activity 9324 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9325 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9326 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9327 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9328 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9329 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9330 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9331 mEphemeralInstallerActivity.theme = 0; 9332 mEphemeralInstallerActivity.exported = true; 9333 mEphemeralInstallerActivity.enabled = true; 9334 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9335 mEphemeralInstallerInfo.priority = 0; 9336 mEphemeralInstallerInfo.preferredOrder = 1; 9337 mEphemeralInstallerInfo.isDefault = true; 9338 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9339 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9340 9341 if (DEBUG_EPHEMERAL) { 9342 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9343 } 9344 } 9345 9346 private static String calculateBundledApkRoot(final String codePathString) { 9347 final File codePath = new File(codePathString); 9348 final File codeRoot; 9349 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9350 codeRoot = Environment.getRootDirectory(); 9351 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9352 codeRoot = Environment.getOemDirectory(); 9353 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9354 codeRoot = Environment.getVendorDirectory(); 9355 } else { 9356 // Unrecognized code path; take its top real segment as the apk root: 9357 // e.g. /something/app/blah.apk => /something 9358 try { 9359 File f = codePath.getCanonicalFile(); 9360 File parent = f.getParentFile(); // non-null because codePath is a file 9361 File tmp; 9362 while ((tmp = parent.getParentFile()) != null) { 9363 f = parent; 9364 parent = tmp; 9365 } 9366 codeRoot = f; 9367 Slog.w(TAG, "Unrecognized code path " 9368 + codePath + " - using " + codeRoot); 9369 } catch (IOException e) { 9370 // Can't canonicalize the code path -- shenanigans? 9371 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9372 return Environment.getRootDirectory().getPath(); 9373 } 9374 } 9375 return codeRoot.getPath(); 9376 } 9377 9378 /** 9379 * Derive and set the location of native libraries for the given package, 9380 * which varies depending on where and how the package was installed. 9381 */ 9382 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9383 final ApplicationInfo info = pkg.applicationInfo; 9384 final String codePath = pkg.codePath; 9385 final File codeFile = new File(codePath); 9386 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9387 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9388 9389 info.nativeLibraryRootDir = null; 9390 info.nativeLibraryRootRequiresIsa = false; 9391 info.nativeLibraryDir = null; 9392 info.secondaryNativeLibraryDir = null; 9393 9394 if (isApkFile(codeFile)) { 9395 // Monolithic install 9396 if (bundledApp) { 9397 // If "/system/lib64/apkname" exists, assume that is the per-package 9398 // native library directory to use; otherwise use "/system/lib/apkname". 9399 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9400 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9401 getPrimaryInstructionSet(info)); 9402 9403 // This is a bundled system app so choose the path based on the ABI. 9404 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9405 // is just the default path. 9406 final String apkName = deriveCodePathName(codePath); 9407 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9408 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9409 apkName).getAbsolutePath(); 9410 9411 if (info.secondaryCpuAbi != null) { 9412 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9413 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9414 secondaryLibDir, apkName).getAbsolutePath(); 9415 } 9416 } else if (asecApp) { 9417 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9418 .getAbsolutePath(); 9419 } else { 9420 final String apkName = deriveCodePathName(codePath); 9421 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9422 .getAbsolutePath(); 9423 } 9424 9425 info.nativeLibraryRootRequiresIsa = false; 9426 info.nativeLibraryDir = info.nativeLibraryRootDir; 9427 } else { 9428 // Cluster install 9429 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9430 info.nativeLibraryRootRequiresIsa = true; 9431 9432 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9433 getPrimaryInstructionSet(info)).getAbsolutePath(); 9434 9435 if (info.secondaryCpuAbi != null) { 9436 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9437 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9438 } 9439 } 9440 } 9441 9442 /** 9443 * Calculate the abis and roots for a bundled app. These can uniquely 9444 * be determined from the contents of the system partition, i.e whether 9445 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9446 * of this information, and instead assume that the system was built 9447 * sensibly. 9448 */ 9449 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9450 PackageSetting pkgSetting) { 9451 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9452 9453 // If "/system/lib64/apkname" exists, assume that is the per-package 9454 // native library directory to use; otherwise use "/system/lib/apkname". 9455 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9456 setBundledAppAbi(pkg, apkRoot, apkName); 9457 // pkgSetting might be null during rescan following uninstall of updates 9458 // to a bundled app, so accommodate that possibility. The settings in 9459 // that case will be established later from the parsed package. 9460 // 9461 // If the settings aren't null, sync them up with what we've just derived. 9462 // note that apkRoot isn't stored in the package settings. 9463 if (pkgSetting != null) { 9464 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9465 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9466 } 9467 } 9468 9469 /** 9470 * Deduces the ABI of a bundled app and sets the relevant fields on the 9471 * parsed pkg object. 9472 * 9473 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9474 * under which system libraries are installed. 9475 * @param apkName the name of the installed package. 9476 */ 9477 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9478 final File codeFile = new File(pkg.codePath); 9479 9480 final boolean has64BitLibs; 9481 final boolean has32BitLibs; 9482 if (isApkFile(codeFile)) { 9483 // Monolithic install 9484 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9485 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9486 } else { 9487 // Cluster install 9488 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9489 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9490 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9491 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9492 has64BitLibs = (new File(rootDir, isa)).exists(); 9493 } else { 9494 has64BitLibs = false; 9495 } 9496 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9497 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9498 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9499 has32BitLibs = (new File(rootDir, isa)).exists(); 9500 } else { 9501 has32BitLibs = false; 9502 } 9503 } 9504 9505 if (has64BitLibs && !has32BitLibs) { 9506 // The package has 64 bit libs, but not 32 bit libs. Its primary 9507 // ABI should be 64 bit. We can safely assume here that the bundled 9508 // native libraries correspond to the most preferred ABI in the list. 9509 9510 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9511 pkg.applicationInfo.secondaryCpuAbi = null; 9512 } else if (has32BitLibs && !has64BitLibs) { 9513 // The package has 32 bit libs but not 64 bit libs. Its primary 9514 // ABI should be 32 bit. 9515 9516 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9517 pkg.applicationInfo.secondaryCpuAbi = null; 9518 } else if (has32BitLibs && has64BitLibs) { 9519 // The application has both 64 and 32 bit bundled libraries. We check 9520 // here that the app declares multiArch support, and warn if it doesn't. 9521 // 9522 // We will be lenient here and record both ABIs. The primary will be the 9523 // ABI that's higher on the list, i.e, a device that's configured to prefer 9524 // 64 bit apps will see a 64 bit primary ABI, 9525 9526 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9527 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9528 } 9529 9530 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9531 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9532 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9533 } else { 9534 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9535 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9536 } 9537 } else { 9538 pkg.applicationInfo.primaryCpuAbi = null; 9539 pkg.applicationInfo.secondaryCpuAbi = null; 9540 } 9541 } 9542 9543 private void killApplication(String pkgName, int appId, String reason) { 9544 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9545 } 9546 9547 private void killApplication(String pkgName, int appId, int userId, String reason) { 9548 // Request the ActivityManager to kill the process(only for existing packages) 9549 // so that we do not end up in a confused state while the user is still using the older 9550 // version of the application while the new one gets installed. 9551 final long token = Binder.clearCallingIdentity(); 9552 try { 9553 IActivityManager am = ActivityManagerNative.getDefault(); 9554 if (am != null) { 9555 try { 9556 am.killApplication(pkgName, appId, userId, reason); 9557 } catch (RemoteException e) { 9558 } 9559 } 9560 } finally { 9561 Binder.restoreCallingIdentity(token); 9562 } 9563 } 9564 9565 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9566 // Remove the parent package setting 9567 PackageSetting ps = (PackageSetting) pkg.mExtras; 9568 if (ps != null) { 9569 removePackageLI(ps, chatty); 9570 } 9571 // Remove the child package setting 9572 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9573 for (int i = 0; i < childCount; i++) { 9574 PackageParser.Package childPkg = pkg.childPackages.get(i); 9575 ps = (PackageSetting) childPkg.mExtras; 9576 if (ps != null) { 9577 removePackageLI(ps, chatty); 9578 } 9579 } 9580 } 9581 9582 void removePackageLI(PackageSetting ps, boolean chatty) { 9583 if (DEBUG_INSTALL) { 9584 if (chatty) 9585 Log.d(TAG, "Removing package " + ps.name); 9586 } 9587 9588 // writer 9589 synchronized (mPackages) { 9590 mPackages.remove(ps.name); 9591 final PackageParser.Package pkg = ps.pkg; 9592 if (pkg != null) { 9593 cleanPackageDataStructuresLILPw(pkg, chatty); 9594 } 9595 } 9596 } 9597 9598 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9599 if (DEBUG_INSTALL) { 9600 if (chatty) 9601 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9602 } 9603 9604 // writer 9605 synchronized (mPackages) { 9606 // Remove the parent package 9607 mPackages.remove(pkg.applicationInfo.packageName); 9608 cleanPackageDataStructuresLILPw(pkg, chatty); 9609 9610 // Remove the child packages 9611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9612 for (int i = 0; i < childCount; i++) { 9613 PackageParser.Package childPkg = pkg.childPackages.get(i); 9614 mPackages.remove(childPkg.applicationInfo.packageName); 9615 cleanPackageDataStructuresLILPw(childPkg, chatty); 9616 } 9617 } 9618 } 9619 9620 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9621 int N = pkg.providers.size(); 9622 StringBuilder r = null; 9623 int i; 9624 for (i=0; i<N; i++) { 9625 PackageParser.Provider p = pkg.providers.get(i); 9626 mProviders.removeProvider(p); 9627 if (p.info.authority == null) { 9628 9629 /* There was another ContentProvider with this authority when 9630 * this app was installed so this authority is null, 9631 * Ignore it as we don't have to unregister the provider. 9632 */ 9633 continue; 9634 } 9635 String names[] = p.info.authority.split(";"); 9636 for (int j = 0; j < names.length; j++) { 9637 if (mProvidersByAuthority.get(names[j]) == p) { 9638 mProvidersByAuthority.remove(names[j]); 9639 if (DEBUG_REMOVE) { 9640 if (chatty) 9641 Log.d(TAG, "Unregistered content provider: " + names[j] 9642 + ", className = " + p.info.name + ", isSyncable = " 9643 + p.info.isSyncable); 9644 } 9645 } 9646 } 9647 if (DEBUG_REMOVE && chatty) { 9648 if (r == null) { 9649 r = new StringBuilder(256); 9650 } else { 9651 r.append(' '); 9652 } 9653 r.append(p.info.name); 9654 } 9655 } 9656 if (r != null) { 9657 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9658 } 9659 9660 N = pkg.services.size(); 9661 r = null; 9662 for (i=0; i<N; i++) { 9663 PackageParser.Service s = pkg.services.get(i); 9664 mServices.removeService(s); 9665 if (chatty) { 9666 if (r == null) { 9667 r = new StringBuilder(256); 9668 } else { 9669 r.append(' '); 9670 } 9671 r.append(s.info.name); 9672 } 9673 } 9674 if (r != null) { 9675 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9676 } 9677 9678 N = pkg.receivers.size(); 9679 r = null; 9680 for (i=0; i<N; i++) { 9681 PackageParser.Activity a = pkg.receivers.get(i); 9682 mReceivers.removeActivity(a, "receiver"); 9683 if (DEBUG_REMOVE && chatty) { 9684 if (r == null) { 9685 r = new StringBuilder(256); 9686 } else { 9687 r.append(' '); 9688 } 9689 r.append(a.info.name); 9690 } 9691 } 9692 if (r != null) { 9693 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9694 } 9695 9696 N = pkg.activities.size(); 9697 r = null; 9698 for (i=0; i<N; i++) { 9699 PackageParser.Activity a = pkg.activities.get(i); 9700 mActivities.removeActivity(a, "activity"); 9701 if (DEBUG_REMOVE && chatty) { 9702 if (r == null) { 9703 r = new StringBuilder(256); 9704 } else { 9705 r.append(' '); 9706 } 9707 r.append(a.info.name); 9708 } 9709 } 9710 if (r != null) { 9711 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9712 } 9713 9714 N = pkg.permissions.size(); 9715 r = null; 9716 for (i=0; i<N; i++) { 9717 PackageParser.Permission p = pkg.permissions.get(i); 9718 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9719 if (bp == null) { 9720 bp = mSettings.mPermissionTrees.get(p.info.name); 9721 } 9722 if (bp != null && bp.perm == p) { 9723 bp.perm = null; 9724 if (DEBUG_REMOVE && chatty) { 9725 if (r == null) { 9726 r = new StringBuilder(256); 9727 } else { 9728 r.append(' '); 9729 } 9730 r.append(p.info.name); 9731 } 9732 } 9733 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9734 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9735 if (appOpPkgs != null) { 9736 appOpPkgs.remove(pkg.packageName); 9737 } 9738 } 9739 } 9740 if (r != null) { 9741 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9742 } 9743 9744 N = pkg.requestedPermissions.size(); 9745 r = null; 9746 for (i=0; i<N; i++) { 9747 String perm = pkg.requestedPermissions.get(i); 9748 BasePermission bp = mSettings.mPermissions.get(perm); 9749 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9750 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9751 if (appOpPkgs != null) { 9752 appOpPkgs.remove(pkg.packageName); 9753 if (appOpPkgs.isEmpty()) { 9754 mAppOpPermissionPackages.remove(perm); 9755 } 9756 } 9757 } 9758 } 9759 if (r != null) { 9760 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9761 } 9762 9763 N = pkg.instrumentation.size(); 9764 r = null; 9765 for (i=0; i<N; i++) { 9766 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9767 mInstrumentation.remove(a.getComponentName()); 9768 if (DEBUG_REMOVE && chatty) { 9769 if (r == null) { 9770 r = new StringBuilder(256); 9771 } else { 9772 r.append(' '); 9773 } 9774 r.append(a.info.name); 9775 } 9776 } 9777 if (r != null) { 9778 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9779 } 9780 9781 r = null; 9782 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9783 // Only system apps can hold shared libraries. 9784 if (pkg.libraryNames != null) { 9785 for (i=0; i<pkg.libraryNames.size(); i++) { 9786 String name = pkg.libraryNames.get(i); 9787 SharedLibraryEntry cur = mSharedLibraries.get(name); 9788 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9789 mSharedLibraries.remove(name); 9790 if (DEBUG_REMOVE && chatty) { 9791 if (r == null) { 9792 r = new StringBuilder(256); 9793 } else { 9794 r.append(' '); 9795 } 9796 r.append(name); 9797 } 9798 } 9799 } 9800 } 9801 } 9802 if (r != null) { 9803 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9804 } 9805 } 9806 9807 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9808 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9809 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9810 return true; 9811 } 9812 } 9813 return false; 9814 } 9815 9816 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9817 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9818 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9819 9820 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9821 // Update the parent permissions 9822 updatePermissionsLPw(pkg.packageName, pkg, flags); 9823 // Update the child permissions 9824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9825 for (int i = 0; i < childCount; i++) { 9826 PackageParser.Package childPkg = pkg.childPackages.get(i); 9827 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9828 } 9829 } 9830 9831 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9832 int flags) { 9833 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9834 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9835 } 9836 9837 private void updatePermissionsLPw(String changingPkg, 9838 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9839 // Make sure there are no dangling permission trees. 9840 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9841 while (it.hasNext()) { 9842 final BasePermission bp = it.next(); 9843 if (bp.packageSetting == null) { 9844 // We may not yet have parsed the package, so just see if 9845 // we still know about its settings. 9846 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9847 } 9848 if (bp.packageSetting == null) { 9849 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9850 + " from package " + bp.sourcePackage); 9851 it.remove(); 9852 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9853 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9854 Slog.i(TAG, "Removing old permission tree: " + bp.name 9855 + " from package " + bp.sourcePackage); 9856 flags |= UPDATE_PERMISSIONS_ALL; 9857 it.remove(); 9858 } 9859 } 9860 } 9861 9862 // Make sure all dynamic permissions have been assigned to a package, 9863 // and make sure there are no dangling permissions. 9864 it = mSettings.mPermissions.values().iterator(); 9865 while (it.hasNext()) { 9866 final BasePermission bp = it.next(); 9867 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9868 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9869 + bp.name + " pkg=" + bp.sourcePackage 9870 + " info=" + bp.pendingInfo); 9871 if (bp.packageSetting == null && bp.pendingInfo != null) { 9872 final BasePermission tree = findPermissionTreeLP(bp.name); 9873 if (tree != null && tree.perm != null) { 9874 bp.packageSetting = tree.packageSetting; 9875 bp.perm = new PackageParser.Permission(tree.perm.owner, 9876 new PermissionInfo(bp.pendingInfo)); 9877 bp.perm.info.packageName = tree.perm.info.packageName; 9878 bp.perm.info.name = bp.name; 9879 bp.uid = tree.uid; 9880 } 9881 } 9882 } 9883 if (bp.packageSetting == null) { 9884 // We may not yet have parsed the package, so just see if 9885 // we still know about its settings. 9886 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9887 } 9888 if (bp.packageSetting == null) { 9889 Slog.w(TAG, "Removing dangling permission: " + bp.name 9890 + " from package " + bp.sourcePackage); 9891 it.remove(); 9892 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9893 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9894 Slog.i(TAG, "Removing old permission: " + bp.name 9895 + " from package " + bp.sourcePackage); 9896 flags |= UPDATE_PERMISSIONS_ALL; 9897 it.remove(); 9898 } 9899 } 9900 } 9901 9902 // Now update the permissions for all packages, in particular 9903 // replace the granted permissions of the system packages. 9904 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9905 for (PackageParser.Package pkg : mPackages.values()) { 9906 if (pkg != pkgInfo) { 9907 // Only replace for packages on requested volume 9908 final String volumeUuid = getVolumeUuidForPackage(pkg); 9909 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9910 && Objects.equals(replaceVolumeUuid, volumeUuid); 9911 grantPermissionsLPw(pkg, replace, changingPkg); 9912 } 9913 } 9914 } 9915 9916 if (pkgInfo != null) { 9917 // Only replace for packages on requested volume 9918 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9919 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9920 && Objects.equals(replaceVolumeUuid, volumeUuid); 9921 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9922 } 9923 } 9924 9925 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9926 String packageOfInterest) { 9927 // IMPORTANT: There are two types of permissions: install and runtime. 9928 // Install time permissions are granted when the app is installed to 9929 // all device users and users added in the future. Runtime permissions 9930 // are granted at runtime explicitly to specific users. Normal and signature 9931 // protected permissions are install time permissions. Dangerous permissions 9932 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9933 // otherwise they are runtime permissions. This function does not manage 9934 // runtime permissions except for the case an app targeting Lollipop MR1 9935 // being upgraded to target a newer SDK, in which case dangerous permissions 9936 // are transformed from install time to runtime ones. 9937 9938 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9939 if (ps == null) { 9940 return; 9941 } 9942 9943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9944 9945 PermissionsState permissionsState = ps.getPermissionsState(); 9946 PermissionsState origPermissions = permissionsState; 9947 9948 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9949 9950 boolean runtimePermissionsRevoked = false; 9951 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9952 9953 boolean changedInstallPermission = false; 9954 9955 if (replace) { 9956 ps.installPermissionsFixed = false; 9957 if (!ps.isSharedUser()) { 9958 origPermissions = new PermissionsState(permissionsState); 9959 permissionsState.reset(); 9960 } else { 9961 // We need to know only about runtime permission changes since the 9962 // calling code always writes the install permissions state but 9963 // the runtime ones are written only if changed. The only cases of 9964 // changed runtime permissions here are promotion of an install to 9965 // runtime and revocation of a runtime from a shared user. 9966 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9967 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9968 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9969 runtimePermissionsRevoked = true; 9970 } 9971 } 9972 } 9973 9974 permissionsState.setGlobalGids(mGlobalGids); 9975 9976 final int N = pkg.requestedPermissions.size(); 9977 for (int i=0; i<N; i++) { 9978 final String name = pkg.requestedPermissions.get(i); 9979 final BasePermission bp = mSettings.mPermissions.get(name); 9980 9981 if (DEBUG_INSTALL) { 9982 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9983 } 9984 9985 if (bp == null || bp.packageSetting == null) { 9986 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9987 Slog.w(TAG, "Unknown permission " + name 9988 + " in package " + pkg.packageName); 9989 } 9990 continue; 9991 } 9992 9993 final String perm = bp.name; 9994 boolean allowedSig = false; 9995 int grant = GRANT_DENIED; 9996 9997 // Keep track of app op permissions. 9998 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9999 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10000 if (pkgs == null) { 10001 pkgs = new ArraySet<>(); 10002 mAppOpPermissionPackages.put(bp.name, pkgs); 10003 } 10004 pkgs.add(pkg.packageName); 10005 } 10006 10007 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10008 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10009 >= Build.VERSION_CODES.M; 10010 switch (level) { 10011 case PermissionInfo.PROTECTION_NORMAL: { 10012 // For all apps normal permissions are install time ones. 10013 grant = GRANT_INSTALL; 10014 } break; 10015 10016 case PermissionInfo.PROTECTION_DANGEROUS: { 10017 // If a permission review is required for legacy apps we represent 10018 // their permissions as always granted runtime ones since we need 10019 // to keep the review required permission flag per user while an 10020 // install permission's state is shared across all users. 10021 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10022 // For legacy apps dangerous permissions are install time ones. 10023 grant = GRANT_INSTALL; 10024 } else if (origPermissions.hasInstallPermission(bp.name)) { 10025 // For legacy apps that became modern, install becomes runtime. 10026 grant = GRANT_UPGRADE; 10027 } else if (mPromoteSystemApps 10028 && isSystemApp(ps) 10029 && mExistingSystemPackages.contains(ps.name)) { 10030 // For legacy system apps, install becomes runtime. 10031 // We cannot check hasInstallPermission() for system apps since those 10032 // permissions were granted implicitly and not persisted pre-M. 10033 grant = GRANT_UPGRADE; 10034 } else { 10035 // For modern apps keep runtime permissions unchanged. 10036 grant = GRANT_RUNTIME; 10037 } 10038 } break; 10039 10040 case PermissionInfo.PROTECTION_SIGNATURE: { 10041 // For all apps signature permissions are install time ones. 10042 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10043 if (allowedSig) { 10044 grant = GRANT_INSTALL; 10045 } 10046 } break; 10047 } 10048 10049 if (DEBUG_INSTALL) { 10050 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10051 } 10052 10053 if (grant != GRANT_DENIED) { 10054 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10055 // If this is an existing, non-system package, then 10056 // we can't add any new permissions to it. 10057 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10058 // Except... if this is a permission that was added 10059 // to the platform (note: need to only do this when 10060 // updating the platform). 10061 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10062 grant = GRANT_DENIED; 10063 } 10064 } 10065 } 10066 10067 switch (grant) { 10068 case GRANT_INSTALL: { 10069 // Revoke this as runtime permission to handle the case of 10070 // a runtime permission being downgraded to an install one. 10071 // Also in permission review mode we keep dangerous permissions 10072 // for legacy apps 10073 for (int userId : UserManagerService.getInstance().getUserIds()) { 10074 if (origPermissions.getRuntimePermissionState( 10075 bp.name, userId) != null) { 10076 // Revoke the runtime permission and clear the flags. 10077 origPermissions.revokeRuntimePermission(bp, userId); 10078 origPermissions.updatePermissionFlags(bp, userId, 10079 PackageManager.MASK_PERMISSION_FLAGS, 0); 10080 // If we revoked a permission permission, we have to write. 10081 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10082 changedRuntimePermissionUserIds, userId); 10083 } 10084 } 10085 // Grant an install permission. 10086 if (permissionsState.grantInstallPermission(bp) != 10087 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10088 changedInstallPermission = true; 10089 } 10090 } break; 10091 10092 case GRANT_RUNTIME: { 10093 // Grant previously granted runtime permissions. 10094 for (int userId : UserManagerService.getInstance().getUserIds()) { 10095 PermissionState permissionState = origPermissions 10096 .getRuntimePermissionState(bp.name, userId); 10097 int flags = permissionState != null 10098 ? permissionState.getFlags() : 0; 10099 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10100 if (permissionsState.grantRuntimePermission(bp, userId) == 10101 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10102 // If we cannot put the permission as it was, we have to write. 10103 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10104 changedRuntimePermissionUserIds, userId); 10105 } 10106 // If the app supports runtime permissions no need for a review. 10107 if (Build.PERMISSIONS_REVIEW_REQUIRED 10108 && appSupportsRuntimePermissions 10109 && (flags & PackageManager 10110 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10111 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10112 // Since we changed the flags, we have to write. 10113 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10114 changedRuntimePermissionUserIds, userId); 10115 } 10116 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10117 && !appSupportsRuntimePermissions) { 10118 // For legacy apps that need a permission review, every new 10119 // runtime permission is granted but it is pending a review. 10120 // We also need to review only platform defined runtime 10121 // permissions as these are the only ones the platform knows 10122 // how to disable the API to simulate revocation as legacy 10123 // apps don't expect to run with revoked permissions. 10124 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10125 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10126 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10127 // We changed the flags, hence have to write. 10128 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10129 changedRuntimePermissionUserIds, userId); 10130 } 10131 } 10132 if (permissionsState.grantRuntimePermission(bp, userId) 10133 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10134 // We changed the permission, hence have to write. 10135 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10136 changedRuntimePermissionUserIds, userId); 10137 } 10138 } 10139 // Propagate the permission flags. 10140 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10141 } 10142 } break; 10143 10144 case GRANT_UPGRADE: { 10145 // Grant runtime permissions for a previously held install permission. 10146 PermissionState permissionState = origPermissions 10147 .getInstallPermissionState(bp.name); 10148 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10149 10150 if (origPermissions.revokeInstallPermission(bp) 10151 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10152 // We will be transferring the permission flags, so clear them. 10153 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10154 PackageManager.MASK_PERMISSION_FLAGS, 0); 10155 changedInstallPermission = true; 10156 } 10157 10158 // If the permission is not to be promoted to runtime we ignore it and 10159 // also its other flags as they are not applicable to install permissions. 10160 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10161 for (int userId : currentUserIds) { 10162 if (permissionsState.grantRuntimePermission(bp, userId) != 10163 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10164 // Transfer the permission flags. 10165 permissionsState.updatePermissionFlags(bp, userId, 10166 flags, flags); 10167 // If we granted the permission, we have to write. 10168 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10169 changedRuntimePermissionUserIds, userId); 10170 } 10171 } 10172 } 10173 } break; 10174 10175 default: { 10176 if (packageOfInterest == null 10177 || packageOfInterest.equals(pkg.packageName)) { 10178 Slog.w(TAG, "Not granting permission " + perm 10179 + " to package " + pkg.packageName 10180 + " because it was previously installed without"); 10181 } 10182 } break; 10183 } 10184 } else { 10185 if (permissionsState.revokeInstallPermission(bp) != 10186 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10187 // Also drop the permission flags. 10188 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10189 PackageManager.MASK_PERMISSION_FLAGS, 0); 10190 changedInstallPermission = true; 10191 Slog.i(TAG, "Un-granting permission " + perm 10192 + " from package " + pkg.packageName 10193 + " (protectionLevel=" + bp.protectionLevel 10194 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10195 + ")"); 10196 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10197 // Don't print warning for app op permissions, since it is fine for them 10198 // not to be granted, there is a UI for the user to decide. 10199 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10200 Slog.w(TAG, "Not granting permission " + perm 10201 + " to package " + pkg.packageName 10202 + " (protectionLevel=" + bp.protectionLevel 10203 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10204 + ")"); 10205 } 10206 } 10207 } 10208 } 10209 10210 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10211 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10212 // This is the first that we have heard about this package, so the 10213 // permissions we have now selected are fixed until explicitly 10214 // changed. 10215 ps.installPermissionsFixed = true; 10216 } 10217 10218 // Persist the runtime permissions state for users with changes. If permissions 10219 // were revoked because no app in the shared user declares them we have to 10220 // write synchronously to avoid losing runtime permissions state. 10221 for (int userId : changedRuntimePermissionUserIds) { 10222 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10223 } 10224 10225 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10226 } 10227 10228 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10229 boolean allowed = false; 10230 final int NP = PackageParser.NEW_PERMISSIONS.length; 10231 for (int ip=0; ip<NP; ip++) { 10232 final PackageParser.NewPermissionInfo npi 10233 = PackageParser.NEW_PERMISSIONS[ip]; 10234 if (npi.name.equals(perm) 10235 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10236 allowed = true; 10237 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10238 + pkg.packageName); 10239 break; 10240 } 10241 } 10242 return allowed; 10243 } 10244 10245 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10246 BasePermission bp, PermissionsState origPermissions) { 10247 boolean allowed; 10248 allowed = (compareSignatures( 10249 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10250 == PackageManager.SIGNATURE_MATCH) 10251 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10252 == PackageManager.SIGNATURE_MATCH); 10253 if (!allowed && (bp.protectionLevel 10254 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10255 if (isSystemApp(pkg)) { 10256 // For updated system applications, a system permission 10257 // is granted only if it had been defined by the original application. 10258 if (pkg.isUpdatedSystemApp()) { 10259 final PackageSetting sysPs = mSettings 10260 .getDisabledSystemPkgLPr(pkg.packageName); 10261 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10262 // If the original was granted this permission, we take 10263 // that grant decision as read and propagate it to the 10264 // update. 10265 if (sysPs.isPrivileged()) { 10266 allowed = true; 10267 } 10268 } else { 10269 // The system apk may have been updated with an older 10270 // version of the one on the data partition, but which 10271 // granted a new system permission that it didn't have 10272 // before. In this case we do want to allow the app to 10273 // now get the new permission if the ancestral apk is 10274 // privileged to get it. 10275 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10276 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10277 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10278 allowed = true; 10279 break; 10280 } 10281 } 10282 } 10283 // Also if a privileged parent package on the system image or any of 10284 // its children requested a privileged permission, the updated child 10285 // packages can also get the permission. 10286 if (pkg.parentPackage != null) { 10287 final PackageSetting disabledSysParentPs = mSettings 10288 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10289 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10290 && disabledSysParentPs.isPrivileged()) { 10291 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10292 allowed = true; 10293 } else if (disabledSysParentPs.pkg.childPackages != null) { 10294 final int count = disabledSysParentPs.pkg.childPackages.size(); 10295 for (int i = 0; i < count; i++) { 10296 PackageParser.Package disabledSysChildPkg = 10297 disabledSysParentPs.pkg.childPackages.get(i); 10298 if (isPackageRequestingPermission(disabledSysChildPkg, 10299 perm)) { 10300 allowed = true; 10301 break; 10302 } 10303 } 10304 } 10305 } 10306 } 10307 } 10308 } else { 10309 allowed = isPrivilegedApp(pkg); 10310 } 10311 } 10312 } 10313 if (!allowed) { 10314 if (!allowed && (bp.protectionLevel 10315 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10316 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10317 // If this was a previously normal/dangerous permission that got moved 10318 // to a system permission as part of the runtime permission redesign, then 10319 // we still want to blindly grant it to old apps. 10320 allowed = true; 10321 } 10322 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10323 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10324 // If this permission is to be granted to the system installer and 10325 // this app is an installer, then it gets the permission. 10326 allowed = true; 10327 } 10328 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10329 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10330 // If this permission is to be granted to the system verifier and 10331 // this app is a verifier, then it gets the permission. 10332 allowed = true; 10333 } 10334 if (!allowed && (bp.protectionLevel 10335 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10336 && isSystemApp(pkg)) { 10337 // Any pre-installed system app is allowed to get this permission. 10338 allowed = true; 10339 } 10340 if (!allowed && (bp.protectionLevel 10341 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10342 // For development permissions, a development permission 10343 // is granted only if it was already granted. 10344 allowed = origPermissions.hasInstallPermission(perm); 10345 } 10346 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10347 && pkg.packageName.equals(mSetupWizardPackage)) { 10348 // If this permission is to be granted to the system setup wizard and 10349 // this app is a setup wizard, then it gets the permission. 10350 allowed = true; 10351 } 10352 } 10353 return allowed; 10354 } 10355 10356 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10357 final int permCount = pkg.requestedPermissions.size(); 10358 for (int j = 0; j < permCount; j++) { 10359 String requestedPermission = pkg.requestedPermissions.get(j); 10360 if (permission.equals(requestedPermission)) { 10361 return true; 10362 } 10363 } 10364 return false; 10365 } 10366 10367 final class ActivityIntentResolver 10368 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10369 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10370 boolean defaultOnly, int userId) { 10371 if (!sUserManager.exists(userId)) return null; 10372 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10373 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10374 } 10375 10376 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10377 int userId) { 10378 if (!sUserManager.exists(userId)) return null; 10379 mFlags = flags; 10380 return super.queryIntent(intent, resolvedType, 10381 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10382 } 10383 10384 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10385 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10386 if (!sUserManager.exists(userId)) return null; 10387 if (packageActivities == null) { 10388 return null; 10389 } 10390 mFlags = flags; 10391 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10392 final int N = packageActivities.size(); 10393 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10394 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10395 10396 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10397 for (int i = 0; i < N; ++i) { 10398 intentFilters = packageActivities.get(i).intents; 10399 if (intentFilters != null && intentFilters.size() > 0) { 10400 PackageParser.ActivityIntentInfo[] array = 10401 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10402 intentFilters.toArray(array); 10403 listCut.add(array); 10404 } 10405 } 10406 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10407 } 10408 10409 /** 10410 * Finds a privileged activity that matches the specified activity names. 10411 */ 10412 private PackageParser.Activity findMatchingActivity( 10413 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10414 for (PackageParser.Activity sysActivity : activityList) { 10415 if (sysActivity.info.name.equals(activityInfo.name)) { 10416 return sysActivity; 10417 } 10418 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10419 return sysActivity; 10420 } 10421 if (sysActivity.info.targetActivity != null) { 10422 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10423 return sysActivity; 10424 } 10425 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10426 return sysActivity; 10427 } 10428 } 10429 } 10430 return null; 10431 } 10432 10433 public class IterGenerator<E> { 10434 public Iterator<E> generate(ActivityIntentInfo info) { 10435 return null; 10436 } 10437 } 10438 10439 public class ActionIterGenerator extends IterGenerator<String> { 10440 @Override 10441 public Iterator<String> generate(ActivityIntentInfo info) { 10442 return info.actionsIterator(); 10443 } 10444 } 10445 10446 public class CategoriesIterGenerator extends IterGenerator<String> { 10447 @Override 10448 public Iterator<String> generate(ActivityIntentInfo info) { 10449 return info.categoriesIterator(); 10450 } 10451 } 10452 10453 public class SchemesIterGenerator extends IterGenerator<String> { 10454 @Override 10455 public Iterator<String> generate(ActivityIntentInfo info) { 10456 return info.schemesIterator(); 10457 } 10458 } 10459 10460 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10461 @Override 10462 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10463 return info.authoritiesIterator(); 10464 } 10465 } 10466 10467 /** 10468 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10469 * MODIFIED. Do not pass in a list that should not be changed. 10470 */ 10471 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10472 IterGenerator<T> generator, Iterator<T> searchIterator) { 10473 // loop through the set of actions; every one must be found in the intent filter 10474 while (searchIterator.hasNext()) { 10475 // we must have at least one filter in the list to consider a match 10476 if (intentList.size() == 0) { 10477 break; 10478 } 10479 10480 final T searchAction = searchIterator.next(); 10481 10482 // loop through the set of intent filters 10483 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10484 while (intentIter.hasNext()) { 10485 final ActivityIntentInfo intentInfo = intentIter.next(); 10486 boolean selectionFound = false; 10487 10488 // loop through the intent filter's selection criteria; at least one 10489 // of them must match the searched criteria 10490 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10491 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10492 final T intentSelection = intentSelectionIter.next(); 10493 if (intentSelection != null && intentSelection.equals(searchAction)) { 10494 selectionFound = true; 10495 break; 10496 } 10497 } 10498 10499 // the selection criteria wasn't found in this filter's set; this filter 10500 // is not a potential match 10501 if (!selectionFound) { 10502 intentIter.remove(); 10503 } 10504 } 10505 } 10506 } 10507 10508 private boolean isProtectedAction(ActivityIntentInfo filter) { 10509 final Iterator<String> actionsIter = filter.actionsIterator(); 10510 while (actionsIter != null && actionsIter.hasNext()) { 10511 final String filterAction = actionsIter.next(); 10512 if (PROTECTED_ACTIONS.contains(filterAction)) { 10513 return true; 10514 } 10515 } 10516 return false; 10517 } 10518 10519 /** 10520 * Adjusts the priority of the given intent filter according to policy. 10521 * <p> 10522 * <ul> 10523 * <li>The priority for non privileged applications is capped to '0'</li> 10524 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10525 * <li>The priority for unbundled updates to privileged applications is capped to the 10526 * priority defined on the system partition</li> 10527 * </ul> 10528 * <p> 10529 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10530 * allowed to obtain any priority on any action. 10531 */ 10532 private void adjustPriority( 10533 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10534 // nothing to do; priority is fine as-is 10535 if (intent.getPriority() <= 0) { 10536 return; 10537 } 10538 10539 final ActivityInfo activityInfo = intent.activity.info; 10540 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10541 10542 final boolean privilegedApp = 10543 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10544 if (!privilegedApp) { 10545 // non-privileged applications can never define a priority >0 10546 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10547 + " package: " + applicationInfo.packageName 10548 + " activity: " + intent.activity.className 10549 + " origPrio: " + intent.getPriority()); 10550 intent.setPriority(0); 10551 return; 10552 } 10553 10554 if (systemActivities == null) { 10555 // the system package is not disabled; we're parsing the system partition 10556 if (isProtectedAction(intent)) { 10557 if (mDeferProtectedFilters) { 10558 // We can't deal with these just yet. No component should ever obtain a 10559 // >0 priority for a protected actions, with ONE exception -- the setup 10560 // wizard. The setup wizard, however, cannot be known until we're able to 10561 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10562 // until all intent filters have been processed. Chicken, meet egg. 10563 // Let the filter temporarily have a high priority and rectify the 10564 // priorities after all system packages have been scanned. 10565 mProtectedFilters.add(intent); 10566 if (DEBUG_FILTERS) { 10567 Slog.i(TAG, "Protected action; save for later;" 10568 + " package: " + applicationInfo.packageName 10569 + " activity: " + intent.activity.className 10570 + " origPrio: " + intent.getPriority()); 10571 } 10572 return; 10573 } else { 10574 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10575 Slog.i(TAG, "No setup wizard;" 10576 + " All protected intents capped to priority 0"); 10577 } 10578 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10579 if (DEBUG_FILTERS) { 10580 Slog.i(TAG, "Found setup wizard;" 10581 + " allow priority " + intent.getPriority() + ";" 10582 + " package: " + intent.activity.info.packageName 10583 + " activity: " + intent.activity.className 10584 + " priority: " + intent.getPriority()); 10585 } 10586 // setup wizard gets whatever it wants 10587 return; 10588 } 10589 Slog.w(TAG, "Protected action; cap priority to 0;" 10590 + " package: " + intent.activity.info.packageName 10591 + " activity: " + intent.activity.className 10592 + " origPrio: " + intent.getPriority()); 10593 intent.setPriority(0); 10594 return; 10595 } 10596 } 10597 // privileged apps on the system image get whatever priority they request 10598 return; 10599 } 10600 10601 // privileged app unbundled update ... try to find the same activity 10602 final PackageParser.Activity foundActivity = 10603 findMatchingActivity(systemActivities, activityInfo); 10604 if (foundActivity == null) { 10605 // this is a new activity; it cannot obtain >0 priority 10606 if (DEBUG_FILTERS) { 10607 Slog.i(TAG, "New activity; cap priority to 0;" 10608 + " package: " + applicationInfo.packageName 10609 + " activity: " + intent.activity.className 10610 + " origPrio: " + intent.getPriority()); 10611 } 10612 intent.setPriority(0); 10613 return; 10614 } 10615 10616 // found activity, now check for filter equivalence 10617 10618 // a shallow copy is enough; we modify the list, not its contents 10619 final List<ActivityIntentInfo> intentListCopy = 10620 new ArrayList<>(foundActivity.intents); 10621 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10622 10623 // find matching action subsets 10624 final Iterator<String> actionsIterator = intent.actionsIterator(); 10625 if (actionsIterator != null) { 10626 getIntentListSubset( 10627 intentListCopy, new ActionIterGenerator(), actionsIterator); 10628 if (intentListCopy.size() == 0) { 10629 // no more intents to match; we're not equivalent 10630 if (DEBUG_FILTERS) { 10631 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10632 + " package: " + applicationInfo.packageName 10633 + " activity: " + intent.activity.className 10634 + " origPrio: " + intent.getPriority()); 10635 } 10636 intent.setPriority(0); 10637 return; 10638 } 10639 } 10640 10641 // find matching category subsets 10642 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10643 if (categoriesIterator != null) { 10644 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10645 categoriesIterator); 10646 if (intentListCopy.size() == 0) { 10647 // no more intents to match; we're not equivalent 10648 if (DEBUG_FILTERS) { 10649 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10650 + " package: " + applicationInfo.packageName 10651 + " activity: " + intent.activity.className 10652 + " origPrio: " + intent.getPriority()); 10653 } 10654 intent.setPriority(0); 10655 return; 10656 } 10657 } 10658 10659 // find matching schemes subsets 10660 final Iterator<String> schemesIterator = intent.schemesIterator(); 10661 if (schemesIterator != null) { 10662 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10663 schemesIterator); 10664 if (intentListCopy.size() == 0) { 10665 // no more intents to match; we're not equivalent 10666 if (DEBUG_FILTERS) { 10667 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10668 + " package: " + applicationInfo.packageName 10669 + " activity: " + intent.activity.className 10670 + " origPrio: " + intent.getPriority()); 10671 } 10672 intent.setPriority(0); 10673 return; 10674 } 10675 } 10676 10677 // find matching authorities subsets 10678 final Iterator<IntentFilter.AuthorityEntry> 10679 authoritiesIterator = intent.authoritiesIterator(); 10680 if (authoritiesIterator != null) { 10681 getIntentListSubset(intentListCopy, 10682 new AuthoritiesIterGenerator(), 10683 authoritiesIterator); 10684 if (intentListCopy.size() == 0) { 10685 // no more intents to match; we're not equivalent 10686 if (DEBUG_FILTERS) { 10687 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10688 + " package: " + applicationInfo.packageName 10689 + " activity: " + intent.activity.className 10690 + " origPrio: " + intent.getPriority()); 10691 } 10692 intent.setPriority(0); 10693 return; 10694 } 10695 } 10696 10697 // we found matching filter(s); app gets the max priority of all intents 10698 int cappedPriority = 0; 10699 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10700 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10701 } 10702 if (intent.getPriority() > cappedPriority) { 10703 if (DEBUG_FILTERS) { 10704 Slog.i(TAG, "Found matching filter(s);" 10705 + " cap priority to " + cappedPriority + ";" 10706 + " package: " + applicationInfo.packageName 10707 + " activity: " + intent.activity.className 10708 + " origPrio: " + intent.getPriority()); 10709 } 10710 intent.setPriority(cappedPriority); 10711 return; 10712 } 10713 // all this for nothing; the requested priority was <= what was on the system 10714 } 10715 10716 public final void addActivity(PackageParser.Activity a, String type) { 10717 mActivities.put(a.getComponentName(), a); 10718 if (DEBUG_SHOW_INFO) 10719 Log.v( 10720 TAG, " " + type + " " + 10721 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10722 if (DEBUG_SHOW_INFO) 10723 Log.v(TAG, " Class=" + a.info.name); 10724 final int NI = a.intents.size(); 10725 for (int j=0; j<NI; j++) { 10726 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10727 if ("activity".equals(type)) { 10728 final PackageSetting ps = 10729 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10730 final List<PackageParser.Activity> systemActivities = 10731 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10732 adjustPriority(systemActivities, intent); 10733 } 10734 if (DEBUG_SHOW_INFO) { 10735 Log.v(TAG, " IntentFilter:"); 10736 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10737 } 10738 if (!intent.debugCheck()) { 10739 Log.w(TAG, "==> For Activity " + a.info.name); 10740 } 10741 addFilter(intent); 10742 } 10743 } 10744 10745 public final void removeActivity(PackageParser.Activity a, String type) { 10746 mActivities.remove(a.getComponentName()); 10747 if (DEBUG_SHOW_INFO) { 10748 Log.v(TAG, " " + type + " " 10749 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10750 : a.info.name) + ":"); 10751 Log.v(TAG, " Class=" + a.info.name); 10752 } 10753 final int NI = a.intents.size(); 10754 for (int j=0; j<NI; j++) { 10755 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10756 if (DEBUG_SHOW_INFO) { 10757 Log.v(TAG, " IntentFilter:"); 10758 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10759 } 10760 removeFilter(intent); 10761 } 10762 } 10763 10764 @Override 10765 protected boolean allowFilterResult( 10766 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10767 ActivityInfo filterAi = filter.activity.info; 10768 for (int i=dest.size()-1; i>=0; i--) { 10769 ActivityInfo destAi = dest.get(i).activityInfo; 10770 if (destAi.name == filterAi.name 10771 && destAi.packageName == filterAi.packageName) { 10772 return false; 10773 } 10774 } 10775 return true; 10776 } 10777 10778 @Override 10779 protected ActivityIntentInfo[] newArray(int size) { 10780 return new ActivityIntentInfo[size]; 10781 } 10782 10783 @Override 10784 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10785 if (!sUserManager.exists(userId)) return true; 10786 PackageParser.Package p = filter.activity.owner; 10787 if (p != null) { 10788 PackageSetting ps = (PackageSetting)p.mExtras; 10789 if (ps != null) { 10790 // System apps are never considered stopped for purposes of 10791 // filtering, because there may be no way for the user to 10792 // actually re-launch them. 10793 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10794 && ps.getStopped(userId); 10795 } 10796 } 10797 return false; 10798 } 10799 10800 @Override 10801 protected boolean isPackageForFilter(String packageName, 10802 PackageParser.ActivityIntentInfo info) { 10803 return packageName.equals(info.activity.owner.packageName); 10804 } 10805 10806 @Override 10807 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10808 int match, int userId) { 10809 if (!sUserManager.exists(userId)) return null; 10810 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10811 return null; 10812 } 10813 final PackageParser.Activity activity = info.activity; 10814 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10815 if (ps == null) { 10816 return null; 10817 } 10818 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10819 ps.readUserState(userId), userId); 10820 if (ai == null) { 10821 return null; 10822 } 10823 final ResolveInfo res = new ResolveInfo(); 10824 res.activityInfo = ai; 10825 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10826 res.filter = info; 10827 } 10828 if (info != null) { 10829 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10830 } 10831 res.priority = info.getPriority(); 10832 res.preferredOrder = activity.owner.mPreferredOrder; 10833 //System.out.println("Result: " + res.activityInfo.className + 10834 // " = " + res.priority); 10835 res.match = match; 10836 res.isDefault = info.hasDefault; 10837 res.labelRes = info.labelRes; 10838 res.nonLocalizedLabel = info.nonLocalizedLabel; 10839 if (userNeedsBadging(userId)) { 10840 res.noResourceId = true; 10841 } else { 10842 res.icon = info.icon; 10843 } 10844 res.iconResourceId = info.icon; 10845 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10846 return res; 10847 } 10848 10849 @Override 10850 protected void sortResults(List<ResolveInfo> results) { 10851 Collections.sort(results, mResolvePrioritySorter); 10852 } 10853 10854 @Override 10855 protected void dumpFilter(PrintWriter out, String prefix, 10856 PackageParser.ActivityIntentInfo filter) { 10857 out.print(prefix); out.print( 10858 Integer.toHexString(System.identityHashCode(filter.activity))); 10859 out.print(' '); 10860 filter.activity.printComponentShortName(out); 10861 out.print(" filter "); 10862 out.println(Integer.toHexString(System.identityHashCode(filter))); 10863 } 10864 10865 @Override 10866 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10867 return filter.activity; 10868 } 10869 10870 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10871 PackageParser.Activity activity = (PackageParser.Activity)label; 10872 out.print(prefix); out.print( 10873 Integer.toHexString(System.identityHashCode(activity))); 10874 out.print(' '); 10875 activity.printComponentShortName(out); 10876 if (count > 1) { 10877 out.print(" ("); out.print(count); out.print(" filters)"); 10878 } 10879 out.println(); 10880 } 10881 10882 // Keys are String (activity class name), values are Activity. 10883 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10884 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10885 private int mFlags; 10886 } 10887 10888 private final class ServiceIntentResolver 10889 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10890 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10891 boolean defaultOnly, int userId) { 10892 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10893 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10894 } 10895 10896 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10897 int userId) { 10898 if (!sUserManager.exists(userId)) return null; 10899 mFlags = flags; 10900 return super.queryIntent(intent, resolvedType, 10901 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10902 } 10903 10904 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10905 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10906 if (!sUserManager.exists(userId)) return null; 10907 if (packageServices == null) { 10908 return null; 10909 } 10910 mFlags = flags; 10911 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10912 final int N = packageServices.size(); 10913 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10914 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10915 10916 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10917 for (int i = 0; i < N; ++i) { 10918 intentFilters = packageServices.get(i).intents; 10919 if (intentFilters != null && intentFilters.size() > 0) { 10920 PackageParser.ServiceIntentInfo[] array = 10921 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10922 intentFilters.toArray(array); 10923 listCut.add(array); 10924 } 10925 } 10926 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10927 } 10928 10929 public final void addService(PackageParser.Service s) { 10930 mServices.put(s.getComponentName(), s); 10931 if (DEBUG_SHOW_INFO) { 10932 Log.v(TAG, " " 10933 + (s.info.nonLocalizedLabel != null 10934 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10935 Log.v(TAG, " Class=" + s.info.name); 10936 } 10937 final int NI = s.intents.size(); 10938 int j; 10939 for (j=0; j<NI; j++) { 10940 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10941 if (DEBUG_SHOW_INFO) { 10942 Log.v(TAG, " IntentFilter:"); 10943 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10944 } 10945 if (!intent.debugCheck()) { 10946 Log.w(TAG, "==> For Service " + s.info.name); 10947 } 10948 addFilter(intent); 10949 } 10950 } 10951 10952 public final void removeService(PackageParser.Service s) { 10953 mServices.remove(s.getComponentName()); 10954 if (DEBUG_SHOW_INFO) { 10955 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10956 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10957 Log.v(TAG, " Class=" + s.info.name); 10958 } 10959 final int NI = s.intents.size(); 10960 int j; 10961 for (j=0; j<NI; j++) { 10962 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10963 if (DEBUG_SHOW_INFO) { 10964 Log.v(TAG, " IntentFilter:"); 10965 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10966 } 10967 removeFilter(intent); 10968 } 10969 } 10970 10971 @Override 10972 protected boolean allowFilterResult( 10973 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10974 ServiceInfo filterSi = filter.service.info; 10975 for (int i=dest.size()-1; i>=0; i--) { 10976 ServiceInfo destAi = dest.get(i).serviceInfo; 10977 if (destAi.name == filterSi.name 10978 && destAi.packageName == filterSi.packageName) { 10979 return false; 10980 } 10981 } 10982 return true; 10983 } 10984 10985 @Override 10986 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10987 return new PackageParser.ServiceIntentInfo[size]; 10988 } 10989 10990 @Override 10991 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10992 if (!sUserManager.exists(userId)) return true; 10993 PackageParser.Package p = filter.service.owner; 10994 if (p != null) { 10995 PackageSetting ps = (PackageSetting)p.mExtras; 10996 if (ps != null) { 10997 // System apps are never considered stopped for purposes of 10998 // filtering, because there may be no way for the user to 10999 // actually re-launch them. 11000 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11001 && ps.getStopped(userId); 11002 } 11003 } 11004 return false; 11005 } 11006 11007 @Override 11008 protected boolean isPackageForFilter(String packageName, 11009 PackageParser.ServiceIntentInfo info) { 11010 return packageName.equals(info.service.owner.packageName); 11011 } 11012 11013 @Override 11014 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11015 int match, int userId) { 11016 if (!sUserManager.exists(userId)) return null; 11017 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11018 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11019 return null; 11020 } 11021 final PackageParser.Service service = info.service; 11022 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11023 if (ps == null) { 11024 return null; 11025 } 11026 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11027 ps.readUserState(userId), userId); 11028 if (si == null) { 11029 return null; 11030 } 11031 final ResolveInfo res = new ResolveInfo(); 11032 res.serviceInfo = si; 11033 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11034 res.filter = filter; 11035 } 11036 res.priority = info.getPriority(); 11037 res.preferredOrder = service.owner.mPreferredOrder; 11038 res.match = match; 11039 res.isDefault = info.hasDefault; 11040 res.labelRes = info.labelRes; 11041 res.nonLocalizedLabel = info.nonLocalizedLabel; 11042 res.icon = info.icon; 11043 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11044 return res; 11045 } 11046 11047 @Override 11048 protected void sortResults(List<ResolveInfo> results) { 11049 Collections.sort(results, mResolvePrioritySorter); 11050 } 11051 11052 @Override 11053 protected void dumpFilter(PrintWriter out, String prefix, 11054 PackageParser.ServiceIntentInfo filter) { 11055 out.print(prefix); out.print( 11056 Integer.toHexString(System.identityHashCode(filter.service))); 11057 out.print(' '); 11058 filter.service.printComponentShortName(out); 11059 out.print(" filter "); 11060 out.println(Integer.toHexString(System.identityHashCode(filter))); 11061 } 11062 11063 @Override 11064 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11065 return filter.service; 11066 } 11067 11068 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11069 PackageParser.Service service = (PackageParser.Service)label; 11070 out.print(prefix); out.print( 11071 Integer.toHexString(System.identityHashCode(service))); 11072 out.print(' '); 11073 service.printComponentShortName(out); 11074 if (count > 1) { 11075 out.print(" ("); out.print(count); out.print(" filters)"); 11076 } 11077 out.println(); 11078 } 11079 11080// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11081// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11082// final List<ResolveInfo> retList = Lists.newArrayList(); 11083// while (i.hasNext()) { 11084// final ResolveInfo resolveInfo = (ResolveInfo) i; 11085// if (isEnabledLP(resolveInfo.serviceInfo)) { 11086// retList.add(resolveInfo); 11087// } 11088// } 11089// return retList; 11090// } 11091 11092 // Keys are String (activity class name), values are Activity. 11093 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11094 = new ArrayMap<ComponentName, PackageParser.Service>(); 11095 private int mFlags; 11096 }; 11097 11098 private final class ProviderIntentResolver 11099 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11100 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11101 boolean defaultOnly, int userId) { 11102 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11103 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11104 } 11105 11106 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11107 int userId) { 11108 if (!sUserManager.exists(userId)) 11109 return null; 11110 mFlags = flags; 11111 return super.queryIntent(intent, resolvedType, 11112 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11113 } 11114 11115 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11116 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11117 if (!sUserManager.exists(userId)) 11118 return null; 11119 if (packageProviders == null) { 11120 return null; 11121 } 11122 mFlags = flags; 11123 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11124 final int N = packageProviders.size(); 11125 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11126 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11127 11128 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11129 for (int i = 0; i < N; ++i) { 11130 intentFilters = packageProviders.get(i).intents; 11131 if (intentFilters != null && intentFilters.size() > 0) { 11132 PackageParser.ProviderIntentInfo[] array = 11133 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11134 intentFilters.toArray(array); 11135 listCut.add(array); 11136 } 11137 } 11138 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11139 } 11140 11141 public final void addProvider(PackageParser.Provider p) { 11142 if (mProviders.containsKey(p.getComponentName())) { 11143 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11144 return; 11145 } 11146 11147 mProviders.put(p.getComponentName(), p); 11148 if (DEBUG_SHOW_INFO) { 11149 Log.v(TAG, " " 11150 + (p.info.nonLocalizedLabel != null 11151 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11152 Log.v(TAG, " Class=" + p.info.name); 11153 } 11154 final int NI = p.intents.size(); 11155 int j; 11156 for (j = 0; j < NI; j++) { 11157 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11158 if (DEBUG_SHOW_INFO) { 11159 Log.v(TAG, " IntentFilter:"); 11160 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11161 } 11162 if (!intent.debugCheck()) { 11163 Log.w(TAG, "==> For Provider " + p.info.name); 11164 } 11165 addFilter(intent); 11166 } 11167 } 11168 11169 public final void removeProvider(PackageParser.Provider p) { 11170 mProviders.remove(p.getComponentName()); 11171 if (DEBUG_SHOW_INFO) { 11172 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11173 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11174 Log.v(TAG, " Class=" + p.info.name); 11175 } 11176 final int NI = p.intents.size(); 11177 int j; 11178 for (j = 0; j < NI; j++) { 11179 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11180 if (DEBUG_SHOW_INFO) { 11181 Log.v(TAG, " IntentFilter:"); 11182 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11183 } 11184 removeFilter(intent); 11185 } 11186 } 11187 11188 @Override 11189 protected boolean allowFilterResult( 11190 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11191 ProviderInfo filterPi = filter.provider.info; 11192 for (int i = dest.size() - 1; i >= 0; i--) { 11193 ProviderInfo destPi = dest.get(i).providerInfo; 11194 if (destPi.name == filterPi.name 11195 && destPi.packageName == filterPi.packageName) { 11196 return false; 11197 } 11198 } 11199 return true; 11200 } 11201 11202 @Override 11203 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11204 return new PackageParser.ProviderIntentInfo[size]; 11205 } 11206 11207 @Override 11208 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11209 if (!sUserManager.exists(userId)) 11210 return true; 11211 PackageParser.Package p = filter.provider.owner; 11212 if (p != null) { 11213 PackageSetting ps = (PackageSetting) p.mExtras; 11214 if (ps != null) { 11215 // System apps are never considered stopped for purposes of 11216 // filtering, because there may be no way for the user to 11217 // actually re-launch them. 11218 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11219 && ps.getStopped(userId); 11220 } 11221 } 11222 return false; 11223 } 11224 11225 @Override 11226 protected boolean isPackageForFilter(String packageName, 11227 PackageParser.ProviderIntentInfo info) { 11228 return packageName.equals(info.provider.owner.packageName); 11229 } 11230 11231 @Override 11232 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11233 int match, int userId) { 11234 if (!sUserManager.exists(userId)) 11235 return null; 11236 final PackageParser.ProviderIntentInfo info = filter; 11237 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11238 return null; 11239 } 11240 final PackageParser.Provider provider = info.provider; 11241 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11242 if (ps == null) { 11243 return null; 11244 } 11245 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11246 ps.readUserState(userId), userId); 11247 if (pi == null) { 11248 return null; 11249 } 11250 final ResolveInfo res = new ResolveInfo(); 11251 res.providerInfo = pi; 11252 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11253 res.filter = filter; 11254 } 11255 res.priority = info.getPriority(); 11256 res.preferredOrder = provider.owner.mPreferredOrder; 11257 res.match = match; 11258 res.isDefault = info.hasDefault; 11259 res.labelRes = info.labelRes; 11260 res.nonLocalizedLabel = info.nonLocalizedLabel; 11261 res.icon = info.icon; 11262 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11263 return res; 11264 } 11265 11266 @Override 11267 protected void sortResults(List<ResolveInfo> results) { 11268 Collections.sort(results, mResolvePrioritySorter); 11269 } 11270 11271 @Override 11272 protected void dumpFilter(PrintWriter out, String prefix, 11273 PackageParser.ProviderIntentInfo filter) { 11274 out.print(prefix); 11275 out.print( 11276 Integer.toHexString(System.identityHashCode(filter.provider))); 11277 out.print(' '); 11278 filter.provider.printComponentShortName(out); 11279 out.print(" filter "); 11280 out.println(Integer.toHexString(System.identityHashCode(filter))); 11281 } 11282 11283 @Override 11284 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11285 return filter.provider; 11286 } 11287 11288 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11289 PackageParser.Provider provider = (PackageParser.Provider)label; 11290 out.print(prefix); out.print( 11291 Integer.toHexString(System.identityHashCode(provider))); 11292 out.print(' '); 11293 provider.printComponentShortName(out); 11294 if (count > 1) { 11295 out.print(" ("); out.print(count); out.print(" filters)"); 11296 } 11297 out.println(); 11298 } 11299 11300 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11301 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11302 private int mFlags; 11303 } 11304 11305 private static final class EphemeralIntentResolver 11306 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11307 /** 11308 * The result that has the highest defined order. Ordering applies on a 11309 * per-package basis. Mapping is from package name to Pair of order and 11310 * EphemeralResolveInfo. 11311 * <p> 11312 * NOTE: This is implemented as a field variable for convenience and efficiency. 11313 * By having a field variable, we're able to track filter ordering as soon as 11314 * a non-zero order is defined. Otherwise, multiple loops across the result set 11315 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11316 * this needs to be contained entirely within {@link #filterResults()}. 11317 */ 11318 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11319 11320 @Override 11321 protected EphemeralResolveIntentInfo[] newArray(int size) { 11322 return new EphemeralResolveIntentInfo[size]; 11323 } 11324 11325 @Override 11326 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11327 return true; 11328 } 11329 11330 @Override 11331 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11332 int userId) { 11333 if (!sUserManager.exists(userId)) { 11334 return null; 11335 } 11336 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11337 final Integer order = info.getOrder(); 11338 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11339 mOrderResult.get(packageName); 11340 // ordering is enabled and this item's order isn't high enough 11341 if (lastOrderResult != null && lastOrderResult.first >= order) { 11342 return null; 11343 } 11344 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11345 if (order > 0) { 11346 // non-zero order, enable ordering 11347 mOrderResult.put(packageName, new Pair<>(order, res)); 11348 } 11349 return res; 11350 } 11351 11352 @Override 11353 protected void filterResults(List<EphemeralResolveInfo> results) { 11354 // only do work if ordering is enabled [most of the time it won't be] 11355 if (mOrderResult.size() == 0) { 11356 return; 11357 } 11358 int resultSize = results.size(); 11359 for (int i = 0; i < resultSize; i++) { 11360 final EphemeralResolveInfo info = results.get(i); 11361 final String packageName = info.getPackageName(); 11362 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11363 if (savedInfo == null) { 11364 // package doesn't having ordering 11365 continue; 11366 } 11367 if (savedInfo.second == info) { 11368 // circled back to the highest ordered item; remove from order list 11369 mOrderResult.remove(savedInfo); 11370 if (mOrderResult.size() == 0) { 11371 // no more ordered items 11372 break; 11373 } 11374 continue; 11375 } 11376 // item has a worse order, remove it from the result list 11377 results.remove(i); 11378 resultSize--; 11379 i--; 11380 } 11381 } 11382 } 11383 11384 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11385 new Comparator<ResolveInfo>() { 11386 public int compare(ResolveInfo r1, ResolveInfo r2) { 11387 int v1 = r1.priority; 11388 int v2 = r2.priority; 11389 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11390 if (v1 != v2) { 11391 return (v1 > v2) ? -1 : 1; 11392 } 11393 v1 = r1.preferredOrder; 11394 v2 = r2.preferredOrder; 11395 if (v1 != v2) { 11396 return (v1 > v2) ? -1 : 1; 11397 } 11398 if (r1.isDefault != r2.isDefault) { 11399 return r1.isDefault ? -1 : 1; 11400 } 11401 v1 = r1.match; 11402 v2 = r2.match; 11403 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11404 if (v1 != v2) { 11405 return (v1 > v2) ? -1 : 1; 11406 } 11407 if (r1.system != r2.system) { 11408 return r1.system ? -1 : 1; 11409 } 11410 if (r1.activityInfo != null) { 11411 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11412 } 11413 if (r1.serviceInfo != null) { 11414 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11415 } 11416 if (r1.providerInfo != null) { 11417 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11418 } 11419 return 0; 11420 } 11421 }; 11422 11423 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11424 new Comparator<ProviderInfo>() { 11425 public int compare(ProviderInfo p1, ProviderInfo p2) { 11426 final int v1 = p1.initOrder; 11427 final int v2 = p2.initOrder; 11428 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11429 } 11430 }; 11431 11432 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11433 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11434 final int[] userIds) { 11435 mHandler.post(new Runnable() { 11436 @Override 11437 public void run() { 11438 try { 11439 final IActivityManager am = ActivityManagerNative.getDefault(); 11440 if (am == null) return; 11441 final int[] resolvedUserIds; 11442 if (userIds == null) { 11443 resolvedUserIds = am.getRunningUserIds(); 11444 } else { 11445 resolvedUserIds = userIds; 11446 } 11447 for (int id : resolvedUserIds) { 11448 final Intent intent = new Intent(action, 11449 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11450 if (extras != null) { 11451 intent.putExtras(extras); 11452 } 11453 if (targetPkg != null) { 11454 intent.setPackage(targetPkg); 11455 } 11456 // Modify the UID when posting to other users 11457 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11458 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11459 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11460 intent.putExtra(Intent.EXTRA_UID, uid); 11461 } 11462 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11463 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11464 if (DEBUG_BROADCASTS) { 11465 RuntimeException here = new RuntimeException("here"); 11466 here.fillInStackTrace(); 11467 Slog.d(TAG, "Sending to user " + id + ": " 11468 + intent.toShortString(false, true, false, false) 11469 + " " + intent.getExtras(), here); 11470 } 11471 am.broadcastIntent(null, intent, null, finishedReceiver, 11472 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11473 null, finishedReceiver != null, false, id); 11474 } 11475 } catch (RemoteException ex) { 11476 } 11477 } 11478 }); 11479 } 11480 11481 /** 11482 * Check if the external storage media is available. This is true if there 11483 * is a mounted external storage medium or if the external storage is 11484 * emulated. 11485 */ 11486 private boolean isExternalMediaAvailable() { 11487 return mMediaMounted || Environment.isExternalStorageEmulated(); 11488 } 11489 11490 @Override 11491 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11492 // writer 11493 synchronized (mPackages) { 11494 if (!isExternalMediaAvailable()) { 11495 // If the external storage is no longer mounted at this point, 11496 // the caller may not have been able to delete all of this 11497 // packages files and can not delete any more. Bail. 11498 return null; 11499 } 11500 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11501 if (lastPackage != null) { 11502 pkgs.remove(lastPackage); 11503 } 11504 if (pkgs.size() > 0) { 11505 return pkgs.get(0); 11506 } 11507 } 11508 return null; 11509 } 11510 11511 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11512 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11513 userId, andCode ? 1 : 0, packageName); 11514 if (mSystemReady) { 11515 msg.sendToTarget(); 11516 } else { 11517 if (mPostSystemReadyMessages == null) { 11518 mPostSystemReadyMessages = new ArrayList<>(); 11519 } 11520 mPostSystemReadyMessages.add(msg); 11521 } 11522 } 11523 11524 void startCleaningPackages() { 11525 // reader 11526 if (!isExternalMediaAvailable()) { 11527 return; 11528 } 11529 synchronized (mPackages) { 11530 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11531 return; 11532 } 11533 } 11534 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11535 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11536 IActivityManager am = ActivityManagerNative.getDefault(); 11537 if (am != null) { 11538 try { 11539 am.startService(null, intent, null, mContext.getOpPackageName(), 11540 UserHandle.USER_SYSTEM); 11541 } catch (RemoteException e) { 11542 } 11543 } 11544 } 11545 11546 @Override 11547 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11548 int installFlags, String installerPackageName, int userId) { 11549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11550 11551 final int callingUid = Binder.getCallingUid(); 11552 enforceCrossUserPermission(callingUid, userId, 11553 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11554 11555 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11556 try { 11557 if (observer != null) { 11558 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11559 } 11560 } catch (RemoteException re) { 11561 } 11562 return; 11563 } 11564 11565 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11566 installFlags |= PackageManager.INSTALL_FROM_ADB; 11567 11568 } else { 11569 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11570 // about installerPackageName. 11571 11572 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11573 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11574 } 11575 11576 UserHandle user; 11577 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11578 user = UserHandle.ALL; 11579 } else { 11580 user = new UserHandle(userId); 11581 } 11582 11583 // Only system components can circumvent runtime permissions when installing. 11584 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11585 && mContext.checkCallingOrSelfPermission(Manifest.permission 11586 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11587 throw new SecurityException("You need the " 11588 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11589 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11590 } 11591 11592 final File originFile = new File(originPath); 11593 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11594 11595 final Message msg = mHandler.obtainMessage(INIT_COPY); 11596 final VerificationInfo verificationInfo = new VerificationInfo( 11597 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11598 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11599 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11600 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11601 null /*certificates*/); 11602 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11603 msg.obj = params; 11604 11605 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11606 System.identityHashCode(msg.obj)); 11607 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11608 System.identityHashCode(msg.obj)); 11609 11610 mHandler.sendMessage(msg); 11611 } 11612 11613 void installStage(String packageName, File stagedDir, String stagedCid, 11614 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11615 String installerPackageName, int installerUid, UserHandle user, 11616 Certificate[][] certificates) { 11617 if (DEBUG_EPHEMERAL) { 11618 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11619 Slog.d(TAG, "Ephemeral install of " + packageName); 11620 } 11621 } 11622 final VerificationInfo verificationInfo = new VerificationInfo( 11623 sessionParams.originatingUri, sessionParams.referrerUri, 11624 sessionParams.originatingUid, installerUid); 11625 11626 final OriginInfo origin; 11627 if (stagedDir != null) { 11628 origin = OriginInfo.fromStagedFile(stagedDir); 11629 } else { 11630 origin = OriginInfo.fromStagedContainer(stagedCid); 11631 } 11632 11633 final Message msg = mHandler.obtainMessage(INIT_COPY); 11634 final InstallParams params = new InstallParams(origin, null, observer, 11635 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11636 verificationInfo, user, sessionParams.abiOverride, 11637 sessionParams.grantedRuntimePermissions, certificates); 11638 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11639 msg.obj = params; 11640 11641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11642 System.identityHashCode(msg.obj)); 11643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11644 System.identityHashCode(msg.obj)); 11645 11646 mHandler.sendMessage(msg); 11647 } 11648 11649 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11650 int userId) { 11651 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11652 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11653 } 11654 11655 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11656 int appId, int userId) { 11657 Bundle extras = new Bundle(1); 11658 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11659 11660 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11661 packageName, extras, 0, null, null, new int[] {userId}); 11662 try { 11663 IActivityManager am = ActivityManagerNative.getDefault(); 11664 if (isSystem && am.isUserRunning(userId, 0)) { 11665 // The just-installed/enabled app is bundled on the system, so presumed 11666 // to be able to run automatically without needing an explicit launch. 11667 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11668 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11669 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11670 .setPackage(packageName); 11671 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11672 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11673 } 11674 } catch (RemoteException e) { 11675 // shouldn't happen 11676 Slog.w(TAG, "Unable to bootstrap installed package", e); 11677 } 11678 } 11679 11680 @Override 11681 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11682 int userId) { 11683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11684 PackageSetting pkgSetting; 11685 final int uid = Binder.getCallingUid(); 11686 enforceCrossUserPermission(uid, userId, 11687 true /* requireFullPermission */, true /* checkShell */, 11688 "setApplicationHiddenSetting for user " + userId); 11689 11690 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11691 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11692 return false; 11693 } 11694 11695 long callingId = Binder.clearCallingIdentity(); 11696 try { 11697 boolean sendAdded = false; 11698 boolean sendRemoved = false; 11699 // writer 11700 synchronized (mPackages) { 11701 pkgSetting = mSettings.mPackages.get(packageName); 11702 if (pkgSetting == null) { 11703 return false; 11704 } 11705 // Do not allow "android" is being disabled 11706 if ("android".equals(packageName)) { 11707 Slog.w(TAG, "Cannot hide package: android"); 11708 return false; 11709 } 11710 // Only allow protected packages to hide themselves. 11711 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11712 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11713 Slog.w(TAG, "Not hiding protected package: " + packageName); 11714 return false; 11715 } 11716 11717 if (pkgSetting.getHidden(userId) != hidden) { 11718 pkgSetting.setHidden(hidden, userId); 11719 mSettings.writePackageRestrictionsLPr(userId); 11720 if (hidden) { 11721 sendRemoved = true; 11722 } else { 11723 sendAdded = true; 11724 } 11725 } 11726 } 11727 if (sendAdded) { 11728 sendPackageAddedForUser(packageName, pkgSetting, userId); 11729 return true; 11730 } 11731 if (sendRemoved) { 11732 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11733 "hiding pkg"); 11734 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11735 return true; 11736 } 11737 } finally { 11738 Binder.restoreCallingIdentity(callingId); 11739 } 11740 return false; 11741 } 11742 11743 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11744 int userId) { 11745 final PackageRemovedInfo info = new PackageRemovedInfo(); 11746 info.removedPackage = packageName; 11747 info.removedUsers = new int[] {userId}; 11748 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11749 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11750 } 11751 11752 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11753 if (pkgList.length > 0) { 11754 Bundle extras = new Bundle(1); 11755 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11756 11757 sendPackageBroadcast( 11758 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11759 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11760 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11761 new int[] {userId}); 11762 } 11763 } 11764 11765 /** 11766 * Returns true if application is not found or there was an error. Otherwise it returns 11767 * the hidden state of the package for the given user. 11768 */ 11769 @Override 11770 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11771 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11772 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11773 true /* requireFullPermission */, false /* checkShell */, 11774 "getApplicationHidden for user " + userId); 11775 PackageSetting pkgSetting; 11776 long callingId = Binder.clearCallingIdentity(); 11777 try { 11778 // writer 11779 synchronized (mPackages) { 11780 pkgSetting = mSettings.mPackages.get(packageName); 11781 if (pkgSetting == null) { 11782 return true; 11783 } 11784 return pkgSetting.getHidden(userId); 11785 } 11786 } finally { 11787 Binder.restoreCallingIdentity(callingId); 11788 } 11789 } 11790 11791 /** 11792 * @hide 11793 */ 11794 @Override 11795 public int installExistingPackageAsUser(String packageName, int userId) { 11796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11797 null); 11798 PackageSetting pkgSetting; 11799 final int uid = Binder.getCallingUid(); 11800 enforceCrossUserPermission(uid, userId, 11801 true /* requireFullPermission */, true /* checkShell */, 11802 "installExistingPackage for user " + userId); 11803 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11804 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11805 } 11806 11807 long callingId = Binder.clearCallingIdentity(); 11808 try { 11809 boolean installed = false; 11810 11811 // writer 11812 synchronized (mPackages) { 11813 pkgSetting = mSettings.mPackages.get(packageName); 11814 if (pkgSetting == null) { 11815 return PackageManager.INSTALL_FAILED_INVALID_URI; 11816 } 11817 if (!pkgSetting.getInstalled(userId)) { 11818 pkgSetting.setInstalled(true, userId); 11819 pkgSetting.setHidden(false, userId); 11820 mSettings.writePackageRestrictionsLPr(userId); 11821 installed = true; 11822 } 11823 } 11824 11825 if (installed) { 11826 if (pkgSetting.pkg != null) { 11827 synchronized (mInstallLock) { 11828 // We don't need to freeze for a brand new install 11829 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11830 } 11831 } 11832 sendPackageAddedForUser(packageName, pkgSetting, userId); 11833 } 11834 } finally { 11835 Binder.restoreCallingIdentity(callingId); 11836 } 11837 11838 return PackageManager.INSTALL_SUCCEEDED; 11839 } 11840 11841 boolean isUserRestricted(int userId, String restrictionKey) { 11842 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11843 if (restrictions.getBoolean(restrictionKey, false)) { 11844 Log.w(TAG, "User is restricted: " + restrictionKey); 11845 return true; 11846 } 11847 return false; 11848 } 11849 11850 @Override 11851 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11852 int userId) { 11853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11854 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11855 true /* requireFullPermission */, true /* checkShell */, 11856 "setPackagesSuspended for user " + userId); 11857 11858 if (ArrayUtils.isEmpty(packageNames)) { 11859 return packageNames; 11860 } 11861 11862 // List of package names for whom the suspended state has changed. 11863 List<String> changedPackages = new ArrayList<>(packageNames.length); 11864 // List of package names for whom the suspended state is not set as requested in this 11865 // method. 11866 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11867 long callingId = Binder.clearCallingIdentity(); 11868 try { 11869 for (int i = 0; i < packageNames.length; i++) { 11870 String packageName = packageNames[i]; 11871 boolean changed = false; 11872 final int appId; 11873 synchronized (mPackages) { 11874 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11875 if (pkgSetting == null) { 11876 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11877 + "\". Skipping suspending/un-suspending."); 11878 unactionedPackages.add(packageName); 11879 continue; 11880 } 11881 appId = pkgSetting.appId; 11882 if (pkgSetting.getSuspended(userId) != suspended) { 11883 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11884 unactionedPackages.add(packageName); 11885 continue; 11886 } 11887 pkgSetting.setSuspended(suspended, userId); 11888 mSettings.writePackageRestrictionsLPr(userId); 11889 changed = true; 11890 changedPackages.add(packageName); 11891 } 11892 } 11893 11894 if (changed && suspended) { 11895 killApplication(packageName, UserHandle.getUid(userId, appId), 11896 "suspending package"); 11897 } 11898 } 11899 } finally { 11900 Binder.restoreCallingIdentity(callingId); 11901 } 11902 11903 if (!changedPackages.isEmpty()) { 11904 sendPackagesSuspendedForUser(changedPackages.toArray( 11905 new String[changedPackages.size()]), userId, suspended); 11906 } 11907 11908 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11909 } 11910 11911 @Override 11912 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11913 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11914 true /* requireFullPermission */, false /* checkShell */, 11915 "isPackageSuspendedForUser for user " + userId); 11916 synchronized (mPackages) { 11917 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11918 if (pkgSetting == null) { 11919 throw new IllegalArgumentException("Unknown target package: " + packageName); 11920 } 11921 return pkgSetting.getSuspended(userId); 11922 } 11923 } 11924 11925 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11926 if (isPackageDeviceAdmin(packageName, userId)) { 11927 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11928 + "\": has an active device admin"); 11929 return false; 11930 } 11931 11932 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11933 if (packageName.equals(activeLauncherPackageName)) { 11934 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11935 + "\": contains the active launcher"); 11936 return false; 11937 } 11938 11939 if (packageName.equals(mRequiredInstallerPackage)) { 11940 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11941 + "\": required for package installation"); 11942 return false; 11943 } 11944 11945 if (packageName.equals(mRequiredUninstallerPackage)) { 11946 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11947 + "\": required for package uninstallation"); 11948 return false; 11949 } 11950 11951 if (packageName.equals(mRequiredVerifierPackage)) { 11952 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11953 + "\": required for package verification"); 11954 return false; 11955 } 11956 11957 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11958 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11959 + "\": is the default dialer"); 11960 return false; 11961 } 11962 11963 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11964 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11965 + "\": protected package"); 11966 return false; 11967 } 11968 11969 return true; 11970 } 11971 11972 private String getActiveLauncherPackageName(int userId) { 11973 Intent intent = new Intent(Intent.ACTION_MAIN); 11974 intent.addCategory(Intent.CATEGORY_HOME); 11975 ResolveInfo resolveInfo = resolveIntent( 11976 intent, 11977 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11978 PackageManager.MATCH_DEFAULT_ONLY, 11979 userId); 11980 11981 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11982 } 11983 11984 private String getDefaultDialerPackageName(int userId) { 11985 synchronized (mPackages) { 11986 return mSettings.getDefaultDialerPackageNameLPw(userId); 11987 } 11988 } 11989 11990 @Override 11991 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11992 mContext.enforceCallingOrSelfPermission( 11993 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11994 "Only package verification agents can verify applications"); 11995 11996 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11997 final PackageVerificationResponse response = new PackageVerificationResponse( 11998 verificationCode, Binder.getCallingUid()); 11999 msg.arg1 = id; 12000 msg.obj = response; 12001 mHandler.sendMessage(msg); 12002 } 12003 12004 @Override 12005 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12006 long millisecondsToDelay) { 12007 mContext.enforceCallingOrSelfPermission( 12008 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12009 "Only package verification agents can extend verification timeouts"); 12010 12011 final PackageVerificationState state = mPendingVerification.get(id); 12012 final PackageVerificationResponse response = new PackageVerificationResponse( 12013 verificationCodeAtTimeout, Binder.getCallingUid()); 12014 12015 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12016 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12017 } 12018 if (millisecondsToDelay < 0) { 12019 millisecondsToDelay = 0; 12020 } 12021 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12022 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12023 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12024 } 12025 12026 if ((state != null) && !state.timeoutExtended()) { 12027 state.extendTimeout(); 12028 12029 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12030 msg.arg1 = id; 12031 msg.obj = response; 12032 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12033 } 12034 } 12035 12036 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12037 int verificationCode, UserHandle user) { 12038 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12039 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12040 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12041 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12042 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12043 12044 mContext.sendBroadcastAsUser(intent, user, 12045 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12046 } 12047 12048 private ComponentName matchComponentForVerifier(String packageName, 12049 List<ResolveInfo> receivers) { 12050 ActivityInfo targetReceiver = null; 12051 12052 final int NR = receivers.size(); 12053 for (int i = 0; i < NR; i++) { 12054 final ResolveInfo info = receivers.get(i); 12055 if (info.activityInfo == null) { 12056 continue; 12057 } 12058 12059 if (packageName.equals(info.activityInfo.packageName)) { 12060 targetReceiver = info.activityInfo; 12061 break; 12062 } 12063 } 12064 12065 if (targetReceiver == null) { 12066 return null; 12067 } 12068 12069 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12070 } 12071 12072 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12073 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12074 if (pkgInfo.verifiers.length == 0) { 12075 return null; 12076 } 12077 12078 final int N = pkgInfo.verifiers.length; 12079 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12080 for (int i = 0; i < N; i++) { 12081 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12082 12083 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12084 receivers); 12085 if (comp == null) { 12086 continue; 12087 } 12088 12089 final int verifierUid = getUidForVerifier(verifierInfo); 12090 if (verifierUid == -1) { 12091 continue; 12092 } 12093 12094 if (DEBUG_VERIFY) { 12095 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12096 + " with the correct signature"); 12097 } 12098 sufficientVerifiers.add(comp); 12099 verificationState.addSufficientVerifier(verifierUid); 12100 } 12101 12102 return sufficientVerifiers; 12103 } 12104 12105 private int getUidForVerifier(VerifierInfo verifierInfo) { 12106 synchronized (mPackages) { 12107 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12108 if (pkg == null) { 12109 return -1; 12110 } else if (pkg.mSignatures.length != 1) { 12111 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12112 + " has more than one signature; ignoring"); 12113 return -1; 12114 } 12115 12116 /* 12117 * If the public key of the package's signature does not match 12118 * our expected public key, then this is a different package and 12119 * we should skip. 12120 */ 12121 12122 final byte[] expectedPublicKey; 12123 try { 12124 final Signature verifierSig = pkg.mSignatures[0]; 12125 final PublicKey publicKey = verifierSig.getPublicKey(); 12126 expectedPublicKey = publicKey.getEncoded(); 12127 } catch (CertificateException e) { 12128 return -1; 12129 } 12130 12131 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12132 12133 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12134 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12135 + " does not have the expected public key; ignoring"); 12136 return -1; 12137 } 12138 12139 return pkg.applicationInfo.uid; 12140 } 12141 } 12142 12143 @Override 12144 public void finishPackageInstall(int token, boolean didLaunch) { 12145 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12146 12147 if (DEBUG_INSTALL) { 12148 Slog.v(TAG, "BM finishing package install for " + token); 12149 } 12150 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12151 12152 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12153 mHandler.sendMessage(msg); 12154 } 12155 12156 /** 12157 * Get the verification agent timeout. 12158 * 12159 * @return verification timeout in milliseconds 12160 */ 12161 private long getVerificationTimeout() { 12162 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12163 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12164 DEFAULT_VERIFICATION_TIMEOUT); 12165 } 12166 12167 /** 12168 * Get the default verification agent response code. 12169 * 12170 * @return default verification response code 12171 */ 12172 private int getDefaultVerificationResponse() { 12173 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12174 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12175 DEFAULT_VERIFICATION_RESPONSE); 12176 } 12177 12178 /** 12179 * Check whether or not package verification has been enabled. 12180 * 12181 * @return true if verification should be performed 12182 */ 12183 private boolean isVerificationEnabled(int userId, int installFlags) { 12184 if (!DEFAULT_VERIFY_ENABLE) { 12185 return false; 12186 } 12187 // Ephemeral apps don't get the full verification treatment 12188 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12189 if (DEBUG_EPHEMERAL) { 12190 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12191 } 12192 return false; 12193 } 12194 12195 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12196 12197 // Check if installing from ADB 12198 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12199 // Do not run verification in a test harness environment 12200 if (ActivityManager.isRunningInTestHarness()) { 12201 return false; 12202 } 12203 if (ensureVerifyAppsEnabled) { 12204 return true; 12205 } 12206 // Check if the developer does not want package verification for ADB installs 12207 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12208 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12209 return false; 12210 } 12211 } 12212 12213 if (ensureVerifyAppsEnabled) { 12214 return true; 12215 } 12216 12217 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12218 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12219 } 12220 12221 @Override 12222 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12223 throws RemoteException { 12224 mContext.enforceCallingOrSelfPermission( 12225 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12226 "Only intentfilter verification agents can verify applications"); 12227 12228 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12229 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12230 Binder.getCallingUid(), verificationCode, failedDomains); 12231 msg.arg1 = id; 12232 msg.obj = response; 12233 mHandler.sendMessage(msg); 12234 } 12235 12236 @Override 12237 public int getIntentVerificationStatus(String packageName, int userId) { 12238 synchronized (mPackages) { 12239 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12240 } 12241 } 12242 12243 @Override 12244 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12245 mContext.enforceCallingOrSelfPermission( 12246 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12247 12248 boolean result = false; 12249 synchronized (mPackages) { 12250 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12251 } 12252 if (result) { 12253 scheduleWritePackageRestrictionsLocked(userId); 12254 } 12255 return result; 12256 } 12257 12258 @Override 12259 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12260 String packageName) { 12261 synchronized (mPackages) { 12262 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12263 } 12264 } 12265 12266 @Override 12267 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12268 if (TextUtils.isEmpty(packageName)) { 12269 return ParceledListSlice.emptyList(); 12270 } 12271 synchronized (mPackages) { 12272 PackageParser.Package pkg = mPackages.get(packageName); 12273 if (pkg == null || pkg.activities == null) { 12274 return ParceledListSlice.emptyList(); 12275 } 12276 final int count = pkg.activities.size(); 12277 ArrayList<IntentFilter> result = new ArrayList<>(); 12278 for (int n=0; n<count; n++) { 12279 PackageParser.Activity activity = pkg.activities.get(n); 12280 if (activity.intents != null && activity.intents.size() > 0) { 12281 result.addAll(activity.intents); 12282 } 12283 } 12284 return new ParceledListSlice<>(result); 12285 } 12286 } 12287 12288 @Override 12289 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12290 mContext.enforceCallingOrSelfPermission( 12291 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12292 12293 synchronized (mPackages) { 12294 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12295 if (packageName != null) { 12296 result |= updateIntentVerificationStatus(packageName, 12297 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12298 userId); 12299 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12300 packageName, userId); 12301 } 12302 return result; 12303 } 12304 } 12305 12306 @Override 12307 public String getDefaultBrowserPackageName(int userId) { 12308 synchronized (mPackages) { 12309 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12310 } 12311 } 12312 12313 /** 12314 * Get the "allow unknown sources" setting. 12315 * 12316 * @return the current "allow unknown sources" setting 12317 */ 12318 private int getUnknownSourcesSettings() { 12319 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12320 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12321 -1); 12322 } 12323 12324 @Override 12325 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12326 final int uid = Binder.getCallingUid(); 12327 // writer 12328 synchronized (mPackages) { 12329 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12330 if (targetPackageSetting == null) { 12331 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12332 } 12333 12334 PackageSetting installerPackageSetting; 12335 if (installerPackageName != null) { 12336 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12337 if (installerPackageSetting == null) { 12338 throw new IllegalArgumentException("Unknown installer package: " 12339 + installerPackageName); 12340 } 12341 } else { 12342 installerPackageSetting = null; 12343 } 12344 12345 Signature[] callerSignature; 12346 Object obj = mSettings.getUserIdLPr(uid); 12347 if (obj != null) { 12348 if (obj instanceof SharedUserSetting) { 12349 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12350 } else if (obj instanceof PackageSetting) { 12351 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12352 } else { 12353 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12354 } 12355 } else { 12356 throw new SecurityException("Unknown calling UID: " + uid); 12357 } 12358 12359 // Verify: can't set installerPackageName to a package that is 12360 // not signed with the same cert as the caller. 12361 if (installerPackageSetting != null) { 12362 if (compareSignatures(callerSignature, 12363 installerPackageSetting.signatures.mSignatures) 12364 != PackageManager.SIGNATURE_MATCH) { 12365 throw new SecurityException( 12366 "Caller does not have same cert as new installer package " 12367 + installerPackageName); 12368 } 12369 } 12370 12371 // Verify: if target already has an installer package, it must 12372 // be signed with the same cert as the caller. 12373 if (targetPackageSetting.installerPackageName != null) { 12374 PackageSetting setting = mSettings.mPackages.get( 12375 targetPackageSetting.installerPackageName); 12376 // If the currently set package isn't valid, then it's always 12377 // okay to change it. 12378 if (setting != null) { 12379 if (compareSignatures(callerSignature, 12380 setting.signatures.mSignatures) 12381 != PackageManager.SIGNATURE_MATCH) { 12382 throw new SecurityException( 12383 "Caller does not have same cert as old installer package " 12384 + targetPackageSetting.installerPackageName); 12385 } 12386 } 12387 } 12388 12389 // Okay! 12390 targetPackageSetting.installerPackageName = installerPackageName; 12391 if (installerPackageName != null) { 12392 mSettings.mInstallerPackages.add(installerPackageName); 12393 } 12394 scheduleWriteSettingsLocked(); 12395 } 12396 } 12397 12398 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12399 // Queue up an async operation since the package installation may take a little while. 12400 mHandler.post(new Runnable() { 12401 public void run() { 12402 mHandler.removeCallbacks(this); 12403 // Result object to be returned 12404 PackageInstalledInfo res = new PackageInstalledInfo(); 12405 res.setReturnCode(currentStatus); 12406 res.uid = -1; 12407 res.pkg = null; 12408 res.removedInfo = null; 12409 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12410 args.doPreInstall(res.returnCode); 12411 synchronized (mInstallLock) { 12412 installPackageTracedLI(args, res); 12413 } 12414 args.doPostInstall(res.returnCode, res.uid); 12415 } 12416 12417 // A restore should be performed at this point if (a) the install 12418 // succeeded, (b) the operation is not an update, and (c) the new 12419 // package has not opted out of backup participation. 12420 final boolean update = res.removedInfo != null 12421 && res.removedInfo.removedPackage != null; 12422 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12423 boolean doRestore = !update 12424 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12425 12426 // Set up the post-install work request bookkeeping. This will be used 12427 // and cleaned up by the post-install event handling regardless of whether 12428 // there's a restore pass performed. Token values are >= 1. 12429 int token; 12430 if (mNextInstallToken < 0) mNextInstallToken = 1; 12431 token = mNextInstallToken++; 12432 12433 PostInstallData data = new PostInstallData(args, res); 12434 mRunningInstalls.put(token, data); 12435 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12436 12437 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12438 // Pass responsibility to the Backup Manager. It will perform a 12439 // restore if appropriate, then pass responsibility back to the 12440 // Package Manager to run the post-install observer callbacks 12441 // and broadcasts. 12442 IBackupManager bm = IBackupManager.Stub.asInterface( 12443 ServiceManager.getService(Context.BACKUP_SERVICE)); 12444 if (bm != null) { 12445 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12446 + " to BM for possible restore"); 12447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12448 try { 12449 // TODO: http://b/22388012 12450 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12451 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12452 } else { 12453 doRestore = false; 12454 } 12455 } catch (RemoteException e) { 12456 // can't happen; the backup manager is local 12457 } catch (Exception e) { 12458 Slog.e(TAG, "Exception trying to enqueue restore", e); 12459 doRestore = false; 12460 } 12461 } else { 12462 Slog.e(TAG, "Backup Manager not found!"); 12463 doRestore = false; 12464 } 12465 } 12466 12467 if (!doRestore) { 12468 // No restore possible, or the Backup Manager was mysteriously not 12469 // available -- just fire the post-install work request directly. 12470 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12471 12472 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12473 12474 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12475 mHandler.sendMessage(msg); 12476 } 12477 } 12478 }); 12479 } 12480 12481 /** 12482 * Callback from PackageSettings whenever an app is first transitioned out of the 12483 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12484 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12485 * here whether the app is the target of an ongoing install, and only send the 12486 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12487 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12488 * handling. 12489 */ 12490 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12491 // Serialize this with the rest of the install-process message chain. In the 12492 // restore-at-install case, this Runnable will necessarily run before the 12493 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12494 // are coherent. In the non-restore case, the app has already completed install 12495 // and been launched through some other means, so it is not in a problematic 12496 // state for observers to see the FIRST_LAUNCH signal. 12497 mHandler.post(new Runnable() { 12498 @Override 12499 public void run() { 12500 for (int i = 0; i < mRunningInstalls.size(); i++) { 12501 final PostInstallData data = mRunningInstalls.valueAt(i); 12502 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12503 continue; 12504 } 12505 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12506 // right package; but is it for the right user? 12507 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12508 if (userId == data.res.newUsers[uIndex]) { 12509 if (DEBUG_BACKUP) { 12510 Slog.i(TAG, "Package " + pkgName 12511 + " being restored so deferring FIRST_LAUNCH"); 12512 } 12513 return; 12514 } 12515 } 12516 } 12517 } 12518 // didn't find it, so not being restored 12519 if (DEBUG_BACKUP) { 12520 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12521 } 12522 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12523 } 12524 }); 12525 } 12526 12527 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12528 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12529 installerPkg, null, userIds); 12530 } 12531 12532 private abstract class HandlerParams { 12533 private static final int MAX_RETRIES = 4; 12534 12535 /** 12536 * Number of times startCopy() has been attempted and had a non-fatal 12537 * error. 12538 */ 12539 private int mRetries = 0; 12540 12541 /** User handle for the user requesting the information or installation. */ 12542 private final UserHandle mUser; 12543 String traceMethod; 12544 int traceCookie; 12545 12546 HandlerParams(UserHandle user) { 12547 mUser = user; 12548 } 12549 12550 UserHandle getUser() { 12551 return mUser; 12552 } 12553 12554 HandlerParams setTraceMethod(String traceMethod) { 12555 this.traceMethod = traceMethod; 12556 return this; 12557 } 12558 12559 HandlerParams setTraceCookie(int traceCookie) { 12560 this.traceCookie = traceCookie; 12561 return this; 12562 } 12563 12564 final boolean startCopy() { 12565 boolean res; 12566 try { 12567 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12568 12569 if (++mRetries > MAX_RETRIES) { 12570 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12571 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12572 handleServiceError(); 12573 return false; 12574 } else { 12575 handleStartCopy(); 12576 res = true; 12577 } 12578 } catch (RemoteException e) { 12579 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12580 mHandler.sendEmptyMessage(MCS_RECONNECT); 12581 res = false; 12582 } 12583 handleReturnCode(); 12584 return res; 12585 } 12586 12587 final void serviceError() { 12588 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12589 handleServiceError(); 12590 handleReturnCode(); 12591 } 12592 12593 abstract void handleStartCopy() throws RemoteException; 12594 abstract void handleServiceError(); 12595 abstract void handleReturnCode(); 12596 } 12597 12598 class MeasureParams extends HandlerParams { 12599 private final PackageStats mStats; 12600 private boolean mSuccess; 12601 12602 private final IPackageStatsObserver mObserver; 12603 12604 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12605 super(new UserHandle(stats.userHandle)); 12606 mObserver = observer; 12607 mStats = stats; 12608 } 12609 12610 @Override 12611 public String toString() { 12612 return "MeasureParams{" 12613 + Integer.toHexString(System.identityHashCode(this)) 12614 + " " + mStats.packageName + "}"; 12615 } 12616 12617 @Override 12618 void handleStartCopy() throws RemoteException { 12619 synchronized (mInstallLock) { 12620 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12621 } 12622 12623 if (mSuccess) { 12624 boolean mounted = false; 12625 try { 12626 final String status = Environment.getExternalStorageState(); 12627 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12628 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12629 } catch (Exception e) { 12630 } 12631 12632 if (mounted) { 12633 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12634 12635 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12636 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12637 12638 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12639 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12640 12641 // Always subtract cache size, since it's a subdirectory 12642 mStats.externalDataSize -= mStats.externalCacheSize; 12643 12644 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12645 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12646 12647 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12648 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12649 } 12650 } 12651 } 12652 12653 @Override 12654 void handleReturnCode() { 12655 if (mObserver != null) { 12656 try { 12657 mObserver.onGetStatsCompleted(mStats, mSuccess); 12658 } catch (RemoteException e) { 12659 Slog.i(TAG, "Observer no longer exists."); 12660 } 12661 } 12662 } 12663 12664 @Override 12665 void handleServiceError() { 12666 Slog.e(TAG, "Could not measure application " + mStats.packageName 12667 + " external storage"); 12668 } 12669 } 12670 12671 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12672 throws RemoteException { 12673 long result = 0; 12674 for (File path : paths) { 12675 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12676 } 12677 return result; 12678 } 12679 12680 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12681 for (File path : paths) { 12682 try { 12683 mcs.clearDirectory(path.getAbsolutePath()); 12684 } catch (RemoteException e) { 12685 } 12686 } 12687 } 12688 12689 static class OriginInfo { 12690 /** 12691 * Location where install is coming from, before it has been 12692 * copied/renamed into place. This could be a single monolithic APK 12693 * file, or a cluster directory. This location may be untrusted. 12694 */ 12695 final File file; 12696 final String cid; 12697 12698 /** 12699 * Flag indicating that {@link #file} or {@link #cid} has already been 12700 * staged, meaning downstream users don't need to defensively copy the 12701 * contents. 12702 */ 12703 final boolean staged; 12704 12705 /** 12706 * Flag indicating that {@link #file} or {@link #cid} is an already 12707 * installed app that is being moved. 12708 */ 12709 final boolean existing; 12710 12711 final String resolvedPath; 12712 final File resolvedFile; 12713 12714 static OriginInfo fromNothing() { 12715 return new OriginInfo(null, null, false, false); 12716 } 12717 12718 static OriginInfo fromUntrustedFile(File file) { 12719 return new OriginInfo(file, null, false, false); 12720 } 12721 12722 static OriginInfo fromExistingFile(File file) { 12723 return new OriginInfo(file, null, false, true); 12724 } 12725 12726 static OriginInfo fromStagedFile(File file) { 12727 return new OriginInfo(file, null, true, false); 12728 } 12729 12730 static OriginInfo fromStagedContainer(String cid) { 12731 return new OriginInfo(null, cid, true, false); 12732 } 12733 12734 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12735 this.file = file; 12736 this.cid = cid; 12737 this.staged = staged; 12738 this.existing = existing; 12739 12740 if (cid != null) { 12741 resolvedPath = PackageHelper.getSdDir(cid); 12742 resolvedFile = new File(resolvedPath); 12743 } else if (file != null) { 12744 resolvedPath = file.getAbsolutePath(); 12745 resolvedFile = file; 12746 } else { 12747 resolvedPath = null; 12748 resolvedFile = null; 12749 } 12750 } 12751 } 12752 12753 static class MoveInfo { 12754 final int moveId; 12755 final String fromUuid; 12756 final String toUuid; 12757 final String packageName; 12758 final String dataAppName; 12759 final int appId; 12760 final String seinfo; 12761 final int targetSdkVersion; 12762 12763 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12764 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12765 this.moveId = moveId; 12766 this.fromUuid = fromUuid; 12767 this.toUuid = toUuid; 12768 this.packageName = packageName; 12769 this.dataAppName = dataAppName; 12770 this.appId = appId; 12771 this.seinfo = seinfo; 12772 this.targetSdkVersion = targetSdkVersion; 12773 } 12774 } 12775 12776 static class VerificationInfo { 12777 /** A constant used to indicate that a uid value is not present. */ 12778 public static final int NO_UID = -1; 12779 12780 /** URI referencing where the package was downloaded from. */ 12781 final Uri originatingUri; 12782 12783 /** HTTP referrer URI associated with the originatingURI. */ 12784 final Uri referrer; 12785 12786 /** UID of the application that the install request originated from. */ 12787 final int originatingUid; 12788 12789 /** UID of application requesting the install */ 12790 final int installerUid; 12791 12792 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12793 this.originatingUri = originatingUri; 12794 this.referrer = referrer; 12795 this.originatingUid = originatingUid; 12796 this.installerUid = installerUid; 12797 } 12798 } 12799 12800 class InstallParams extends HandlerParams { 12801 final OriginInfo origin; 12802 final MoveInfo move; 12803 final IPackageInstallObserver2 observer; 12804 int installFlags; 12805 final String installerPackageName; 12806 final String volumeUuid; 12807 private InstallArgs mArgs; 12808 private int mRet; 12809 final String packageAbiOverride; 12810 final String[] grantedRuntimePermissions; 12811 final VerificationInfo verificationInfo; 12812 final Certificate[][] certificates; 12813 12814 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12815 int installFlags, String installerPackageName, String volumeUuid, 12816 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12817 String[] grantedPermissions, Certificate[][] certificates) { 12818 super(user); 12819 this.origin = origin; 12820 this.move = move; 12821 this.observer = observer; 12822 this.installFlags = installFlags; 12823 this.installerPackageName = installerPackageName; 12824 this.volumeUuid = volumeUuid; 12825 this.verificationInfo = verificationInfo; 12826 this.packageAbiOverride = packageAbiOverride; 12827 this.grantedRuntimePermissions = grantedPermissions; 12828 this.certificates = certificates; 12829 } 12830 12831 @Override 12832 public String toString() { 12833 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12834 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12835 } 12836 12837 private int installLocationPolicy(PackageInfoLite pkgLite) { 12838 String packageName = pkgLite.packageName; 12839 int installLocation = pkgLite.installLocation; 12840 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12841 // reader 12842 synchronized (mPackages) { 12843 // Currently installed package which the new package is attempting to replace or 12844 // null if no such package is installed. 12845 PackageParser.Package installedPkg = mPackages.get(packageName); 12846 // Package which currently owns the data which the new package will own if installed. 12847 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12848 // will be null whereas dataOwnerPkg will contain information about the package 12849 // which was uninstalled while keeping its data. 12850 PackageParser.Package dataOwnerPkg = installedPkg; 12851 if (dataOwnerPkg == null) { 12852 PackageSetting ps = mSettings.mPackages.get(packageName); 12853 if (ps != null) { 12854 dataOwnerPkg = ps.pkg; 12855 } 12856 } 12857 12858 if (dataOwnerPkg != null) { 12859 // If installed, the package will get access to data left on the device by its 12860 // predecessor. As a security measure, this is permited only if this is not a 12861 // version downgrade or if the predecessor package is marked as debuggable and 12862 // a downgrade is explicitly requested. 12863 // 12864 // On debuggable platform builds, downgrades are permitted even for 12865 // non-debuggable packages to make testing easier. Debuggable platform builds do 12866 // not offer security guarantees and thus it's OK to disable some security 12867 // mechanisms to make debugging/testing easier on those builds. However, even on 12868 // debuggable builds downgrades of packages are permitted only if requested via 12869 // installFlags. This is because we aim to keep the behavior of debuggable 12870 // platform builds as close as possible to the behavior of non-debuggable 12871 // platform builds. 12872 final boolean downgradeRequested = 12873 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12874 final boolean packageDebuggable = 12875 (dataOwnerPkg.applicationInfo.flags 12876 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12877 final boolean downgradePermitted = 12878 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12879 if (!downgradePermitted) { 12880 try { 12881 checkDowngrade(dataOwnerPkg, pkgLite); 12882 } catch (PackageManagerException e) { 12883 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12884 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12885 } 12886 } 12887 } 12888 12889 if (installedPkg != null) { 12890 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12891 // Check for updated system application. 12892 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12893 if (onSd) { 12894 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12895 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12896 } 12897 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12898 } else { 12899 if (onSd) { 12900 // Install flag overrides everything. 12901 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12902 } 12903 // If current upgrade specifies particular preference 12904 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12905 // Application explicitly specified internal. 12906 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12907 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12908 // App explictly prefers external. Let policy decide 12909 } else { 12910 // Prefer previous location 12911 if (isExternal(installedPkg)) { 12912 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12913 } 12914 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12915 } 12916 } 12917 } else { 12918 // Invalid install. Return error code 12919 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12920 } 12921 } 12922 } 12923 // All the special cases have been taken care of. 12924 // Return result based on recommended install location. 12925 if (onSd) { 12926 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12927 } 12928 return pkgLite.recommendedInstallLocation; 12929 } 12930 12931 /* 12932 * Invoke remote method to get package information and install 12933 * location values. Override install location based on default 12934 * policy if needed and then create install arguments based 12935 * on the install location. 12936 */ 12937 public void handleStartCopy() throws RemoteException { 12938 int ret = PackageManager.INSTALL_SUCCEEDED; 12939 12940 // If we're already staged, we've firmly committed to an install location 12941 if (origin.staged) { 12942 if (origin.file != null) { 12943 installFlags |= PackageManager.INSTALL_INTERNAL; 12944 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12945 } else if (origin.cid != null) { 12946 installFlags |= PackageManager.INSTALL_EXTERNAL; 12947 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12948 } else { 12949 throw new IllegalStateException("Invalid stage location"); 12950 } 12951 } 12952 12953 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12954 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12955 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12956 PackageInfoLite pkgLite = null; 12957 12958 if (onInt && onSd) { 12959 // Check if both bits are set. 12960 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12961 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12962 } else if (onSd && ephemeral) { 12963 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12964 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12965 } else { 12966 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12967 packageAbiOverride); 12968 12969 if (DEBUG_EPHEMERAL && ephemeral) { 12970 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12971 } 12972 12973 /* 12974 * If we have too little free space, try to free cache 12975 * before giving up. 12976 */ 12977 if (!origin.staged && pkgLite.recommendedInstallLocation 12978 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12979 // TODO: focus freeing disk space on the target device 12980 final StorageManager storage = StorageManager.from(mContext); 12981 final long lowThreshold = storage.getStorageLowBytes( 12982 Environment.getDataDirectory()); 12983 12984 final long sizeBytes = mContainerService.calculateInstalledSize( 12985 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12986 12987 try { 12988 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12989 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12990 installFlags, packageAbiOverride); 12991 } catch (InstallerException e) { 12992 Slog.w(TAG, "Failed to free cache", e); 12993 } 12994 12995 /* 12996 * The cache free must have deleted the file we 12997 * downloaded to install. 12998 * 12999 * TODO: fix the "freeCache" call to not delete 13000 * the file we care about. 13001 */ 13002 if (pkgLite.recommendedInstallLocation 13003 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13004 pkgLite.recommendedInstallLocation 13005 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13006 } 13007 } 13008 } 13009 13010 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13011 int loc = pkgLite.recommendedInstallLocation; 13012 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13013 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13014 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13015 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13016 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13017 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13018 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13019 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13020 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13021 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13022 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13023 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13024 } else { 13025 // Override with defaults if needed. 13026 loc = installLocationPolicy(pkgLite); 13027 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13028 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13029 } else if (!onSd && !onInt) { 13030 // Override install location with flags 13031 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13032 // Set the flag to install on external media. 13033 installFlags |= PackageManager.INSTALL_EXTERNAL; 13034 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13035 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13036 if (DEBUG_EPHEMERAL) { 13037 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13038 } 13039 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13040 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13041 |PackageManager.INSTALL_INTERNAL); 13042 } else { 13043 // Make sure the flag for installing on external 13044 // media is unset 13045 installFlags |= PackageManager.INSTALL_INTERNAL; 13046 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13047 } 13048 } 13049 } 13050 } 13051 13052 final InstallArgs args = createInstallArgs(this); 13053 mArgs = args; 13054 13055 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13056 // TODO: http://b/22976637 13057 // Apps installed for "all" users use the device owner to verify the app 13058 UserHandle verifierUser = getUser(); 13059 if (verifierUser == UserHandle.ALL) { 13060 verifierUser = UserHandle.SYSTEM; 13061 } 13062 13063 /* 13064 * Determine if we have any installed package verifiers. If we 13065 * do, then we'll defer to them to verify the packages. 13066 */ 13067 final int requiredUid = mRequiredVerifierPackage == null ? -1 13068 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13069 verifierUser.getIdentifier()); 13070 if (!origin.existing && requiredUid != -1 13071 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13072 final Intent verification = new Intent( 13073 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13074 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13075 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13076 PACKAGE_MIME_TYPE); 13077 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13078 13079 // Query all live verifiers based on current user state 13080 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13081 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13082 13083 if (DEBUG_VERIFY) { 13084 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13085 + verification.toString() + " with " + pkgLite.verifiers.length 13086 + " optional verifiers"); 13087 } 13088 13089 final int verificationId = mPendingVerificationToken++; 13090 13091 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13092 13093 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13094 installerPackageName); 13095 13096 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13097 installFlags); 13098 13099 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13100 pkgLite.packageName); 13101 13102 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13103 pkgLite.versionCode); 13104 13105 if (verificationInfo != null) { 13106 if (verificationInfo.originatingUri != null) { 13107 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13108 verificationInfo.originatingUri); 13109 } 13110 if (verificationInfo.referrer != null) { 13111 verification.putExtra(Intent.EXTRA_REFERRER, 13112 verificationInfo.referrer); 13113 } 13114 if (verificationInfo.originatingUid >= 0) { 13115 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13116 verificationInfo.originatingUid); 13117 } 13118 if (verificationInfo.installerUid >= 0) { 13119 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13120 verificationInfo.installerUid); 13121 } 13122 } 13123 13124 final PackageVerificationState verificationState = new PackageVerificationState( 13125 requiredUid, args); 13126 13127 mPendingVerification.append(verificationId, verificationState); 13128 13129 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13130 receivers, verificationState); 13131 13132 /* 13133 * If any sufficient verifiers were listed in the package 13134 * manifest, attempt to ask them. 13135 */ 13136 if (sufficientVerifiers != null) { 13137 final int N = sufficientVerifiers.size(); 13138 if (N == 0) { 13139 Slog.i(TAG, "Additional verifiers required, but none installed."); 13140 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13141 } else { 13142 for (int i = 0; i < N; i++) { 13143 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13144 13145 final Intent sufficientIntent = new Intent(verification); 13146 sufficientIntent.setComponent(verifierComponent); 13147 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13148 } 13149 } 13150 } 13151 13152 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13153 mRequiredVerifierPackage, receivers); 13154 if (ret == PackageManager.INSTALL_SUCCEEDED 13155 && mRequiredVerifierPackage != null) { 13156 Trace.asyncTraceBegin( 13157 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13158 /* 13159 * Send the intent to the required verification agent, 13160 * but only start the verification timeout after the 13161 * target BroadcastReceivers have run. 13162 */ 13163 verification.setComponent(requiredVerifierComponent); 13164 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13165 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13166 new BroadcastReceiver() { 13167 @Override 13168 public void onReceive(Context context, Intent intent) { 13169 final Message msg = mHandler 13170 .obtainMessage(CHECK_PENDING_VERIFICATION); 13171 msg.arg1 = verificationId; 13172 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13173 } 13174 }, null, 0, null, null); 13175 13176 /* 13177 * We don't want the copy to proceed until verification 13178 * succeeds, so null out this field. 13179 */ 13180 mArgs = null; 13181 } 13182 } else { 13183 /* 13184 * No package verification is enabled, so immediately start 13185 * the remote call to initiate copy using temporary file. 13186 */ 13187 ret = args.copyApk(mContainerService, true); 13188 } 13189 } 13190 13191 mRet = ret; 13192 } 13193 13194 @Override 13195 void handleReturnCode() { 13196 // If mArgs is null, then MCS couldn't be reached. When it 13197 // reconnects, it will try again to install. At that point, this 13198 // will succeed. 13199 if (mArgs != null) { 13200 processPendingInstall(mArgs, mRet); 13201 } 13202 } 13203 13204 @Override 13205 void handleServiceError() { 13206 mArgs = createInstallArgs(this); 13207 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13208 } 13209 13210 public boolean isForwardLocked() { 13211 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13212 } 13213 } 13214 13215 /** 13216 * Used during creation of InstallArgs 13217 * 13218 * @param installFlags package installation flags 13219 * @return true if should be installed on external storage 13220 */ 13221 private static boolean installOnExternalAsec(int installFlags) { 13222 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13223 return false; 13224 } 13225 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13226 return true; 13227 } 13228 return false; 13229 } 13230 13231 /** 13232 * Used during creation of InstallArgs 13233 * 13234 * @param installFlags package installation flags 13235 * @return true if should be installed as forward locked 13236 */ 13237 private static boolean installForwardLocked(int installFlags) { 13238 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13239 } 13240 13241 private InstallArgs createInstallArgs(InstallParams params) { 13242 if (params.move != null) { 13243 return new MoveInstallArgs(params); 13244 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13245 return new AsecInstallArgs(params); 13246 } else { 13247 return new FileInstallArgs(params); 13248 } 13249 } 13250 13251 /** 13252 * Create args that describe an existing installed package. Typically used 13253 * when cleaning up old installs, or used as a move source. 13254 */ 13255 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13256 String resourcePath, String[] instructionSets) { 13257 final boolean isInAsec; 13258 if (installOnExternalAsec(installFlags)) { 13259 /* Apps on SD card are always in ASEC containers. */ 13260 isInAsec = true; 13261 } else if (installForwardLocked(installFlags) 13262 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13263 /* 13264 * Forward-locked apps are only in ASEC containers if they're the 13265 * new style 13266 */ 13267 isInAsec = true; 13268 } else { 13269 isInAsec = false; 13270 } 13271 13272 if (isInAsec) { 13273 return new AsecInstallArgs(codePath, instructionSets, 13274 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13275 } else { 13276 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13277 } 13278 } 13279 13280 static abstract class InstallArgs { 13281 /** @see InstallParams#origin */ 13282 final OriginInfo origin; 13283 /** @see InstallParams#move */ 13284 final MoveInfo move; 13285 13286 final IPackageInstallObserver2 observer; 13287 // Always refers to PackageManager flags only 13288 final int installFlags; 13289 final String installerPackageName; 13290 final String volumeUuid; 13291 final UserHandle user; 13292 final String abiOverride; 13293 final String[] installGrantPermissions; 13294 /** If non-null, drop an async trace when the install completes */ 13295 final String traceMethod; 13296 final int traceCookie; 13297 final Certificate[][] certificates; 13298 13299 // The list of instruction sets supported by this app. This is currently 13300 // only used during the rmdex() phase to clean up resources. We can get rid of this 13301 // if we move dex files under the common app path. 13302 /* nullable */ String[] instructionSets; 13303 13304 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13305 int installFlags, String installerPackageName, String volumeUuid, 13306 UserHandle user, String[] instructionSets, 13307 String abiOverride, String[] installGrantPermissions, 13308 String traceMethod, int traceCookie, Certificate[][] certificates) { 13309 this.origin = origin; 13310 this.move = move; 13311 this.installFlags = installFlags; 13312 this.observer = observer; 13313 this.installerPackageName = installerPackageName; 13314 this.volumeUuid = volumeUuid; 13315 this.user = user; 13316 this.instructionSets = instructionSets; 13317 this.abiOverride = abiOverride; 13318 this.installGrantPermissions = installGrantPermissions; 13319 this.traceMethod = traceMethod; 13320 this.traceCookie = traceCookie; 13321 this.certificates = certificates; 13322 } 13323 13324 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13325 abstract int doPreInstall(int status); 13326 13327 /** 13328 * Rename package into final resting place. All paths on the given 13329 * scanned package should be updated to reflect the rename. 13330 */ 13331 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13332 abstract int doPostInstall(int status, int uid); 13333 13334 /** @see PackageSettingBase#codePathString */ 13335 abstract String getCodePath(); 13336 /** @see PackageSettingBase#resourcePathString */ 13337 abstract String getResourcePath(); 13338 13339 // Need installer lock especially for dex file removal. 13340 abstract void cleanUpResourcesLI(); 13341 abstract boolean doPostDeleteLI(boolean delete); 13342 13343 /** 13344 * Called before the source arguments are copied. This is used mostly 13345 * for MoveParams when it needs to read the source file to put it in the 13346 * destination. 13347 */ 13348 int doPreCopy() { 13349 return PackageManager.INSTALL_SUCCEEDED; 13350 } 13351 13352 /** 13353 * Called after the source arguments are copied. This is used mostly for 13354 * MoveParams when it needs to read the source file to put it in the 13355 * destination. 13356 */ 13357 int doPostCopy(int uid) { 13358 return PackageManager.INSTALL_SUCCEEDED; 13359 } 13360 13361 protected boolean isFwdLocked() { 13362 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13363 } 13364 13365 protected boolean isExternalAsec() { 13366 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13367 } 13368 13369 protected boolean isEphemeral() { 13370 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13371 } 13372 13373 UserHandle getUser() { 13374 return user; 13375 } 13376 } 13377 13378 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13379 if (!allCodePaths.isEmpty()) { 13380 if (instructionSets == null) { 13381 throw new IllegalStateException("instructionSet == null"); 13382 } 13383 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13384 for (String codePath : allCodePaths) { 13385 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13386 try { 13387 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13388 } catch (InstallerException ignored) { 13389 } 13390 } 13391 } 13392 } 13393 } 13394 13395 /** 13396 * Logic to handle installation of non-ASEC applications, including copying 13397 * and renaming logic. 13398 */ 13399 class FileInstallArgs extends InstallArgs { 13400 private File codeFile; 13401 private File resourceFile; 13402 13403 // Example topology: 13404 // /data/app/com.example/base.apk 13405 // /data/app/com.example/split_foo.apk 13406 // /data/app/com.example/lib/arm/libfoo.so 13407 // /data/app/com.example/lib/arm64/libfoo.so 13408 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13409 13410 /** New install */ 13411 FileInstallArgs(InstallParams params) { 13412 super(params.origin, params.move, params.observer, params.installFlags, 13413 params.installerPackageName, params.volumeUuid, 13414 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13415 params.grantedRuntimePermissions, 13416 params.traceMethod, params.traceCookie, params.certificates); 13417 if (isFwdLocked()) { 13418 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13419 } 13420 } 13421 13422 /** Existing install */ 13423 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13424 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13425 null, null, null, 0, null /*certificates*/); 13426 this.codeFile = (codePath != null) ? new File(codePath) : null; 13427 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13428 } 13429 13430 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13432 try { 13433 return doCopyApk(imcs, temp); 13434 } finally { 13435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13436 } 13437 } 13438 13439 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13440 if (origin.staged) { 13441 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13442 codeFile = origin.file; 13443 resourceFile = origin.file; 13444 return PackageManager.INSTALL_SUCCEEDED; 13445 } 13446 13447 try { 13448 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13449 final File tempDir = 13450 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13451 codeFile = tempDir; 13452 resourceFile = tempDir; 13453 } catch (IOException e) { 13454 Slog.w(TAG, "Failed to create copy file: " + e); 13455 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13456 } 13457 13458 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13459 @Override 13460 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13461 if (!FileUtils.isValidExtFilename(name)) { 13462 throw new IllegalArgumentException("Invalid filename: " + name); 13463 } 13464 try { 13465 final File file = new File(codeFile, name); 13466 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13467 O_RDWR | O_CREAT, 0644); 13468 Os.chmod(file.getAbsolutePath(), 0644); 13469 return new ParcelFileDescriptor(fd); 13470 } catch (ErrnoException e) { 13471 throw new RemoteException("Failed to open: " + e.getMessage()); 13472 } 13473 } 13474 }; 13475 13476 int ret = PackageManager.INSTALL_SUCCEEDED; 13477 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13478 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13479 Slog.e(TAG, "Failed to copy package"); 13480 return ret; 13481 } 13482 13483 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13484 NativeLibraryHelper.Handle handle = null; 13485 try { 13486 handle = NativeLibraryHelper.Handle.create(codeFile); 13487 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13488 abiOverride); 13489 } catch (IOException e) { 13490 Slog.e(TAG, "Copying native libraries failed", e); 13491 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13492 } finally { 13493 IoUtils.closeQuietly(handle); 13494 } 13495 13496 return ret; 13497 } 13498 13499 int doPreInstall(int status) { 13500 if (status != PackageManager.INSTALL_SUCCEEDED) { 13501 cleanUp(); 13502 } 13503 return status; 13504 } 13505 13506 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13507 if (status != PackageManager.INSTALL_SUCCEEDED) { 13508 cleanUp(); 13509 return false; 13510 } 13511 13512 final File targetDir = codeFile.getParentFile(); 13513 final File beforeCodeFile = codeFile; 13514 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13515 13516 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13517 try { 13518 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13519 } catch (ErrnoException e) { 13520 Slog.w(TAG, "Failed to rename", e); 13521 return false; 13522 } 13523 13524 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13525 Slog.w(TAG, "Failed to restorecon"); 13526 return false; 13527 } 13528 13529 // Reflect the rename internally 13530 codeFile = afterCodeFile; 13531 resourceFile = afterCodeFile; 13532 13533 // Reflect the rename in scanned details 13534 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13535 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13536 afterCodeFile, pkg.baseCodePath)); 13537 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13538 afterCodeFile, pkg.splitCodePaths)); 13539 13540 // Reflect the rename in app info 13541 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13542 pkg.setApplicationInfoCodePath(pkg.codePath); 13543 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13544 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13545 pkg.setApplicationInfoResourcePath(pkg.codePath); 13546 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13547 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13548 13549 return true; 13550 } 13551 13552 int doPostInstall(int status, int uid) { 13553 if (status != PackageManager.INSTALL_SUCCEEDED) { 13554 cleanUp(); 13555 } 13556 return status; 13557 } 13558 13559 @Override 13560 String getCodePath() { 13561 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13562 } 13563 13564 @Override 13565 String getResourcePath() { 13566 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13567 } 13568 13569 private boolean cleanUp() { 13570 if (codeFile == null || !codeFile.exists()) { 13571 return false; 13572 } 13573 13574 removeCodePathLI(codeFile); 13575 13576 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13577 resourceFile.delete(); 13578 } 13579 13580 return true; 13581 } 13582 13583 void cleanUpResourcesLI() { 13584 // Try enumerating all code paths before deleting 13585 List<String> allCodePaths = Collections.EMPTY_LIST; 13586 if (codeFile != null && codeFile.exists()) { 13587 try { 13588 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13589 allCodePaths = pkg.getAllCodePaths(); 13590 } catch (PackageParserException e) { 13591 // Ignored; we tried our best 13592 } 13593 } 13594 13595 cleanUp(); 13596 removeDexFiles(allCodePaths, instructionSets); 13597 } 13598 13599 boolean doPostDeleteLI(boolean delete) { 13600 // XXX err, shouldn't we respect the delete flag? 13601 cleanUpResourcesLI(); 13602 return true; 13603 } 13604 } 13605 13606 private boolean isAsecExternal(String cid) { 13607 final String asecPath = PackageHelper.getSdFilesystem(cid); 13608 return !asecPath.startsWith(mAsecInternalPath); 13609 } 13610 13611 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13612 PackageManagerException { 13613 if (copyRet < 0) { 13614 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13615 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13616 throw new PackageManagerException(copyRet, message); 13617 } 13618 } 13619 } 13620 13621 /** 13622 * Extract the MountService "container ID" from the full code path of an 13623 * .apk. 13624 */ 13625 static String cidFromCodePath(String fullCodePath) { 13626 int eidx = fullCodePath.lastIndexOf("/"); 13627 String subStr1 = fullCodePath.substring(0, eidx); 13628 int sidx = subStr1.lastIndexOf("/"); 13629 return subStr1.substring(sidx+1, eidx); 13630 } 13631 13632 /** 13633 * Logic to handle installation of ASEC applications, including copying and 13634 * renaming logic. 13635 */ 13636 class AsecInstallArgs extends InstallArgs { 13637 static final String RES_FILE_NAME = "pkg.apk"; 13638 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13639 13640 String cid; 13641 String packagePath; 13642 String resourcePath; 13643 13644 /** New install */ 13645 AsecInstallArgs(InstallParams params) { 13646 super(params.origin, params.move, params.observer, params.installFlags, 13647 params.installerPackageName, params.volumeUuid, 13648 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13649 params.grantedRuntimePermissions, 13650 params.traceMethod, params.traceCookie, params.certificates); 13651 } 13652 13653 /** Existing install */ 13654 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13655 boolean isExternal, boolean isForwardLocked) { 13656 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13657 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13658 instructionSets, null, null, null, 0, null /*certificates*/); 13659 // Hackily pretend we're still looking at a full code path 13660 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13661 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13662 } 13663 13664 // Extract cid from fullCodePath 13665 int eidx = fullCodePath.lastIndexOf("/"); 13666 String subStr1 = fullCodePath.substring(0, eidx); 13667 int sidx = subStr1.lastIndexOf("/"); 13668 cid = subStr1.substring(sidx+1, eidx); 13669 setMountPath(subStr1); 13670 } 13671 13672 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13673 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13674 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13675 instructionSets, null, null, null, 0, null /*certificates*/); 13676 this.cid = cid; 13677 setMountPath(PackageHelper.getSdDir(cid)); 13678 } 13679 13680 void createCopyFile() { 13681 cid = mInstallerService.allocateExternalStageCidLegacy(); 13682 } 13683 13684 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13685 if (origin.staged && origin.cid != null) { 13686 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13687 cid = origin.cid; 13688 setMountPath(PackageHelper.getSdDir(cid)); 13689 return PackageManager.INSTALL_SUCCEEDED; 13690 } 13691 13692 if (temp) { 13693 createCopyFile(); 13694 } else { 13695 /* 13696 * Pre-emptively destroy the container since it's destroyed if 13697 * copying fails due to it existing anyway. 13698 */ 13699 PackageHelper.destroySdDir(cid); 13700 } 13701 13702 final String newMountPath = imcs.copyPackageToContainer( 13703 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13704 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13705 13706 if (newMountPath != null) { 13707 setMountPath(newMountPath); 13708 return PackageManager.INSTALL_SUCCEEDED; 13709 } else { 13710 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13711 } 13712 } 13713 13714 @Override 13715 String getCodePath() { 13716 return packagePath; 13717 } 13718 13719 @Override 13720 String getResourcePath() { 13721 return resourcePath; 13722 } 13723 13724 int doPreInstall(int status) { 13725 if (status != PackageManager.INSTALL_SUCCEEDED) { 13726 // Destroy container 13727 PackageHelper.destroySdDir(cid); 13728 } else { 13729 boolean mounted = PackageHelper.isContainerMounted(cid); 13730 if (!mounted) { 13731 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13732 Process.SYSTEM_UID); 13733 if (newMountPath != null) { 13734 setMountPath(newMountPath); 13735 } else { 13736 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13737 } 13738 } 13739 } 13740 return status; 13741 } 13742 13743 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13744 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13745 String newMountPath = null; 13746 if (PackageHelper.isContainerMounted(cid)) { 13747 // Unmount the container 13748 if (!PackageHelper.unMountSdDir(cid)) { 13749 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13750 return false; 13751 } 13752 } 13753 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13754 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13755 " which might be stale. Will try to clean up."); 13756 // Clean up the stale container and proceed to recreate. 13757 if (!PackageHelper.destroySdDir(newCacheId)) { 13758 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13759 return false; 13760 } 13761 // Successfully cleaned up stale container. Try to rename again. 13762 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13763 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13764 + " inspite of cleaning it up."); 13765 return false; 13766 } 13767 } 13768 if (!PackageHelper.isContainerMounted(newCacheId)) { 13769 Slog.w(TAG, "Mounting container " + newCacheId); 13770 newMountPath = PackageHelper.mountSdDir(newCacheId, 13771 getEncryptKey(), Process.SYSTEM_UID); 13772 } else { 13773 newMountPath = PackageHelper.getSdDir(newCacheId); 13774 } 13775 if (newMountPath == null) { 13776 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13777 return false; 13778 } 13779 Log.i(TAG, "Succesfully renamed " + cid + 13780 " to " + newCacheId + 13781 " at new path: " + newMountPath); 13782 cid = newCacheId; 13783 13784 final File beforeCodeFile = new File(packagePath); 13785 setMountPath(newMountPath); 13786 final File afterCodeFile = new File(packagePath); 13787 13788 // Reflect the rename in scanned details 13789 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13790 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13791 afterCodeFile, pkg.baseCodePath)); 13792 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13793 afterCodeFile, pkg.splitCodePaths)); 13794 13795 // Reflect the rename in app info 13796 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13797 pkg.setApplicationInfoCodePath(pkg.codePath); 13798 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13799 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13800 pkg.setApplicationInfoResourcePath(pkg.codePath); 13801 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13802 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13803 13804 return true; 13805 } 13806 13807 private void setMountPath(String mountPath) { 13808 final File mountFile = new File(mountPath); 13809 13810 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13811 if (monolithicFile.exists()) { 13812 packagePath = monolithicFile.getAbsolutePath(); 13813 if (isFwdLocked()) { 13814 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13815 } else { 13816 resourcePath = packagePath; 13817 } 13818 } else { 13819 packagePath = mountFile.getAbsolutePath(); 13820 resourcePath = packagePath; 13821 } 13822 } 13823 13824 int doPostInstall(int status, int uid) { 13825 if (status != PackageManager.INSTALL_SUCCEEDED) { 13826 cleanUp(); 13827 } else { 13828 final int groupOwner; 13829 final String protectedFile; 13830 if (isFwdLocked()) { 13831 groupOwner = UserHandle.getSharedAppGid(uid); 13832 protectedFile = RES_FILE_NAME; 13833 } else { 13834 groupOwner = -1; 13835 protectedFile = null; 13836 } 13837 13838 if (uid < Process.FIRST_APPLICATION_UID 13839 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13840 Slog.e(TAG, "Failed to finalize " + cid); 13841 PackageHelper.destroySdDir(cid); 13842 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13843 } 13844 13845 boolean mounted = PackageHelper.isContainerMounted(cid); 13846 if (!mounted) { 13847 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13848 } 13849 } 13850 return status; 13851 } 13852 13853 private void cleanUp() { 13854 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13855 13856 // Destroy secure container 13857 PackageHelper.destroySdDir(cid); 13858 } 13859 13860 private List<String> getAllCodePaths() { 13861 final File codeFile = new File(getCodePath()); 13862 if (codeFile != null && codeFile.exists()) { 13863 try { 13864 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13865 return pkg.getAllCodePaths(); 13866 } catch (PackageParserException e) { 13867 // Ignored; we tried our best 13868 } 13869 } 13870 return Collections.EMPTY_LIST; 13871 } 13872 13873 void cleanUpResourcesLI() { 13874 // Enumerate all code paths before deleting 13875 cleanUpResourcesLI(getAllCodePaths()); 13876 } 13877 13878 private void cleanUpResourcesLI(List<String> allCodePaths) { 13879 cleanUp(); 13880 removeDexFiles(allCodePaths, instructionSets); 13881 } 13882 13883 String getPackageName() { 13884 return getAsecPackageName(cid); 13885 } 13886 13887 boolean doPostDeleteLI(boolean delete) { 13888 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13889 final List<String> allCodePaths = getAllCodePaths(); 13890 boolean mounted = PackageHelper.isContainerMounted(cid); 13891 if (mounted) { 13892 // Unmount first 13893 if (PackageHelper.unMountSdDir(cid)) { 13894 mounted = false; 13895 } 13896 } 13897 if (!mounted && delete) { 13898 cleanUpResourcesLI(allCodePaths); 13899 } 13900 return !mounted; 13901 } 13902 13903 @Override 13904 int doPreCopy() { 13905 if (isFwdLocked()) { 13906 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13907 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13908 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13909 } 13910 } 13911 13912 return PackageManager.INSTALL_SUCCEEDED; 13913 } 13914 13915 @Override 13916 int doPostCopy(int uid) { 13917 if (isFwdLocked()) { 13918 if (uid < Process.FIRST_APPLICATION_UID 13919 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13920 RES_FILE_NAME)) { 13921 Slog.e(TAG, "Failed to finalize " + cid); 13922 PackageHelper.destroySdDir(cid); 13923 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13924 } 13925 } 13926 13927 return PackageManager.INSTALL_SUCCEEDED; 13928 } 13929 } 13930 13931 /** 13932 * Logic to handle movement of existing installed applications. 13933 */ 13934 class MoveInstallArgs extends InstallArgs { 13935 private File codeFile; 13936 private File resourceFile; 13937 13938 /** New install */ 13939 MoveInstallArgs(InstallParams params) { 13940 super(params.origin, params.move, params.observer, params.installFlags, 13941 params.installerPackageName, params.volumeUuid, 13942 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13943 params.grantedRuntimePermissions, 13944 params.traceMethod, params.traceCookie, params.certificates); 13945 } 13946 13947 int copyApk(IMediaContainerService imcs, boolean temp) { 13948 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13949 + move.fromUuid + " to " + move.toUuid); 13950 synchronized (mInstaller) { 13951 try { 13952 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13953 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13954 } catch (InstallerException e) { 13955 Slog.w(TAG, "Failed to move app", e); 13956 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13957 } 13958 } 13959 13960 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13961 resourceFile = codeFile; 13962 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13963 13964 return PackageManager.INSTALL_SUCCEEDED; 13965 } 13966 13967 int doPreInstall(int status) { 13968 if (status != PackageManager.INSTALL_SUCCEEDED) { 13969 cleanUp(move.toUuid); 13970 } 13971 return status; 13972 } 13973 13974 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13975 if (status != PackageManager.INSTALL_SUCCEEDED) { 13976 cleanUp(move.toUuid); 13977 return false; 13978 } 13979 13980 // Reflect the move in app info 13981 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13982 pkg.setApplicationInfoCodePath(pkg.codePath); 13983 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13984 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13985 pkg.setApplicationInfoResourcePath(pkg.codePath); 13986 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13987 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13988 13989 return true; 13990 } 13991 13992 int doPostInstall(int status, int uid) { 13993 if (status == PackageManager.INSTALL_SUCCEEDED) { 13994 cleanUp(move.fromUuid); 13995 } else { 13996 cleanUp(move.toUuid); 13997 } 13998 return status; 13999 } 14000 14001 @Override 14002 String getCodePath() { 14003 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14004 } 14005 14006 @Override 14007 String getResourcePath() { 14008 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14009 } 14010 14011 private boolean cleanUp(String volumeUuid) { 14012 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14013 move.dataAppName); 14014 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14015 final int[] userIds = sUserManager.getUserIds(); 14016 synchronized (mInstallLock) { 14017 // Clean up both app data and code 14018 // All package moves are frozen until finished 14019 for (int userId : userIds) { 14020 try { 14021 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14022 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14023 } catch (InstallerException e) { 14024 Slog.w(TAG, String.valueOf(e)); 14025 } 14026 } 14027 removeCodePathLI(codeFile); 14028 } 14029 return true; 14030 } 14031 14032 void cleanUpResourcesLI() { 14033 throw new UnsupportedOperationException(); 14034 } 14035 14036 boolean doPostDeleteLI(boolean delete) { 14037 throw new UnsupportedOperationException(); 14038 } 14039 } 14040 14041 static String getAsecPackageName(String packageCid) { 14042 int idx = packageCid.lastIndexOf("-"); 14043 if (idx == -1) { 14044 return packageCid; 14045 } 14046 return packageCid.substring(0, idx); 14047 } 14048 14049 // Utility method used to create code paths based on package name and available index. 14050 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14051 String idxStr = ""; 14052 int idx = 1; 14053 // Fall back to default value of idx=1 if prefix is not 14054 // part of oldCodePath 14055 if (oldCodePath != null) { 14056 String subStr = oldCodePath; 14057 // Drop the suffix right away 14058 if (suffix != null && subStr.endsWith(suffix)) { 14059 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14060 } 14061 // If oldCodePath already contains prefix find out the 14062 // ending index to either increment or decrement. 14063 int sidx = subStr.lastIndexOf(prefix); 14064 if (sidx != -1) { 14065 subStr = subStr.substring(sidx + prefix.length()); 14066 if (subStr != null) { 14067 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14068 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14069 } 14070 try { 14071 idx = Integer.parseInt(subStr); 14072 if (idx <= 1) { 14073 idx++; 14074 } else { 14075 idx--; 14076 } 14077 } catch(NumberFormatException e) { 14078 } 14079 } 14080 } 14081 } 14082 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14083 return prefix + idxStr; 14084 } 14085 14086 private File getNextCodePath(File targetDir, String packageName) { 14087 int suffix = 1; 14088 File result; 14089 do { 14090 result = new File(targetDir, packageName + "-" + suffix); 14091 suffix++; 14092 } while (result.exists()); 14093 return result; 14094 } 14095 14096 // Utility method that returns the relative package path with respect 14097 // to the installation directory. Like say for /data/data/com.test-1.apk 14098 // string com.test-1 is returned. 14099 static String deriveCodePathName(String codePath) { 14100 if (codePath == null) { 14101 return null; 14102 } 14103 final File codeFile = new File(codePath); 14104 final String name = codeFile.getName(); 14105 if (codeFile.isDirectory()) { 14106 return name; 14107 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14108 final int lastDot = name.lastIndexOf('.'); 14109 return name.substring(0, lastDot); 14110 } else { 14111 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14112 return null; 14113 } 14114 } 14115 14116 static class PackageInstalledInfo { 14117 String name; 14118 int uid; 14119 // The set of users that originally had this package installed. 14120 int[] origUsers; 14121 // The set of users that now have this package installed. 14122 int[] newUsers; 14123 PackageParser.Package pkg; 14124 int returnCode; 14125 String returnMsg; 14126 PackageRemovedInfo removedInfo; 14127 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14128 14129 public void setError(int code, String msg) { 14130 setReturnCode(code); 14131 setReturnMessage(msg); 14132 Slog.w(TAG, msg); 14133 } 14134 14135 public void setError(String msg, PackageParserException e) { 14136 setReturnCode(e.error); 14137 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14138 Slog.w(TAG, msg, e); 14139 } 14140 14141 public void setError(String msg, PackageManagerException e) { 14142 returnCode = e.error; 14143 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14144 Slog.w(TAG, msg, e); 14145 } 14146 14147 public void setReturnCode(int returnCode) { 14148 this.returnCode = returnCode; 14149 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14150 for (int i = 0; i < childCount; i++) { 14151 addedChildPackages.valueAt(i).returnCode = returnCode; 14152 } 14153 } 14154 14155 private void setReturnMessage(String returnMsg) { 14156 this.returnMsg = returnMsg; 14157 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14158 for (int i = 0; i < childCount; i++) { 14159 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14160 } 14161 } 14162 14163 // In some error cases we want to convey more info back to the observer 14164 String origPackage; 14165 String origPermission; 14166 } 14167 14168 /* 14169 * Install a non-existing package. 14170 */ 14171 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14172 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14173 PackageInstalledInfo res) { 14174 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14175 14176 // Remember this for later, in case we need to rollback this install 14177 String pkgName = pkg.packageName; 14178 14179 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14180 14181 synchronized(mPackages) { 14182 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14183 // A package with the same name is already installed, though 14184 // it has been renamed to an older name. The package we 14185 // are trying to install should be installed as an update to 14186 // the existing one, but that has not been requested, so bail. 14187 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14188 + " without first uninstalling package running as " 14189 + mSettings.mRenamedPackages.get(pkgName)); 14190 return; 14191 } 14192 if (mPackages.containsKey(pkgName)) { 14193 // Don't allow installation over an existing package with the same name. 14194 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14195 + " without first uninstalling."); 14196 return; 14197 } 14198 } 14199 14200 try { 14201 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14202 System.currentTimeMillis(), user); 14203 14204 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14205 14206 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14207 prepareAppDataAfterInstallLIF(newPackage); 14208 14209 } else { 14210 // Remove package from internal structures, but keep around any 14211 // data that might have already existed 14212 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14213 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14214 } 14215 } catch (PackageManagerException e) { 14216 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14217 } 14218 14219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14220 } 14221 14222 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14223 // Can't rotate keys during boot or if sharedUser. 14224 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14225 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14226 return false; 14227 } 14228 // app is using upgradeKeySets; make sure all are valid 14229 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14230 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14231 for (int i = 0; i < upgradeKeySets.length; i++) { 14232 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14233 Slog.wtf(TAG, "Package " 14234 + (oldPs.name != null ? oldPs.name : "<null>") 14235 + " contains upgrade-key-set reference to unknown key-set: " 14236 + upgradeKeySets[i] 14237 + " reverting to signatures check."); 14238 return false; 14239 } 14240 } 14241 return true; 14242 } 14243 14244 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14245 // Upgrade keysets are being used. Determine if new package has a superset of the 14246 // required keys. 14247 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14248 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14249 for (int i = 0; i < upgradeKeySets.length; i++) { 14250 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14251 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14252 return true; 14253 } 14254 } 14255 return false; 14256 } 14257 14258 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14259 try (DigestInputStream digestStream = 14260 new DigestInputStream(new FileInputStream(file), digest)) { 14261 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14262 } 14263 } 14264 14265 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14266 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14267 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14268 14269 final PackageParser.Package oldPackage; 14270 final String pkgName = pkg.packageName; 14271 final int[] allUsers; 14272 final int[] installedUsers; 14273 14274 synchronized(mPackages) { 14275 oldPackage = mPackages.get(pkgName); 14276 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14277 14278 // don't allow upgrade to target a release SDK from a pre-release SDK 14279 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14280 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14281 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14282 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14283 if (oldTargetsPreRelease 14284 && !newTargetsPreRelease 14285 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14286 Slog.w(TAG, "Can't install package targeting released sdk"); 14287 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14288 return; 14289 } 14290 14291 // don't allow an upgrade from full to ephemeral 14292 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14293 if (isEphemeral && !oldIsEphemeral) { 14294 // can't downgrade from full to ephemeral 14295 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14296 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14297 return; 14298 } 14299 14300 // verify signatures are valid 14301 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14302 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14303 if (!checkUpgradeKeySetLP(ps, pkg)) { 14304 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14305 "New package not signed by keys specified by upgrade-keysets: " 14306 + pkgName); 14307 return; 14308 } 14309 } else { 14310 // default to original signature matching 14311 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14312 != PackageManager.SIGNATURE_MATCH) { 14313 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14314 "New package has a different signature: " + pkgName); 14315 return; 14316 } 14317 } 14318 14319 // don't allow a system upgrade unless the upgrade hash matches 14320 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14321 byte[] digestBytes = null; 14322 try { 14323 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14324 updateDigest(digest, new File(pkg.baseCodePath)); 14325 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14326 for (String path : pkg.splitCodePaths) { 14327 updateDigest(digest, new File(path)); 14328 } 14329 } 14330 digestBytes = digest.digest(); 14331 } catch (NoSuchAlgorithmException | IOException e) { 14332 res.setError(INSTALL_FAILED_INVALID_APK, 14333 "Could not compute hash: " + pkgName); 14334 return; 14335 } 14336 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14337 res.setError(INSTALL_FAILED_INVALID_APK, 14338 "New package fails restrict-update check: " + pkgName); 14339 return; 14340 } 14341 // retain upgrade restriction 14342 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14343 } 14344 14345 // Check for shared user id changes 14346 String invalidPackageName = 14347 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14348 if (invalidPackageName != null) { 14349 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14350 "Package " + invalidPackageName + " tried to change user " 14351 + oldPackage.mSharedUserId); 14352 return; 14353 } 14354 14355 // In case of rollback, remember per-user/profile install state 14356 allUsers = sUserManager.getUserIds(); 14357 installedUsers = ps.queryInstalledUsers(allUsers, true); 14358 } 14359 14360 // Update what is removed 14361 res.removedInfo = new PackageRemovedInfo(); 14362 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14363 res.removedInfo.removedPackage = oldPackage.packageName; 14364 res.removedInfo.isUpdate = true; 14365 res.removedInfo.origUsers = installedUsers; 14366 final int childCount = (oldPackage.childPackages != null) 14367 ? oldPackage.childPackages.size() : 0; 14368 for (int i = 0; i < childCount; i++) { 14369 boolean childPackageUpdated = false; 14370 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14371 if (res.addedChildPackages != null) { 14372 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14373 if (childRes != null) { 14374 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14375 childRes.removedInfo.removedPackage = childPkg.packageName; 14376 childRes.removedInfo.isUpdate = true; 14377 childPackageUpdated = true; 14378 } 14379 } 14380 if (!childPackageUpdated) { 14381 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14382 childRemovedRes.removedPackage = childPkg.packageName; 14383 childRemovedRes.isUpdate = false; 14384 childRemovedRes.dataRemoved = true; 14385 synchronized (mPackages) { 14386 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14387 if (childPs != null) { 14388 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14389 } 14390 } 14391 if (res.removedInfo.removedChildPackages == null) { 14392 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14393 } 14394 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14395 } 14396 } 14397 14398 boolean sysPkg = (isSystemApp(oldPackage)); 14399 if (sysPkg) { 14400 // Set the system/privileged flags as needed 14401 final boolean privileged = 14402 (oldPackage.applicationInfo.privateFlags 14403 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14404 final int systemPolicyFlags = policyFlags 14405 | PackageParser.PARSE_IS_SYSTEM 14406 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14407 14408 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14409 user, allUsers, installerPackageName, res); 14410 } else { 14411 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14412 user, allUsers, installerPackageName, res); 14413 } 14414 } 14415 14416 public List<String> getPreviousCodePaths(String packageName) { 14417 final PackageSetting ps = mSettings.mPackages.get(packageName); 14418 final List<String> result = new ArrayList<String>(); 14419 if (ps != null && ps.oldCodePaths != null) { 14420 result.addAll(ps.oldCodePaths); 14421 } 14422 return result; 14423 } 14424 14425 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14426 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14427 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14428 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14429 + deletedPackage); 14430 14431 String pkgName = deletedPackage.packageName; 14432 boolean deletedPkg = true; 14433 boolean addedPkg = false; 14434 boolean updatedSettings = false; 14435 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14436 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14437 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14438 14439 final long origUpdateTime = (pkg.mExtras != null) 14440 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14441 14442 // First delete the existing package while retaining the data directory 14443 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14444 res.removedInfo, true, pkg)) { 14445 // If the existing package wasn't successfully deleted 14446 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14447 deletedPkg = false; 14448 } else { 14449 // Successfully deleted the old package; proceed with replace. 14450 14451 // If deleted package lived in a container, give users a chance to 14452 // relinquish resources before killing. 14453 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14454 if (DEBUG_INSTALL) { 14455 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14456 } 14457 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14458 final ArrayList<String> pkgList = new ArrayList<String>(1); 14459 pkgList.add(deletedPackage.applicationInfo.packageName); 14460 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14461 } 14462 14463 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14464 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14465 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14466 14467 try { 14468 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14469 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14470 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14471 14472 // Update the in-memory copy of the previous code paths. 14473 PackageSetting ps = mSettings.mPackages.get(pkgName); 14474 if (!killApp) { 14475 if (ps.oldCodePaths == null) { 14476 ps.oldCodePaths = new ArraySet<>(); 14477 } 14478 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14479 if (deletedPackage.splitCodePaths != null) { 14480 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14481 } 14482 } else { 14483 ps.oldCodePaths = null; 14484 } 14485 if (ps.childPackageNames != null) { 14486 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14487 final String childPkgName = ps.childPackageNames.get(i); 14488 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14489 childPs.oldCodePaths = ps.oldCodePaths; 14490 } 14491 } 14492 prepareAppDataAfterInstallLIF(newPackage); 14493 addedPkg = true; 14494 } catch (PackageManagerException e) { 14495 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14496 } 14497 } 14498 14499 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14500 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14501 14502 // Revert all internal state mutations and added folders for the failed install 14503 if (addedPkg) { 14504 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14505 res.removedInfo, true, null); 14506 } 14507 14508 // Restore the old package 14509 if (deletedPkg) { 14510 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14511 File restoreFile = new File(deletedPackage.codePath); 14512 // Parse old package 14513 boolean oldExternal = isExternal(deletedPackage); 14514 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14515 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14516 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14517 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14518 try { 14519 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14520 null); 14521 } catch (PackageManagerException e) { 14522 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14523 + e.getMessage()); 14524 return; 14525 } 14526 14527 synchronized (mPackages) { 14528 // Ensure the installer package name up to date 14529 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14530 14531 // Update permissions for restored package 14532 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14533 14534 mSettings.writeLPr(); 14535 } 14536 14537 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14538 } 14539 } else { 14540 synchronized (mPackages) { 14541 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14542 if (ps != null) { 14543 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14544 if (res.removedInfo.removedChildPackages != null) { 14545 final int childCount = res.removedInfo.removedChildPackages.size(); 14546 // Iterate in reverse as we may modify the collection 14547 for (int i = childCount - 1; i >= 0; i--) { 14548 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14549 if (res.addedChildPackages.containsKey(childPackageName)) { 14550 res.removedInfo.removedChildPackages.removeAt(i); 14551 } else { 14552 PackageRemovedInfo childInfo = res.removedInfo 14553 .removedChildPackages.valueAt(i); 14554 childInfo.removedForAllUsers = mPackages.get( 14555 childInfo.removedPackage) == null; 14556 } 14557 } 14558 } 14559 } 14560 } 14561 } 14562 } 14563 14564 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14565 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14566 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14567 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14568 + ", old=" + deletedPackage); 14569 14570 final boolean disabledSystem; 14571 14572 // Remove existing system package 14573 removePackageLI(deletedPackage, true); 14574 14575 synchronized (mPackages) { 14576 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14577 } 14578 if (!disabledSystem) { 14579 // We didn't need to disable the .apk as a current system package, 14580 // which means we are replacing another update that is already 14581 // installed. We need to make sure to delete the older one's .apk. 14582 res.removedInfo.args = createInstallArgsForExisting(0, 14583 deletedPackage.applicationInfo.getCodePath(), 14584 deletedPackage.applicationInfo.getResourcePath(), 14585 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14586 } else { 14587 res.removedInfo.args = null; 14588 } 14589 14590 // Successfully disabled the old package. Now proceed with re-installation 14591 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14592 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14593 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14594 14595 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14596 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14597 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14598 14599 PackageParser.Package newPackage = null; 14600 try { 14601 // Add the package to the internal data structures 14602 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14603 14604 // Set the update and install times 14605 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14606 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14607 System.currentTimeMillis()); 14608 14609 // Update the package dynamic state if succeeded 14610 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14611 // Now that the install succeeded make sure we remove data 14612 // directories for any child package the update removed. 14613 final int deletedChildCount = (deletedPackage.childPackages != null) 14614 ? deletedPackage.childPackages.size() : 0; 14615 final int newChildCount = (newPackage.childPackages != null) 14616 ? newPackage.childPackages.size() : 0; 14617 for (int i = 0; i < deletedChildCount; i++) { 14618 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14619 boolean childPackageDeleted = true; 14620 for (int j = 0; j < newChildCount; j++) { 14621 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14622 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14623 childPackageDeleted = false; 14624 break; 14625 } 14626 } 14627 if (childPackageDeleted) { 14628 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14629 deletedChildPkg.packageName); 14630 if (ps != null && res.removedInfo.removedChildPackages != null) { 14631 PackageRemovedInfo removedChildRes = res.removedInfo 14632 .removedChildPackages.get(deletedChildPkg.packageName); 14633 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14634 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14635 } 14636 } 14637 } 14638 14639 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14640 prepareAppDataAfterInstallLIF(newPackage); 14641 } 14642 } catch (PackageManagerException e) { 14643 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14644 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14645 } 14646 14647 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14648 // Re installation failed. Restore old information 14649 // Remove new pkg information 14650 if (newPackage != null) { 14651 removeInstalledPackageLI(newPackage, true); 14652 } 14653 // Add back the old system package 14654 try { 14655 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14656 } catch (PackageManagerException e) { 14657 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14658 } 14659 14660 synchronized (mPackages) { 14661 if (disabledSystem) { 14662 enableSystemPackageLPw(deletedPackage); 14663 } 14664 14665 // Ensure the installer package name up to date 14666 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14667 14668 // Update permissions for restored package 14669 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14670 14671 mSettings.writeLPr(); 14672 } 14673 14674 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14675 + " after failed upgrade"); 14676 } 14677 } 14678 14679 /** 14680 * Checks whether the parent or any of the child packages have a change shared 14681 * user. For a package to be a valid update the shred users of the parent and 14682 * the children should match. We may later support changing child shared users. 14683 * @param oldPkg The updated package. 14684 * @param newPkg The update package. 14685 * @return The shared user that change between the versions. 14686 */ 14687 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14688 PackageParser.Package newPkg) { 14689 // Check parent shared user 14690 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14691 return newPkg.packageName; 14692 } 14693 // Check child shared users 14694 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14695 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14696 for (int i = 0; i < newChildCount; i++) { 14697 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14698 // If this child was present, did it have the same shared user? 14699 for (int j = 0; j < oldChildCount; j++) { 14700 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14701 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14702 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14703 return newChildPkg.packageName; 14704 } 14705 } 14706 } 14707 return null; 14708 } 14709 14710 private void removeNativeBinariesLI(PackageSetting ps) { 14711 // Remove the lib path for the parent package 14712 if (ps != null) { 14713 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14714 // Remove the lib path for the child packages 14715 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14716 for (int i = 0; i < childCount; i++) { 14717 PackageSetting childPs = null; 14718 synchronized (mPackages) { 14719 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14720 } 14721 if (childPs != null) { 14722 NativeLibraryHelper.removeNativeBinariesLI(childPs 14723 .legacyNativeLibraryPathString); 14724 } 14725 } 14726 } 14727 } 14728 14729 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14730 // Enable the parent package 14731 mSettings.enableSystemPackageLPw(pkg.packageName); 14732 // Enable the child packages 14733 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14734 for (int i = 0; i < childCount; i++) { 14735 PackageParser.Package childPkg = pkg.childPackages.get(i); 14736 mSettings.enableSystemPackageLPw(childPkg.packageName); 14737 } 14738 } 14739 14740 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14741 PackageParser.Package newPkg) { 14742 // Disable the parent package (parent always replaced) 14743 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14744 // Disable the child packages 14745 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14746 for (int i = 0; i < childCount; i++) { 14747 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14748 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14749 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14750 } 14751 return disabled; 14752 } 14753 14754 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14755 String installerPackageName) { 14756 // Enable the parent package 14757 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14758 // Enable the child packages 14759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14760 for (int i = 0; i < childCount; i++) { 14761 PackageParser.Package childPkg = pkg.childPackages.get(i); 14762 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14763 } 14764 } 14765 14766 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14767 // Collect all used permissions in the UID 14768 ArraySet<String> usedPermissions = new ArraySet<>(); 14769 final int packageCount = su.packages.size(); 14770 for (int i = 0; i < packageCount; i++) { 14771 PackageSetting ps = su.packages.valueAt(i); 14772 if (ps.pkg == null) { 14773 continue; 14774 } 14775 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14776 for (int j = 0; j < requestedPermCount; j++) { 14777 String permission = ps.pkg.requestedPermissions.get(j); 14778 BasePermission bp = mSettings.mPermissions.get(permission); 14779 if (bp != null) { 14780 usedPermissions.add(permission); 14781 } 14782 } 14783 } 14784 14785 PermissionsState permissionsState = su.getPermissionsState(); 14786 // Prune install permissions 14787 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14788 final int installPermCount = installPermStates.size(); 14789 for (int i = installPermCount - 1; i >= 0; i--) { 14790 PermissionState permissionState = installPermStates.get(i); 14791 if (!usedPermissions.contains(permissionState.getName())) { 14792 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14793 if (bp != null) { 14794 permissionsState.revokeInstallPermission(bp); 14795 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14796 PackageManager.MASK_PERMISSION_FLAGS, 0); 14797 } 14798 } 14799 } 14800 14801 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14802 14803 // Prune runtime permissions 14804 for (int userId : allUserIds) { 14805 List<PermissionState> runtimePermStates = permissionsState 14806 .getRuntimePermissionStates(userId); 14807 final int runtimePermCount = runtimePermStates.size(); 14808 for (int i = runtimePermCount - 1; i >= 0; i--) { 14809 PermissionState permissionState = runtimePermStates.get(i); 14810 if (!usedPermissions.contains(permissionState.getName())) { 14811 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14812 if (bp != null) { 14813 permissionsState.revokeRuntimePermission(bp, userId); 14814 permissionsState.updatePermissionFlags(bp, userId, 14815 PackageManager.MASK_PERMISSION_FLAGS, 0); 14816 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14817 runtimePermissionChangedUserIds, userId); 14818 } 14819 } 14820 } 14821 } 14822 14823 return runtimePermissionChangedUserIds; 14824 } 14825 14826 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14827 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14828 // Update the parent package setting 14829 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14830 res, user); 14831 // Update the child packages setting 14832 final int childCount = (newPackage.childPackages != null) 14833 ? newPackage.childPackages.size() : 0; 14834 for (int i = 0; i < childCount; i++) { 14835 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14836 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14837 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14838 childRes.origUsers, childRes, user); 14839 } 14840 } 14841 14842 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14843 String installerPackageName, int[] allUsers, int[] installedForUsers, 14844 PackageInstalledInfo res, UserHandle user) { 14845 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14846 14847 String pkgName = newPackage.packageName; 14848 synchronized (mPackages) { 14849 //write settings. the installStatus will be incomplete at this stage. 14850 //note that the new package setting would have already been 14851 //added to mPackages. It hasn't been persisted yet. 14852 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14854 mSettings.writeLPr(); 14855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14856 } 14857 14858 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14859 synchronized (mPackages) { 14860 updatePermissionsLPw(newPackage.packageName, newPackage, 14861 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14862 ? UPDATE_PERMISSIONS_ALL : 0)); 14863 // For system-bundled packages, we assume that installing an upgraded version 14864 // of the package implies that the user actually wants to run that new code, 14865 // so we enable the package. 14866 PackageSetting ps = mSettings.mPackages.get(pkgName); 14867 final int userId = user.getIdentifier(); 14868 if (ps != null) { 14869 if (isSystemApp(newPackage)) { 14870 if (DEBUG_INSTALL) { 14871 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14872 } 14873 // Enable system package for requested users 14874 if (res.origUsers != null) { 14875 for (int origUserId : res.origUsers) { 14876 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14877 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14878 origUserId, installerPackageName); 14879 } 14880 } 14881 } 14882 // Also convey the prior install/uninstall state 14883 if (allUsers != null && installedForUsers != null) { 14884 for (int currentUserId : allUsers) { 14885 final boolean installed = ArrayUtils.contains( 14886 installedForUsers, currentUserId); 14887 if (DEBUG_INSTALL) { 14888 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14889 } 14890 ps.setInstalled(installed, currentUserId); 14891 } 14892 // these install state changes will be persisted in the 14893 // upcoming call to mSettings.writeLPr(). 14894 } 14895 } 14896 // It's implied that when a user requests installation, they want the app to be 14897 // installed and enabled. 14898 if (userId != UserHandle.USER_ALL) { 14899 ps.setInstalled(true, userId); 14900 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14901 } 14902 } 14903 res.name = pkgName; 14904 res.uid = newPackage.applicationInfo.uid; 14905 res.pkg = newPackage; 14906 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14907 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14908 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14909 //to update install status 14910 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14911 mSettings.writeLPr(); 14912 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14913 } 14914 14915 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14916 } 14917 14918 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14919 try { 14920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14921 installPackageLI(args, res); 14922 } finally { 14923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14924 } 14925 } 14926 14927 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14928 final int installFlags = args.installFlags; 14929 final String installerPackageName = args.installerPackageName; 14930 final String volumeUuid = args.volumeUuid; 14931 final File tmpPackageFile = new File(args.getCodePath()); 14932 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14933 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14934 || (args.volumeUuid != null)); 14935 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14936 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14937 boolean replace = false; 14938 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14939 if (args.move != null) { 14940 // moving a complete application; perform an initial scan on the new install location 14941 scanFlags |= SCAN_INITIAL; 14942 } 14943 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14944 scanFlags |= SCAN_DONT_KILL_APP; 14945 } 14946 14947 // Result object to be returned 14948 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14949 14950 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14951 14952 // Sanity check 14953 if (ephemeral && (forwardLocked || onExternal)) { 14954 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14955 + " external=" + onExternal); 14956 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14957 return; 14958 } 14959 14960 // Retrieve PackageSettings and parse package 14961 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14962 | PackageParser.PARSE_ENFORCE_CODE 14963 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14964 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14965 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14966 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14967 PackageParser pp = new PackageParser(); 14968 pp.setSeparateProcesses(mSeparateProcesses); 14969 pp.setDisplayMetrics(mMetrics); 14970 14971 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14972 final PackageParser.Package pkg; 14973 try { 14974 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14975 } catch (PackageParserException e) { 14976 res.setError("Failed parse during installPackageLI", e); 14977 return; 14978 } finally { 14979 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14980 } 14981 14982 // If we are installing a clustered package add results for the children 14983 if (pkg.childPackages != null) { 14984 synchronized (mPackages) { 14985 final int childCount = pkg.childPackages.size(); 14986 for (int i = 0; i < childCount; i++) { 14987 PackageParser.Package childPkg = pkg.childPackages.get(i); 14988 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14989 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14990 childRes.pkg = childPkg; 14991 childRes.name = childPkg.packageName; 14992 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14993 if (childPs != null) { 14994 childRes.origUsers = childPs.queryInstalledUsers( 14995 sUserManager.getUserIds(), true); 14996 } 14997 if ((mPackages.containsKey(childPkg.packageName))) { 14998 childRes.removedInfo = new PackageRemovedInfo(); 14999 childRes.removedInfo.removedPackage = childPkg.packageName; 15000 } 15001 if (res.addedChildPackages == null) { 15002 res.addedChildPackages = new ArrayMap<>(); 15003 } 15004 res.addedChildPackages.put(childPkg.packageName, childRes); 15005 } 15006 } 15007 } 15008 15009 // If package doesn't declare API override, mark that we have an install 15010 // time CPU ABI override. 15011 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15012 pkg.cpuAbiOverride = args.abiOverride; 15013 } 15014 15015 String pkgName = res.name = pkg.packageName; 15016 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15017 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15018 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15019 return; 15020 } 15021 } 15022 15023 try { 15024 // either use what we've been given or parse directly from the APK 15025 if (args.certificates != null) { 15026 try { 15027 PackageParser.populateCertificates(pkg, args.certificates); 15028 } catch (PackageParserException e) { 15029 // there was something wrong with the certificates we were given; 15030 // try to pull them from the APK 15031 PackageParser.collectCertificates(pkg, parseFlags); 15032 } 15033 } else { 15034 PackageParser.collectCertificates(pkg, parseFlags); 15035 } 15036 } catch (PackageParserException e) { 15037 res.setError("Failed collect during installPackageLI", e); 15038 return; 15039 } 15040 15041 // Get rid of all references to package scan path via parser. 15042 pp = null; 15043 String oldCodePath = null; 15044 boolean systemApp = false; 15045 synchronized (mPackages) { 15046 // Check if installing already existing package 15047 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15048 String oldName = mSettings.mRenamedPackages.get(pkgName); 15049 if (pkg.mOriginalPackages != null 15050 && pkg.mOriginalPackages.contains(oldName) 15051 && mPackages.containsKey(oldName)) { 15052 // This package is derived from an original package, 15053 // and this device has been updating from that original 15054 // name. We must continue using the original name, so 15055 // rename the new package here. 15056 pkg.setPackageName(oldName); 15057 pkgName = pkg.packageName; 15058 replace = true; 15059 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15060 + oldName + " pkgName=" + pkgName); 15061 } else if (mPackages.containsKey(pkgName)) { 15062 // This package, under its official name, already exists 15063 // on the device; we should replace it. 15064 replace = true; 15065 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15066 } 15067 15068 // Child packages are installed through the parent package 15069 if (pkg.parentPackage != null) { 15070 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15071 "Package " + pkg.packageName + " is child of package " 15072 + pkg.parentPackage.parentPackage + ". Child packages " 15073 + "can be updated only through the parent package."); 15074 return; 15075 } 15076 15077 if (replace) { 15078 // Prevent apps opting out from runtime permissions 15079 PackageParser.Package oldPackage = mPackages.get(pkgName); 15080 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15081 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15082 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15083 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15084 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15085 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15086 + " doesn't support runtime permissions but the old" 15087 + " target SDK " + oldTargetSdk + " does."); 15088 return; 15089 } 15090 15091 // Prevent installing of child packages 15092 if (oldPackage.parentPackage != null) { 15093 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15094 "Package " + pkg.packageName + " is child of package " 15095 + oldPackage.parentPackage + ". Child packages " 15096 + "can be updated only through the parent package."); 15097 return; 15098 } 15099 } 15100 } 15101 15102 PackageSetting ps = mSettings.mPackages.get(pkgName); 15103 if (ps != null) { 15104 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15105 15106 // Quick sanity check that we're signed correctly if updating; 15107 // we'll check this again later when scanning, but we want to 15108 // bail early here before tripping over redefined permissions. 15109 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15110 if (!checkUpgradeKeySetLP(ps, pkg)) { 15111 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15112 + pkg.packageName + " upgrade keys do not match the " 15113 + "previously installed version"); 15114 return; 15115 } 15116 } else { 15117 try { 15118 verifySignaturesLP(ps, pkg); 15119 } catch (PackageManagerException e) { 15120 res.setError(e.error, e.getMessage()); 15121 return; 15122 } 15123 } 15124 15125 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15126 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15127 systemApp = (ps.pkg.applicationInfo.flags & 15128 ApplicationInfo.FLAG_SYSTEM) != 0; 15129 } 15130 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15131 } 15132 15133 // Check whether the newly-scanned package wants to define an already-defined perm 15134 int N = pkg.permissions.size(); 15135 for (int i = N-1; i >= 0; i--) { 15136 PackageParser.Permission perm = pkg.permissions.get(i); 15137 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15138 if (bp != null) { 15139 // If the defining package is signed with our cert, it's okay. This 15140 // also includes the "updating the same package" case, of course. 15141 // "updating same package" could also involve key-rotation. 15142 final boolean sigsOk; 15143 if (bp.sourcePackage.equals(pkg.packageName) 15144 && (bp.packageSetting instanceof PackageSetting) 15145 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15146 scanFlags))) { 15147 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15148 } else { 15149 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15150 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15151 } 15152 if (!sigsOk) { 15153 // If the owning package is the system itself, we log but allow 15154 // install to proceed; we fail the install on all other permission 15155 // redefinitions. 15156 if (!bp.sourcePackage.equals("android")) { 15157 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15158 + pkg.packageName + " attempting to redeclare permission " 15159 + perm.info.name + " already owned by " + bp.sourcePackage); 15160 res.origPermission = perm.info.name; 15161 res.origPackage = bp.sourcePackage; 15162 return; 15163 } else { 15164 Slog.w(TAG, "Package " + pkg.packageName 15165 + " attempting to redeclare system permission " 15166 + perm.info.name + "; ignoring new declaration"); 15167 pkg.permissions.remove(i); 15168 } 15169 } 15170 } 15171 } 15172 } 15173 15174 if (systemApp) { 15175 if (onExternal) { 15176 // Abort update; system app can't be replaced with app on sdcard 15177 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15178 "Cannot install updates to system apps on sdcard"); 15179 return; 15180 } else if (ephemeral) { 15181 // Abort update; system app can't be replaced with an ephemeral app 15182 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15183 "Cannot update a system app with an ephemeral app"); 15184 return; 15185 } 15186 } 15187 15188 if (args.move != null) { 15189 // We did an in-place move, so dex is ready to roll 15190 scanFlags |= SCAN_NO_DEX; 15191 scanFlags |= SCAN_MOVE; 15192 15193 synchronized (mPackages) { 15194 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15195 if (ps == null) { 15196 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15197 "Missing settings for moved package " + pkgName); 15198 } 15199 15200 // We moved the entire application as-is, so bring over the 15201 // previously derived ABI information. 15202 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15203 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15204 } 15205 15206 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15207 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15208 scanFlags |= SCAN_NO_DEX; 15209 15210 try { 15211 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15212 args.abiOverride : pkg.cpuAbiOverride); 15213 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15214 true /* extract libs */); 15215 } catch (PackageManagerException pme) { 15216 Slog.e(TAG, "Error deriving application ABI", pme); 15217 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15218 return; 15219 } 15220 15221 // Shared libraries for the package need to be updated. 15222 synchronized (mPackages) { 15223 try { 15224 updateSharedLibrariesLPw(pkg, null); 15225 } catch (PackageManagerException e) { 15226 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15227 } 15228 } 15229 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15230 // Do not run PackageDexOptimizer through the local performDexOpt 15231 // method because `pkg` may not be in `mPackages` yet. 15232 // 15233 // Also, don't fail application installs if the dexopt step fails. 15234 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15235 null /* instructionSets */, false /* checkProfiles */, 15236 getCompilerFilterForReason(REASON_INSTALL), 15237 getOrCreateCompilerPackageStats(pkg)); 15238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15239 15240 // Notify BackgroundDexOptService that the package has been changed. 15241 // If this is an update of a package which used to fail to compile, 15242 // BDOS will remove it from its blacklist. 15243 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15244 } 15245 15246 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15247 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15248 return; 15249 } 15250 15251 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15252 15253 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15254 "installPackageLI")) { 15255 if (replace) { 15256 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15257 installerPackageName, res); 15258 } else { 15259 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15260 args.user, installerPackageName, volumeUuid, res); 15261 } 15262 } 15263 synchronized (mPackages) { 15264 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15265 if (ps != null) { 15266 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15267 } 15268 15269 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15270 for (int i = 0; i < childCount; i++) { 15271 PackageParser.Package childPkg = pkg.childPackages.get(i); 15272 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15273 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15274 if (childPs != null) { 15275 childRes.newUsers = childPs.queryInstalledUsers( 15276 sUserManager.getUserIds(), true); 15277 } 15278 } 15279 } 15280 } 15281 15282 private void startIntentFilterVerifications(int userId, boolean replacing, 15283 PackageParser.Package pkg) { 15284 if (mIntentFilterVerifierComponent == null) { 15285 Slog.w(TAG, "No IntentFilter verification will not be done as " 15286 + "there is no IntentFilterVerifier available!"); 15287 return; 15288 } 15289 15290 final int verifierUid = getPackageUid( 15291 mIntentFilterVerifierComponent.getPackageName(), 15292 MATCH_DEBUG_TRIAGED_MISSING, 15293 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15294 15295 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15296 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15297 mHandler.sendMessage(msg); 15298 15299 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15300 for (int i = 0; i < childCount; i++) { 15301 PackageParser.Package childPkg = pkg.childPackages.get(i); 15302 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15303 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15304 mHandler.sendMessage(msg); 15305 } 15306 } 15307 15308 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15309 PackageParser.Package pkg) { 15310 int size = pkg.activities.size(); 15311 if (size == 0) { 15312 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15313 "No activity, so no need to verify any IntentFilter!"); 15314 return; 15315 } 15316 15317 final boolean hasDomainURLs = hasDomainURLs(pkg); 15318 if (!hasDomainURLs) { 15319 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15320 "No domain URLs, so no need to verify any IntentFilter!"); 15321 return; 15322 } 15323 15324 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15325 + " if any IntentFilter from the " + size 15326 + " Activities needs verification ..."); 15327 15328 int count = 0; 15329 final String packageName = pkg.packageName; 15330 15331 synchronized (mPackages) { 15332 // If this is a new install and we see that we've already run verification for this 15333 // package, we have nothing to do: it means the state was restored from backup. 15334 if (!replacing) { 15335 IntentFilterVerificationInfo ivi = 15336 mSettings.getIntentFilterVerificationLPr(packageName); 15337 if (ivi != null) { 15338 if (DEBUG_DOMAIN_VERIFICATION) { 15339 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15340 + ivi.getStatusString()); 15341 } 15342 return; 15343 } 15344 } 15345 15346 // If any filters need to be verified, then all need to be. 15347 boolean needToVerify = false; 15348 for (PackageParser.Activity a : pkg.activities) { 15349 for (ActivityIntentInfo filter : a.intents) { 15350 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15351 if (DEBUG_DOMAIN_VERIFICATION) { 15352 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15353 } 15354 needToVerify = true; 15355 break; 15356 } 15357 } 15358 } 15359 15360 if (needToVerify) { 15361 final int verificationId = mIntentFilterVerificationToken++; 15362 for (PackageParser.Activity a : pkg.activities) { 15363 for (ActivityIntentInfo filter : a.intents) { 15364 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15365 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15366 "Verification needed for IntentFilter:" + filter.toString()); 15367 mIntentFilterVerifier.addOneIntentFilterVerification( 15368 verifierUid, userId, verificationId, filter, packageName); 15369 count++; 15370 } 15371 } 15372 } 15373 } 15374 } 15375 15376 if (count > 0) { 15377 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15378 + " IntentFilter verification" + (count > 1 ? "s" : "") 15379 + " for userId:" + userId); 15380 mIntentFilterVerifier.startVerifications(userId); 15381 } else { 15382 if (DEBUG_DOMAIN_VERIFICATION) { 15383 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15384 } 15385 } 15386 } 15387 15388 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15389 final ComponentName cn = filter.activity.getComponentName(); 15390 final String packageName = cn.getPackageName(); 15391 15392 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15393 packageName); 15394 if (ivi == null) { 15395 return true; 15396 } 15397 int status = ivi.getStatus(); 15398 switch (status) { 15399 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15400 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15401 return true; 15402 15403 default: 15404 // Nothing to do 15405 return false; 15406 } 15407 } 15408 15409 private static boolean isMultiArch(ApplicationInfo info) { 15410 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15411 } 15412 15413 private static boolean isExternal(PackageParser.Package pkg) { 15414 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15415 } 15416 15417 private static boolean isExternal(PackageSetting ps) { 15418 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15419 } 15420 15421 private static boolean isEphemeral(PackageParser.Package pkg) { 15422 return pkg.applicationInfo.isEphemeralApp(); 15423 } 15424 15425 private static boolean isEphemeral(PackageSetting ps) { 15426 return ps.pkg != null && isEphemeral(ps.pkg); 15427 } 15428 15429 private static boolean isSystemApp(PackageParser.Package pkg) { 15430 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15431 } 15432 15433 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15434 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15435 } 15436 15437 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15438 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15439 } 15440 15441 private static boolean isSystemApp(PackageSetting ps) { 15442 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15443 } 15444 15445 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15446 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15447 } 15448 15449 private int packageFlagsToInstallFlags(PackageSetting ps) { 15450 int installFlags = 0; 15451 if (isEphemeral(ps)) { 15452 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15453 } 15454 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15455 // This existing package was an external ASEC install when we have 15456 // the external flag without a UUID 15457 installFlags |= PackageManager.INSTALL_EXTERNAL; 15458 } 15459 if (ps.isForwardLocked()) { 15460 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15461 } 15462 return installFlags; 15463 } 15464 15465 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15466 if (isExternal(pkg)) { 15467 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15468 return StorageManager.UUID_PRIMARY_PHYSICAL; 15469 } else { 15470 return pkg.volumeUuid; 15471 } 15472 } else { 15473 return StorageManager.UUID_PRIVATE_INTERNAL; 15474 } 15475 } 15476 15477 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15478 if (isExternal(pkg)) { 15479 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15480 return mSettings.getExternalVersion(); 15481 } else { 15482 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15483 } 15484 } else { 15485 return mSettings.getInternalVersion(); 15486 } 15487 } 15488 15489 private void deleteTempPackageFiles() { 15490 final FilenameFilter filter = new FilenameFilter() { 15491 public boolean accept(File dir, String name) { 15492 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15493 } 15494 }; 15495 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15496 file.delete(); 15497 } 15498 } 15499 15500 @Override 15501 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15502 int flags) { 15503 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15504 flags); 15505 } 15506 15507 @Override 15508 public void deletePackage(final String packageName, 15509 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15510 mContext.enforceCallingOrSelfPermission( 15511 android.Manifest.permission.DELETE_PACKAGES, null); 15512 Preconditions.checkNotNull(packageName); 15513 Preconditions.checkNotNull(observer); 15514 final int uid = Binder.getCallingUid(); 15515 if (!isOrphaned(packageName) 15516 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15517 try { 15518 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15519 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15520 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15521 observer.onUserActionRequired(intent); 15522 } catch (RemoteException re) { 15523 } 15524 return; 15525 } 15526 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15527 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15528 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15529 mContext.enforceCallingOrSelfPermission( 15530 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15531 "deletePackage for user " + userId); 15532 } 15533 15534 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15535 try { 15536 observer.onPackageDeleted(packageName, 15537 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15538 } catch (RemoteException re) { 15539 } 15540 return; 15541 } 15542 15543 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15544 try { 15545 observer.onPackageDeleted(packageName, 15546 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15547 } catch (RemoteException re) { 15548 } 15549 return; 15550 } 15551 15552 if (DEBUG_REMOVE) { 15553 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15554 + " deleteAllUsers: " + deleteAllUsers ); 15555 } 15556 // Queue up an async operation since the package deletion may take a little while. 15557 mHandler.post(new Runnable() { 15558 public void run() { 15559 mHandler.removeCallbacks(this); 15560 int returnCode; 15561 if (!deleteAllUsers) { 15562 returnCode = deletePackageX(packageName, userId, deleteFlags); 15563 } else { 15564 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15565 // If nobody is blocking uninstall, proceed with delete for all users 15566 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15567 returnCode = deletePackageX(packageName, userId, deleteFlags); 15568 } else { 15569 // Otherwise uninstall individually for users with blockUninstalls=false 15570 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15571 for (int userId : users) { 15572 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15573 returnCode = deletePackageX(packageName, userId, userFlags); 15574 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15575 Slog.w(TAG, "Package delete failed for user " + userId 15576 + ", returnCode " + returnCode); 15577 } 15578 } 15579 } 15580 // The app has only been marked uninstalled for certain users. 15581 // We still need to report that delete was blocked 15582 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15583 } 15584 } 15585 try { 15586 observer.onPackageDeleted(packageName, returnCode, null); 15587 } catch (RemoteException e) { 15588 Log.i(TAG, "Observer no longer exists."); 15589 } //end catch 15590 } //end run 15591 }); 15592 } 15593 15594 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15595 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15596 || callingUid == Process.SYSTEM_UID) { 15597 return true; 15598 } 15599 final int callingUserId = UserHandle.getUserId(callingUid); 15600 // If the caller installed the pkgName, then allow it to silently uninstall. 15601 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15602 return true; 15603 } 15604 15605 // Allow package verifier to silently uninstall. 15606 if (mRequiredVerifierPackage != null && 15607 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15608 return true; 15609 } 15610 15611 // Allow package uninstaller to silently uninstall. 15612 if (mRequiredUninstallerPackage != null && 15613 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15614 return true; 15615 } 15616 15617 // Allow storage manager to silently uninstall. 15618 if (mStorageManagerPackage != null && 15619 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15620 return true; 15621 } 15622 return false; 15623 } 15624 15625 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15626 int[] result = EMPTY_INT_ARRAY; 15627 for (int userId : userIds) { 15628 if (getBlockUninstallForUser(packageName, userId)) { 15629 result = ArrayUtils.appendInt(result, userId); 15630 } 15631 } 15632 return result; 15633 } 15634 15635 @Override 15636 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15637 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15638 } 15639 15640 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15641 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15642 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15643 try { 15644 if (dpm != null) { 15645 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15646 /* callingUserOnly =*/ false); 15647 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15648 : deviceOwnerComponentName.getPackageName(); 15649 // Does the package contains the device owner? 15650 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15651 // this check is probably not needed, since DO should be registered as a device 15652 // admin on some user too. (Original bug for this: b/17657954) 15653 if (packageName.equals(deviceOwnerPackageName)) { 15654 return true; 15655 } 15656 // Does it contain a device admin for any user? 15657 int[] users; 15658 if (userId == UserHandle.USER_ALL) { 15659 users = sUserManager.getUserIds(); 15660 } else { 15661 users = new int[]{userId}; 15662 } 15663 for (int i = 0; i < users.length; ++i) { 15664 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15665 return true; 15666 } 15667 } 15668 } 15669 } catch (RemoteException e) { 15670 } 15671 return false; 15672 } 15673 15674 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15675 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15676 } 15677 15678 /** 15679 * This method is an internal method that could be get invoked either 15680 * to delete an installed package or to clean up a failed installation. 15681 * After deleting an installed package, a broadcast is sent to notify any 15682 * listeners that the package has been removed. For cleaning up a failed 15683 * installation, the broadcast is not necessary since the package's 15684 * installation wouldn't have sent the initial broadcast either 15685 * The key steps in deleting a package are 15686 * deleting the package information in internal structures like mPackages, 15687 * deleting the packages base directories through installd 15688 * updating mSettings to reflect current status 15689 * persisting settings for later use 15690 * sending a broadcast if necessary 15691 */ 15692 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15693 final PackageRemovedInfo info = new PackageRemovedInfo(); 15694 final boolean res; 15695 15696 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15697 ? UserHandle.USER_ALL : userId; 15698 15699 if (isPackageDeviceAdmin(packageName, removeUser)) { 15700 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15701 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15702 } 15703 15704 PackageSetting uninstalledPs = null; 15705 15706 // for the uninstall-updates case and restricted profiles, remember the per- 15707 // user handle installed state 15708 int[] allUsers; 15709 synchronized (mPackages) { 15710 uninstalledPs = mSettings.mPackages.get(packageName); 15711 if (uninstalledPs == null) { 15712 Slog.w(TAG, "Not removing non-existent package " + packageName); 15713 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15714 } 15715 allUsers = sUserManager.getUserIds(); 15716 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15717 } 15718 15719 final int freezeUser; 15720 if (isUpdatedSystemApp(uninstalledPs) 15721 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15722 // We're downgrading a system app, which will apply to all users, so 15723 // freeze them all during the downgrade 15724 freezeUser = UserHandle.USER_ALL; 15725 } else { 15726 freezeUser = removeUser; 15727 } 15728 15729 synchronized (mInstallLock) { 15730 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15731 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15732 deleteFlags, "deletePackageX")) { 15733 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15734 deleteFlags | REMOVE_CHATTY, info, true, null); 15735 } 15736 synchronized (mPackages) { 15737 if (res) { 15738 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15739 } 15740 } 15741 } 15742 15743 if (res) { 15744 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15745 info.sendPackageRemovedBroadcasts(killApp); 15746 info.sendSystemPackageUpdatedBroadcasts(); 15747 info.sendSystemPackageAppearedBroadcasts(); 15748 } 15749 // Force a gc here. 15750 Runtime.getRuntime().gc(); 15751 // Delete the resources here after sending the broadcast to let 15752 // other processes clean up before deleting resources. 15753 if (info.args != null) { 15754 synchronized (mInstallLock) { 15755 info.args.doPostDeleteLI(true); 15756 } 15757 } 15758 15759 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15760 } 15761 15762 class PackageRemovedInfo { 15763 String removedPackage; 15764 int uid = -1; 15765 int removedAppId = -1; 15766 int[] origUsers; 15767 int[] removedUsers = null; 15768 boolean isRemovedPackageSystemUpdate = false; 15769 boolean isUpdate; 15770 boolean dataRemoved; 15771 boolean removedForAllUsers; 15772 // Clean up resources deleted packages. 15773 InstallArgs args = null; 15774 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15775 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15776 15777 void sendPackageRemovedBroadcasts(boolean killApp) { 15778 sendPackageRemovedBroadcastInternal(killApp); 15779 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15780 for (int i = 0; i < childCount; i++) { 15781 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15782 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15783 } 15784 } 15785 15786 void sendSystemPackageUpdatedBroadcasts() { 15787 if (isRemovedPackageSystemUpdate) { 15788 sendSystemPackageUpdatedBroadcastsInternal(); 15789 final int childCount = (removedChildPackages != null) 15790 ? removedChildPackages.size() : 0; 15791 for (int i = 0; i < childCount; i++) { 15792 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15793 if (childInfo.isRemovedPackageSystemUpdate) { 15794 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15795 } 15796 } 15797 } 15798 } 15799 15800 void sendSystemPackageAppearedBroadcasts() { 15801 final int packageCount = (appearedChildPackages != null) 15802 ? appearedChildPackages.size() : 0; 15803 for (int i = 0; i < packageCount; i++) { 15804 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15805 for (int userId : installedInfo.newUsers) { 15806 sendPackageAddedForUser(installedInfo.name, true, 15807 UserHandle.getAppId(installedInfo.uid), userId); 15808 } 15809 } 15810 } 15811 15812 private void sendSystemPackageUpdatedBroadcastsInternal() { 15813 Bundle extras = new Bundle(2); 15814 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15815 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15816 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15817 extras, 0, null, null, null); 15818 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15819 extras, 0, null, null, null); 15820 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15821 null, 0, removedPackage, null, null); 15822 } 15823 15824 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15825 Bundle extras = new Bundle(2); 15826 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15827 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15828 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15829 if (isUpdate || isRemovedPackageSystemUpdate) { 15830 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15831 } 15832 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15833 if (removedPackage != null) { 15834 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15835 extras, 0, null, null, removedUsers); 15836 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15837 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15838 removedPackage, extras, 0, null, null, removedUsers); 15839 } 15840 } 15841 if (removedAppId >= 0) { 15842 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15843 removedUsers); 15844 } 15845 } 15846 } 15847 15848 /* 15849 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15850 * flag is not set, the data directory is removed as well. 15851 * make sure this flag is set for partially installed apps. If not its meaningless to 15852 * delete a partially installed application. 15853 */ 15854 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15855 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15856 String packageName = ps.name; 15857 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15858 // Retrieve object to delete permissions for shared user later on 15859 final PackageParser.Package deletedPkg; 15860 final PackageSetting deletedPs; 15861 // reader 15862 synchronized (mPackages) { 15863 deletedPkg = mPackages.get(packageName); 15864 deletedPs = mSettings.mPackages.get(packageName); 15865 if (outInfo != null) { 15866 outInfo.removedPackage = packageName; 15867 outInfo.removedUsers = deletedPs != null 15868 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15869 : null; 15870 } 15871 } 15872 15873 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15874 15875 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15876 final PackageParser.Package resolvedPkg; 15877 if (deletedPkg != null) { 15878 resolvedPkg = deletedPkg; 15879 } else { 15880 // We don't have a parsed package when it lives on an ejected 15881 // adopted storage device, so fake something together 15882 resolvedPkg = new PackageParser.Package(ps.name); 15883 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15884 } 15885 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15886 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15887 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15888 if (outInfo != null) { 15889 outInfo.dataRemoved = true; 15890 } 15891 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15892 } 15893 15894 // writer 15895 synchronized (mPackages) { 15896 if (deletedPs != null) { 15897 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15898 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15899 clearDefaultBrowserIfNeeded(packageName); 15900 if (outInfo != null) { 15901 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15902 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15903 } 15904 updatePermissionsLPw(deletedPs.name, null, 0); 15905 if (deletedPs.sharedUser != null) { 15906 // Remove permissions associated with package. Since runtime 15907 // permissions are per user we have to kill the removed package 15908 // or packages running under the shared user of the removed 15909 // package if revoking the permissions requested only by the removed 15910 // package is successful and this causes a change in gids. 15911 for (int userId : UserManagerService.getInstance().getUserIds()) { 15912 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15913 userId); 15914 if (userIdToKill == UserHandle.USER_ALL 15915 || userIdToKill >= UserHandle.USER_SYSTEM) { 15916 // If gids changed for this user, kill all affected packages. 15917 mHandler.post(new Runnable() { 15918 @Override 15919 public void run() { 15920 // This has to happen with no lock held. 15921 killApplication(deletedPs.name, deletedPs.appId, 15922 KILL_APP_REASON_GIDS_CHANGED); 15923 } 15924 }); 15925 break; 15926 } 15927 } 15928 } 15929 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15930 } 15931 // make sure to preserve per-user disabled state if this removal was just 15932 // a downgrade of a system app to the factory package 15933 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15934 if (DEBUG_REMOVE) { 15935 Slog.d(TAG, "Propagating install state across downgrade"); 15936 } 15937 for (int userId : allUserHandles) { 15938 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15939 if (DEBUG_REMOVE) { 15940 Slog.d(TAG, " user " + userId + " => " + installed); 15941 } 15942 ps.setInstalled(installed, userId); 15943 } 15944 } 15945 } 15946 // can downgrade to reader 15947 if (writeSettings) { 15948 // Save settings now 15949 mSettings.writeLPr(); 15950 } 15951 } 15952 if (outInfo != null) { 15953 // A user ID was deleted here. Go through all users and remove it 15954 // from KeyStore. 15955 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15956 } 15957 } 15958 15959 static boolean locationIsPrivileged(File path) { 15960 try { 15961 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15962 .getCanonicalPath(); 15963 return path.getCanonicalPath().startsWith(privilegedAppDir); 15964 } catch (IOException e) { 15965 Slog.e(TAG, "Unable to access code path " + path); 15966 } 15967 return false; 15968 } 15969 15970 /* 15971 * Tries to delete system package. 15972 */ 15973 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15974 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15975 boolean writeSettings) { 15976 if (deletedPs.parentPackageName != null) { 15977 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15978 return false; 15979 } 15980 15981 final boolean applyUserRestrictions 15982 = (allUserHandles != null) && (outInfo.origUsers != null); 15983 final PackageSetting disabledPs; 15984 // Confirm if the system package has been updated 15985 // An updated system app can be deleted. This will also have to restore 15986 // the system pkg from system partition 15987 // reader 15988 synchronized (mPackages) { 15989 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15990 } 15991 15992 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15993 + " disabledPs=" + disabledPs); 15994 15995 if (disabledPs == null) { 15996 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15997 return false; 15998 } else if (DEBUG_REMOVE) { 15999 Slog.d(TAG, "Deleting system pkg from data partition"); 16000 } 16001 16002 if (DEBUG_REMOVE) { 16003 if (applyUserRestrictions) { 16004 Slog.d(TAG, "Remembering install states:"); 16005 for (int userId : allUserHandles) { 16006 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16007 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16008 } 16009 } 16010 } 16011 16012 // Delete the updated package 16013 outInfo.isRemovedPackageSystemUpdate = true; 16014 if (outInfo.removedChildPackages != null) { 16015 final int childCount = (deletedPs.childPackageNames != null) 16016 ? deletedPs.childPackageNames.size() : 0; 16017 for (int i = 0; i < childCount; i++) { 16018 String childPackageName = deletedPs.childPackageNames.get(i); 16019 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16020 .contains(childPackageName)) { 16021 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16022 childPackageName); 16023 if (childInfo != null) { 16024 childInfo.isRemovedPackageSystemUpdate = true; 16025 } 16026 } 16027 } 16028 } 16029 16030 if (disabledPs.versionCode < deletedPs.versionCode) { 16031 // Delete data for downgrades 16032 flags &= ~PackageManager.DELETE_KEEP_DATA; 16033 } else { 16034 // Preserve data by setting flag 16035 flags |= PackageManager.DELETE_KEEP_DATA; 16036 } 16037 16038 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16039 outInfo, writeSettings, disabledPs.pkg); 16040 if (!ret) { 16041 return false; 16042 } 16043 16044 // writer 16045 synchronized (mPackages) { 16046 // Reinstate the old system package 16047 enableSystemPackageLPw(disabledPs.pkg); 16048 // Remove any native libraries from the upgraded package. 16049 removeNativeBinariesLI(deletedPs); 16050 } 16051 16052 // Install the system package 16053 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16054 int parseFlags = mDefParseFlags 16055 | PackageParser.PARSE_MUST_BE_APK 16056 | PackageParser.PARSE_IS_SYSTEM 16057 | PackageParser.PARSE_IS_SYSTEM_DIR; 16058 if (locationIsPrivileged(disabledPs.codePath)) { 16059 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16060 } 16061 16062 final PackageParser.Package newPkg; 16063 try { 16064 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16065 } catch (PackageManagerException e) { 16066 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16067 + e.getMessage()); 16068 return false; 16069 } 16070 try { 16071 // update shared libraries for the newly re-installed system package 16072 updateSharedLibrariesLPw(newPkg, null); 16073 } catch (PackageManagerException e) { 16074 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16075 } 16076 16077 prepareAppDataAfterInstallLIF(newPkg); 16078 16079 // writer 16080 synchronized (mPackages) { 16081 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16082 16083 // Propagate the permissions state as we do not want to drop on the floor 16084 // runtime permissions. The update permissions method below will take 16085 // care of removing obsolete permissions and grant install permissions. 16086 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16087 updatePermissionsLPw(newPkg.packageName, newPkg, 16088 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16089 16090 if (applyUserRestrictions) { 16091 if (DEBUG_REMOVE) { 16092 Slog.d(TAG, "Propagating install state across reinstall"); 16093 } 16094 for (int userId : allUserHandles) { 16095 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16096 if (DEBUG_REMOVE) { 16097 Slog.d(TAG, " user " + userId + " => " + installed); 16098 } 16099 ps.setInstalled(installed, userId); 16100 16101 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16102 } 16103 // Regardless of writeSettings we need to ensure that this restriction 16104 // state propagation is persisted 16105 mSettings.writeAllUsersPackageRestrictionsLPr(); 16106 } 16107 // can downgrade to reader here 16108 if (writeSettings) { 16109 mSettings.writeLPr(); 16110 } 16111 } 16112 return true; 16113 } 16114 16115 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16116 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16117 PackageRemovedInfo outInfo, boolean writeSettings, 16118 PackageParser.Package replacingPackage) { 16119 synchronized (mPackages) { 16120 if (outInfo != null) { 16121 outInfo.uid = ps.appId; 16122 } 16123 16124 if (outInfo != null && outInfo.removedChildPackages != null) { 16125 final int childCount = (ps.childPackageNames != null) 16126 ? ps.childPackageNames.size() : 0; 16127 for (int i = 0; i < childCount; i++) { 16128 String childPackageName = ps.childPackageNames.get(i); 16129 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16130 if (childPs == null) { 16131 return false; 16132 } 16133 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16134 childPackageName); 16135 if (childInfo != null) { 16136 childInfo.uid = childPs.appId; 16137 } 16138 } 16139 } 16140 } 16141 16142 // Delete package data from internal structures and also remove data if flag is set 16143 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16144 16145 // Delete the child packages data 16146 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16147 for (int i = 0; i < childCount; i++) { 16148 PackageSetting childPs; 16149 synchronized (mPackages) { 16150 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16151 } 16152 if (childPs != null) { 16153 PackageRemovedInfo childOutInfo = (outInfo != null 16154 && outInfo.removedChildPackages != null) 16155 ? outInfo.removedChildPackages.get(childPs.name) : null; 16156 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16157 && (replacingPackage != null 16158 && !replacingPackage.hasChildPackage(childPs.name)) 16159 ? flags & ~DELETE_KEEP_DATA : flags; 16160 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16161 deleteFlags, writeSettings); 16162 } 16163 } 16164 16165 // Delete application code and resources only for parent packages 16166 if (ps.parentPackageName == null) { 16167 if (deleteCodeAndResources && (outInfo != null)) { 16168 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16169 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16170 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16171 } 16172 } 16173 16174 return true; 16175 } 16176 16177 @Override 16178 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16179 int userId) { 16180 mContext.enforceCallingOrSelfPermission( 16181 android.Manifest.permission.DELETE_PACKAGES, null); 16182 synchronized (mPackages) { 16183 PackageSetting ps = mSettings.mPackages.get(packageName); 16184 if (ps == null) { 16185 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16186 return false; 16187 } 16188 if (!ps.getInstalled(userId)) { 16189 // Can't block uninstall for an app that is not installed or enabled. 16190 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16191 return false; 16192 } 16193 ps.setBlockUninstall(blockUninstall, userId); 16194 mSettings.writePackageRestrictionsLPr(userId); 16195 } 16196 return true; 16197 } 16198 16199 @Override 16200 public boolean getBlockUninstallForUser(String packageName, int userId) { 16201 synchronized (mPackages) { 16202 PackageSetting ps = mSettings.mPackages.get(packageName); 16203 if (ps == null) { 16204 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16205 return false; 16206 } 16207 return ps.getBlockUninstall(userId); 16208 } 16209 } 16210 16211 @Override 16212 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16213 int callingUid = Binder.getCallingUid(); 16214 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16215 throw new SecurityException( 16216 "setRequiredForSystemUser can only be run by the system or root"); 16217 } 16218 synchronized (mPackages) { 16219 PackageSetting ps = mSettings.mPackages.get(packageName); 16220 if (ps == null) { 16221 Log.w(TAG, "Package doesn't exist: " + packageName); 16222 return false; 16223 } 16224 if (systemUserApp) { 16225 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16226 } else { 16227 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16228 } 16229 mSettings.writeLPr(); 16230 } 16231 return true; 16232 } 16233 16234 /* 16235 * This method handles package deletion in general 16236 */ 16237 private boolean deletePackageLIF(String packageName, UserHandle user, 16238 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16239 PackageRemovedInfo outInfo, boolean writeSettings, 16240 PackageParser.Package replacingPackage) { 16241 if (packageName == null) { 16242 Slog.w(TAG, "Attempt to delete null packageName."); 16243 return false; 16244 } 16245 16246 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16247 16248 PackageSetting ps; 16249 16250 synchronized (mPackages) { 16251 ps = mSettings.mPackages.get(packageName); 16252 if (ps == null) { 16253 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16254 return false; 16255 } 16256 16257 if (ps.parentPackageName != null && (!isSystemApp(ps) 16258 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16259 if (DEBUG_REMOVE) { 16260 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16261 + ((user == null) ? UserHandle.USER_ALL : user)); 16262 } 16263 final int removedUserId = (user != null) ? user.getIdentifier() 16264 : UserHandle.USER_ALL; 16265 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16266 return false; 16267 } 16268 markPackageUninstalledForUserLPw(ps, user); 16269 scheduleWritePackageRestrictionsLocked(user); 16270 return true; 16271 } 16272 } 16273 16274 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16275 && user.getIdentifier() != UserHandle.USER_ALL)) { 16276 // The caller is asking that the package only be deleted for a single 16277 // user. To do this, we just mark its uninstalled state and delete 16278 // its data. If this is a system app, we only allow this to happen if 16279 // they have set the special DELETE_SYSTEM_APP which requests different 16280 // semantics than normal for uninstalling system apps. 16281 markPackageUninstalledForUserLPw(ps, user); 16282 16283 if (!isSystemApp(ps)) { 16284 // Do not uninstall the APK if an app should be cached 16285 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16286 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16287 // Other user still have this package installed, so all 16288 // we need to do is clear this user's data and save that 16289 // it is uninstalled. 16290 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16291 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16292 return false; 16293 } 16294 scheduleWritePackageRestrictionsLocked(user); 16295 return true; 16296 } else { 16297 // We need to set it back to 'installed' so the uninstall 16298 // broadcasts will be sent correctly. 16299 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16300 ps.setInstalled(true, user.getIdentifier()); 16301 } 16302 } else { 16303 // This is a system app, so we assume that the 16304 // other users still have this package installed, so all 16305 // we need to do is clear this user's data and save that 16306 // it is uninstalled. 16307 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16308 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16309 return false; 16310 } 16311 scheduleWritePackageRestrictionsLocked(user); 16312 return true; 16313 } 16314 } 16315 16316 // If we are deleting a composite package for all users, keep track 16317 // of result for each child. 16318 if (ps.childPackageNames != null && outInfo != null) { 16319 synchronized (mPackages) { 16320 final int childCount = ps.childPackageNames.size(); 16321 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16322 for (int i = 0; i < childCount; i++) { 16323 String childPackageName = ps.childPackageNames.get(i); 16324 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16325 childInfo.removedPackage = childPackageName; 16326 outInfo.removedChildPackages.put(childPackageName, childInfo); 16327 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16328 if (childPs != null) { 16329 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16330 } 16331 } 16332 } 16333 } 16334 16335 boolean ret = false; 16336 if (isSystemApp(ps)) { 16337 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16338 // When an updated system application is deleted we delete the existing resources 16339 // as well and fall back to existing code in system partition 16340 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16341 } else { 16342 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16343 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16344 outInfo, writeSettings, replacingPackage); 16345 } 16346 16347 // Take a note whether we deleted the package for all users 16348 if (outInfo != null) { 16349 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16350 if (outInfo.removedChildPackages != null) { 16351 synchronized (mPackages) { 16352 final int childCount = outInfo.removedChildPackages.size(); 16353 for (int i = 0; i < childCount; i++) { 16354 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16355 if (childInfo != null) { 16356 childInfo.removedForAllUsers = mPackages.get( 16357 childInfo.removedPackage) == null; 16358 } 16359 } 16360 } 16361 } 16362 // If we uninstalled an update to a system app there may be some 16363 // child packages that appeared as they are declared in the system 16364 // app but were not declared in the update. 16365 if (isSystemApp(ps)) { 16366 synchronized (mPackages) { 16367 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16368 final int childCount = (updatedPs.childPackageNames != null) 16369 ? updatedPs.childPackageNames.size() : 0; 16370 for (int i = 0; i < childCount; i++) { 16371 String childPackageName = updatedPs.childPackageNames.get(i); 16372 if (outInfo.removedChildPackages == null 16373 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16374 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16375 if (childPs == null) { 16376 continue; 16377 } 16378 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16379 installRes.name = childPackageName; 16380 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16381 installRes.pkg = mPackages.get(childPackageName); 16382 installRes.uid = childPs.pkg.applicationInfo.uid; 16383 if (outInfo.appearedChildPackages == null) { 16384 outInfo.appearedChildPackages = new ArrayMap<>(); 16385 } 16386 outInfo.appearedChildPackages.put(childPackageName, installRes); 16387 } 16388 } 16389 } 16390 } 16391 } 16392 16393 return ret; 16394 } 16395 16396 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16397 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16398 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16399 for (int nextUserId : userIds) { 16400 if (DEBUG_REMOVE) { 16401 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16402 } 16403 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16404 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16405 false /*hidden*/, false /*suspended*/, null, null, null, 16406 false /*blockUninstall*/, 16407 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16408 } 16409 } 16410 16411 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16412 PackageRemovedInfo outInfo) { 16413 final PackageParser.Package pkg; 16414 synchronized (mPackages) { 16415 pkg = mPackages.get(ps.name); 16416 } 16417 16418 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16419 : new int[] {userId}; 16420 for (int nextUserId : userIds) { 16421 if (DEBUG_REMOVE) { 16422 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16423 + nextUserId); 16424 } 16425 16426 destroyAppDataLIF(pkg, userId, 16427 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16428 destroyAppProfilesLIF(pkg, userId); 16429 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16430 schedulePackageCleaning(ps.name, nextUserId, false); 16431 synchronized (mPackages) { 16432 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16433 scheduleWritePackageRestrictionsLocked(nextUserId); 16434 } 16435 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16436 } 16437 } 16438 16439 if (outInfo != null) { 16440 outInfo.removedPackage = ps.name; 16441 outInfo.removedAppId = ps.appId; 16442 outInfo.removedUsers = userIds; 16443 } 16444 16445 return true; 16446 } 16447 16448 private final class ClearStorageConnection implements ServiceConnection { 16449 IMediaContainerService mContainerService; 16450 16451 @Override 16452 public void onServiceConnected(ComponentName name, IBinder service) { 16453 synchronized (this) { 16454 mContainerService = IMediaContainerService.Stub.asInterface(service); 16455 notifyAll(); 16456 } 16457 } 16458 16459 @Override 16460 public void onServiceDisconnected(ComponentName name) { 16461 } 16462 } 16463 16464 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16465 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16466 16467 final boolean mounted; 16468 if (Environment.isExternalStorageEmulated()) { 16469 mounted = true; 16470 } else { 16471 final String status = Environment.getExternalStorageState(); 16472 16473 mounted = status.equals(Environment.MEDIA_MOUNTED) 16474 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16475 } 16476 16477 if (!mounted) { 16478 return; 16479 } 16480 16481 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16482 int[] users; 16483 if (userId == UserHandle.USER_ALL) { 16484 users = sUserManager.getUserIds(); 16485 } else { 16486 users = new int[] { userId }; 16487 } 16488 final ClearStorageConnection conn = new ClearStorageConnection(); 16489 if (mContext.bindServiceAsUser( 16490 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16491 try { 16492 for (int curUser : users) { 16493 long timeout = SystemClock.uptimeMillis() + 5000; 16494 synchronized (conn) { 16495 long now; 16496 while (conn.mContainerService == null && 16497 (now = SystemClock.uptimeMillis()) < timeout) { 16498 try { 16499 conn.wait(timeout - now); 16500 } catch (InterruptedException e) { 16501 } 16502 } 16503 } 16504 if (conn.mContainerService == null) { 16505 return; 16506 } 16507 16508 final UserEnvironment userEnv = new UserEnvironment(curUser); 16509 clearDirectory(conn.mContainerService, 16510 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16511 if (allData) { 16512 clearDirectory(conn.mContainerService, 16513 userEnv.buildExternalStorageAppDataDirs(packageName)); 16514 clearDirectory(conn.mContainerService, 16515 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16516 } 16517 } 16518 } finally { 16519 mContext.unbindService(conn); 16520 } 16521 } 16522 } 16523 16524 @Override 16525 public void clearApplicationProfileData(String packageName) { 16526 enforceSystemOrRoot("Only the system can clear all profile data"); 16527 16528 final PackageParser.Package pkg; 16529 synchronized (mPackages) { 16530 pkg = mPackages.get(packageName); 16531 } 16532 16533 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16534 synchronized (mInstallLock) { 16535 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16536 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16537 true /* removeBaseMarker */); 16538 } 16539 } 16540 } 16541 16542 @Override 16543 public void clearApplicationUserData(final String packageName, 16544 final IPackageDataObserver observer, final int userId) { 16545 mContext.enforceCallingOrSelfPermission( 16546 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16547 16548 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16549 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16550 16551 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16552 throw new SecurityException("Cannot clear data for a protected package: " 16553 + packageName); 16554 } 16555 // Queue up an async operation since the package deletion may take a little while. 16556 mHandler.post(new Runnable() { 16557 public void run() { 16558 mHandler.removeCallbacks(this); 16559 final boolean succeeded; 16560 try (PackageFreezer freezer = freezePackage(packageName, 16561 "clearApplicationUserData")) { 16562 synchronized (mInstallLock) { 16563 succeeded = clearApplicationUserDataLIF(packageName, userId); 16564 } 16565 clearExternalStorageDataSync(packageName, userId, true); 16566 } 16567 if (succeeded) { 16568 // invoke DeviceStorageMonitor's update method to clear any notifications 16569 DeviceStorageMonitorInternal dsm = LocalServices 16570 .getService(DeviceStorageMonitorInternal.class); 16571 if (dsm != null) { 16572 dsm.checkMemory(); 16573 } 16574 } 16575 if(observer != null) { 16576 try { 16577 observer.onRemoveCompleted(packageName, succeeded); 16578 } catch (RemoteException e) { 16579 Log.i(TAG, "Observer no longer exists."); 16580 } 16581 } //end if observer 16582 } //end run 16583 }); 16584 } 16585 16586 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16587 if (packageName == null) { 16588 Slog.w(TAG, "Attempt to delete null packageName."); 16589 return false; 16590 } 16591 16592 // Try finding details about the requested package 16593 PackageParser.Package pkg; 16594 synchronized (mPackages) { 16595 pkg = mPackages.get(packageName); 16596 if (pkg == null) { 16597 final PackageSetting ps = mSettings.mPackages.get(packageName); 16598 if (ps != null) { 16599 pkg = ps.pkg; 16600 } 16601 } 16602 16603 if (pkg == null) { 16604 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16605 return false; 16606 } 16607 16608 PackageSetting ps = (PackageSetting) pkg.mExtras; 16609 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16610 } 16611 16612 clearAppDataLIF(pkg, userId, 16613 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16614 16615 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16616 removeKeystoreDataIfNeeded(userId, appId); 16617 16618 UserManagerInternal umInternal = getUserManagerInternal(); 16619 final int flags; 16620 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16621 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16622 } else if (umInternal.isUserRunning(userId)) { 16623 flags = StorageManager.FLAG_STORAGE_DE; 16624 } else { 16625 flags = 0; 16626 } 16627 prepareAppDataContentsLIF(pkg, userId, flags); 16628 16629 return true; 16630 } 16631 16632 /** 16633 * Reverts user permission state changes (permissions and flags) in 16634 * all packages for a given user. 16635 * 16636 * @param userId The device user for which to do a reset. 16637 */ 16638 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16639 final int packageCount = mPackages.size(); 16640 for (int i = 0; i < packageCount; i++) { 16641 PackageParser.Package pkg = mPackages.valueAt(i); 16642 PackageSetting ps = (PackageSetting) pkg.mExtras; 16643 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16644 } 16645 } 16646 16647 private void resetNetworkPolicies(int userId) { 16648 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16649 } 16650 16651 /** 16652 * Reverts user permission state changes (permissions and flags). 16653 * 16654 * @param ps The package for which to reset. 16655 * @param userId The device user for which to do a reset. 16656 */ 16657 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16658 final PackageSetting ps, final int userId) { 16659 if (ps.pkg == null) { 16660 return; 16661 } 16662 16663 // These are flags that can change base on user actions. 16664 final int userSettableMask = FLAG_PERMISSION_USER_SET 16665 | FLAG_PERMISSION_USER_FIXED 16666 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16667 | FLAG_PERMISSION_REVIEW_REQUIRED; 16668 16669 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16670 | FLAG_PERMISSION_POLICY_FIXED; 16671 16672 boolean writeInstallPermissions = false; 16673 boolean writeRuntimePermissions = false; 16674 16675 final int permissionCount = ps.pkg.requestedPermissions.size(); 16676 for (int i = 0; i < permissionCount; i++) { 16677 String permission = ps.pkg.requestedPermissions.get(i); 16678 16679 BasePermission bp = mSettings.mPermissions.get(permission); 16680 if (bp == null) { 16681 continue; 16682 } 16683 16684 // If shared user we just reset the state to which only this app contributed. 16685 if (ps.sharedUser != null) { 16686 boolean used = false; 16687 final int packageCount = ps.sharedUser.packages.size(); 16688 for (int j = 0; j < packageCount; j++) { 16689 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16690 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16691 && pkg.pkg.requestedPermissions.contains(permission)) { 16692 used = true; 16693 break; 16694 } 16695 } 16696 if (used) { 16697 continue; 16698 } 16699 } 16700 16701 PermissionsState permissionsState = ps.getPermissionsState(); 16702 16703 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16704 16705 // Always clear the user settable flags. 16706 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16707 bp.name) != null; 16708 // If permission review is enabled and this is a legacy app, mark the 16709 // permission as requiring a review as this is the initial state. 16710 int flags = 0; 16711 if (Build.PERMISSIONS_REVIEW_REQUIRED 16712 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16713 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16714 } 16715 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16716 if (hasInstallState) { 16717 writeInstallPermissions = true; 16718 } else { 16719 writeRuntimePermissions = true; 16720 } 16721 } 16722 16723 // Below is only runtime permission handling. 16724 if (!bp.isRuntime()) { 16725 continue; 16726 } 16727 16728 // Never clobber system or policy. 16729 if ((oldFlags & policyOrSystemFlags) != 0) { 16730 continue; 16731 } 16732 16733 // If this permission was granted by default, make sure it is. 16734 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16735 if (permissionsState.grantRuntimePermission(bp, userId) 16736 != PERMISSION_OPERATION_FAILURE) { 16737 writeRuntimePermissions = true; 16738 } 16739 // If permission review is enabled the permissions for a legacy apps 16740 // are represented as constantly granted runtime ones, so don't revoke. 16741 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16742 // Otherwise, reset the permission. 16743 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16744 switch (revokeResult) { 16745 case PERMISSION_OPERATION_SUCCESS: 16746 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16747 writeRuntimePermissions = true; 16748 final int appId = ps.appId; 16749 mHandler.post(new Runnable() { 16750 @Override 16751 public void run() { 16752 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16753 } 16754 }); 16755 } break; 16756 } 16757 } 16758 } 16759 16760 // Synchronously write as we are taking permissions away. 16761 if (writeRuntimePermissions) { 16762 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16763 } 16764 16765 // Synchronously write as we are taking permissions away. 16766 if (writeInstallPermissions) { 16767 mSettings.writeLPr(); 16768 } 16769 } 16770 16771 /** 16772 * Remove entries from the keystore daemon. Will only remove it if the 16773 * {@code appId} is valid. 16774 */ 16775 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16776 if (appId < 0) { 16777 return; 16778 } 16779 16780 final KeyStore keyStore = KeyStore.getInstance(); 16781 if (keyStore != null) { 16782 if (userId == UserHandle.USER_ALL) { 16783 for (final int individual : sUserManager.getUserIds()) { 16784 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16785 } 16786 } else { 16787 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16788 } 16789 } else { 16790 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16791 } 16792 } 16793 16794 @Override 16795 public void deleteApplicationCacheFiles(final String packageName, 16796 final IPackageDataObserver observer) { 16797 final int userId = UserHandle.getCallingUserId(); 16798 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16799 } 16800 16801 @Override 16802 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16803 final IPackageDataObserver observer) { 16804 mContext.enforceCallingOrSelfPermission( 16805 android.Manifest.permission.DELETE_CACHE_FILES, null); 16806 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16807 /* requireFullPermission= */ true, /* checkShell= */ false, 16808 "delete application cache files"); 16809 16810 final PackageParser.Package pkg; 16811 synchronized (mPackages) { 16812 pkg = mPackages.get(packageName); 16813 } 16814 16815 // Queue up an async operation since the package deletion may take a little while. 16816 mHandler.post(new Runnable() { 16817 public void run() { 16818 synchronized (mInstallLock) { 16819 final int flags = StorageManager.FLAG_STORAGE_DE 16820 | StorageManager.FLAG_STORAGE_CE; 16821 // We're only clearing cache files, so we don't care if the 16822 // app is unfrozen and still able to run 16823 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16824 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16825 } 16826 clearExternalStorageDataSync(packageName, userId, false); 16827 if (observer != null) { 16828 try { 16829 observer.onRemoveCompleted(packageName, true); 16830 } catch (RemoteException e) { 16831 Log.i(TAG, "Observer no longer exists."); 16832 } 16833 } 16834 } 16835 }); 16836 } 16837 16838 @Override 16839 public void getPackageSizeInfo(final String packageName, int userHandle, 16840 final IPackageStatsObserver observer) { 16841 mContext.enforceCallingOrSelfPermission( 16842 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16843 if (packageName == null) { 16844 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16845 } 16846 16847 PackageStats stats = new PackageStats(packageName, userHandle); 16848 16849 /* 16850 * Queue up an async operation since the package measurement may take a 16851 * little while. 16852 */ 16853 Message msg = mHandler.obtainMessage(INIT_COPY); 16854 msg.obj = new MeasureParams(stats, observer); 16855 mHandler.sendMessage(msg); 16856 } 16857 16858 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16859 final PackageSetting ps; 16860 synchronized (mPackages) { 16861 ps = mSettings.mPackages.get(packageName); 16862 if (ps == null) { 16863 Slog.w(TAG, "Failed to find settings for " + packageName); 16864 return false; 16865 } 16866 } 16867 try { 16868 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16869 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16870 ps.getCeDataInode(userId), ps.codePathString, stats); 16871 } catch (InstallerException e) { 16872 Slog.w(TAG, String.valueOf(e)); 16873 return false; 16874 } 16875 16876 // For now, ignore code size of packages on system partition 16877 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16878 stats.codeSize = 0; 16879 } 16880 16881 return true; 16882 } 16883 16884 private int getUidTargetSdkVersionLockedLPr(int uid) { 16885 Object obj = mSettings.getUserIdLPr(uid); 16886 if (obj instanceof SharedUserSetting) { 16887 final SharedUserSetting sus = (SharedUserSetting) obj; 16888 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16889 final Iterator<PackageSetting> it = sus.packages.iterator(); 16890 while (it.hasNext()) { 16891 final PackageSetting ps = it.next(); 16892 if (ps.pkg != null) { 16893 int v = ps.pkg.applicationInfo.targetSdkVersion; 16894 if (v < vers) vers = v; 16895 } 16896 } 16897 return vers; 16898 } else if (obj instanceof PackageSetting) { 16899 final PackageSetting ps = (PackageSetting) obj; 16900 if (ps.pkg != null) { 16901 return ps.pkg.applicationInfo.targetSdkVersion; 16902 } 16903 } 16904 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16905 } 16906 16907 @Override 16908 public void addPreferredActivity(IntentFilter filter, int match, 16909 ComponentName[] set, ComponentName activity, int userId) { 16910 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16911 "Adding preferred"); 16912 } 16913 16914 private void addPreferredActivityInternal(IntentFilter filter, int match, 16915 ComponentName[] set, ComponentName activity, boolean always, int userId, 16916 String opname) { 16917 // writer 16918 int callingUid = Binder.getCallingUid(); 16919 enforceCrossUserPermission(callingUid, userId, 16920 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16921 if (filter.countActions() == 0) { 16922 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16923 return; 16924 } 16925 synchronized (mPackages) { 16926 if (mContext.checkCallingOrSelfPermission( 16927 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16928 != PackageManager.PERMISSION_GRANTED) { 16929 if (getUidTargetSdkVersionLockedLPr(callingUid) 16930 < Build.VERSION_CODES.FROYO) { 16931 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16932 + callingUid); 16933 return; 16934 } 16935 mContext.enforceCallingOrSelfPermission( 16936 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16937 } 16938 16939 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16940 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16941 + userId + ":"); 16942 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16943 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16944 scheduleWritePackageRestrictionsLocked(userId); 16945 postPreferredActivityChangedBroadcast(userId); 16946 } 16947 } 16948 16949 private void postPreferredActivityChangedBroadcast(int userId) { 16950 mHandler.post(() -> { 16951 final IActivityManager am = ActivityManagerNative.getDefault(); 16952 if (am == null) { 16953 return; 16954 } 16955 16956 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16957 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16958 try { 16959 am.broadcastIntent(null, intent, null, null, 16960 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16961 null, false, false, userId); 16962 } catch (RemoteException e) { 16963 } 16964 }); 16965 } 16966 16967 @Override 16968 public void replacePreferredActivity(IntentFilter filter, int match, 16969 ComponentName[] set, ComponentName activity, int userId) { 16970 if (filter.countActions() != 1) { 16971 throw new IllegalArgumentException( 16972 "replacePreferredActivity expects filter to have only 1 action."); 16973 } 16974 if (filter.countDataAuthorities() != 0 16975 || filter.countDataPaths() != 0 16976 || filter.countDataSchemes() > 1 16977 || filter.countDataTypes() != 0) { 16978 throw new IllegalArgumentException( 16979 "replacePreferredActivity expects filter to have no data authorities, " + 16980 "paths, or types; and at most one scheme."); 16981 } 16982 16983 final int callingUid = Binder.getCallingUid(); 16984 enforceCrossUserPermission(callingUid, userId, 16985 true /* requireFullPermission */, false /* checkShell */, 16986 "replace preferred activity"); 16987 synchronized (mPackages) { 16988 if (mContext.checkCallingOrSelfPermission( 16989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16990 != PackageManager.PERMISSION_GRANTED) { 16991 if (getUidTargetSdkVersionLockedLPr(callingUid) 16992 < Build.VERSION_CODES.FROYO) { 16993 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16994 + Binder.getCallingUid()); 16995 return; 16996 } 16997 mContext.enforceCallingOrSelfPermission( 16998 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16999 } 17000 17001 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17002 if (pir != null) { 17003 // Get all of the existing entries that exactly match this filter. 17004 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17005 if (existing != null && existing.size() == 1) { 17006 PreferredActivity cur = existing.get(0); 17007 if (DEBUG_PREFERRED) { 17008 Slog.i(TAG, "Checking replace of preferred:"); 17009 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17010 if (!cur.mPref.mAlways) { 17011 Slog.i(TAG, " -- CUR; not mAlways!"); 17012 } else { 17013 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17014 Slog.i(TAG, " -- CUR: mSet=" 17015 + Arrays.toString(cur.mPref.mSetComponents)); 17016 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17017 Slog.i(TAG, " -- NEW: mMatch=" 17018 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17019 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17020 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17021 } 17022 } 17023 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17024 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17025 && cur.mPref.sameSet(set)) { 17026 // Setting the preferred activity to what it happens to be already 17027 if (DEBUG_PREFERRED) { 17028 Slog.i(TAG, "Replacing with same preferred activity " 17029 + cur.mPref.mShortComponent + " for user " 17030 + userId + ":"); 17031 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17032 } 17033 return; 17034 } 17035 } 17036 17037 if (existing != null) { 17038 if (DEBUG_PREFERRED) { 17039 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17040 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17041 } 17042 for (int i = 0; i < existing.size(); i++) { 17043 PreferredActivity pa = existing.get(i); 17044 if (DEBUG_PREFERRED) { 17045 Slog.i(TAG, "Removing existing preferred activity " 17046 + pa.mPref.mComponent + ":"); 17047 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17048 } 17049 pir.removeFilter(pa); 17050 } 17051 } 17052 } 17053 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17054 "Replacing preferred"); 17055 } 17056 } 17057 17058 @Override 17059 public void clearPackagePreferredActivities(String packageName) { 17060 final int uid = Binder.getCallingUid(); 17061 // writer 17062 synchronized (mPackages) { 17063 PackageParser.Package pkg = mPackages.get(packageName); 17064 if (pkg == null || pkg.applicationInfo.uid != uid) { 17065 if (mContext.checkCallingOrSelfPermission( 17066 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17067 != PackageManager.PERMISSION_GRANTED) { 17068 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17069 < Build.VERSION_CODES.FROYO) { 17070 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17071 + Binder.getCallingUid()); 17072 return; 17073 } 17074 mContext.enforceCallingOrSelfPermission( 17075 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17076 } 17077 } 17078 17079 int user = UserHandle.getCallingUserId(); 17080 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17081 scheduleWritePackageRestrictionsLocked(user); 17082 } 17083 } 17084 } 17085 17086 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17087 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17088 ArrayList<PreferredActivity> removed = null; 17089 boolean changed = false; 17090 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17091 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17092 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17093 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17094 continue; 17095 } 17096 Iterator<PreferredActivity> it = pir.filterIterator(); 17097 while (it.hasNext()) { 17098 PreferredActivity pa = it.next(); 17099 // Mark entry for removal only if it matches the package name 17100 // and the entry is of type "always". 17101 if (packageName == null || 17102 (pa.mPref.mComponent.getPackageName().equals(packageName) 17103 && pa.mPref.mAlways)) { 17104 if (removed == null) { 17105 removed = new ArrayList<PreferredActivity>(); 17106 } 17107 removed.add(pa); 17108 } 17109 } 17110 if (removed != null) { 17111 for (int j=0; j<removed.size(); j++) { 17112 PreferredActivity pa = removed.get(j); 17113 pir.removeFilter(pa); 17114 } 17115 changed = true; 17116 } 17117 } 17118 if (changed) { 17119 postPreferredActivityChangedBroadcast(userId); 17120 } 17121 return changed; 17122 } 17123 17124 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17125 private void clearIntentFilterVerificationsLPw(int userId) { 17126 final int packageCount = mPackages.size(); 17127 for (int i = 0; i < packageCount; i++) { 17128 PackageParser.Package pkg = mPackages.valueAt(i); 17129 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17130 } 17131 } 17132 17133 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17134 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17135 if (userId == UserHandle.USER_ALL) { 17136 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17137 sUserManager.getUserIds())) { 17138 for (int oneUserId : sUserManager.getUserIds()) { 17139 scheduleWritePackageRestrictionsLocked(oneUserId); 17140 } 17141 } 17142 } else { 17143 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17144 scheduleWritePackageRestrictionsLocked(userId); 17145 } 17146 } 17147 } 17148 17149 void clearDefaultBrowserIfNeeded(String packageName) { 17150 for (int oneUserId : sUserManager.getUserIds()) { 17151 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17152 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17153 if (packageName.equals(defaultBrowserPackageName)) { 17154 setDefaultBrowserPackageName(null, oneUserId); 17155 } 17156 } 17157 } 17158 17159 @Override 17160 public void resetApplicationPreferences(int userId) { 17161 mContext.enforceCallingOrSelfPermission( 17162 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17163 final long identity = Binder.clearCallingIdentity(); 17164 // writer 17165 try { 17166 synchronized (mPackages) { 17167 clearPackagePreferredActivitiesLPw(null, userId); 17168 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17169 // TODO: We have to reset the default SMS and Phone. This requires 17170 // significant refactoring to keep all default apps in the package 17171 // manager (cleaner but more work) or have the services provide 17172 // callbacks to the package manager to request a default app reset. 17173 applyFactoryDefaultBrowserLPw(userId); 17174 clearIntentFilterVerificationsLPw(userId); 17175 primeDomainVerificationsLPw(userId); 17176 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17177 scheduleWritePackageRestrictionsLocked(userId); 17178 } 17179 resetNetworkPolicies(userId); 17180 } finally { 17181 Binder.restoreCallingIdentity(identity); 17182 } 17183 } 17184 17185 @Override 17186 public int getPreferredActivities(List<IntentFilter> outFilters, 17187 List<ComponentName> outActivities, String packageName) { 17188 17189 int num = 0; 17190 final int userId = UserHandle.getCallingUserId(); 17191 // reader 17192 synchronized (mPackages) { 17193 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17194 if (pir != null) { 17195 final Iterator<PreferredActivity> it = pir.filterIterator(); 17196 while (it.hasNext()) { 17197 final PreferredActivity pa = it.next(); 17198 if (packageName == null 17199 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17200 && pa.mPref.mAlways)) { 17201 if (outFilters != null) { 17202 outFilters.add(new IntentFilter(pa)); 17203 } 17204 if (outActivities != null) { 17205 outActivities.add(pa.mPref.mComponent); 17206 } 17207 } 17208 } 17209 } 17210 } 17211 17212 return num; 17213 } 17214 17215 @Override 17216 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17217 int userId) { 17218 int callingUid = Binder.getCallingUid(); 17219 if (callingUid != Process.SYSTEM_UID) { 17220 throw new SecurityException( 17221 "addPersistentPreferredActivity can only be run by the system"); 17222 } 17223 if (filter.countActions() == 0) { 17224 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17225 return; 17226 } 17227 synchronized (mPackages) { 17228 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17229 ":"); 17230 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17231 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17232 new PersistentPreferredActivity(filter, activity)); 17233 scheduleWritePackageRestrictionsLocked(userId); 17234 postPreferredActivityChangedBroadcast(userId); 17235 } 17236 } 17237 17238 @Override 17239 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17240 int callingUid = Binder.getCallingUid(); 17241 if (callingUid != Process.SYSTEM_UID) { 17242 throw new SecurityException( 17243 "clearPackagePersistentPreferredActivities can only be run by the system"); 17244 } 17245 ArrayList<PersistentPreferredActivity> removed = null; 17246 boolean changed = false; 17247 synchronized (mPackages) { 17248 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17249 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17250 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17251 .valueAt(i); 17252 if (userId != thisUserId) { 17253 continue; 17254 } 17255 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17256 while (it.hasNext()) { 17257 PersistentPreferredActivity ppa = it.next(); 17258 // Mark entry for removal only if it matches the package name. 17259 if (ppa.mComponent.getPackageName().equals(packageName)) { 17260 if (removed == null) { 17261 removed = new ArrayList<PersistentPreferredActivity>(); 17262 } 17263 removed.add(ppa); 17264 } 17265 } 17266 if (removed != null) { 17267 for (int j=0; j<removed.size(); j++) { 17268 PersistentPreferredActivity ppa = removed.get(j); 17269 ppir.removeFilter(ppa); 17270 } 17271 changed = true; 17272 } 17273 } 17274 17275 if (changed) { 17276 scheduleWritePackageRestrictionsLocked(userId); 17277 postPreferredActivityChangedBroadcast(userId); 17278 } 17279 } 17280 } 17281 17282 /** 17283 * Common machinery for picking apart a restored XML blob and passing 17284 * it to a caller-supplied functor to be applied to the running system. 17285 */ 17286 private void restoreFromXml(XmlPullParser parser, int userId, 17287 String expectedStartTag, BlobXmlRestorer functor) 17288 throws IOException, XmlPullParserException { 17289 int type; 17290 while ((type = parser.next()) != XmlPullParser.START_TAG 17291 && type != XmlPullParser.END_DOCUMENT) { 17292 } 17293 if (type != XmlPullParser.START_TAG) { 17294 // oops didn't find a start tag?! 17295 if (DEBUG_BACKUP) { 17296 Slog.e(TAG, "Didn't find start tag during restore"); 17297 } 17298 return; 17299 } 17300Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17301 // this is supposed to be TAG_PREFERRED_BACKUP 17302 if (!expectedStartTag.equals(parser.getName())) { 17303 if (DEBUG_BACKUP) { 17304 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17305 } 17306 return; 17307 } 17308 17309 // skip interfering stuff, then we're aligned with the backing implementation 17310 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17311Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17312 functor.apply(parser, userId); 17313 } 17314 17315 private interface BlobXmlRestorer { 17316 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17317 } 17318 17319 /** 17320 * Non-Binder method, support for the backup/restore mechanism: write the 17321 * full set of preferred activities in its canonical XML format. Returns the 17322 * XML output as a byte array, or null if there is none. 17323 */ 17324 @Override 17325 public byte[] getPreferredActivityBackup(int userId) { 17326 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17327 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17328 } 17329 17330 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17331 try { 17332 final XmlSerializer serializer = new FastXmlSerializer(); 17333 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17334 serializer.startDocument(null, true); 17335 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17336 17337 synchronized (mPackages) { 17338 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17339 } 17340 17341 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17342 serializer.endDocument(); 17343 serializer.flush(); 17344 } catch (Exception e) { 17345 if (DEBUG_BACKUP) { 17346 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17347 } 17348 return null; 17349 } 17350 17351 return dataStream.toByteArray(); 17352 } 17353 17354 @Override 17355 public void restorePreferredActivities(byte[] backup, int userId) { 17356 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17357 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17358 } 17359 17360 try { 17361 final XmlPullParser parser = Xml.newPullParser(); 17362 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17363 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17364 new BlobXmlRestorer() { 17365 @Override 17366 public void apply(XmlPullParser parser, int userId) 17367 throws XmlPullParserException, IOException { 17368 synchronized (mPackages) { 17369 mSettings.readPreferredActivitiesLPw(parser, userId); 17370 } 17371 } 17372 } ); 17373 } catch (Exception e) { 17374 if (DEBUG_BACKUP) { 17375 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17376 } 17377 } 17378 } 17379 17380 /** 17381 * Non-Binder method, support for the backup/restore mechanism: write the 17382 * default browser (etc) settings in its canonical XML format. Returns the default 17383 * browser XML representation as a byte array, or null if there is none. 17384 */ 17385 @Override 17386 public byte[] getDefaultAppsBackup(int userId) { 17387 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17388 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17389 } 17390 17391 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17392 try { 17393 final XmlSerializer serializer = new FastXmlSerializer(); 17394 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17395 serializer.startDocument(null, true); 17396 serializer.startTag(null, TAG_DEFAULT_APPS); 17397 17398 synchronized (mPackages) { 17399 mSettings.writeDefaultAppsLPr(serializer, userId); 17400 } 17401 17402 serializer.endTag(null, TAG_DEFAULT_APPS); 17403 serializer.endDocument(); 17404 serializer.flush(); 17405 } catch (Exception e) { 17406 if (DEBUG_BACKUP) { 17407 Slog.e(TAG, "Unable to write default apps for backup", e); 17408 } 17409 return null; 17410 } 17411 17412 return dataStream.toByteArray(); 17413 } 17414 17415 @Override 17416 public void restoreDefaultApps(byte[] backup, int userId) { 17417 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17418 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17419 } 17420 17421 try { 17422 final XmlPullParser parser = Xml.newPullParser(); 17423 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17424 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17425 new BlobXmlRestorer() { 17426 @Override 17427 public void apply(XmlPullParser parser, int userId) 17428 throws XmlPullParserException, IOException { 17429 synchronized (mPackages) { 17430 mSettings.readDefaultAppsLPw(parser, userId); 17431 } 17432 } 17433 } ); 17434 } catch (Exception e) { 17435 if (DEBUG_BACKUP) { 17436 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17437 } 17438 } 17439 } 17440 17441 @Override 17442 public byte[] getIntentFilterVerificationBackup(int userId) { 17443 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17444 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17445 } 17446 17447 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17448 try { 17449 final XmlSerializer serializer = new FastXmlSerializer(); 17450 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17451 serializer.startDocument(null, true); 17452 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17453 17454 synchronized (mPackages) { 17455 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17456 } 17457 17458 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17459 serializer.endDocument(); 17460 serializer.flush(); 17461 } catch (Exception e) { 17462 if (DEBUG_BACKUP) { 17463 Slog.e(TAG, "Unable to write default apps for backup", e); 17464 } 17465 return null; 17466 } 17467 17468 return dataStream.toByteArray(); 17469 } 17470 17471 @Override 17472 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17473 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17474 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17475 } 17476 17477 try { 17478 final XmlPullParser parser = Xml.newPullParser(); 17479 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17480 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17481 new BlobXmlRestorer() { 17482 @Override 17483 public void apply(XmlPullParser parser, int userId) 17484 throws XmlPullParserException, IOException { 17485 synchronized (mPackages) { 17486 mSettings.readAllDomainVerificationsLPr(parser, userId); 17487 mSettings.writeLPr(); 17488 } 17489 } 17490 } ); 17491 } catch (Exception e) { 17492 if (DEBUG_BACKUP) { 17493 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17494 } 17495 } 17496 } 17497 17498 @Override 17499 public byte[] getPermissionGrantBackup(int userId) { 17500 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17501 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 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_PERMISSION_BACKUP); 17510 17511 synchronized (mPackages) { 17512 serializeRuntimePermissionGrantsLPr(serializer, userId); 17513 } 17514 17515 serializer.endTag(null, TAG_PERMISSION_BACKUP); 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 restorePermissionGrants(byte[] backup, int userId) { 17530 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17531 throw new SecurityException("Only the system may call restorePermissionGrants()"); 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_PERMISSION_BACKUP, 17538 new BlobXmlRestorer() { 17539 @Override 17540 public void apply(XmlPullParser parser, int userId) 17541 throws XmlPullParserException, IOException { 17542 synchronized (mPackages) { 17543 processRestoredPermissionGrantsLPr(parser, userId); 17544 } 17545 } 17546 } ); 17547 } catch (Exception e) { 17548 if (DEBUG_BACKUP) { 17549 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17550 } 17551 } 17552 } 17553 17554 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17555 throws IOException { 17556 serializer.startTag(null, TAG_ALL_GRANTS); 17557 17558 final int N = mSettings.mPackages.size(); 17559 for (int i = 0; i < N; i++) { 17560 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17561 boolean pkgGrantsKnown = false; 17562 17563 PermissionsState packagePerms = ps.getPermissionsState(); 17564 17565 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17566 final int grantFlags = state.getFlags(); 17567 // only look at grants that are not system/policy fixed 17568 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17569 final boolean isGranted = state.isGranted(); 17570 // And only back up the user-twiddled state bits 17571 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17572 final String packageName = mSettings.mPackages.keyAt(i); 17573 if (!pkgGrantsKnown) { 17574 serializer.startTag(null, TAG_GRANT); 17575 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17576 pkgGrantsKnown = true; 17577 } 17578 17579 final boolean userSet = 17580 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17581 final boolean userFixed = 17582 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17583 final boolean revoke = 17584 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17585 17586 serializer.startTag(null, TAG_PERMISSION); 17587 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17588 if (isGranted) { 17589 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17590 } 17591 if (userSet) { 17592 serializer.attribute(null, ATTR_USER_SET, "true"); 17593 } 17594 if (userFixed) { 17595 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17596 } 17597 if (revoke) { 17598 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17599 } 17600 serializer.endTag(null, TAG_PERMISSION); 17601 } 17602 } 17603 } 17604 17605 if (pkgGrantsKnown) { 17606 serializer.endTag(null, TAG_GRANT); 17607 } 17608 } 17609 17610 serializer.endTag(null, TAG_ALL_GRANTS); 17611 } 17612 17613 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17614 throws XmlPullParserException, IOException { 17615 String pkgName = null; 17616 int outerDepth = parser.getDepth(); 17617 int type; 17618 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17619 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17620 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17621 continue; 17622 } 17623 17624 final String tagName = parser.getName(); 17625 if (tagName.equals(TAG_GRANT)) { 17626 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17627 if (DEBUG_BACKUP) { 17628 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17629 } 17630 } else if (tagName.equals(TAG_PERMISSION)) { 17631 17632 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17633 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17634 17635 int newFlagSet = 0; 17636 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17637 newFlagSet |= FLAG_PERMISSION_USER_SET; 17638 } 17639 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17640 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17641 } 17642 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17643 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17644 } 17645 if (DEBUG_BACKUP) { 17646 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17647 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17648 } 17649 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17650 if (ps != null) { 17651 // Already installed so we apply the grant immediately 17652 if (DEBUG_BACKUP) { 17653 Slog.v(TAG, " + already installed; applying"); 17654 } 17655 PermissionsState perms = ps.getPermissionsState(); 17656 BasePermission bp = mSettings.mPermissions.get(permName); 17657 if (bp != null) { 17658 if (isGranted) { 17659 perms.grantRuntimePermission(bp, userId); 17660 } 17661 if (newFlagSet != 0) { 17662 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17663 } 17664 } 17665 } else { 17666 // Need to wait for post-restore install to apply the grant 17667 if (DEBUG_BACKUP) { 17668 Slog.v(TAG, " - not yet installed; saving for later"); 17669 } 17670 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17671 isGranted, newFlagSet, userId); 17672 } 17673 } else { 17674 PackageManagerService.reportSettingsProblem(Log.WARN, 17675 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17676 XmlUtils.skipCurrentTag(parser); 17677 } 17678 } 17679 17680 scheduleWriteSettingsLocked(); 17681 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17682 } 17683 17684 @Override 17685 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17686 int sourceUserId, int targetUserId, int flags) { 17687 mContext.enforceCallingOrSelfPermission( 17688 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17689 int callingUid = Binder.getCallingUid(); 17690 enforceOwnerRights(ownerPackage, callingUid); 17691 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17692 if (intentFilter.countActions() == 0) { 17693 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17694 return; 17695 } 17696 synchronized (mPackages) { 17697 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17698 ownerPackage, targetUserId, flags); 17699 CrossProfileIntentResolver resolver = 17700 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17701 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17702 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17703 if (existing != null) { 17704 int size = existing.size(); 17705 for (int i = 0; i < size; i++) { 17706 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17707 return; 17708 } 17709 } 17710 } 17711 resolver.addFilter(newFilter); 17712 scheduleWritePackageRestrictionsLocked(sourceUserId); 17713 } 17714 } 17715 17716 @Override 17717 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17718 mContext.enforceCallingOrSelfPermission( 17719 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17720 int callingUid = Binder.getCallingUid(); 17721 enforceOwnerRights(ownerPackage, callingUid); 17722 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17723 synchronized (mPackages) { 17724 CrossProfileIntentResolver resolver = 17725 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17726 ArraySet<CrossProfileIntentFilter> set = 17727 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17728 for (CrossProfileIntentFilter filter : set) { 17729 if (filter.getOwnerPackage().equals(ownerPackage)) { 17730 resolver.removeFilter(filter); 17731 } 17732 } 17733 scheduleWritePackageRestrictionsLocked(sourceUserId); 17734 } 17735 } 17736 17737 // Enforcing that callingUid is owning pkg on userId 17738 private void enforceOwnerRights(String pkg, int callingUid) { 17739 // The system owns everything. 17740 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17741 return; 17742 } 17743 int callingUserId = UserHandle.getUserId(callingUid); 17744 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17745 if (pi == null) { 17746 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17747 + callingUserId); 17748 } 17749 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17750 throw new SecurityException("Calling uid " + callingUid 17751 + " does not own package " + pkg); 17752 } 17753 } 17754 17755 @Override 17756 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17757 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17758 } 17759 17760 private Intent getHomeIntent() { 17761 Intent intent = new Intent(Intent.ACTION_MAIN); 17762 intent.addCategory(Intent.CATEGORY_HOME); 17763 intent.addCategory(Intent.CATEGORY_DEFAULT); 17764 return intent; 17765 } 17766 17767 private IntentFilter getHomeFilter() { 17768 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17769 filter.addCategory(Intent.CATEGORY_HOME); 17770 filter.addCategory(Intent.CATEGORY_DEFAULT); 17771 return filter; 17772 } 17773 17774 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17775 int userId) { 17776 Intent intent = getHomeIntent(); 17777 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17778 PackageManager.GET_META_DATA, userId); 17779 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17780 true, false, false, userId); 17781 17782 allHomeCandidates.clear(); 17783 if (list != null) { 17784 for (ResolveInfo ri : list) { 17785 allHomeCandidates.add(ri); 17786 } 17787 } 17788 return (preferred == null || preferred.activityInfo == null) 17789 ? null 17790 : new ComponentName(preferred.activityInfo.packageName, 17791 preferred.activityInfo.name); 17792 } 17793 17794 @Override 17795 public void setHomeActivity(ComponentName comp, int userId) { 17796 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17797 getHomeActivitiesAsUser(homeActivities, userId); 17798 17799 boolean found = false; 17800 17801 final int size = homeActivities.size(); 17802 final ComponentName[] set = new ComponentName[size]; 17803 for (int i = 0; i < size; i++) { 17804 final ResolveInfo candidate = homeActivities.get(i); 17805 final ActivityInfo info = candidate.activityInfo; 17806 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17807 set[i] = activityName; 17808 if (!found && activityName.equals(comp)) { 17809 found = true; 17810 } 17811 } 17812 if (!found) { 17813 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17814 + userId); 17815 } 17816 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17817 set, comp, userId); 17818 } 17819 17820 private @Nullable String getSetupWizardPackageName() { 17821 final Intent intent = new Intent(Intent.ACTION_MAIN); 17822 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17823 17824 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17825 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17826 | MATCH_DISABLED_COMPONENTS, 17827 UserHandle.myUserId()); 17828 if (matches.size() == 1) { 17829 return matches.get(0).getComponentInfo().packageName; 17830 } else { 17831 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17832 + ": matches=" + matches); 17833 return null; 17834 } 17835 } 17836 17837 private @Nullable String getStorageManagerPackageName() { 17838 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17839 17840 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17841 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17842 | MATCH_DISABLED_COMPONENTS, 17843 UserHandle.myUserId()); 17844 if (matches.size() == 1) { 17845 return matches.get(0).getComponentInfo().packageName; 17846 } else { 17847 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17848 + matches.size() + ": matches=" + matches); 17849 return null; 17850 } 17851 } 17852 17853 @Override 17854 public void setApplicationEnabledSetting(String appPackageName, 17855 int newState, int flags, int userId, String callingPackage) { 17856 if (!sUserManager.exists(userId)) return; 17857 if (callingPackage == null) { 17858 callingPackage = Integer.toString(Binder.getCallingUid()); 17859 } 17860 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17861 } 17862 17863 @Override 17864 public void setComponentEnabledSetting(ComponentName componentName, 17865 int newState, int flags, int userId) { 17866 if (!sUserManager.exists(userId)) return; 17867 setEnabledSetting(componentName.getPackageName(), 17868 componentName.getClassName(), newState, flags, userId, null); 17869 } 17870 17871 private void setEnabledSetting(final String packageName, String className, int newState, 17872 final int flags, int userId, String callingPackage) { 17873 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17874 || newState == COMPONENT_ENABLED_STATE_ENABLED 17875 || newState == COMPONENT_ENABLED_STATE_DISABLED 17876 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17877 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17878 throw new IllegalArgumentException("Invalid new component state: " 17879 + newState); 17880 } 17881 PackageSetting pkgSetting; 17882 final int uid = Binder.getCallingUid(); 17883 final int permission; 17884 if (uid == Process.SYSTEM_UID) { 17885 permission = PackageManager.PERMISSION_GRANTED; 17886 } else { 17887 permission = mContext.checkCallingOrSelfPermission( 17888 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17889 } 17890 enforceCrossUserPermission(uid, userId, 17891 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17892 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17893 boolean sendNow = false; 17894 boolean isApp = (className == null); 17895 String componentName = isApp ? packageName : className; 17896 int packageUid = -1; 17897 ArrayList<String> components; 17898 17899 // writer 17900 synchronized (mPackages) { 17901 pkgSetting = mSettings.mPackages.get(packageName); 17902 if (pkgSetting == null) { 17903 if (className == null) { 17904 throw new IllegalArgumentException("Unknown package: " + packageName); 17905 } 17906 throw new IllegalArgumentException( 17907 "Unknown component: " + packageName + "/" + className); 17908 } 17909 } 17910 17911 // Limit who can change which apps 17912 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17913 // Don't allow apps that don't have permission to modify other apps 17914 if (!allowedByPermission) { 17915 throw new SecurityException( 17916 "Permission Denial: attempt to change component state from pid=" 17917 + Binder.getCallingPid() 17918 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17919 } 17920 // Don't allow changing protected packages. 17921 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17922 throw new SecurityException("Cannot disable a protected package: " + packageName); 17923 } 17924 } 17925 17926 synchronized (mPackages) { 17927 if (uid == Process.SHELL_UID) { 17928 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17929 int oldState = pkgSetting.getEnabled(userId); 17930 if (className == null 17931 && 17932 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17933 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17934 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17935 && 17936 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17937 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17938 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17939 // ok 17940 } else { 17941 throw new SecurityException( 17942 "Shell cannot change component state for " + packageName + "/" 17943 + className + " to " + newState); 17944 } 17945 } 17946 if (className == null) { 17947 // We're dealing with an application/package level state change 17948 if (pkgSetting.getEnabled(userId) == newState) { 17949 // Nothing to do 17950 return; 17951 } 17952 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17953 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17954 // Don't care about who enables an app. 17955 callingPackage = null; 17956 } 17957 pkgSetting.setEnabled(newState, userId, callingPackage); 17958 // pkgSetting.pkg.mSetEnabled = newState; 17959 } else { 17960 // We're dealing with a component level state change 17961 // First, verify that this is a valid class name. 17962 PackageParser.Package pkg = pkgSetting.pkg; 17963 if (pkg == null || !pkg.hasComponentClassName(className)) { 17964 if (pkg != null && 17965 pkg.applicationInfo.targetSdkVersion >= 17966 Build.VERSION_CODES.JELLY_BEAN) { 17967 throw new IllegalArgumentException("Component class " + className 17968 + " does not exist in " + packageName); 17969 } else { 17970 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17971 + className + " does not exist in " + packageName); 17972 } 17973 } 17974 switch (newState) { 17975 case COMPONENT_ENABLED_STATE_ENABLED: 17976 if (!pkgSetting.enableComponentLPw(className, userId)) { 17977 return; 17978 } 17979 break; 17980 case COMPONENT_ENABLED_STATE_DISABLED: 17981 if (!pkgSetting.disableComponentLPw(className, userId)) { 17982 return; 17983 } 17984 break; 17985 case COMPONENT_ENABLED_STATE_DEFAULT: 17986 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17987 return; 17988 } 17989 break; 17990 default: 17991 Slog.e(TAG, "Invalid new component state: " + newState); 17992 return; 17993 } 17994 } 17995 scheduleWritePackageRestrictionsLocked(userId); 17996 components = mPendingBroadcasts.get(userId, packageName); 17997 final boolean newPackage = components == null; 17998 if (newPackage) { 17999 components = new ArrayList<String>(); 18000 } 18001 if (!components.contains(componentName)) { 18002 components.add(componentName); 18003 } 18004 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18005 sendNow = true; 18006 // Purge entry from pending broadcast list if another one exists already 18007 // since we are sending one right away. 18008 mPendingBroadcasts.remove(userId, packageName); 18009 } else { 18010 if (newPackage) { 18011 mPendingBroadcasts.put(userId, packageName, components); 18012 } 18013 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18014 // Schedule a message 18015 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18016 } 18017 } 18018 } 18019 18020 long callingId = Binder.clearCallingIdentity(); 18021 try { 18022 if (sendNow) { 18023 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18024 sendPackageChangedBroadcast(packageName, 18025 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18026 } 18027 } finally { 18028 Binder.restoreCallingIdentity(callingId); 18029 } 18030 } 18031 18032 @Override 18033 public void flushPackageRestrictionsAsUser(int userId) { 18034 if (!sUserManager.exists(userId)) { 18035 return; 18036 } 18037 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18038 false /* checkShell */, "flushPackageRestrictions"); 18039 synchronized (mPackages) { 18040 mSettings.writePackageRestrictionsLPr(userId); 18041 mDirtyUsers.remove(userId); 18042 if (mDirtyUsers.isEmpty()) { 18043 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18044 } 18045 } 18046 } 18047 18048 private void sendPackageChangedBroadcast(String packageName, 18049 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18050 if (DEBUG_INSTALL) 18051 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18052 + componentNames); 18053 Bundle extras = new Bundle(4); 18054 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18055 String nameList[] = new String[componentNames.size()]; 18056 componentNames.toArray(nameList); 18057 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18058 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18059 extras.putInt(Intent.EXTRA_UID, packageUid); 18060 // If this is not reporting a change of the overall package, then only send it 18061 // to registered receivers. We don't want to launch a swath of apps for every 18062 // little component state change. 18063 final int flags = !componentNames.contains(packageName) 18064 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18065 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18066 new int[] {UserHandle.getUserId(packageUid)}); 18067 } 18068 18069 @Override 18070 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18071 if (!sUserManager.exists(userId)) return; 18072 final int uid = Binder.getCallingUid(); 18073 final int permission = mContext.checkCallingOrSelfPermission( 18074 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18075 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18076 enforceCrossUserPermission(uid, userId, 18077 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18078 // writer 18079 synchronized (mPackages) { 18080 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18081 allowedByPermission, uid, userId)) { 18082 scheduleWritePackageRestrictionsLocked(userId); 18083 } 18084 } 18085 } 18086 18087 @Override 18088 public String getInstallerPackageName(String packageName) { 18089 // reader 18090 synchronized (mPackages) { 18091 return mSettings.getInstallerPackageNameLPr(packageName); 18092 } 18093 } 18094 18095 public boolean isOrphaned(String packageName) { 18096 // reader 18097 synchronized (mPackages) { 18098 return mSettings.isOrphaned(packageName); 18099 } 18100 } 18101 18102 @Override 18103 public int getApplicationEnabledSetting(String packageName, int userId) { 18104 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18105 int uid = Binder.getCallingUid(); 18106 enforceCrossUserPermission(uid, userId, 18107 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18108 // reader 18109 synchronized (mPackages) { 18110 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18111 } 18112 } 18113 18114 @Override 18115 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18116 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18117 int uid = Binder.getCallingUid(); 18118 enforceCrossUserPermission(uid, userId, 18119 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18120 // reader 18121 synchronized (mPackages) { 18122 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18123 } 18124 } 18125 18126 @Override 18127 public void enterSafeMode() { 18128 enforceSystemOrRoot("Only the system can request entering safe mode"); 18129 18130 if (!mSystemReady) { 18131 mSafeMode = true; 18132 } 18133 } 18134 18135 @Override 18136 public void systemReady() { 18137 mSystemReady = true; 18138 18139 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18140 // disabled after already being started. 18141 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18142 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18143 18144 // Read the compatibilty setting when the system is ready. 18145 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18146 mContext.getContentResolver(), 18147 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18148 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18149 if (DEBUG_SETTINGS) { 18150 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18151 } 18152 18153 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18154 18155 synchronized (mPackages) { 18156 // Verify that all of the preferred activity components actually 18157 // exist. It is possible for applications to be updated and at 18158 // that point remove a previously declared activity component that 18159 // had been set as a preferred activity. We try to clean this up 18160 // the next time we encounter that preferred activity, but it is 18161 // possible for the user flow to never be able to return to that 18162 // situation so here we do a sanity check to make sure we haven't 18163 // left any junk around. 18164 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18165 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18166 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18167 removed.clear(); 18168 for (PreferredActivity pa : pir.filterSet()) { 18169 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18170 removed.add(pa); 18171 } 18172 } 18173 if (removed.size() > 0) { 18174 for (int r=0; r<removed.size(); r++) { 18175 PreferredActivity pa = removed.get(r); 18176 Slog.w(TAG, "Removing dangling preferred activity: " 18177 + pa.mPref.mComponent); 18178 pir.removeFilter(pa); 18179 } 18180 mSettings.writePackageRestrictionsLPr( 18181 mSettings.mPreferredActivities.keyAt(i)); 18182 } 18183 } 18184 18185 for (int userId : UserManagerService.getInstance().getUserIds()) { 18186 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18187 grantPermissionsUserIds = ArrayUtils.appendInt( 18188 grantPermissionsUserIds, userId); 18189 } 18190 } 18191 } 18192 sUserManager.systemReady(); 18193 18194 // If we upgraded grant all default permissions before kicking off. 18195 for (int userId : grantPermissionsUserIds) { 18196 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18197 } 18198 18199 // If we did not grant default permissions, we preload from this the 18200 // default permission exceptions lazily to ensure we don't hit the 18201 // disk on a new user creation. 18202 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18203 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18204 } 18205 18206 // Kick off any messages waiting for system ready 18207 if (mPostSystemReadyMessages != null) { 18208 for (Message msg : mPostSystemReadyMessages) { 18209 msg.sendToTarget(); 18210 } 18211 mPostSystemReadyMessages = null; 18212 } 18213 18214 // Watch for external volumes that come and go over time 18215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18216 storage.registerListener(mStorageListener); 18217 18218 mInstallerService.systemReady(); 18219 mPackageDexOptimizer.systemReady(); 18220 18221 MountServiceInternal mountServiceInternal = LocalServices.getService( 18222 MountServiceInternal.class); 18223 mountServiceInternal.addExternalStoragePolicy( 18224 new MountServiceInternal.ExternalStorageMountPolicy() { 18225 @Override 18226 public int getMountMode(int uid, String packageName) { 18227 if (Process.isIsolated(uid)) { 18228 return Zygote.MOUNT_EXTERNAL_NONE; 18229 } 18230 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18231 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18232 } 18233 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18234 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18235 } 18236 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18237 return Zygote.MOUNT_EXTERNAL_READ; 18238 } 18239 return Zygote.MOUNT_EXTERNAL_WRITE; 18240 } 18241 18242 @Override 18243 public boolean hasExternalStorage(int uid, String packageName) { 18244 return true; 18245 } 18246 }); 18247 18248 // Now that we're mostly running, clean up stale users and apps 18249 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18250 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18251 } 18252 18253 @Override 18254 public boolean isSafeMode() { 18255 return mSafeMode; 18256 } 18257 18258 @Override 18259 public boolean hasSystemUidErrors() { 18260 return mHasSystemUidErrors; 18261 } 18262 18263 static String arrayToString(int[] array) { 18264 StringBuffer buf = new StringBuffer(128); 18265 buf.append('['); 18266 if (array != null) { 18267 for (int i=0; i<array.length; i++) { 18268 if (i > 0) buf.append(", "); 18269 buf.append(array[i]); 18270 } 18271 } 18272 buf.append(']'); 18273 return buf.toString(); 18274 } 18275 18276 static class DumpState { 18277 public static final int DUMP_LIBS = 1 << 0; 18278 public static final int DUMP_FEATURES = 1 << 1; 18279 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18280 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18281 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18282 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18283 public static final int DUMP_PERMISSIONS = 1 << 6; 18284 public static final int DUMP_PACKAGES = 1 << 7; 18285 public static final int DUMP_SHARED_USERS = 1 << 8; 18286 public static final int DUMP_MESSAGES = 1 << 9; 18287 public static final int DUMP_PROVIDERS = 1 << 10; 18288 public static final int DUMP_VERIFIERS = 1 << 11; 18289 public static final int DUMP_PREFERRED = 1 << 12; 18290 public static final int DUMP_PREFERRED_XML = 1 << 13; 18291 public static final int DUMP_KEYSETS = 1 << 14; 18292 public static final int DUMP_VERSION = 1 << 15; 18293 public static final int DUMP_INSTALLS = 1 << 16; 18294 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18295 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18296 public static final int DUMP_FROZEN = 1 << 19; 18297 public static final int DUMP_DEXOPT = 1 << 20; 18298 public static final int DUMP_COMPILER_STATS = 1 << 21; 18299 18300 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18301 18302 private int mTypes; 18303 18304 private int mOptions; 18305 18306 private boolean mTitlePrinted; 18307 18308 private SharedUserSetting mSharedUser; 18309 18310 public boolean isDumping(int type) { 18311 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18312 return true; 18313 } 18314 18315 return (mTypes & type) != 0; 18316 } 18317 18318 public void setDump(int type) { 18319 mTypes |= type; 18320 } 18321 18322 public boolean isOptionEnabled(int option) { 18323 return (mOptions & option) != 0; 18324 } 18325 18326 public void setOptionEnabled(int option) { 18327 mOptions |= option; 18328 } 18329 18330 public boolean onTitlePrinted() { 18331 final boolean printed = mTitlePrinted; 18332 mTitlePrinted = true; 18333 return printed; 18334 } 18335 18336 public boolean getTitlePrinted() { 18337 return mTitlePrinted; 18338 } 18339 18340 public void setTitlePrinted(boolean enabled) { 18341 mTitlePrinted = enabled; 18342 } 18343 18344 public SharedUserSetting getSharedUser() { 18345 return mSharedUser; 18346 } 18347 18348 public void setSharedUser(SharedUserSetting user) { 18349 mSharedUser = user; 18350 } 18351 } 18352 18353 @Override 18354 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18355 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18356 (new PackageManagerShellCommand(this)).exec( 18357 this, in, out, err, args, resultReceiver); 18358 } 18359 18360 @Override 18361 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18362 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18363 != PackageManager.PERMISSION_GRANTED) { 18364 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18365 + Binder.getCallingPid() 18366 + ", uid=" + Binder.getCallingUid() 18367 + " without permission " 18368 + android.Manifest.permission.DUMP); 18369 return; 18370 } 18371 18372 DumpState dumpState = new DumpState(); 18373 boolean fullPreferred = false; 18374 boolean checkin = false; 18375 18376 String packageName = null; 18377 ArraySet<String> permissionNames = null; 18378 18379 int opti = 0; 18380 while (opti < args.length) { 18381 String opt = args[opti]; 18382 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18383 break; 18384 } 18385 opti++; 18386 18387 if ("-a".equals(opt)) { 18388 // Right now we only know how to print all. 18389 } else if ("-h".equals(opt)) { 18390 pw.println("Package manager dump options:"); 18391 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18392 pw.println(" --checkin: dump for a checkin"); 18393 pw.println(" -f: print details of intent filters"); 18394 pw.println(" -h: print this help"); 18395 pw.println(" cmd may be one of:"); 18396 pw.println(" l[ibraries]: list known shared libraries"); 18397 pw.println(" f[eatures]: list device features"); 18398 pw.println(" k[eysets]: print known keysets"); 18399 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18400 pw.println(" perm[issions]: dump permissions"); 18401 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18402 pw.println(" pref[erred]: print preferred package settings"); 18403 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18404 pw.println(" prov[iders]: dump content providers"); 18405 pw.println(" p[ackages]: dump installed packages"); 18406 pw.println(" s[hared-users]: dump shared user IDs"); 18407 pw.println(" m[essages]: print collected runtime messages"); 18408 pw.println(" v[erifiers]: print package verifier info"); 18409 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18410 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18411 pw.println(" version: print database version info"); 18412 pw.println(" write: write current settings now"); 18413 pw.println(" installs: details about install sessions"); 18414 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18415 pw.println(" dexopt: dump dexopt state"); 18416 pw.println(" compiler-stats: dump compiler statistics"); 18417 pw.println(" <package.name>: info about given package"); 18418 return; 18419 } else if ("--checkin".equals(opt)) { 18420 checkin = true; 18421 } else if ("-f".equals(opt)) { 18422 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18423 } else { 18424 pw.println("Unknown argument: " + opt + "; use -h for help"); 18425 } 18426 } 18427 18428 // Is the caller requesting to dump a particular piece of data? 18429 if (opti < args.length) { 18430 String cmd = args[opti]; 18431 opti++; 18432 // Is this a package name? 18433 if ("android".equals(cmd) || cmd.contains(".")) { 18434 packageName = cmd; 18435 // When dumping a single package, we always dump all of its 18436 // filter information since the amount of data will be reasonable. 18437 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18438 } else if ("check-permission".equals(cmd)) { 18439 if (opti >= args.length) { 18440 pw.println("Error: check-permission missing permission argument"); 18441 return; 18442 } 18443 String perm = args[opti]; 18444 opti++; 18445 if (opti >= args.length) { 18446 pw.println("Error: check-permission missing package argument"); 18447 return; 18448 } 18449 String pkg = args[opti]; 18450 opti++; 18451 int user = UserHandle.getUserId(Binder.getCallingUid()); 18452 if (opti < args.length) { 18453 try { 18454 user = Integer.parseInt(args[opti]); 18455 } catch (NumberFormatException e) { 18456 pw.println("Error: check-permission user argument is not a number: " 18457 + args[opti]); 18458 return; 18459 } 18460 } 18461 pw.println(checkPermission(perm, pkg, user)); 18462 return; 18463 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18464 dumpState.setDump(DumpState.DUMP_LIBS); 18465 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18466 dumpState.setDump(DumpState.DUMP_FEATURES); 18467 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18468 if (opti >= args.length) { 18469 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18470 | DumpState.DUMP_SERVICE_RESOLVERS 18471 | DumpState.DUMP_RECEIVER_RESOLVERS 18472 | DumpState.DUMP_CONTENT_RESOLVERS); 18473 } else { 18474 while (opti < args.length) { 18475 String name = args[opti]; 18476 if ("a".equals(name) || "activity".equals(name)) { 18477 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18478 } else if ("s".equals(name) || "service".equals(name)) { 18479 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18480 } else if ("r".equals(name) || "receiver".equals(name)) { 18481 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18482 } else if ("c".equals(name) || "content".equals(name)) { 18483 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18484 } else { 18485 pw.println("Error: unknown resolver table type: " + name); 18486 return; 18487 } 18488 opti++; 18489 } 18490 } 18491 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18492 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18493 } else if ("permission".equals(cmd)) { 18494 if (opti >= args.length) { 18495 pw.println("Error: permission requires permission name"); 18496 return; 18497 } 18498 permissionNames = new ArraySet<>(); 18499 while (opti < args.length) { 18500 permissionNames.add(args[opti]); 18501 opti++; 18502 } 18503 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18504 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18505 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18506 dumpState.setDump(DumpState.DUMP_PREFERRED); 18507 } else if ("preferred-xml".equals(cmd)) { 18508 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18509 if (opti < args.length && "--full".equals(args[opti])) { 18510 fullPreferred = true; 18511 opti++; 18512 } 18513 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18514 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18515 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18516 dumpState.setDump(DumpState.DUMP_PACKAGES); 18517 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18518 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18519 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18520 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18521 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18522 dumpState.setDump(DumpState.DUMP_MESSAGES); 18523 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18524 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18525 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18526 || "intent-filter-verifiers".equals(cmd)) { 18527 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18528 } else if ("version".equals(cmd)) { 18529 dumpState.setDump(DumpState.DUMP_VERSION); 18530 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18531 dumpState.setDump(DumpState.DUMP_KEYSETS); 18532 } else if ("installs".equals(cmd)) { 18533 dumpState.setDump(DumpState.DUMP_INSTALLS); 18534 } else if ("frozen".equals(cmd)) { 18535 dumpState.setDump(DumpState.DUMP_FROZEN); 18536 } else if ("dexopt".equals(cmd)) { 18537 dumpState.setDump(DumpState.DUMP_DEXOPT); 18538 } else if ("compiler-stats".equals(cmd)) { 18539 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18540 } else if ("write".equals(cmd)) { 18541 synchronized (mPackages) { 18542 mSettings.writeLPr(); 18543 pw.println("Settings written."); 18544 return; 18545 } 18546 } 18547 } 18548 18549 if (checkin) { 18550 pw.println("vers,1"); 18551 } 18552 18553 // reader 18554 synchronized (mPackages) { 18555 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18556 if (!checkin) { 18557 if (dumpState.onTitlePrinted()) 18558 pw.println(); 18559 pw.println("Database versions:"); 18560 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18561 } 18562 } 18563 18564 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18565 if (!checkin) { 18566 if (dumpState.onTitlePrinted()) 18567 pw.println(); 18568 pw.println("Verifiers:"); 18569 pw.print(" Required: "); 18570 pw.print(mRequiredVerifierPackage); 18571 pw.print(" (uid="); 18572 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18573 UserHandle.USER_SYSTEM)); 18574 pw.println(")"); 18575 } else if (mRequiredVerifierPackage != null) { 18576 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18577 pw.print(","); 18578 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18579 UserHandle.USER_SYSTEM)); 18580 } 18581 } 18582 18583 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18584 packageName == null) { 18585 if (mIntentFilterVerifierComponent != null) { 18586 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18587 if (!checkin) { 18588 if (dumpState.onTitlePrinted()) 18589 pw.println(); 18590 pw.println("Intent Filter Verifier:"); 18591 pw.print(" Using: "); 18592 pw.print(verifierPackageName); 18593 pw.print(" (uid="); 18594 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18595 UserHandle.USER_SYSTEM)); 18596 pw.println(")"); 18597 } else if (verifierPackageName != null) { 18598 pw.print("ifv,"); pw.print(verifierPackageName); 18599 pw.print(","); 18600 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18601 UserHandle.USER_SYSTEM)); 18602 } 18603 } else { 18604 pw.println(); 18605 pw.println("No Intent Filter Verifier available!"); 18606 } 18607 } 18608 18609 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18610 boolean printedHeader = false; 18611 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18612 while (it.hasNext()) { 18613 String name = it.next(); 18614 SharedLibraryEntry ent = mSharedLibraries.get(name); 18615 if (!checkin) { 18616 if (!printedHeader) { 18617 if (dumpState.onTitlePrinted()) 18618 pw.println(); 18619 pw.println("Libraries:"); 18620 printedHeader = true; 18621 } 18622 pw.print(" "); 18623 } else { 18624 pw.print("lib,"); 18625 } 18626 pw.print(name); 18627 if (!checkin) { 18628 pw.print(" -> "); 18629 } 18630 if (ent.path != null) { 18631 if (!checkin) { 18632 pw.print("(jar) "); 18633 pw.print(ent.path); 18634 } else { 18635 pw.print(",jar,"); 18636 pw.print(ent.path); 18637 } 18638 } else { 18639 if (!checkin) { 18640 pw.print("(apk) "); 18641 pw.print(ent.apk); 18642 } else { 18643 pw.print(",apk,"); 18644 pw.print(ent.apk); 18645 } 18646 } 18647 pw.println(); 18648 } 18649 } 18650 18651 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18652 if (dumpState.onTitlePrinted()) 18653 pw.println(); 18654 if (!checkin) { 18655 pw.println("Features:"); 18656 } 18657 18658 for (FeatureInfo feat : mAvailableFeatures.values()) { 18659 if (checkin) { 18660 pw.print("feat,"); 18661 pw.print(feat.name); 18662 pw.print(","); 18663 pw.println(feat.version); 18664 } else { 18665 pw.print(" "); 18666 pw.print(feat.name); 18667 if (feat.version > 0) { 18668 pw.print(" version="); 18669 pw.print(feat.version); 18670 } 18671 pw.println(); 18672 } 18673 } 18674 } 18675 18676 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18677 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18678 : "Activity Resolver Table:", " ", packageName, 18679 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18680 dumpState.setTitlePrinted(true); 18681 } 18682 } 18683 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18684 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18685 : "Receiver Resolver Table:", " ", packageName, 18686 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18687 dumpState.setTitlePrinted(true); 18688 } 18689 } 18690 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18691 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18692 : "Service Resolver Table:", " ", packageName, 18693 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18694 dumpState.setTitlePrinted(true); 18695 } 18696 } 18697 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18698 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18699 : "Provider Resolver Table:", " ", packageName, 18700 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18701 dumpState.setTitlePrinted(true); 18702 } 18703 } 18704 18705 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18706 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18707 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18708 int user = mSettings.mPreferredActivities.keyAt(i); 18709 if (pir.dump(pw, 18710 dumpState.getTitlePrinted() 18711 ? "\nPreferred Activities User " + user + ":" 18712 : "Preferred Activities User " + user + ":", " ", 18713 packageName, true, false)) { 18714 dumpState.setTitlePrinted(true); 18715 } 18716 } 18717 } 18718 18719 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18720 pw.flush(); 18721 FileOutputStream fout = new FileOutputStream(fd); 18722 BufferedOutputStream str = new BufferedOutputStream(fout); 18723 XmlSerializer serializer = new FastXmlSerializer(); 18724 try { 18725 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18726 serializer.startDocument(null, true); 18727 serializer.setFeature( 18728 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18729 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18730 serializer.endDocument(); 18731 serializer.flush(); 18732 } catch (IllegalArgumentException e) { 18733 pw.println("Failed writing: " + e); 18734 } catch (IllegalStateException e) { 18735 pw.println("Failed writing: " + e); 18736 } catch (IOException e) { 18737 pw.println("Failed writing: " + e); 18738 } 18739 } 18740 18741 if (!checkin 18742 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18743 && packageName == null) { 18744 pw.println(); 18745 int count = mSettings.mPackages.size(); 18746 if (count == 0) { 18747 pw.println("No applications!"); 18748 pw.println(); 18749 } else { 18750 final String prefix = " "; 18751 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18752 if (allPackageSettings.size() == 0) { 18753 pw.println("No domain preferred apps!"); 18754 pw.println(); 18755 } else { 18756 pw.println("App verification status:"); 18757 pw.println(); 18758 count = 0; 18759 for (PackageSetting ps : allPackageSettings) { 18760 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18761 if (ivi == null || ivi.getPackageName() == null) continue; 18762 pw.println(prefix + "Package: " + ivi.getPackageName()); 18763 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18764 pw.println(prefix + "Status: " + ivi.getStatusString()); 18765 pw.println(); 18766 count++; 18767 } 18768 if (count == 0) { 18769 pw.println(prefix + "No app verification established."); 18770 pw.println(); 18771 } 18772 for (int userId : sUserManager.getUserIds()) { 18773 pw.println("App linkages for user " + userId + ":"); 18774 pw.println(); 18775 count = 0; 18776 for (PackageSetting ps : allPackageSettings) { 18777 final long status = ps.getDomainVerificationStatusForUser(userId); 18778 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18779 continue; 18780 } 18781 pw.println(prefix + "Package: " + ps.name); 18782 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18783 String statusStr = IntentFilterVerificationInfo. 18784 getStatusStringFromValue(status); 18785 pw.println(prefix + "Status: " + statusStr); 18786 pw.println(); 18787 count++; 18788 } 18789 if (count == 0) { 18790 pw.println(prefix + "No configured app linkages."); 18791 pw.println(); 18792 } 18793 } 18794 } 18795 } 18796 } 18797 18798 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18799 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18800 if (packageName == null && permissionNames == null) { 18801 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18802 if (iperm == 0) { 18803 if (dumpState.onTitlePrinted()) 18804 pw.println(); 18805 pw.println("AppOp Permissions:"); 18806 } 18807 pw.print(" AppOp Permission "); 18808 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18809 pw.println(":"); 18810 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18811 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18812 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18813 } 18814 } 18815 } 18816 } 18817 18818 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18819 boolean printedSomething = false; 18820 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18821 if (packageName != null && !packageName.equals(p.info.packageName)) { 18822 continue; 18823 } 18824 if (!printedSomething) { 18825 if (dumpState.onTitlePrinted()) 18826 pw.println(); 18827 pw.println("Registered ContentProviders:"); 18828 printedSomething = true; 18829 } 18830 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18831 pw.print(" "); pw.println(p.toString()); 18832 } 18833 printedSomething = false; 18834 for (Map.Entry<String, PackageParser.Provider> entry : 18835 mProvidersByAuthority.entrySet()) { 18836 PackageParser.Provider p = entry.getValue(); 18837 if (packageName != null && !packageName.equals(p.info.packageName)) { 18838 continue; 18839 } 18840 if (!printedSomething) { 18841 if (dumpState.onTitlePrinted()) 18842 pw.println(); 18843 pw.println("ContentProvider Authorities:"); 18844 printedSomething = true; 18845 } 18846 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18847 pw.print(" "); pw.println(p.toString()); 18848 if (p.info != null && p.info.applicationInfo != null) { 18849 final String appInfo = p.info.applicationInfo.toString(); 18850 pw.print(" applicationInfo="); pw.println(appInfo); 18851 } 18852 } 18853 } 18854 18855 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18856 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18857 } 18858 18859 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18860 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18861 } 18862 18863 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18864 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18865 } 18866 18867 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18868 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18869 } 18870 18871 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18872 // XXX should handle packageName != null by dumping only install data that 18873 // the given package is involved with. 18874 if (dumpState.onTitlePrinted()) pw.println(); 18875 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18876 } 18877 18878 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18879 // XXX should handle packageName != null by dumping only install data that 18880 // the given package is involved with. 18881 if (dumpState.onTitlePrinted()) pw.println(); 18882 18883 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18884 ipw.println(); 18885 ipw.println("Frozen packages:"); 18886 ipw.increaseIndent(); 18887 if (mFrozenPackages.size() == 0) { 18888 ipw.println("(none)"); 18889 } else { 18890 for (int i = 0; i < mFrozenPackages.size(); i++) { 18891 ipw.println(mFrozenPackages.valueAt(i)); 18892 } 18893 } 18894 ipw.decreaseIndent(); 18895 } 18896 18897 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18898 if (dumpState.onTitlePrinted()) pw.println(); 18899 dumpDexoptStateLPr(pw, packageName); 18900 } 18901 18902 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18903 if (dumpState.onTitlePrinted()) pw.println(); 18904 dumpCompilerStatsLPr(pw, packageName); 18905 } 18906 18907 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18908 if (dumpState.onTitlePrinted()) pw.println(); 18909 mSettings.dumpReadMessagesLPr(pw, dumpState); 18910 18911 pw.println(); 18912 pw.println("Package warning messages:"); 18913 BufferedReader in = null; 18914 String line = null; 18915 try { 18916 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18917 while ((line = in.readLine()) != null) { 18918 if (line.contains("ignored: updated version")) continue; 18919 pw.println(line); 18920 } 18921 } catch (IOException ignored) { 18922 } finally { 18923 IoUtils.closeQuietly(in); 18924 } 18925 } 18926 18927 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18928 BufferedReader in = null; 18929 String line = null; 18930 try { 18931 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18932 while ((line = in.readLine()) != null) { 18933 if (line.contains("ignored: updated version")) continue; 18934 pw.print("msg,"); 18935 pw.println(line); 18936 } 18937 } catch (IOException ignored) { 18938 } finally { 18939 IoUtils.closeQuietly(in); 18940 } 18941 } 18942 } 18943 } 18944 18945 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18946 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18947 ipw.println(); 18948 ipw.println("Dexopt state:"); 18949 ipw.increaseIndent(); 18950 Collection<PackageParser.Package> packages = null; 18951 if (packageName != null) { 18952 PackageParser.Package targetPackage = mPackages.get(packageName); 18953 if (targetPackage != null) { 18954 packages = Collections.singletonList(targetPackage); 18955 } else { 18956 ipw.println("Unable to find package: " + packageName); 18957 return; 18958 } 18959 } else { 18960 packages = mPackages.values(); 18961 } 18962 18963 for (PackageParser.Package pkg : packages) { 18964 ipw.println("[" + pkg.packageName + "]"); 18965 ipw.increaseIndent(); 18966 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18967 ipw.decreaseIndent(); 18968 } 18969 } 18970 18971 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18972 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18973 ipw.println(); 18974 ipw.println("Compiler stats:"); 18975 ipw.increaseIndent(); 18976 Collection<PackageParser.Package> packages = null; 18977 if (packageName != null) { 18978 PackageParser.Package targetPackage = mPackages.get(packageName); 18979 if (targetPackage != null) { 18980 packages = Collections.singletonList(targetPackage); 18981 } else { 18982 ipw.println("Unable to find package: " + packageName); 18983 return; 18984 } 18985 } else { 18986 packages = mPackages.values(); 18987 } 18988 18989 for (PackageParser.Package pkg : packages) { 18990 ipw.println("[" + pkg.packageName + "]"); 18991 ipw.increaseIndent(); 18992 18993 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18994 if (stats == null) { 18995 ipw.println("(No recorded stats)"); 18996 } else { 18997 stats.dump(ipw); 18998 } 18999 ipw.decreaseIndent(); 19000 } 19001 } 19002 19003 private String dumpDomainString(String packageName) { 19004 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19005 .getList(); 19006 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19007 19008 ArraySet<String> result = new ArraySet<>(); 19009 if (iviList.size() > 0) { 19010 for (IntentFilterVerificationInfo ivi : iviList) { 19011 for (String host : ivi.getDomains()) { 19012 result.add(host); 19013 } 19014 } 19015 } 19016 if (filters != null && filters.size() > 0) { 19017 for (IntentFilter filter : filters) { 19018 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19019 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19020 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19021 result.addAll(filter.getHostsList()); 19022 } 19023 } 19024 } 19025 19026 StringBuilder sb = new StringBuilder(result.size() * 16); 19027 for (String domain : result) { 19028 if (sb.length() > 0) sb.append(" "); 19029 sb.append(domain); 19030 } 19031 return sb.toString(); 19032 } 19033 19034 // ------- apps on sdcard specific code ------- 19035 static final boolean DEBUG_SD_INSTALL = false; 19036 19037 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19038 19039 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19040 19041 private boolean mMediaMounted = false; 19042 19043 static String getEncryptKey() { 19044 try { 19045 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19046 SD_ENCRYPTION_KEYSTORE_NAME); 19047 if (sdEncKey == null) { 19048 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19049 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19050 if (sdEncKey == null) { 19051 Slog.e(TAG, "Failed to create encryption keys"); 19052 return null; 19053 } 19054 } 19055 return sdEncKey; 19056 } catch (NoSuchAlgorithmException nsae) { 19057 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19058 return null; 19059 } catch (IOException ioe) { 19060 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19061 return null; 19062 } 19063 } 19064 19065 /* 19066 * Update media status on PackageManager. 19067 */ 19068 @Override 19069 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19070 int callingUid = Binder.getCallingUid(); 19071 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19072 throw new SecurityException("Media status can only be updated by the system"); 19073 } 19074 // reader; this apparently protects mMediaMounted, but should probably 19075 // be a different lock in that case. 19076 synchronized (mPackages) { 19077 Log.i(TAG, "Updating external media status from " 19078 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19079 + (mediaStatus ? "mounted" : "unmounted")); 19080 if (DEBUG_SD_INSTALL) 19081 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19082 + ", mMediaMounted=" + mMediaMounted); 19083 if (mediaStatus == mMediaMounted) { 19084 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19085 : 0, -1); 19086 mHandler.sendMessage(msg); 19087 return; 19088 } 19089 mMediaMounted = mediaStatus; 19090 } 19091 // Queue up an async operation since the package installation may take a 19092 // little while. 19093 mHandler.post(new Runnable() { 19094 public void run() { 19095 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19096 } 19097 }); 19098 } 19099 19100 /** 19101 * Called by MountService when the initial ASECs to scan are available. 19102 * Should block until all the ASEC containers are finished being scanned. 19103 */ 19104 public void scanAvailableAsecs() { 19105 updateExternalMediaStatusInner(true, false, false); 19106 } 19107 19108 /* 19109 * Collect information of applications on external media, map them against 19110 * existing containers and update information based on current mount status. 19111 * Please note that we always have to report status if reportStatus has been 19112 * set to true especially when unloading packages. 19113 */ 19114 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19115 boolean externalStorage) { 19116 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19117 int[] uidArr = EmptyArray.INT; 19118 19119 final String[] list = PackageHelper.getSecureContainerList(); 19120 if (ArrayUtils.isEmpty(list)) { 19121 Log.i(TAG, "No secure containers found"); 19122 } else { 19123 // Process list of secure containers and categorize them 19124 // as active or stale based on their package internal state. 19125 19126 // reader 19127 synchronized (mPackages) { 19128 for (String cid : list) { 19129 // Leave stages untouched for now; installer service owns them 19130 if (PackageInstallerService.isStageName(cid)) continue; 19131 19132 if (DEBUG_SD_INSTALL) 19133 Log.i(TAG, "Processing container " + cid); 19134 String pkgName = getAsecPackageName(cid); 19135 if (pkgName == null) { 19136 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19137 continue; 19138 } 19139 if (DEBUG_SD_INSTALL) 19140 Log.i(TAG, "Looking for pkg : " + pkgName); 19141 19142 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19143 if (ps == null) { 19144 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19145 continue; 19146 } 19147 19148 /* 19149 * Skip packages that are not external if we're unmounting 19150 * external storage. 19151 */ 19152 if (externalStorage && !isMounted && !isExternal(ps)) { 19153 continue; 19154 } 19155 19156 final AsecInstallArgs args = new AsecInstallArgs(cid, 19157 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19158 // The package status is changed only if the code path 19159 // matches between settings and the container id. 19160 if (ps.codePathString != null 19161 && ps.codePathString.startsWith(args.getCodePath())) { 19162 if (DEBUG_SD_INSTALL) { 19163 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19164 + " at code path: " + ps.codePathString); 19165 } 19166 19167 // We do have a valid package installed on sdcard 19168 processCids.put(args, ps.codePathString); 19169 final int uid = ps.appId; 19170 if (uid != -1) { 19171 uidArr = ArrayUtils.appendInt(uidArr, uid); 19172 } 19173 } else { 19174 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19175 + ps.codePathString); 19176 } 19177 } 19178 } 19179 19180 Arrays.sort(uidArr); 19181 } 19182 19183 // Process packages with valid entries. 19184 if (isMounted) { 19185 if (DEBUG_SD_INSTALL) 19186 Log.i(TAG, "Loading packages"); 19187 loadMediaPackages(processCids, uidArr, externalStorage); 19188 startCleaningPackages(); 19189 mInstallerService.onSecureContainersAvailable(); 19190 } else { 19191 if (DEBUG_SD_INSTALL) 19192 Log.i(TAG, "Unloading packages"); 19193 unloadMediaPackages(processCids, uidArr, reportStatus); 19194 } 19195 } 19196 19197 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19198 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19199 final int size = infos.size(); 19200 final String[] packageNames = new String[size]; 19201 final int[] packageUids = new int[size]; 19202 for (int i = 0; i < size; i++) { 19203 final ApplicationInfo info = infos.get(i); 19204 packageNames[i] = info.packageName; 19205 packageUids[i] = info.uid; 19206 } 19207 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19208 finishedReceiver); 19209 } 19210 19211 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19212 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19213 sendResourcesChangedBroadcast(mediaStatus, replacing, 19214 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19215 } 19216 19217 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19218 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19219 int size = pkgList.length; 19220 if (size > 0) { 19221 // Send broadcasts here 19222 Bundle extras = new Bundle(); 19223 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19224 if (uidArr != null) { 19225 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19226 } 19227 if (replacing) { 19228 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19229 } 19230 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19231 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19232 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19233 } 19234 } 19235 19236 /* 19237 * Look at potentially valid container ids from processCids If package 19238 * information doesn't match the one on record or package scanning fails, 19239 * the cid is added to list of removeCids. We currently don't delete stale 19240 * containers. 19241 */ 19242 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19243 boolean externalStorage) { 19244 ArrayList<String> pkgList = new ArrayList<String>(); 19245 Set<AsecInstallArgs> keys = processCids.keySet(); 19246 19247 for (AsecInstallArgs args : keys) { 19248 String codePath = processCids.get(args); 19249 if (DEBUG_SD_INSTALL) 19250 Log.i(TAG, "Loading container : " + args.cid); 19251 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19252 try { 19253 // Make sure there are no container errors first. 19254 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19255 Slog.e(TAG, "Failed to mount cid : " + args.cid 19256 + " when installing from sdcard"); 19257 continue; 19258 } 19259 // Check code path here. 19260 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19261 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19262 + " does not match one in settings " + codePath); 19263 continue; 19264 } 19265 // Parse package 19266 int parseFlags = mDefParseFlags; 19267 if (args.isExternalAsec()) { 19268 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19269 } 19270 if (args.isFwdLocked()) { 19271 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19272 } 19273 19274 synchronized (mInstallLock) { 19275 PackageParser.Package pkg = null; 19276 try { 19277 // Sadly we don't know the package name yet to freeze it 19278 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19279 SCAN_IGNORE_FROZEN, 0, null); 19280 } catch (PackageManagerException e) { 19281 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19282 } 19283 // Scan the package 19284 if (pkg != null) { 19285 /* 19286 * TODO why is the lock being held? doPostInstall is 19287 * called in other places without the lock. This needs 19288 * to be straightened out. 19289 */ 19290 // writer 19291 synchronized (mPackages) { 19292 retCode = PackageManager.INSTALL_SUCCEEDED; 19293 pkgList.add(pkg.packageName); 19294 // Post process args 19295 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19296 pkg.applicationInfo.uid); 19297 } 19298 } else { 19299 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19300 } 19301 } 19302 19303 } finally { 19304 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19305 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19306 } 19307 } 19308 } 19309 // writer 19310 synchronized (mPackages) { 19311 // If the platform SDK has changed since the last time we booted, 19312 // we need to re-grant app permission to catch any new ones that 19313 // appear. This is really a hack, and means that apps can in some 19314 // cases get permissions that the user didn't initially explicitly 19315 // allow... it would be nice to have some better way to handle 19316 // this situation. 19317 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19318 : mSettings.getInternalVersion(); 19319 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19320 : StorageManager.UUID_PRIVATE_INTERNAL; 19321 19322 int updateFlags = UPDATE_PERMISSIONS_ALL; 19323 if (ver.sdkVersion != mSdkVersion) { 19324 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19325 + mSdkVersion + "; regranting permissions for external"); 19326 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19327 } 19328 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19329 19330 // Yay, everything is now upgraded 19331 ver.forceCurrent(); 19332 19333 // can downgrade to reader 19334 // Persist settings 19335 mSettings.writeLPr(); 19336 } 19337 // Send a broadcast to let everyone know we are done processing 19338 if (pkgList.size() > 0) { 19339 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19340 } 19341 } 19342 19343 /* 19344 * Utility method to unload a list of specified containers 19345 */ 19346 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19347 // Just unmount all valid containers. 19348 for (AsecInstallArgs arg : cidArgs) { 19349 synchronized (mInstallLock) { 19350 arg.doPostDeleteLI(false); 19351 } 19352 } 19353 } 19354 19355 /* 19356 * Unload packages mounted on external media. This involves deleting package 19357 * data from internal structures, sending broadcasts about disabled packages, 19358 * gc'ing to free up references, unmounting all secure containers 19359 * corresponding to packages on external media, and posting a 19360 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19361 * that we always have to post this message if status has been requested no 19362 * matter what. 19363 */ 19364 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19365 final boolean reportStatus) { 19366 if (DEBUG_SD_INSTALL) 19367 Log.i(TAG, "unloading media packages"); 19368 ArrayList<String> pkgList = new ArrayList<String>(); 19369 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19370 final Set<AsecInstallArgs> keys = processCids.keySet(); 19371 for (AsecInstallArgs args : keys) { 19372 String pkgName = args.getPackageName(); 19373 if (DEBUG_SD_INSTALL) 19374 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19375 // Delete package internally 19376 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19377 synchronized (mInstallLock) { 19378 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19379 final boolean res; 19380 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19381 "unloadMediaPackages")) { 19382 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19383 null); 19384 } 19385 if (res) { 19386 pkgList.add(pkgName); 19387 } else { 19388 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19389 failedList.add(args); 19390 } 19391 } 19392 } 19393 19394 // reader 19395 synchronized (mPackages) { 19396 // We didn't update the settings after removing each package; 19397 // write them now for all packages. 19398 mSettings.writeLPr(); 19399 } 19400 19401 // We have to absolutely send UPDATED_MEDIA_STATUS only 19402 // after confirming that all the receivers processed the ordered 19403 // broadcast when packages get disabled, force a gc to clean things up. 19404 // and unload all the containers. 19405 if (pkgList.size() > 0) { 19406 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19407 new IIntentReceiver.Stub() { 19408 public void performReceive(Intent intent, int resultCode, String data, 19409 Bundle extras, boolean ordered, boolean sticky, 19410 int sendingUser) throws RemoteException { 19411 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19412 reportStatus ? 1 : 0, 1, keys); 19413 mHandler.sendMessage(msg); 19414 } 19415 }); 19416 } else { 19417 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19418 keys); 19419 mHandler.sendMessage(msg); 19420 } 19421 } 19422 19423 private void loadPrivatePackages(final VolumeInfo vol) { 19424 mHandler.post(new Runnable() { 19425 @Override 19426 public void run() { 19427 loadPrivatePackagesInner(vol); 19428 } 19429 }); 19430 } 19431 19432 private void loadPrivatePackagesInner(VolumeInfo vol) { 19433 final String volumeUuid = vol.fsUuid; 19434 if (TextUtils.isEmpty(volumeUuid)) { 19435 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19436 return; 19437 } 19438 19439 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19440 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19441 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19442 19443 final VersionInfo ver; 19444 final List<PackageSetting> packages; 19445 synchronized (mPackages) { 19446 ver = mSettings.findOrCreateVersion(volumeUuid); 19447 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19448 } 19449 19450 for (PackageSetting ps : packages) { 19451 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19452 synchronized (mInstallLock) { 19453 final PackageParser.Package pkg; 19454 try { 19455 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19456 loaded.add(pkg.applicationInfo); 19457 19458 } catch (PackageManagerException e) { 19459 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19460 } 19461 19462 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19463 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19464 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19465 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19466 } 19467 } 19468 } 19469 19470 // Reconcile app data for all started/unlocked users 19471 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19472 final UserManager um = mContext.getSystemService(UserManager.class); 19473 UserManagerInternal umInternal = getUserManagerInternal(); 19474 for (UserInfo user : um.getUsers()) { 19475 final int flags; 19476 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19477 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19478 } else if (umInternal.isUserRunning(user.id)) { 19479 flags = StorageManager.FLAG_STORAGE_DE; 19480 } else { 19481 continue; 19482 } 19483 19484 try { 19485 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19486 synchronized (mInstallLock) { 19487 reconcileAppsDataLI(volumeUuid, user.id, flags); 19488 } 19489 } catch (IllegalStateException e) { 19490 // Device was probably ejected, and we'll process that event momentarily 19491 Slog.w(TAG, "Failed to prepare storage: " + e); 19492 } 19493 } 19494 19495 synchronized (mPackages) { 19496 int updateFlags = UPDATE_PERMISSIONS_ALL; 19497 if (ver.sdkVersion != mSdkVersion) { 19498 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19499 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19500 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19501 } 19502 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19503 19504 // Yay, everything is now upgraded 19505 ver.forceCurrent(); 19506 19507 mSettings.writeLPr(); 19508 } 19509 19510 for (PackageFreezer freezer : freezers) { 19511 freezer.close(); 19512 } 19513 19514 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19515 sendResourcesChangedBroadcast(true, false, loaded, null); 19516 } 19517 19518 private void unloadPrivatePackages(final VolumeInfo vol) { 19519 mHandler.post(new Runnable() { 19520 @Override 19521 public void run() { 19522 unloadPrivatePackagesInner(vol); 19523 } 19524 }); 19525 } 19526 19527 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19528 final String volumeUuid = vol.fsUuid; 19529 if (TextUtils.isEmpty(volumeUuid)) { 19530 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19531 return; 19532 } 19533 19534 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19535 synchronized (mInstallLock) { 19536 synchronized (mPackages) { 19537 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19538 for (PackageSetting ps : packages) { 19539 if (ps.pkg == null) continue; 19540 19541 final ApplicationInfo info = ps.pkg.applicationInfo; 19542 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19543 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19544 19545 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19546 "unloadPrivatePackagesInner")) { 19547 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19548 false, null)) { 19549 unloaded.add(info); 19550 } else { 19551 Slog.w(TAG, "Failed to unload " + ps.codePath); 19552 } 19553 } 19554 19555 // Try very hard to release any references to this package 19556 // so we don't risk the system server being killed due to 19557 // open FDs 19558 AttributeCache.instance().removePackage(ps.name); 19559 } 19560 19561 mSettings.writeLPr(); 19562 } 19563 } 19564 19565 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19566 sendResourcesChangedBroadcast(false, false, unloaded, null); 19567 19568 // Try very hard to release any references to this path so we don't risk 19569 // the system server being killed due to open FDs 19570 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19571 19572 for (int i = 0; i < 3; i++) { 19573 System.gc(); 19574 System.runFinalization(); 19575 } 19576 } 19577 19578 /** 19579 * Prepare storage areas for given user on all mounted devices. 19580 */ 19581 void prepareUserData(int userId, int userSerial, int flags) { 19582 synchronized (mInstallLock) { 19583 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19584 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19585 final String volumeUuid = vol.getFsUuid(); 19586 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19587 } 19588 } 19589 } 19590 19591 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19592 boolean allowRecover) { 19593 // Prepare storage and verify that serial numbers are consistent; if 19594 // there's a mismatch we need to destroy to avoid leaking data 19595 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19596 try { 19597 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19598 19599 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19600 UserManagerService.enforceSerialNumber( 19601 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19602 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19603 UserManagerService.enforceSerialNumber( 19604 Environment.getDataSystemDeDirectory(userId), userSerial); 19605 } 19606 } 19607 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19608 UserManagerService.enforceSerialNumber( 19609 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19610 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19611 UserManagerService.enforceSerialNumber( 19612 Environment.getDataSystemCeDirectory(userId), userSerial); 19613 } 19614 } 19615 19616 synchronized (mInstallLock) { 19617 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19618 } 19619 } catch (Exception e) { 19620 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19621 + " because we failed to prepare: " + e); 19622 destroyUserDataLI(volumeUuid, userId, 19623 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19624 19625 if (allowRecover) { 19626 // Try one last time; if we fail again we're really in trouble 19627 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19628 } 19629 } 19630 } 19631 19632 /** 19633 * Destroy storage areas for given user on all mounted devices. 19634 */ 19635 void destroyUserData(int userId, int flags) { 19636 synchronized (mInstallLock) { 19637 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19638 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19639 final String volumeUuid = vol.getFsUuid(); 19640 destroyUserDataLI(volumeUuid, userId, flags); 19641 } 19642 } 19643 } 19644 19645 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19646 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19647 try { 19648 // Clean up app data, profile data, and media data 19649 mInstaller.destroyUserData(volumeUuid, userId, flags); 19650 19651 // Clean up system data 19652 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19653 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19654 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19655 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19656 } 19657 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19658 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19659 } 19660 } 19661 19662 // Data with special labels is now gone, so finish the job 19663 storage.destroyUserStorage(volumeUuid, userId, flags); 19664 19665 } catch (Exception e) { 19666 logCriticalInfo(Log.WARN, 19667 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19668 } 19669 } 19670 19671 /** 19672 * Examine all users present on given mounted volume, and destroy data 19673 * belonging to users that are no longer valid, or whose user ID has been 19674 * recycled. 19675 */ 19676 private void reconcileUsers(String volumeUuid) { 19677 final List<File> files = new ArrayList<>(); 19678 Collections.addAll(files, FileUtils 19679 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19680 Collections.addAll(files, FileUtils 19681 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19682 Collections.addAll(files, FileUtils 19683 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19684 Collections.addAll(files, FileUtils 19685 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19686 for (File file : files) { 19687 if (!file.isDirectory()) continue; 19688 19689 final int userId; 19690 final UserInfo info; 19691 try { 19692 userId = Integer.parseInt(file.getName()); 19693 info = sUserManager.getUserInfo(userId); 19694 } catch (NumberFormatException e) { 19695 Slog.w(TAG, "Invalid user directory " + file); 19696 continue; 19697 } 19698 19699 boolean destroyUser = false; 19700 if (info == null) { 19701 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19702 + " because no matching user was found"); 19703 destroyUser = true; 19704 } else if (!mOnlyCore) { 19705 try { 19706 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19707 } catch (IOException e) { 19708 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19709 + " because we failed to enforce serial number: " + e); 19710 destroyUser = true; 19711 } 19712 } 19713 19714 if (destroyUser) { 19715 synchronized (mInstallLock) { 19716 destroyUserDataLI(volumeUuid, userId, 19717 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19718 } 19719 } 19720 } 19721 } 19722 19723 private void assertPackageKnown(String volumeUuid, String packageName) 19724 throws PackageManagerException { 19725 synchronized (mPackages) { 19726 final PackageSetting ps = mSettings.mPackages.get(packageName); 19727 if (ps == null) { 19728 throw new PackageManagerException("Package " + packageName + " is unknown"); 19729 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19730 throw new PackageManagerException( 19731 "Package " + packageName + " found on unknown volume " + volumeUuid 19732 + "; expected volume " + ps.volumeUuid); 19733 } 19734 } 19735 } 19736 19737 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19738 throws PackageManagerException { 19739 synchronized (mPackages) { 19740 final PackageSetting ps = mSettings.mPackages.get(packageName); 19741 if (ps == null) { 19742 throw new PackageManagerException("Package " + packageName + " is unknown"); 19743 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19744 throw new PackageManagerException( 19745 "Package " + packageName + " found on unknown volume " + volumeUuid 19746 + "; expected volume " + ps.volumeUuid); 19747 } else if (!ps.getInstalled(userId)) { 19748 throw new PackageManagerException( 19749 "Package " + packageName + " not installed for user " + userId); 19750 } 19751 } 19752 } 19753 19754 /** 19755 * Examine all apps present on given mounted volume, and destroy apps that 19756 * aren't expected, either due to uninstallation or reinstallation on 19757 * another volume. 19758 */ 19759 private void reconcileApps(String volumeUuid) { 19760 final File[] files = FileUtils 19761 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19762 for (File file : files) { 19763 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19764 && !PackageInstallerService.isStageName(file.getName()); 19765 if (!isPackage) { 19766 // Ignore entries which are not packages 19767 continue; 19768 } 19769 19770 try { 19771 final PackageLite pkg = PackageParser.parsePackageLite(file, 19772 PackageParser.PARSE_MUST_BE_APK); 19773 assertPackageKnown(volumeUuid, pkg.packageName); 19774 19775 } catch (PackageParserException | PackageManagerException e) { 19776 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19777 synchronized (mInstallLock) { 19778 removeCodePathLI(file); 19779 } 19780 } 19781 } 19782 } 19783 19784 /** 19785 * Reconcile all app data for the given user. 19786 * <p> 19787 * Verifies that directories exist and that ownership and labeling is 19788 * correct for all installed apps on all mounted volumes. 19789 */ 19790 void reconcileAppsData(int userId, int flags) { 19791 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19792 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19793 final String volumeUuid = vol.getFsUuid(); 19794 synchronized (mInstallLock) { 19795 reconcileAppsDataLI(volumeUuid, userId, flags); 19796 } 19797 } 19798 } 19799 19800 /** 19801 * Reconcile all app data on given mounted volume. 19802 * <p> 19803 * Destroys app data that isn't expected, either due to uninstallation or 19804 * reinstallation on another volume. 19805 * <p> 19806 * Verifies that directories exist and that ownership and labeling is 19807 * correct for all installed apps. 19808 */ 19809 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19810 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19811 + Integer.toHexString(flags)); 19812 19813 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19814 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19815 19816 // First look for stale data that doesn't belong, and check if things 19817 // have changed since we did our last restorecon 19818 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19819 if (StorageManager.isFileEncryptedNativeOrEmulated() 19820 && !StorageManager.isUserKeyUnlocked(userId)) { 19821 throw new RuntimeException( 19822 "Yikes, someone asked us to reconcile CE storage while " + userId 19823 + " was still locked; this would have caused massive data loss!"); 19824 } 19825 19826 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19827 for (File file : files) { 19828 final String packageName = file.getName(); 19829 try { 19830 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19831 } catch (PackageManagerException e) { 19832 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19833 try { 19834 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19835 StorageManager.FLAG_STORAGE_CE, 0); 19836 } catch (InstallerException e2) { 19837 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19838 } 19839 } 19840 } 19841 } 19842 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19843 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19844 for (File file : files) { 19845 final String packageName = file.getName(); 19846 try { 19847 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19848 } catch (PackageManagerException e) { 19849 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19850 try { 19851 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19852 StorageManager.FLAG_STORAGE_DE, 0); 19853 } catch (InstallerException e2) { 19854 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19855 } 19856 } 19857 } 19858 } 19859 19860 // Ensure that data directories are ready to roll for all packages 19861 // installed for this volume and user 19862 final List<PackageSetting> packages; 19863 synchronized (mPackages) { 19864 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19865 } 19866 int preparedCount = 0; 19867 for (PackageSetting ps : packages) { 19868 final String packageName = ps.name; 19869 if (ps.pkg == null) { 19870 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19871 // TODO: might be due to legacy ASEC apps; we should circle back 19872 // and reconcile again once they're scanned 19873 continue; 19874 } 19875 19876 if (ps.getInstalled(userId)) { 19877 prepareAppDataLIF(ps.pkg, userId, flags); 19878 19879 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19880 // We may have just shuffled around app data directories, so 19881 // prepare them one more time 19882 prepareAppDataLIF(ps.pkg, userId, flags); 19883 } 19884 19885 preparedCount++; 19886 } 19887 } 19888 19889 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19890 } 19891 19892 /** 19893 * Prepare app data for the given app just after it was installed or 19894 * upgraded. This method carefully only touches users that it's installed 19895 * for, and it forces a restorecon to handle any seinfo changes. 19896 * <p> 19897 * Verifies that directories exist and that ownership and labeling is 19898 * correct for all installed apps. If there is an ownership mismatch, it 19899 * will try recovering system apps by wiping data; third-party app data is 19900 * left intact. 19901 * <p> 19902 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19903 */ 19904 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19905 final PackageSetting ps; 19906 synchronized (mPackages) { 19907 ps = mSettings.mPackages.get(pkg.packageName); 19908 mSettings.writeKernelMappingLPr(ps); 19909 } 19910 19911 final UserManager um = mContext.getSystemService(UserManager.class); 19912 UserManagerInternal umInternal = getUserManagerInternal(); 19913 for (UserInfo user : um.getUsers()) { 19914 final int flags; 19915 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19916 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19917 } else if (umInternal.isUserRunning(user.id)) { 19918 flags = StorageManager.FLAG_STORAGE_DE; 19919 } else { 19920 continue; 19921 } 19922 19923 if (ps.getInstalled(user.id)) { 19924 // TODO: when user data is locked, mark that we're still dirty 19925 prepareAppDataLIF(pkg, user.id, flags); 19926 } 19927 } 19928 } 19929 19930 /** 19931 * Prepare app data for the given app. 19932 * <p> 19933 * Verifies that directories exist and that ownership and labeling is 19934 * correct for all installed apps. If there is an ownership mismatch, this 19935 * will try recovering system apps by wiping data; third-party app data is 19936 * left intact. 19937 */ 19938 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 19939 if (pkg == null) { 19940 Slog.wtf(TAG, "Package was null!", new Throwable()); 19941 return; 19942 } 19943 prepareAppDataLeafLIF(pkg, userId, flags); 19944 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19945 for (int i = 0; i < childCount; i++) { 19946 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 19947 } 19948 } 19949 19950 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19951 if (DEBUG_APP_DATA) { 19952 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19953 + Integer.toHexString(flags)); 19954 } 19955 19956 final String volumeUuid = pkg.volumeUuid; 19957 final String packageName = pkg.packageName; 19958 final ApplicationInfo app = pkg.applicationInfo; 19959 final int appId = UserHandle.getAppId(app.uid); 19960 19961 Preconditions.checkNotNull(app.seinfo); 19962 19963 try { 19964 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19965 appId, app.seinfo, app.targetSdkVersion); 19966 } catch (InstallerException e) { 19967 if (app.isSystemApp()) { 19968 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19969 + ", but trying to recover: " + e); 19970 destroyAppDataLeafLIF(pkg, userId, flags); 19971 try { 19972 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19973 appId, app.seinfo, app.targetSdkVersion); 19974 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19975 } catch (InstallerException e2) { 19976 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19977 } 19978 } else { 19979 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19980 } 19981 } 19982 19983 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19984 try { 19985 // CE storage is unlocked right now, so read out the inode and 19986 // remember for use later when it's locked 19987 // TODO: mark this structure as dirty so we persist it! 19988 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19989 StorageManager.FLAG_STORAGE_CE); 19990 synchronized (mPackages) { 19991 final PackageSetting ps = mSettings.mPackages.get(packageName); 19992 if (ps != null) { 19993 ps.setCeDataInode(ceDataInode, userId); 19994 } 19995 } 19996 } catch (InstallerException e) { 19997 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19998 } 19999 } 20000 20001 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20002 } 20003 20004 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20005 if (pkg == null) { 20006 Slog.wtf(TAG, "Package was null!", new Throwable()); 20007 return; 20008 } 20009 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20010 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20011 for (int i = 0; i < childCount; i++) { 20012 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20013 } 20014 } 20015 20016 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20017 final String volumeUuid = pkg.volumeUuid; 20018 final String packageName = pkg.packageName; 20019 final ApplicationInfo app = pkg.applicationInfo; 20020 20021 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20022 // Create a native library symlink only if we have native libraries 20023 // and if the native libraries are 32 bit libraries. We do not provide 20024 // this symlink for 64 bit libraries. 20025 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20026 final String nativeLibPath = app.nativeLibraryDir; 20027 try { 20028 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20029 nativeLibPath, userId); 20030 } catch (InstallerException e) { 20031 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20032 } 20033 } 20034 } 20035 } 20036 20037 /** 20038 * For system apps on non-FBE devices, this method migrates any existing 20039 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20040 * requested by the app. 20041 */ 20042 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20043 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20044 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20045 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20046 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20047 try { 20048 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20049 storageTarget); 20050 } catch (InstallerException e) { 20051 logCriticalInfo(Log.WARN, 20052 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20053 } 20054 return true; 20055 } else { 20056 return false; 20057 } 20058 } 20059 20060 public PackageFreezer freezePackage(String packageName, String killReason) { 20061 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20062 } 20063 20064 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20065 return new PackageFreezer(packageName, userId, killReason); 20066 } 20067 20068 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20069 String killReason) { 20070 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20071 } 20072 20073 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20074 String killReason) { 20075 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20076 return new PackageFreezer(); 20077 } else { 20078 return freezePackage(packageName, userId, killReason); 20079 } 20080 } 20081 20082 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20083 String killReason) { 20084 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20085 } 20086 20087 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20088 String killReason) { 20089 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20090 return new PackageFreezer(); 20091 } else { 20092 return freezePackage(packageName, userId, killReason); 20093 } 20094 } 20095 20096 /** 20097 * Class that freezes and kills the given package upon creation, and 20098 * unfreezes it upon closing. This is typically used when doing surgery on 20099 * app code/data to prevent the app from running while you're working. 20100 */ 20101 private class PackageFreezer implements AutoCloseable { 20102 private final String mPackageName; 20103 private final PackageFreezer[] mChildren; 20104 20105 private final boolean mWeFroze; 20106 20107 private final AtomicBoolean mClosed = new AtomicBoolean(); 20108 private final CloseGuard mCloseGuard = CloseGuard.get(); 20109 20110 /** 20111 * Create and return a stub freezer that doesn't actually do anything, 20112 * typically used when someone requested 20113 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20114 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20115 */ 20116 public PackageFreezer() { 20117 mPackageName = null; 20118 mChildren = null; 20119 mWeFroze = false; 20120 mCloseGuard.open("close"); 20121 } 20122 20123 public PackageFreezer(String packageName, int userId, String killReason) { 20124 synchronized (mPackages) { 20125 mPackageName = packageName; 20126 mWeFroze = mFrozenPackages.add(mPackageName); 20127 20128 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20129 if (ps != null) { 20130 killApplication(ps.name, ps.appId, userId, killReason); 20131 } 20132 20133 final PackageParser.Package p = mPackages.get(packageName); 20134 if (p != null && p.childPackages != null) { 20135 final int N = p.childPackages.size(); 20136 mChildren = new PackageFreezer[N]; 20137 for (int i = 0; i < N; i++) { 20138 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20139 userId, killReason); 20140 } 20141 } else { 20142 mChildren = null; 20143 } 20144 } 20145 mCloseGuard.open("close"); 20146 } 20147 20148 @Override 20149 protected void finalize() throws Throwable { 20150 try { 20151 mCloseGuard.warnIfOpen(); 20152 close(); 20153 } finally { 20154 super.finalize(); 20155 } 20156 } 20157 20158 @Override 20159 public void close() { 20160 mCloseGuard.close(); 20161 if (mClosed.compareAndSet(false, true)) { 20162 synchronized (mPackages) { 20163 if (mWeFroze) { 20164 mFrozenPackages.remove(mPackageName); 20165 } 20166 20167 if (mChildren != null) { 20168 for (PackageFreezer freezer : mChildren) { 20169 freezer.close(); 20170 } 20171 } 20172 } 20173 } 20174 } 20175 } 20176 20177 /** 20178 * Verify that given package is currently frozen. 20179 */ 20180 private void checkPackageFrozen(String packageName) { 20181 synchronized (mPackages) { 20182 if (!mFrozenPackages.contains(packageName)) { 20183 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20184 } 20185 } 20186 } 20187 20188 @Override 20189 public int movePackage(final String packageName, final String volumeUuid) { 20190 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20191 20192 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20193 final int moveId = mNextMoveId.getAndIncrement(); 20194 mHandler.post(new Runnable() { 20195 @Override 20196 public void run() { 20197 try { 20198 movePackageInternal(packageName, volumeUuid, moveId, user); 20199 } catch (PackageManagerException e) { 20200 Slog.w(TAG, "Failed to move " + packageName, e); 20201 mMoveCallbacks.notifyStatusChanged(moveId, 20202 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20203 } 20204 } 20205 }); 20206 return moveId; 20207 } 20208 20209 private void movePackageInternal(final String packageName, final String volumeUuid, 20210 final int moveId, UserHandle user) throws PackageManagerException { 20211 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20212 final PackageManager pm = mContext.getPackageManager(); 20213 20214 final boolean currentAsec; 20215 final String currentVolumeUuid; 20216 final File codeFile; 20217 final String installerPackageName; 20218 final String packageAbiOverride; 20219 final int appId; 20220 final String seinfo; 20221 final String label; 20222 final int targetSdkVersion; 20223 final PackageFreezer freezer; 20224 final int[] installedUserIds; 20225 20226 // reader 20227 synchronized (mPackages) { 20228 final PackageParser.Package pkg = mPackages.get(packageName); 20229 final PackageSetting ps = mSettings.mPackages.get(packageName); 20230 if (pkg == null || ps == null) { 20231 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20232 } 20233 20234 if (pkg.applicationInfo.isSystemApp()) { 20235 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20236 "Cannot move system application"); 20237 } 20238 20239 if (pkg.applicationInfo.isExternalAsec()) { 20240 currentAsec = true; 20241 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20242 } else if (pkg.applicationInfo.isForwardLocked()) { 20243 currentAsec = true; 20244 currentVolumeUuid = "forward_locked"; 20245 } else { 20246 currentAsec = false; 20247 currentVolumeUuid = ps.volumeUuid; 20248 20249 final File probe = new File(pkg.codePath); 20250 final File probeOat = new File(probe, "oat"); 20251 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20252 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20253 "Move only supported for modern cluster style installs"); 20254 } 20255 } 20256 20257 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20258 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20259 "Package already moved to " + volumeUuid); 20260 } 20261 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20262 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20263 "Device admin cannot be moved"); 20264 } 20265 20266 if (mFrozenPackages.contains(packageName)) { 20267 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20268 "Failed to move already frozen package"); 20269 } 20270 20271 codeFile = new File(pkg.codePath); 20272 installerPackageName = ps.installerPackageName; 20273 packageAbiOverride = ps.cpuAbiOverrideString; 20274 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20275 seinfo = pkg.applicationInfo.seinfo; 20276 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20277 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20278 freezer = freezePackage(packageName, "movePackageInternal"); 20279 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20280 } 20281 20282 final Bundle extras = new Bundle(); 20283 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20284 extras.putString(Intent.EXTRA_TITLE, label); 20285 mMoveCallbacks.notifyCreated(moveId, extras); 20286 20287 int installFlags; 20288 final boolean moveCompleteApp; 20289 final File measurePath; 20290 20291 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20292 installFlags = INSTALL_INTERNAL; 20293 moveCompleteApp = !currentAsec; 20294 measurePath = Environment.getDataAppDirectory(volumeUuid); 20295 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20296 installFlags = INSTALL_EXTERNAL; 20297 moveCompleteApp = false; 20298 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20299 } else { 20300 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20301 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20302 || !volume.isMountedWritable()) { 20303 freezer.close(); 20304 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20305 "Move location not mounted private volume"); 20306 } 20307 20308 Preconditions.checkState(!currentAsec); 20309 20310 installFlags = INSTALL_INTERNAL; 20311 moveCompleteApp = true; 20312 measurePath = Environment.getDataAppDirectory(volumeUuid); 20313 } 20314 20315 final PackageStats stats = new PackageStats(null, -1); 20316 synchronized (mInstaller) { 20317 for (int userId : installedUserIds) { 20318 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20319 freezer.close(); 20320 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20321 "Failed to measure package size"); 20322 } 20323 } 20324 } 20325 20326 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20327 + stats.dataSize); 20328 20329 final long startFreeBytes = measurePath.getFreeSpace(); 20330 final long sizeBytes; 20331 if (moveCompleteApp) { 20332 sizeBytes = stats.codeSize + stats.dataSize; 20333 } else { 20334 sizeBytes = stats.codeSize; 20335 } 20336 20337 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20338 freezer.close(); 20339 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20340 "Not enough free space to move"); 20341 } 20342 20343 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20344 20345 final CountDownLatch installedLatch = new CountDownLatch(1); 20346 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20347 @Override 20348 public void onUserActionRequired(Intent intent) throws RemoteException { 20349 throw new IllegalStateException(); 20350 } 20351 20352 @Override 20353 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20354 Bundle extras) throws RemoteException { 20355 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20356 + PackageManager.installStatusToString(returnCode, msg)); 20357 20358 installedLatch.countDown(); 20359 freezer.close(); 20360 20361 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20362 switch (status) { 20363 case PackageInstaller.STATUS_SUCCESS: 20364 mMoveCallbacks.notifyStatusChanged(moveId, 20365 PackageManager.MOVE_SUCCEEDED); 20366 break; 20367 case PackageInstaller.STATUS_FAILURE_STORAGE: 20368 mMoveCallbacks.notifyStatusChanged(moveId, 20369 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20370 break; 20371 default: 20372 mMoveCallbacks.notifyStatusChanged(moveId, 20373 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20374 break; 20375 } 20376 } 20377 }; 20378 20379 final MoveInfo move; 20380 if (moveCompleteApp) { 20381 // Kick off a thread to report progress estimates 20382 new Thread() { 20383 @Override 20384 public void run() { 20385 while (true) { 20386 try { 20387 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20388 break; 20389 } 20390 } catch (InterruptedException ignored) { 20391 } 20392 20393 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20394 final int progress = 10 + (int) MathUtils.constrain( 20395 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20396 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20397 } 20398 } 20399 }.start(); 20400 20401 final String dataAppName = codeFile.getName(); 20402 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20403 dataAppName, appId, seinfo, targetSdkVersion); 20404 } else { 20405 move = null; 20406 } 20407 20408 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20409 20410 final Message msg = mHandler.obtainMessage(INIT_COPY); 20411 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20412 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20413 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20414 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20415 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20416 msg.obj = params; 20417 20418 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20419 System.identityHashCode(msg.obj)); 20420 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20421 System.identityHashCode(msg.obj)); 20422 20423 mHandler.sendMessage(msg); 20424 } 20425 20426 @Override 20427 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20428 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20429 20430 final int realMoveId = mNextMoveId.getAndIncrement(); 20431 final Bundle extras = new Bundle(); 20432 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20433 mMoveCallbacks.notifyCreated(realMoveId, extras); 20434 20435 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20436 @Override 20437 public void onCreated(int moveId, Bundle extras) { 20438 // Ignored 20439 } 20440 20441 @Override 20442 public void onStatusChanged(int moveId, int status, long estMillis) { 20443 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20444 } 20445 }; 20446 20447 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20448 storage.setPrimaryStorageUuid(volumeUuid, callback); 20449 return realMoveId; 20450 } 20451 20452 @Override 20453 public int getMoveStatus(int moveId) { 20454 mContext.enforceCallingOrSelfPermission( 20455 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20456 return mMoveCallbacks.mLastStatus.get(moveId); 20457 } 20458 20459 @Override 20460 public void registerMoveCallback(IPackageMoveObserver callback) { 20461 mContext.enforceCallingOrSelfPermission( 20462 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20463 mMoveCallbacks.register(callback); 20464 } 20465 20466 @Override 20467 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20468 mContext.enforceCallingOrSelfPermission( 20469 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20470 mMoveCallbacks.unregister(callback); 20471 } 20472 20473 @Override 20474 public boolean setInstallLocation(int loc) { 20475 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20476 null); 20477 if (getInstallLocation() == loc) { 20478 return true; 20479 } 20480 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20481 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20482 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20483 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20484 return true; 20485 } 20486 return false; 20487 } 20488 20489 @Override 20490 public int getInstallLocation() { 20491 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20492 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20493 PackageHelper.APP_INSTALL_AUTO); 20494 } 20495 20496 /** Called by UserManagerService */ 20497 void cleanUpUser(UserManagerService userManager, int userHandle) { 20498 synchronized (mPackages) { 20499 mDirtyUsers.remove(userHandle); 20500 mUserNeedsBadging.delete(userHandle); 20501 mSettings.removeUserLPw(userHandle); 20502 mPendingBroadcasts.remove(userHandle); 20503 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20504 removeUnusedPackagesLPw(userManager, userHandle); 20505 } 20506 } 20507 20508 /** 20509 * We're removing userHandle and would like to remove any downloaded packages 20510 * that are no longer in use by any other user. 20511 * @param userHandle the user being removed 20512 */ 20513 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20514 final boolean DEBUG_CLEAN_APKS = false; 20515 int [] users = userManager.getUserIds(); 20516 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20517 while (psit.hasNext()) { 20518 PackageSetting ps = psit.next(); 20519 if (ps.pkg == null) { 20520 continue; 20521 } 20522 final String packageName = ps.pkg.packageName; 20523 // Skip over if system app 20524 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20525 continue; 20526 } 20527 if (DEBUG_CLEAN_APKS) { 20528 Slog.i(TAG, "Checking package " + packageName); 20529 } 20530 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20531 if (keep) { 20532 if (DEBUG_CLEAN_APKS) { 20533 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20534 } 20535 } else { 20536 for (int i = 0; i < users.length; i++) { 20537 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20538 keep = true; 20539 if (DEBUG_CLEAN_APKS) { 20540 Slog.i(TAG, " Keeping package " + packageName + " for user " 20541 + users[i]); 20542 } 20543 break; 20544 } 20545 } 20546 } 20547 if (!keep) { 20548 if (DEBUG_CLEAN_APKS) { 20549 Slog.i(TAG, " Removing package " + packageName); 20550 } 20551 mHandler.post(new Runnable() { 20552 public void run() { 20553 deletePackageX(packageName, userHandle, 0); 20554 } //end run 20555 }); 20556 } 20557 } 20558 } 20559 20560 /** Called by UserManagerService */ 20561 void createNewUser(int userId) { 20562 synchronized (mInstallLock) { 20563 mSettings.createNewUserLI(this, mInstaller, userId); 20564 } 20565 synchronized (mPackages) { 20566 scheduleWritePackageRestrictionsLocked(userId); 20567 scheduleWritePackageListLocked(userId); 20568 applyFactoryDefaultBrowserLPw(userId); 20569 primeDomainVerificationsLPw(userId); 20570 } 20571 } 20572 20573 void onNewUserCreated(final int userId) { 20574 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20575 // If permission review for legacy apps is required, we represent 20576 // dagerous permissions for such apps as always granted runtime 20577 // permissions to keep per user flag state whether review is needed. 20578 // Hence, if a new user is added we have to propagate dangerous 20579 // permission grants for these legacy apps. 20580 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20581 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20582 | UPDATE_PERMISSIONS_REPLACE_ALL); 20583 } 20584 } 20585 20586 @Override 20587 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20588 mContext.enforceCallingOrSelfPermission( 20589 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20590 "Only package verification agents can read the verifier device identity"); 20591 20592 synchronized (mPackages) { 20593 return mSettings.getVerifierDeviceIdentityLPw(); 20594 } 20595 } 20596 20597 @Override 20598 public void setPermissionEnforced(String permission, boolean enforced) { 20599 // TODO: Now that we no longer change GID for storage, this should to away. 20600 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20601 "setPermissionEnforced"); 20602 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20603 synchronized (mPackages) { 20604 if (mSettings.mReadExternalStorageEnforced == null 20605 || mSettings.mReadExternalStorageEnforced != enforced) { 20606 mSettings.mReadExternalStorageEnforced = enforced; 20607 mSettings.writeLPr(); 20608 } 20609 } 20610 // kill any non-foreground processes so we restart them and 20611 // grant/revoke the GID. 20612 final IActivityManager am = ActivityManagerNative.getDefault(); 20613 if (am != null) { 20614 final long token = Binder.clearCallingIdentity(); 20615 try { 20616 am.killProcessesBelowForeground("setPermissionEnforcement"); 20617 } catch (RemoteException e) { 20618 } finally { 20619 Binder.restoreCallingIdentity(token); 20620 } 20621 } 20622 } else { 20623 throw new IllegalArgumentException("No selective enforcement for " + permission); 20624 } 20625 } 20626 20627 @Override 20628 @Deprecated 20629 public boolean isPermissionEnforced(String permission) { 20630 return true; 20631 } 20632 20633 @Override 20634 public boolean isStorageLow() { 20635 final long token = Binder.clearCallingIdentity(); 20636 try { 20637 final DeviceStorageMonitorInternal 20638 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20639 if (dsm != null) { 20640 return dsm.isMemoryLow(); 20641 } else { 20642 return false; 20643 } 20644 } finally { 20645 Binder.restoreCallingIdentity(token); 20646 } 20647 } 20648 20649 @Override 20650 public IPackageInstaller getPackageInstaller() { 20651 return mInstallerService; 20652 } 20653 20654 private boolean userNeedsBadging(int userId) { 20655 int index = mUserNeedsBadging.indexOfKey(userId); 20656 if (index < 0) { 20657 final UserInfo userInfo; 20658 final long token = Binder.clearCallingIdentity(); 20659 try { 20660 userInfo = sUserManager.getUserInfo(userId); 20661 } finally { 20662 Binder.restoreCallingIdentity(token); 20663 } 20664 final boolean b; 20665 if (userInfo != null && userInfo.isManagedProfile()) { 20666 b = true; 20667 } else { 20668 b = false; 20669 } 20670 mUserNeedsBadging.put(userId, b); 20671 return b; 20672 } 20673 return mUserNeedsBadging.valueAt(index); 20674 } 20675 20676 @Override 20677 public KeySet getKeySetByAlias(String packageName, String alias) { 20678 if (packageName == null || alias == null) { 20679 return null; 20680 } 20681 synchronized(mPackages) { 20682 final PackageParser.Package pkg = mPackages.get(packageName); 20683 if (pkg == null) { 20684 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20685 throw new IllegalArgumentException("Unknown package: " + packageName); 20686 } 20687 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20688 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20689 } 20690 } 20691 20692 @Override 20693 public KeySet getSigningKeySet(String packageName) { 20694 if (packageName == null) { 20695 return null; 20696 } 20697 synchronized(mPackages) { 20698 final PackageParser.Package pkg = mPackages.get(packageName); 20699 if (pkg == null) { 20700 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20701 throw new IllegalArgumentException("Unknown package: " + packageName); 20702 } 20703 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20704 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20705 throw new SecurityException("May not access signing KeySet of other apps."); 20706 } 20707 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20708 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20709 } 20710 } 20711 20712 @Override 20713 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20714 if (packageName == null || ks == null) { 20715 return false; 20716 } 20717 synchronized(mPackages) { 20718 final PackageParser.Package pkg = mPackages.get(packageName); 20719 if (pkg == null) { 20720 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20721 throw new IllegalArgumentException("Unknown package: " + packageName); 20722 } 20723 IBinder ksh = ks.getToken(); 20724 if (ksh instanceof KeySetHandle) { 20725 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20726 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20727 } 20728 return false; 20729 } 20730 } 20731 20732 @Override 20733 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20734 if (packageName == null || ks == null) { 20735 return false; 20736 } 20737 synchronized(mPackages) { 20738 final PackageParser.Package pkg = mPackages.get(packageName); 20739 if (pkg == null) { 20740 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20741 throw new IllegalArgumentException("Unknown package: " + packageName); 20742 } 20743 IBinder ksh = ks.getToken(); 20744 if (ksh instanceof KeySetHandle) { 20745 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20746 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20747 } 20748 return false; 20749 } 20750 } 20751 20752 private void deletePackageIfUnusedLPr(final String packageName) { 20753 PackageSetting ps = mSettings.mPackages.get(packageName); 20754 if (ps == null) { 20755 return; 20756 } 20757 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20758 // TODO Implement atomic delete if package is unused 20759 // It is currently possible that the package will be deleted even if it is installed 20760 // after this method returns. 20761 mHandler.post(new Runnable() { 20762 public void run() { 20763 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20764 } 20765 }); 20766 } 20767 } 20768 20769 /** 20770 * Check and throw if the given before/after packages would be considered a 20771 * downgrade. 20772 */ 20773 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20774 throws PackageManagerException { 20775 if (after.versionCode < before.mVersionCode) { 20776 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20777 "Update version code " + after.versionCode + " is older than current " 20778 + before.mVersionCode); 20779 } else if (after.versionCode == before.mVersionCode) { 20780 if (after.baseRevisionCode < before.baseRevisionCode) { 20781 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20782 "Update base revision code " + after.baseRevisionCode 20783 + " is older than current " + before.baseRevisionCode); 20784 } 20785 20786 if (!ArrayUtils.isEmpty(after.splitNames)) { 20787 for (int i = 0; i < after.splitNames.length; i++) { 20788 final String splitName = after.splitNames[i]; 20789 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20790 if (j != -1) { 20791 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20792 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20793 "Update split " + splitName + " revision code " 20794 + after.splitRevisionCodes[i] + " is older than current " 20795 + before.splitRevisionCodes[j]); 20796 } 20797 } 20798 } 20799 } 20800 } 20801 } 20802 20803 private static class MoveCallbacks extends Handler { 20804 private static final int MSG_CREATED = 1; 20805 private static final int MSG_STATUS_CHANGED = 2; 20806 20807 private final RemoteCallbackList<IPackageMoveObserver> 20808 mCallbacks = new RemoteCallbackList<>(); 20809 20810 private final SparseIntArray mLastStatus = new SparseIntArray(); 20811 20812 public MoveCallbacks(Looper looper) { 20813 super(looper); 20814 } 20815 20816 public void register(IPackageMoveObserver callback) { 20817 mCallbacks.register(callback); 20818 } 20819 20820 public void unregister(IPackageMoveObserver callback) { 20821 mCallbacks.unregister(callback); 20822 } 20823 20824 @Override 20825 public void handleMessage(Message msg) { 20826 final SomeArgs args = (SomeArgs) msg.obj; 20827 final int n = mCallbacks.beginBroadcast(); 20828 for (int i = 0; i < n; i++) { 20829 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20830 try { 20831 invokeCallback(callback, msg.what, args); 20832 } catch (RemoteException ignored) { 20833 } 20834 } 20835 mCallbacks.finishBroadcast(); 20836 args.recycle(); 20837 } 20838 20839 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20840 throws RemoteException { 20841 switch (what) { 20842 case MSG_CREATED: { 20843 callback.onCreated(args.argi1, (Bundle) args.arg2); 20844 break; 20845 } 20846 case MSG_STATUS_CHANGED: { 20847 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20848 break; 20849 } 20850 } 20851 } 20852 20853 private void notifyCreated(int moveId, Bundle extras) { 20854 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20855 20856 final SomeArgs args = SomeArgs.obtain(); 20857 args.argi1 = moveId; 20858 args.arg2 = extras; 20859 obtainMessage(MSG_CREATED, args).sendToTarget(); 20860 } 20861 20862 private void notifyStatusChanged(int moveId, int status) { 20863 notifyStatusChanged(moveId, status, -1); 20864 } 20865 20866 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20867 Slog.v(TAG, "Move " + moveId + " status " + status); 20868 20869 final SomeArgs args = SomeArgs.obtain(); 20870 args.argi1 = moveId; 20871 args.argi2 = status; 20872 args.arg3 = estMillis; 20873 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20874 20875 synchronized (mLastStatus) { 20876 mLastStatus.put(moveId, status); 20877 } 20878 } 20879 } 20880 20881 private final static class OnPermissionChangeListeners extends Handler { 20882 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20883 20884 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20885 new RemoteCallbackList<>(); 20886 20887 public OnPermissionChangeListeners(Looper looper) { 20888 super(looper); 20889 } 20890 20891 @Override 20892 public void handleMessage(Message msg) { 20893 switch (msg.what) { 20894 case MSG_ON_PERMISSIONS_CHANGED: { 20895 final int uid = msg.arg1; 20896 handleOnPermissionsChanged(uid); 20897 } break; 20898 } 20899 } 20900 20901 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20902 mPermissionListeners.register(listener); 20903 20904 } 20905 20906 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20907 mPermissionListeners.unregister(listener); 20908 } 20909 20910 public void onPermissionsChanged(int uid) { 20911 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20912 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20913 } 20914 } 20915 20916 private void handleOnPermissionsChanged(int uid) { 20917 final int count = mPermissionListeners.beginBroadcast(); 20918 try { 20919 for (int i = 0; i < count; i++) { 20920 IOnPermissionsChangeListener callback = mPermissionListeners 20921 .getBroadcastItem(i); 20922 try { 20923 callback.onPermissionsChanged(uid); 20924 } catch (RemoteException e) { 20925 Log.e(TAG, "Permission listener is dead", e); 20926 } 20927 } 20928 } finally { 20929 mPermissionListeners.finishBroadcast(); 20930 } 20931 } 20932 } 20933 20934 private class PackageManagerInternalImpl extends PackageManagerInternal { 20935 @Override 20936 public void setLocationPackagesProvider(PackagesProvider provider) { 20937 synchronized (mPackages) { 20938 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20939 } 20940 } 20941 20942 @Override 20943 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20944 synchronized (mPackages) { 20945 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20946 } 20947 } 20948 20949 @Override 20950 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20951 synchronized (mPackages) { 20952 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20953 } 20954 } 20955 20956 @Override 20957 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20958 synchronized (mPackages) { 20959 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20960 } 20961 } 20962 20963 @Override 20964 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20965 synchronized (mPackages) { 20966 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20967 } 20968 } 20969 20970 @Override 20971 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20972 synchronized (mPackages) { 20973 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20974 } 20975 } 20976 20977 @Override 20978 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20979 synchronized (mPackages) { 20980 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20981 packageName, userId); 20982 } 20983 } 20984 20985 @Override 20986 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20987 synchronized (mPackages) { 20988 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20989 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20990 packageName, userId); 20991 } 20992 } 20993 20994 @Override 20995 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20996 synchronized (mPackages) { 20997 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20998 packageName, userId); 20999 } 21000 } 21001 21002 @Override 21003 public void setKeepUninstalledPackages(final List<String> packageList) { 21004 Preconditions.checkNotNull(packageList); 21005 List<String> removedFromList = null; 21006 synchronized (mPackages) { 21007 if (mKeepUninstalledPackages != null) { 21008 final int packagesCount = mKeepUninstalledPackages.size(); 21009 for (int i = 0; i < packagesCount; i++) { 21010 String oldPackage = mKeepUninstalledPackages.get(i); 21011 if (packageList != null && packageList.contains(oldPackage)) { 21012 continue; 21013 } 21014 if (removedFromList == null) { 21015 removedFromList = new ArrayList<>(); 21016 } 21017 removedFromList.add(oldPackage); 21018 } 21019 } 21020 mKeepUninstalledPackages = new ArrayList<>(packageList); 21021 if (removedFromList != null) { 21022 final int removedCount = removedFromList.size(); 21023 for (int i = 0; i < removedCount; i++) { 21024 deletePackageIfUnusedLPr(removedFromList.get(i)); 21025 } 21026 } 21027 } 21028 } 21029 21030 @Override 21031 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21032 synchronized (mPackages) { 21033 // If we do not support permission review, done. 21034 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 21035 return false; 21036 } 21037 21038 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21039 if (packageSetting == null) { 21040 return false; 21041 } 21042 21043 // Permission review applies only to apps not supporting the new permission model. 21044 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21045 return false; 21046 } 21047 21048 // Legacy apps have the permission and get user consent on launch. 21049 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21050 return permissionsState.isPermissionReviewRequired(userId); 21051 } 21052 } 21053 21054 @Override 21055 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21056 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21057 } 21058 21059 @Override 21060 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21061 int userId) { 21062 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21063 } 21064 21065 @Override 21066 public void setDeviceAndProfileOwnerPackages( 21067 int deviceOwnerUserId, String deviceOwnerPackage, 21068 SparseArray<String> profileOwnerPackages) { 21069 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21070 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21071 } 21072 21073 @Override 21074 public boolean isPackageDataProtected(int userId, String packageName) { 21075 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21076 } 21077 21078 @Override 21079 public boolean wasPackageEverLaunched(String packageName, int userId) { 21080 synchronized (mPackages) { 21081 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21082 } 21083 } 21084 } 21085 21086 @Override 21087 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21088 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21089 synchronized (mPackages) { 21090 final long identity = Binder.clearCallingIdentity(); 21091 try { 21092 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21093 packageNames, userId); 21094 } finally { 21095 Binder.restoreCallingIdentity(identity); 21096 } 21097 } 21098 } 21099 21100 private static void enforceSystemOrPhoneCaller(String tag) { 21101 int callingUid = Binder.getCallingUid(); 21102 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21103 throw new SecurityException( 21104 "Cannot call " + tag + " from UID " + callingUid); 21105 } 21106 } 21107 21108 boolean isHistoricalPackageUsageAvailable() { 21109 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21110 } 21111 21112 /** 21113 * Return a <b>copy</b> of the collection of packages known to the package manager. 21114 * @return A copy of the values of mPackages. 21115 */ 21116 Collection<PackageParser.Package> getPackages() { 21117 synchronized (mPackages) { 21118 return new ArrayList<>(mPackages.values()); 21119 } 21120 } 21121 21122 /** 21123 * Logs process start information (including base APK hash) to the security log. 21124 * @hide 21125 */ 21126 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21127 String apkFile, int pid) { 21128 if (!SecurityLog.isLoggingEnabled()) { 21129 return; 21130 } 21131 Bundle data = new Bundle(); 21132 data.putLong("startTimestamp", System.currentTimeMillis()); 21133 data.putString("processName", processName); 21134 data.putInt("uid", uid); 21135 data.putString("seinfo", seinfo); 21136 data.putString("apkFile", apkFile); 21137 data.putInt("pid", pid); 21138 Message msg = mProcessLoggingHandler.obtainMessage( 21139 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21140 msg.setData(data); 21141 mProcessLoggingHandler.sendMessage(msg); 21142 } 21143 21144 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21145 return mCompilerStats.getPackageStats(pkgName); 21146 } 21147 21148 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21149 return getOrCreateCompilerPackageStats(pkg.packageName); 21150 } 21151 21152 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21153 return mCompilerStats.getOrCreatePackageStats(pkgName); 21154 } 21155 21156 public void deleteCompilerPackageStats(String pkgName) { 21157 mCompilerStats.deletePackageStats(pkgName); 21158 } 21159} 21160