PackageManagerService.java revision e9ac5b42d242f9ff679b7ab2ed718163f0f7c799
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 uid = UserHandle.getAppId(uid); 4643 // reader 4644 synchronized (mPackages) { 4645 Object obj = mSettings.getUserIdLPr(uid); 4646 if (obj instanceof SharedUserSetting) { 4647 final SharedUserSetting sus = (SharedUserSetting) obj; 4648 final int N = sus.packages.size(); 4649 final String[] res = new String[N]; 4650 for (int i = 0; i < N; i++) { 4651 res[i] = sus.packages.valueAt(i).name; 4652 } 4653 return res; 4654 } else if (obj instanceof PackageSetting) { 4655 final PackageSetting ps = (PackageSetting) obj; 4656 return new String[] { ps.name }; 4657 } 4658 } 4659 return null; 4660 } 4661 4662 @Override 4663 public String getNameForUid(int uid) { 4664 // reader 4665 synchronized (mPackages) { 4666 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4667 if (obj instanceof SharedUserSetting) { 4668 final SharedUserSetting sus = (SharedUserSetting) obj; 4669 return sus.name + ":" + sus.userId; 4670 } else if (obj instanceof PackageSetting) { 4671 final PackageSetting ps = (PackageSetting) obj; 4672 return ps.name; 4673 } 4674 } 4675 return null; 4676 } 4677 4678 @Override 4679 public int getUidForSharedUser(String sharedUserName) { 4680 if(sharedUserName == null) { 4681 return -1; 4682 } 4683 // reader 4684 synchronized (mPackages) { 4685 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4686 if (suid == null) { 4687 return -1; 4688 } 4689 return suid.userId; 4690 } 4691 } 4692 4693 @Override 4694 public int getFlagsForUid(int uid) { 4695 synchronized (mPackages) { 4696 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4697 if (obj instanceof SharedUserSetting) { 4698 final SharedUserSetting sus = (SharedUserSetting) obj; 4699 return sus.pkgFlags; 4700 } else if (obj instanceof PackageSetting) { 4701 final PackageSetting ps = (PackageSetting) obj; 4702 return ps.pkgFlags; 4703 } 4704 } 4705 return 0; 4706 } 4707 4708 @Override 4709 public int getPrivateFlagsForUid(int uid) { 4710 synchronized (mPackages) { 4711 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4712 if (obj instanceof SharedUserSetting) { 4713 final SharedUserSetting sus = (SharedUserSetting) obj; 4714 return sus.pkgPrivateFlags; 4715 } else if (obj instanceof PackageSetting) { 4716 final PackageSetting ps = (PackageSetting) obj; 4717 return ps.pkgPrivateFlags; 4718 } 4719 } 4720 return 0; 4721 } 4722 4723 @Override 4724 public boolean isUidPrivileged(int uid) { 4725 uid = UserHandle.getAppId(uid); 4726 // reader 4727 synchronized (mPackages) { 4728 Object obj = mSettings.getUserIdLPr(uid); 4729 if (obj instanceof SharedUserSetting) { 4730 final SharedUserSetting sus = (SharedUserSetting) obj; 4731 final Iterator<PackageSetting> it = sus.packages.iterator(); 4732 while (it.hasNext()) { 4733 if (it.next().isPrivileged()) { 4734 return true; 4735 } 4736 } 4737 } else if (obj instanceof PackageSetting) { 4738 final PackageSetting ps = (PackageSetting) obj; 4739 return ps.isPrivileged(); 4740 } 4741 } 4742 return false; 4743 } 4744 4745 @Override 4746 public String[] getAppOpPermissionPackages(String permissionName) { 4747 synchronized (mPackages) { 4748 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4749 if (pkgs == null) { 4750 return null; 4751 } 4752 return pkgs.toArray(new String[pkgs.size()]); 4753 } 4754 } 4755 4756 @Override 4757 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4758 int flags, int userId) { 4759 try { 4760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4761 4762 if (!sUserManager.exists(userId)) return null; 4763 flags = updateFlagsForResolve(flags, userId, intent); 4764 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4765 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4766 4767 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4768 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4769 flags, userId); 4770 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4771 4772 final ResolveInfo bestChoice = 4773 chooseBestActivity(intent, resolvedType, flags, query, userId); 4774 return bestChoice; 4775 } finally { 4776 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4777 } 4778 } 4779 4780 @Override 4781 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4782 IntentFilter filter, int match, ComponentName activity) { 4783 final int userId = UserHandle.getCallingUserId(); 4784 if (DEBUG_PREFERRED) { 4785 Log.v(TAG, "setLastChosenActivity intent=" + intent 4786 + " resolvedType=" + resolvedType 4787 + " flags=" + flags 4788 + " filter=" + filter 4789 + " match=" + match 4790 + " activity=" + activity); 4791 filter.dump(new PrintStreamPrinter(System.out), " "); 4792 } 4793 intent.setComponent(null); 4794 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4795 userId); 4796 // Find any earlier preferred or last chosen entries and nuke them 4797 findPreferredActivity(intent, resolvedType, 4798 flags, query, 0, false, true, false, userId); 4799 // Add the new activity as the last chosen for this filter 4800 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4801 "Setting last chosen"); 4802 } 4803 4804 @Override 4805 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4806 final int userId = UserHandle.getCallingUserId(); 4807 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4808 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4809 userId); 4810 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4811 false, false, false, userId); 4812 } 4813 4814 private boolean isEphemeralDisabled() { 4815 // ephemeral apps have been disabled across the board 4816 if (DISABLE_EPHEMERAL_APPS) { 4817 return true; 4818 } 4819 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4820 if (!mSystemReady) { 4821 return true; 4822 } 4823 // we can't get a content resolver until the system is ready; these checks must happen last 4824 final ContentResolver resolver = mContext.getContentResolver(); 4825 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4826 return true; 4827 } 4828 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4829 } 4830 4831 private boolean isEphemeralAllowed( 4832 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4833 boolean skipPackageCheck) { 4834 // Short circuit and return early if possible. 4835 if (isEphemeralDisabled()) { 4836 return false; 4837 } 4838 final int callingUser = UserHandle.getCallingUserId(); 4839 if (callingUser != UserHandle.USER_SYSTEM) { 4840 return false; 4841 } 4842 if (mEphemeralResolverConnection == null) { 4843 return false; 4844 } 4845 if (intent.getComponent() != null) { 4846 return false; 4847 } 4848 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4849 return false; 4850 } 4851 if (!skipPackageCheck && intent.getPackage() != null) { 4852 return false; 4853 } 4854 final boolean isWebUri = hasWebURI(intent); 4855 if (!isWebUri || intent.getData().getHost() == null) { 4856 return false; 4857 } 4858 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4859 synchronized (mPackages) { 4860 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4861 for (int n = 0; n < count; n++) { 4862 ResolveInfo info = resolvedActivities.get(n); 4863 String packageName = info.activityInfo.packageName; 4864 PackageSetting ps = mSettings.mPackages.get(packageName); 4865 if (ps != null) { 4866 // Try to get the status from User settings first 4867 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4868 int status = (int) (packedStatus >> 32); 4869 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4870 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4871 if (DEBUG_EPHEMERAL) { 4872 Slog.v(TAG, "DENY ephemeral apps;" 4873 + " pkg: " + packageName + ", status: " + status); 4874 } 4875 return false; 4876 } 4877 } 4878 } 4879 } 4880 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4881 return true; 4882 } 4883 4884 private static EphemeralResolveInfo getEphemeralResolveInfo( 4885 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4886 String resolvedType, int userId, String packageName) { 4887 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4888 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4889 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4890 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4891 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4892 ephemeralPrefixCount); 4893 final int[] shaPrefix = digest.getDigestPrefix(); 4894 final byte[][] digestBytes = digest.getDigestBytes(); 4895 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4896 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4897 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4898 // No hash prefix match; there are no ephemeral apps for this domain. 4899 return null; 4900 } 4901 4902 // Go in reverse order so we match the narrowest scope first. 4903 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4904 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4905 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4906 continue; 4907 } 4908 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4909 // No filters; this should never happen. 4910 if (filters.isEmpty()) { 4911 continue; 4912 } 4913 if (packageName != null 4914 && !packageName.equals(ephemeralApplication.getPackageName())) { 4915 continue; 4916 } 4917 // We have a domain match; resolve the filters to see if anything matches. 4918 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4919 for (int j = filters.size() - 1; j >= 0; --j) { 4920 final EphemeralResolveIntentInfo intentInfo = 4921 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4922 ephemeralResolver.addFilter(intentInfo); 4923 } 4924 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4925 intent, resolvedType, false /*defaultOnly*/, userId); 4926 if (!matchedResolveInfoList.isEmpty()) { 4927 return matchedResolveInfoList.get(0); 4928 } 4929 } 4930 } 4931 // Hash or filter mis-match; no ephemeral apps for this domain. 4932 return null; 4933 } 4934 4935 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4936 int flags, List<ResolveInfo> query, int userId) { 4937 if (query != null) { 4938 final int N = query.size(); 4939 if (N == 1) { 4940 return query.get(0); 4941 } else if (N > 1) { 4942 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4943 // If there is more than one activity with the same priority, 4944 // then let the user decide between them. 4945 ResolveInfo r0 = query.get(0); 4946 ResolveInfo r1 = query.get(1); 4947 if (DEBUG_INTENT_MATCHING || debug) { 4948 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4949 + r1.activityInfo.name + "=" + r1.priority); 4950 } 4951 // If the first activity has a higher priority, or a different 4952 // default, then it is always desirable to pick it. 4953 if (r0.priority != r1.priority 4954 || r0.preferredOrder != r1.preferredOrder 4955 || r0.isDefault != r1.isDefault) { 4956 return query.get(0); 4957 } 4958 // If we have saved a preference for a preferred activity for 4959 // this Intent, use that. 4960 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4961 flags, query, r0.priority, true, false, debug, userId); 4962 if (ri != null) { 4963 return ri; 4964 } 4965 ri = new ResolveInfo(mResolveInfo); 4966 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4967 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4968 // If all of the options come from the same package, show the application's 4969 // label and icon instead of the generic resolver's. 4970 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4971 // and then throw away the ResolveInfo itself, meaning that the caller loses 4972 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4973 // a fallback for this case; we only set the target package's resources on 4974 // the ResolveInfo, not the ActivityInfo. 4975 final String intentPackage = intent.getPackage(); 4976 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4977 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4978 ri.resolvePackageName = intentPackage; 4979 if (userNeedsBadging(userId)) { 4980 ri.noResourceId = true; 4981 } else { 4982 ri.icon = appi.icon; 4983 } 4984 ri.iconResourceId = appi.icon; 4985 ri.labelRes = appi.labelRes; 4986 } 4987 ri.activityInfo.applicationInfo = new ApplicationInfo( 4988 ri.activityInfo.applicationInfo); 4989 if (userId != 0) { 4990 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4991 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4992 } 4993 // Make sure that the resolver is displayable in car mode 4994 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4995 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4996 return ri; 4997 } 4998 } 4999 return null; 5000 } 5001 5002 /** 5003 * Return true if the given list is not empty and all of its contents have 5004 * an activityInfo with the given package name. 5005 */ 5006 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5007 if (ArrayUtils.isEmpty(list)) { 5008 return false; 5009 } 5010 for (int i = 0, N = list.size(); i < N; i++) { 5011 final ResolveInfo ri = list.get(i); 5012 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5013 if (ai == null || !packageName.equals(ai.packageName)) { 5014 return false; 5015 } 5016 } 5017 return true; 5018 } 5019 5020 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5021 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5022 final int N = query.size(); 5023 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5024 .get(userId); 5025 // Get the list of persistent preferred activities that handle the intent 5026 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5027 List<PersistentPreferredActivity> pprefs = ppir != null 5028 ? ppir.queryIntent(intent, resolvedType, 5029 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5030 : null; 5031 if (pprefs != null && pprefs.size() > 0) { 5032 final int M = pprefs.size(); 5033 for (int i=0; i<M; i++) { 5034 final PersistentPreferredActivity ppa = pprefs.get(i); 5035 if (DEBUG_PREFERRED || debug) { 5036 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5037 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5038 + "\n component=" + ppa.mComponent); 5039 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5040 } 5041 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5042 flags | MATCH_DISABLED_COMPONENTS, userId); 5043 if (DEBUG_PREFERRED || debug) { 5044 Slog.v(TAG, "Found persistent preferred activity:"); 5045 if (ai != null) { 5046 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5047 } else { 5048 Slog.v(TAG, " null"); 5049 } 5050 } 5051 if (ai == null) { 5052 // This previously registered persistent preferred activity 5053 // component is no longer known. Ignore it and do NOT remove it. 5054 continue; 5055 } 5056 for (int j=0; j<N; j++) { 5057 final ResolveInfo ri = query.get(j); 5058 if (!ri.activityInfo.applicationInfo.packageName 5059 .equals(ai.applicationInfo.packageName)) { 5060 continue; 5061 } 5062 if (!ri.activityInfo.name.equals(ai.name)) { 5063 continue; 5064 } 5065 // Found a persistent preference that can handle the intent. 5066 if (DEBUG_PREFERRED || debug) { 5067 Slog.v(TAG, "Returning persistent preferred activity: " + 5068 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5069 } 5070 return ri; 5071 } 5072 } 5073 } 5074 return null; 5075 } 5076 5077 // TODO: handle preferred activities missing while user has amnesia 5078 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5079 List<ResolveInfo> query, int priority, boolean always, 5080 boolean removeMatches, boolean debug, int userId) { 5081 if (!sUserManager.exists(userId)) return null; 5082 flags = updateFlagsForResolve(flags, userId, intent); 5083 // writer 5084 synchronized (mPackages) { 5085 if (intent.getSelector() != null) { 5086 intent = intent.getSelector(); 5087 } 5088 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5089 5090 // Try to find a matching persistent preferred activity. 5091 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5092 debug, userId); 5093 5094 // If a persistent preferred activity matched, use it. 5095 if (pri != null) { 5096 return pri; 5097 } 5098 5099 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5100 // Get the list of preferred activities that handle the intent 5101 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5102 List<PreferredActivity> prefs = pir != null 5103 ? pir.queryIntent(intent, resolvedType, 5104 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5105 : null; 5106 if (prefs != null && prefs.size() > 0) { 5107 boolean changed = false; 5108 try { 5109 // First figure out how good the original match set is. 5110 // We will only allow preferred activities that came 5111 // from the same match quality. 5112 int match = 0; 5113 5114 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5115 5116 final int N = query.size(); 5117 for (int j=0; j<N; j++) { 5118 final ResolveInfo ri = query.get(j); 5119 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5120 + ": 0x" + Integer.toHexString(match)); 5121 if (ri.match > match) { 5122 match = ri.match; 5123 } 5124 } 5125 5126 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5127 + Integer.toHexString(match)); 5128 5129 match &= IntentFilter.MATCH_CATEGORY_MASK; 5130 final int M = prefs.size(); 5131 for (int i=0; i<M; i++) { 5132 final PreferredActivity pa = prefs.get(i); 5133 if (DEBUG_PREFERRED || debug) { 5134 Slog.v(TAG, "Checking PreferredActivity ds=" 5135 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5136 + "\n component=" + pa.mPref.mComponent); 5137 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5138 } 5139 if (pa.mPref.mMatch != match) { 5140 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5141 + Integer.toHexString(pa.mPref.mMatch)); 5142 continue; 5143 } 5144 // If it's not an "always" type preferred activity and that's what we're 5145 // looking for, skip it. 5146 if (always && !pa.mPref.mAlways) { 5147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5148 continue; 5149 } 5150 final ActivityInfo ai = getActivityInfo( 5151 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5152 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5153 userId); 5154 if (DEBUG_PREFERRED || debug) { 5155 Slog.v(TAG, "Found preferred activity:"); 5156 if (ai != null) { 5157 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5158 } else { 5159 Slog.v(TAG, " null"); 5160 } 5161 } 5162 if (ai == null) { 5163 // This previously registered preferred activity 5164 // component is no longer known. Most likely an update 5165 // to the app was installed and in the new version this 5166 // component no longer exists. Clean it up by removing 5167 // it from the preferred activities list, and skip it. 5168 Slog.w(TAG, "Removing dangling preferred activity: " 5169 + pa.mPref.mComponent); 5170 pir.removeFilter(pa); 5171 changed = true; 5172 continue; 5173 } 5174 for (int j=0; j<N; j++) { 5175 final ResolveInfo ri = query.get(j); 5176 if (!ri.activityInfo.applicationInfo.packageName 5177 .equals(ai.applicationInfo.packageName)) { 5178 continue; 5179 } 5180 if (!ri.activityInfo.name.equals(ai.name)) { 5181 continue; 5182 } 5183 5184 if (removeMatches) { 5185 pir.removeFilter(pa); 5186 changed = true; 5187 if (DEBUG_PREFERRED) { 5188 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5189 } 5190 break; 5191 } 5192 5193 // Okay we found a previously set preferred or last chosen app. 5194 // If the result set is different from when this 5195 // was created, we need to clear it and re-ask the 5196 // user their preference, if we're looking for an "always" type entry. 5197 if (always && !pa.mPref.sameSet(query)) { 5198 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5199 + intent + " type " + resolvedType); 5200 if (DEBUG_PREFERRED) { 5201 Slog.v(TAG, "Removing preferred activity since set changed " 5202 + pa.mPref.mComponent); 5203 } 5204 pir.removeFilter(pa); 5205 // Re-add the filter as a "last chosen" entry (!always) 5206 PreferredActivity lastChosen = new PreferredActivity( 5207 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5208 pir.addFilter(lastChosen); 5209 changed = true; 5210 return null; 5211 } 5212 5213 // Yay! Either the set matched or we're looking for the last chosen 5214 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5215 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5216 return ri; 5217 } 5218 } 5219 } finally { 5220 if (changed) { 5221 if (DEBUG_PREFERRED) { 5222 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5223 } 5224 scheduleWritePackageRestrictionsLocked(userId); 5225 } 5226 } 5227 } 5228 } 5229 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5230 return null; 5231 } 5232 5233 /* 5234 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5235 */ 5236 @Override 5237 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5238 int targetUserId) { 5239 mContext.enforceCallingOrSelfPermission( 5240 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5241 List<CrossProfileIntentFilter> matches = 5242 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5243 if (matches != null) { 5244 int size = matches.size(); 5245 for (int i = 0; i < size; i++) { 5246 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5247 } 5248 } 5249 if (hasWebURI(intent)) { 5250 // cross-profile app linking works only towards the parent. 5251 final UserInfo parent = getProfileParent(sourceUserId); 5252 synchronized(mPackages) { 5253 int flags = updateFlagsForResolve(0, parent.id, intent); 5254 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5255 intent, resolvedType, flags, sourceUserId, parent.id); 5256 return xpDomainInfo != null; 5257 } 5258 } 5259 return false; 5260 } 5261 5262 private UserInfo getProfileParent(int userId) { 5263 final long identity = Binder.clearCallingIdentity(); 5264 try { 5265 return sUserManager.getProfileParent(userId); 5266 } finally { 5267 Binder.restoreCallingIdentity(identity); 5268 } 5269 } 5270 5271 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5272 String resolvedType, int userId) { 5273 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5274 if (resolver != null) { 5275 return resolver.queryIntent(intent, resolvedType, false, userId); 5276 } 5277 return null; 5278 } 5279 5280 @Override 5281 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5282 String resolvedType, int flags, int userId) { 5283 try { 5284 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5285 5286 return new ParceledListSlice<>( 5287 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5288 } finally { 5289 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5290 } 5291 } 5292 5293 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5294 String resolvedType, int flags, int userId) { 5295 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5296 flags = updateFlagsForResolve(flags, userId, intent); 5297 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5298 false /* requireFullPermission */, false /* checkShell */, 5299 "query intent activities"); 5300 ComponentName comp = intent.getComponent(); 5301 if (comp == null) { 5302 if (intent.getSelector() != null) { 5303 intent = intent.getSelector(); 5304 comp = intent.getComponent(); 5305 } 5306 } 5307 5308 if (comp != null) { 5309 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5310 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5311 if (ai != null) { 5312 final ResolveInfo ri = new ResolveInfo(); 5313 ri.activityInfo = ai; 5314 list.add(ri); 5315 } 5316 return list; 5317 } 5318 5319 // reader 5320 boolean sortResult = false; 5321 boolean addEphemeral = false; 5322 boolean matchEphemeralPackage = false; 5323 List<ResolveInfo> result; 5324 final String pkgName = intent.getPackage(); 5325 synchronized (mPackages) { 5326 if (pkgName == null) { 5327 List<CrossProfileIntentFilter> matchingFilters = 5328 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5329 // Check for results that need to skip the current profile. 5330 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5331 resolvedType, flags, userId); 5332 if (xpResolveInfo != null) { 5333 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5334 xpResult.add(xpResolveInfo); 5335 return filterIfNotSystemUser(xpResult, userId); 5336 } 5337 5338 // Check for results in the current profile. 5339 result = filterIfNotSystemUser(mActivities.queryIntent( 5340 intent, resolvedType, flags, userId), userId); 5341 addEphemeral = 5342 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5343 5344 // Check for cross profile results. 5345 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5346 xpResolveInfo = queryCrossProfileIntents( 5347 matchingFilters, intent, resolvedType, flags, userId, 5348 hasNonNegativePriorityResult); 5349 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5350 boolean isVisibleToUser = filterIfNotSystemUser( 5351 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5352 if (isVisibleToUser) { 5353 result.add(xpResolveInfo); 5354 sortResult = true; 5355 } 5356 } 5357 if (hasWebURI(intent)) { 5358 CrossProfileDomainInfo xpDomainInfo = null; 5359 final UserInfo parent = getProfileParent(userId); 5360 if (parent != null) { 5361 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5362 flags, userId, parent.id); 5363 } 5364 if (xpDomainInfo != null) { 5365 if (xpResolveInfo != null) { 5366 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5367 // in the result. 5368 result.remove(xpResolveInfo); 5369 } 5370 if (result.size() == 0 && !addEphemeral) { 5371 result.add(xpDomainInfo.resolveInfo); 5372 return result; 5373 } 5374 } 5375 if (result.size() > 1 || addEphemeral) { 5376 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5377 intent, flags, result, xpDomainInfo, userId); 5378 sortResult = true; 5379 } 5380 } 5381 } else { 5382 final PackageParser.Package pkg = mPackages.get(pkgName); 5383 if (pkg != null) { 5384 result = filterIfNotSystemUser( 5385 mActivities.queryIntentForPackage( 5386 intent, resolvedType, flags, pkg.activities, userId), 5387 userId); 5388 } else { 5389 // the caller wants to resolve for a particular package; however, there 5390 // were no installed results, so, try to find an ephemeral result 5391 addEphemeral = isEphemeralAllowed( 5392 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5393 matchEphemeralPackage = true; 5394 result = new ArrayList<ResolveInfo>(); 5395 } 5396 } 5397 } 5398 if (addEphemeral) { 5399 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5400 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5401 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5402 matchEphemeralPackage ? pkgName : null); 5403 if (ai != null) { 5404 if (DEBUG_EPHEMERAL) { 5405 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5406 } 5407 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5408 ephemeralInstaller.ephemeralResolveInfo = ai; 5409 // make sure this resolver is the default 5410 ephemeralInstaller.isDefault = true; 5411 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5412 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5413 // add a non-generic filter 5414 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5415 ephemeralInstaller.filter.addDataPath( 5416 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5417 result.add(ephemeralInstaller); 5418 } 5419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5420 } 5421 if (sortResult) { 5422 Collections.sort(result, mResolvePrioritySorter); 5423 } 5424 return result; 5425 } 5426 5427 private static class CrossProfileDomainInfo { 5428 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5429 ResolveInfo resolveInfo; 5430 /* Best domain verification status of the activities found in the other profile */ 5431 int bestDomainVerificationStatus; 5432 } 5433 5434 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5435 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5436 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5437 sourceUserId)) { 5438 return null; 5439 } 5440 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5441 resolvedType, flags, parentUserId); 5442 5443 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5444 return null; 5445 } 5446 CrossProfileDomainInfo result = null; 5447 int size = resultTargetUser.size(); 5448 for (int i = 0; i < size; i++) { 5449 ResolveInfo riTargetUser = resultTargetUser.get(i); 5450 // Intent filter verification is only for filters that specify a host. So don't return 5451 // those that handle all web uris. 5452 if (riTargetUser.handleAllWebDataURI) { 5453 continue; 5454 } 5455 String packageName = riTargetUser.activityInfo.packageName; 5456 PackageSetting ps = mSettings.mPackages.get(packageName); 5457 if (ps == null) { 5458 continue; 5459 } 5460 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5461 int status = (int)(verificationState >> 32); 5462 if (result == null) { 5463 result = new CrossProfileDomainInfo(); 5464 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5465 sourceUserId, parentUserId); 5466 result.bestDomainVerificationStatus = status; 5467 } else { 5468 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5469 result.bestDomainVerificationStatus); 5470 } 5471 } 5472 // Don't consider matches with status NEVER across profiles. 5473 if (result != null && result.bestDomainVerificationStatus 5474 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5475 return null; 5476 } 5477 return result; 5478 } 5479 5480 /** 5481 * Verification statuses are ordered from the worse to the best, except for 5482 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5483 */ 5484 private int bestDomainVerificationStatus(int status1, int status2) { 5485 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5486 return status2; 5487 } 5488 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5489 return status1; 5490 } 5491 return (int) MathUtils.max(status1, status2); 5492 } 5493 5494 private boolean isUserEnabled(int userId) { 5495 long callingId = Binder.clearCallingIdentity(); 5496 try { 5497 UserInfo userInfo = sUserManager.getUserInfo(userId); 5498 return userInfo != null && userInfo.isEnabled(); 5499 } finally { 5500 Binder.restoreCallingIdentity(callingId); 5501 } 5502 } 5503 5504 /** 5505 * Filter out activities with systemUserOnly flag set, when current user is not System. 5506 * 5507 * @return filtered list 5508 */ 5509 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5510 if (userId == UserHandle.USER_SYSTEM) { 5511 return resolveInfos; 5512 } 5513 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5514 ResolveInfo info = resolveInfos.get(i); 5515 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5516 resolveInfos.remove(i); 5517 } 5518 } 5519 return resolveInfos; 5520 } 5521 5522 /** 5523 * @param resolveInfos list of resolve infos in descending priority order 5524 * @return if the list contains a resolve info with non-negative priority 5525 */ 5526 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5527 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5528 } 5529 5530 private static boolean hasWebURI(Intent intent) { 5531 if (intent.getData() == null) { 5532 return false; 5533 } 5534 final String scheme = intent.getScheme(); 5535 if (TextUtils.isEmpty(scheme)) { 5536 return false; 5537 } 5538 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5539 } 5540 5541 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5542 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5543 int userId) { 5544 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5545 5546 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5547 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5548 candidates.size()); 5549 } 5550 5551 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5552 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5553 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5554 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5555 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5556 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5557 5558 synchronized (mPackages) { 5559 final int count = candidates.size(); 5560 // First, try to use linked apps. Partition the candidates into four lists: 5561 // one for the final results, one for the "do not use ever", one for "undefined status" 5562 // and finally one for "browser app type". 5563 for (int n=0; n<count; n++) { 5564 ResolveInfo info = candidates.get(n); 5565 String packageName = info.activityInfo.packageName; 5566 PackageSetting ps = mSettings.mPackages.get(packageName); 5567 if (ps != null) { 5568 // Add to the special match all list (Browser use case) 5569 if (info.handleAllWebDataURI) { 5570 matchAllList.add(info); 5571 continue; 5572 } 5573 // Try to get the status from User settings first 5574 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5575 int status = (int)(packedStatus >> 32); 5576 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5577 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5578 if (DEBUG_DOMAIN_VERIFICATION) { 5579 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5580 + " : linkgen=" + linkGeneration); 5581 } 5582 // Use link-enabled generation as preferredOrder, i.e. 5583 // prefer newly-enabled over earlier-enabled. 5584 info.preferredOrder = linkGeneration; 5585 alwaysList.add(info); 5586 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5587 if (DEBUG_DOMAIN_VERIFICATION) { 5588 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5589 } 5590 neverList.add(info); 5591 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5592 if (DEBUG_DOMAIN_VERIFICATION) { 5593 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5594 } 5595 alwaysAskList.add(info); 5596 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5597 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5598 if (DEBUG_DOMAIN_VERIFICATION) { 5599 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5600 } 5601 undefinedList.add(info); 5602 } 5603 } 5604 } 5605 5606 // We'll want to include browser possibilities in a few cases 5607 boolean includeBrowser = false; 5608 5609 // First try to add the "always" resolution(s) for the current user, if any 5610 if (alwaysList.size() > 0) { 5611 result.addAll(alwaysList); 5612 } else { 5613 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5614 result.addAll(undefinedList); 5615 // Maybe add one for the other profile. 5616 if (xpDomainInfo != null && ( 5617 xpDomainInfo.bestDomainVerificationStatus 5618 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5619 result.add(xpDomainInfo.resolveInfo); 5620 } 5621 includeBrowser = true; 5622 } 5623 5624 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5625 // If there were 'always' entries their preferred order has been set, so we also 5626 // back that off to make the alternatives equivalent 5627 if (alwaysAskList.size() > 0) { 5628 for (ResolveInfo i : result) { 5629 i.preferredOrder = 0; 5630 } 5631 result.addAll(alwaysAskList); 5632 includeBrowser = true; 5633 } 5634 5635 if (includeBrowser) { 5636 // Also add browsers (all of them or only the default one) 5637 if (DEBUG_DOMAIN_VERIFICATION) { 5638 Slog.v(TAG, " ...including browsers in candidate set"); 5639 } 5640 if ((matchFlags & MATCH_ALL) != 0) { 5641 result.addAll(matchAllList); 5642 } else { 5643 // Browser/generic handling case. If there's a default browser, go straight 5644 // to that (but only if there is no other higher-priority match). 5645 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5646 int maxMatchPrio = 0; 5647 ResolveInfo defaultBrowserMatch = null; 5648 final int numCandidates = matchAllList.size(); 5649 for (int n = 0; n < numCandidates; n++) { 5650 ResolveInfo info = matchAllList.get(n); 5651 // track the highest overall match priority... 5652 if (info.priority > maxMatchPrio) { 5653 maxMatchPrio = info.priority; 5654 } 5655 // ...and the highest-priority default browser match 5656 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5657 if (defaultBrowserMatch == null 5658 || (defaultBrowserMatch.priority < info.priority)) { 5659 if (debug) { 5660 Slog.v(TAG, "Considering default browser match " + info); 5661 } 5662 defaultBrowserMatch = info; 5663 } 5664 } 5665 } 5666 if (defaultBrowserMatch != null 5667 && defaultBrowserMatch.priority >= maxMatchPrio 5668 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5669 { 5670 if (debug) { 5671 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5672 } 5673 result.add(defaultBrowserMatch); 5674 } else { 5675 result.addAll(matchAllList); 5676 } 5677 } 5678 5679 // If there is nothing selected, add all candidates and remove the ones that the user 5680 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5681 if (result.size() == 0) { 5682 result.addAll(candidates); 5683 result.removeAll(neverList); 5684 } 5685 } 5686 } 5687 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5688 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5689 result.size()); 5690 for (ResolveInfo info : result) { 5691 Slog.v(TAG, " + " + info.activityInfo); 5692 } 5693 } 5694 return result; 5695 } 5696 5697 // Returns a packed value as a long: 5698 // 5699 // high 'int'-sized word: link status: undefined/ask/never/always. 5700 // low 'int'-sized word: relative priority among 'always' results. 5701 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5702 long result = ps.getDomainVerificationStatusForUser(userId); 5703 // if none available, get the master status 5704 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5705 if (ps.getIntentFilterVerificationInfo() != null) { 5706 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5707 } 5708 } 5709 return result; 5710 } 5711 5712 private ResolveInfo querySkipCurrentProfileIntents( 5713 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5714 int flags, int sourceUserId) { 5715 if (matchingFilters != null) { 5716 int size = matchingFilters.size(); 5717 for (int i = 0; i < size; i ++) { 5718 CrossProfileIntentFilter filter = matchingFilters.get(i); 5719 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5720 // Checking if there are activities in the target user that can handle the 5721 // intent. 5722 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5723 resolvedType, flags, sourceUserId); 5724 if (resolveInfo != null) { 5725 return resolveInfo; 5726 } 5727 } 5728 } 5729 } 5730 return null; 5731 } 5732 5733 // Return matching ResolveInfo in target user if any. 5734 private ResolveInfo queryCrossProfileIntents( 5735 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5736 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5737 if (matchingFilters != null) { 5738 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5739 // match the same intent. For performance reasons, it is better not to 5740 // run queryIntent twice for the same userId 5741 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5742 int size = matchingFilters.size(); 5743 for (int i = 0; i < size; i++) { 5744 CrossProfileIntentFilter filter = matchingFilters.get(i); 5745 int targetUserId = filter.getTargetUserId(); 5746 boolean skipCurrentProfile = 5747 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5748 boolean skipCurrentProfileIfNoMatchFound = 5749 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5750 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5751 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5752 // Checking if there are activities in the target user that can handle the 5753 // intent. 5754 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5755 resolvedType, flags, sourceUserId); 5756 if (resolveInfo != null) return resolveInfo; 5757 alreadyTriedUserIds.put(targetUserId, true); 5758 } 5759 } 5760 } 5761 return null; 5762 } 5763 5764 /** 5765 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5766 * will forward the intent to the filter's target user. 5767 * Otherwise, returns null. 5768 */ 5769 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5770 String resolvedType, int flags, int sourceUserId) { 5771 int targetUserId = filter.getTargetUserId(); 5772 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5773 resolvedType, flags, targetUserId); 5774 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5775 // If all the matches in the target profile are suspended, return null. 5776 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5777 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5778 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5779 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5780 targetUserId); 5781 } 5782 } 5783 } 5784 return null; 5785 } 5786 5787 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5788 int sourceUserId, int targetUserId) { 5789 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5790 long ident = Binder.clearCallingIdentity(); 5791 boolean targetIsProfile; 5792 try { 5793 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5794 } finally { 5795 Binder.restoreCallingIdentity(ident); 5796 } 5797 String className; 5798 if (targetIsProfile) { 5799 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5800 } else { 5801 className = FORWARD_INTENT_TO_PARENT; 5802 } 5803 ComponentName forwardingActivityComponentName = new ComponentName( 5804 mAndroidApplication.packageName, className); 5805 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5806 sourceUserId); 5807 if (!targetIsProfile) { 5808 forwardingActivityInfo.showUserIcon = targetUserId; 5809 forwardingResolveInfo.noResourceId = true; 5810 } 5811 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5812 forwardingResolveInfo.priority = 0; 5813 forwardingResolveInfo.preferredOrder = 0; 5814 forwardingResolveInfo.match = 0; 5815 forwardingResolveInfo.isDefault = true; 5816 forwardingResolveInfo.filter = filter; 5817 forwardingResolveInfo.targetUserId = targetUserId; 5818 return forwardingResolveInfo; 5819 } 5820 5821 @Override 5822 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5823 Intent[] specifics, String[] specificTypes, Intent intent, 5824 String resolvedType, int flags, int userId) { 5825 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5826 specificTypes, intent, resolvedType, flags, userId)); 5827 } 5828 5829 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5830 Intent[] specifics, String[] specificTypes, Intent intent, 5831 String resolvedType, int flags, int userId) { 5832 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5833 flags = updateFlagsForResolve(flags, userId, intent); 5834 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5835 false /* requireFullPermission */, false /* checkShell */, 5836 "query intent activity options"); 5837 final String resultsAction = intent.getAction(); 5838 5839 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5840 | PackageManager.GET_RESOLVED_FILTER, userId); 5841 5842 if (DEBUG_INTENT_MATCHING) { 5843 Log.v(TAG, "Query " + intent + ": " + results); 5844 } 5845 5846 int specificsPos = 0; 5847 int N; 5848 5849 // todo: note that the algorithm used here is O(N^2). This 5850 // isn't a problem in our current environment, but if we start running 5851 // into situations where we have more than 5 or 10 matches then this 5852 // should probably be changed to something smarter... 5853 5854 // First we go through and resolve each of the specific items 5855 // that were supplied, taking care of removing any corresponding 5856 // duplicate items in the generic resolve list. 5857 if (specifics != null) { 5858 for (int i=0; i<specifics.length; i++) { 5859 final Intent sintent = specifics[i]; 5860 if (sintent == null) { 5861 continue; 5862 } 5863 5864 if (DEBUG_INTENT_MATCHING) { 5865 Log.v(TAG, "Specific #" + i + ": " + sintent); 5866 } 5867 5868 String action = sintent.getAction(); 5869 if (resultsAction != null && resultsAction.equals(action)) { 5870 // If this action was explicitly requested, then don't 5871 // remove things that have it. 5872 action = null; 5873 } 5874 5875 ResolveInfo ri = null; 5876 ActivityInfo ai = null; 5877 5878 ComponentName comp = sintent.getComponent(); 5879 if (comp == null) { 5880 ri = resolveIntent( 5881 sintent, 5882 specificTypes != null ? specificTypes[i] : null, 5883 flags, userId); 5884 if (ri == null) { 5885 continue; 5886 } 5887 if (ri == mResolveInfo) { 5888 // ACK! Must do something better with this. 5889 } 5890 ai = ri.activityInfo; 5891 comp = new ComponentName(ai.applicationInfo.packageName, 5892 ai.name); 5893 } else { 5894 ai = getActivityInfo(comp, flags, userId); 5895 if (ai == null) { 5896 continue; 5897 } 5898 } 5899 5900 // Look for any generic query activities that are duplicates 5901 // of this specific one, and remove them from the results. 5902 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5903 N = results.size(); 5904 int j; 5905 for (j=specificsPos; j<N; j++) { 5906 ResolveInfo sri = results.get(j); 5907 if ((sri.activityInfo.name.equals(comp.getClassName()) 5908 && sri.activityInfo.applicationInfo.packageName.equals( 5909 comp.getPackageName())) 5910 || (action != null && sri.filter.matchAction(action))) { 5911 results.remove(j); 5912 if (DEBUG_INTENT_MATCHING) Log.v( 5913 TAG, "Removing duplicate item from " + j 5914 + " due to specific " + specificsPos); 5915 if (ri == null) { 5916 ri = sri; 5917 } 5918 j--; 5919 N--; 5920 } 5921 } 5922 5923 // Add this specific item to its proper place. 5924 if (ri == null) { 5925 ri = new ResolveInfo(); 5926 ri.activityInfo = ai; 5927 } 5928 results.add(specificsPos, ri); 5929 ri.specificIndex = i; 5930 specificsPos++; 5931 } 5932 } 5933 5934 // Now we go through the remaining generic results and remove any 5935 // duplicate actions that are found here. 5936 N = results.size(); 5937 for (int i=specificsPos; i<N-1; i++) { 5938 final ResolveInfo rii = results.get(i); 5939 if (rii.filter == null) { 5940 continue; 5941 } 5942 5943 // Iterate over all of the actions of this result's intent 5944 // filter... typically this should be just one. 5945 final Iterator<String> it = rii.filter.actionsIterator(); 5946 if (it == null) { 5947 continue; 5948 } 5949 while (it.hasNext()) { 5950 final String action = it.next(); 5951 if (resultsAction != null && resultsAction.equals(action)) { 5952 // If this action was explicitly requested, then don't 5953 // remove things that have it. 5954 continue; 5955 } 5956 for (int j=i+1; j<N; j++) { 5957 final ResolveInfo rij = results.get(j); 5958 if (rij.filter != null && rij.filter.hasAction(action)) { 5959 results.remove(j); 5960 if (DEBUG_INTENT_MATCHING) Log.v( 5961 TAG, "Removing duplicate item from " + j 5962 + " due to action " + action + " at " + i); 5963 j--; 5964 N--; 5965 } 5966 } 5967 } 5968 5969 // If the caller didn't request filter information, drop it now 5970 // so we don't have to marshall/unmarshall it. 5971 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5972 rii.filter = null; 5973 } 5974 } 5975 5976 // Filter out the caller activity if so requested. 5977 if (caller != null) { 5978 N = results.size(); 5979 for (int i=0; i<N; i++) { 5980 ActivityInfo ainfo = results.get(i).activityInfo; 5981 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5982 && caller.getClassName().equals(ainfo.name)) { 5983 results.remove(i); 5984 break; 5985 } 5986 } 5987 } 5988 5989 // If the caller didn't request filter information, 5990 // drop them now so we don't have to 5991 // marshall/unmarshall it. 5992 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5993 N = results.size(); 5994 for (int i=0; i<N; i++) { 5995 results.get(i).filter = null; 5996 } 5997 } 5998 5999 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6000 return results; 6001 } 6002 6003 @Override 6004 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6005 String resolvedType, int flags, int userId) { 6006 return new ParceledListSlice<>( 6007 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6008 } 6009 6010 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6011 String resolvedType, int flags, int userId) { 6012 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6013 flags = updateFlagsForResolve(flags, userId, intent); 6014 ComponentName comp = intent.getComponent(); 6015 if (comp == null) { 6016 if (intent.getSelector() != null) { 6017 intent = intent.getSelector(); 6018 comp = intent.getComponent(); 6019 } 6020 } 6021 if (comp != null) { 6022 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6023 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6024 if (ai != null) { 6025 ResolveInfo ri = new ResolveInfo(); 6026 ri.activityInfo = ai; 6027 list.add(ri); 6028 } 6029 return list; 6030 } 6031 6032 // reader 6033 synchronized (mPackages) { 6034 String pkgName = intent.getPackage(); 6035 if (pkgName == null) { 6036 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6037 } 6038 final PackageParser.Package pkg = mPackages.get(pkgName); 6039 if (pkg != null) { 6040 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6041 userId); 6042 } 6043 return Collections.emptyList(); 6044 } 6045 } 6046 6047 @Override 6048 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6049 if (!sUserManager.exists(userId)) return null; 6050 flags = updateFlagsForResolve(flags, userId, intent); 6051 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6052 if (query != null) { 6053 if (query.size() >= 1) { 6054 // If there is more than one service with the same priority, 6055 // just arbitrarily pick the first one. 6056 return query.get(0); 6057 } 6058 } 6059 return null; 6060 } 6061 6062 @Override 6063 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6064 String resolvedType, int flags, int userId) { 6065 return new ParceledListSlice<>( 6066 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6067 } 6068 6069 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6070 String resolvedType, int flags, int userId) { 6071 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6072 flags = updateFlagsForResolve(flags, userId, intent); 6073 ComponentName comp = intent.getComponent(); 6074 if (comp == null) { 6075 if (intent.getSelector() != null) { 6076 intent = intent.getSelector(); 6077 comp = intent.getComponent(); 6078 } 6079 } 6080 if (comp != null) { 6081 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6082 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6083 if (si != null) { 6084 final ResolveInfo ri = new ResolveInfo(); 6085 ri.serviceInfo = si; 6086 list.add(ri); 6087 } 6088 return list; 6089 } 6090 6091 // reader 6092 synchronized (mPackages) { 6093 String pkgName = intent.getPackage(); 6094 if (pkgName == null) { 6095 return mServices.queryIntent(intent, resolvedType, flags, userId); 6096 } 6097 final PackageParser.Package pkg = mPackages.get(pkgName); 6098 if (pkg != null) { 6099 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6100 userId); 6101 } 6102 return Collections.emptyList(); 6103 } 6104 } 6105 6106 @Override 6107 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6108 String resolvedType, int flags, int userId) { 6109 return new ParceledListSlice<>( 6110 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6111 } 6112 6113 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6114 Intent intent, String resolvedType, int flags, int userId) { 6115 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6116 flags = updateFlagsForResolve(flags, userId, intent); 6117 ComponentName comp = intent.getComponent(); 6118 if (comp == null) { 6119 if (intent.getSelector() != null) { 6120 intent = intent.getSelector(); 6121 comp = intent.getComponent(); 6122 } 6123 } 6124 if (comp != null) { 6125 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6126 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6127 if (pi != null) { 6128 final ResolveInfo ri = new ResolveInfo(); 6129 ri.providerInfo = pi; 6130 list.add(ri); 6131 } 6132 return list; 6133 } 6134 6135 // reader 6136 synchronized (mPackages) { 6137 String pkgName = intent.getPackage(); 6138 if (pkgName == null) { 6139 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6140 } 6141 final PackageParser.Package pkg = mPackages.get(pkgName); 6142 if (pkg != null) { 6143 return mProviders.queryIntentForPackage( 6144 intent, resolvedType, flags, pkg.providers, userId); 6145 } 6146 return Collections.emptyList(); 6147 } 6148 } 6149 6150 @Override 6151 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6152 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6153 flags = updateFlagsForPackage(flags, userId, null); 6154 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6156 true /* requireFullPermission */, false /* checkShell */, 6157 "get installed packages"); 6158 6159 // writer 6160 synchronized (mPackages) { 6161 ArrayList<PackageInfo> list; 6162 if (listUninstalled) { 6163 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6164 for (PackageSetting ps : mSettings.mPackages.values()) { 6165 final PackageInfo pi; 6166 if (ps.pkg != null) { 6167 pi = generatePackageInfo(ps, flags, userId); 6168 } else { 6169 pi = generatePackageInfo(ps, flags, userId); 6170 } 6171 if (pi != null) { 6172 list.add(pi); 6173 } 6174 } 6175 } else { 6176 list = new ArrayList<PackageInfo>(mPackages.size()); 6177 for (PackageParser.Package p : mPackages.values()) { 6178 final PackageInfo pi = 6179 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6180 if (pi != null) { 6181 list.add(pi); 6182 } 6183 } 6184 } 6185 6186 return new ParceledListSlice<PackageInfo>(list); 6187 } 6188 } 6189 6190 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6191 String[] permissions, boolean[] tmp, int flags, int userId) { 6192 int numMatch = 0; 6193 final PermissionsState permissionsState = ps.getPermissionsState(); 6194 for (int i=0; i<permissions.length; i++) { 6195 final String permission = permissions[i]; 6196 if (permissionsState.hasPermission(permission, userId)) { 6197 tmp[i] = true; 6198 numMatch++; 6199 } else { 6200 tmp[i] = false; 6201 } 6202 } 6203 if (numMatch == 0) { 6204 return; 6205 } 6206 final PackageInfo pi; 6207 if (ps.pkg != null) { 6208 pi = generatePackageInfo(ps, flags, userId); 6209 } else { 6210 pi = generatePackageInfo(ps, flags, userId); 6211 } 6212 // The above might return null in cases of uninstalled apps or install-state 6213 // skew across users/profiles. 6214 if (pi != null) { 6215 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6216 if (numMatch == permissions.length) { 6217 pi.requestedPermissions = permissions; 6218 } else { 6219 pi.requestedPermissions = new String[numMatch]; 6220 numMatch = 0; 6221 for (int i=0; i<permissions.length; i++) { 6222 if (tmp[i]) { 6223 pi.requestedPermissions[numMatch] = permissions[i]; 6224 numMatch++; 6225 } 6226 } 6227 } 6228 } 6229 list.add(pi); 6230 } 6231 } 6232 6233 @Override 6234 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6235 String[] permissions, int flags, int userId) { 6236 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6237 flags = updateFlagsForPackage(flags, userId, permissions); 6238 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6239 6240 // writer 6241 synchronized (mPackages) { 6242 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6243 boolean[] tmpBools = new boolean[permissions.length]; 6244 if (listUninstalled) { 6245 for (PackageSetting ps : mSettings.mPackages.values()) { 6246 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6247 } 6248 } else { 6249 for (PackageParser.Package pkg : mPackages.values()) { 6250 PackageSetting ps = (PackageSetting)pkg.mExtras; 6251 if (ps != null) { 6252 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6253 userId); 6254 } 6255 } 6256 } 6257 6258 return new ParceledListSlice<PackageInfo>(list); 6259 } 6260 } 6261 6262 @Override 6263 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6264 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6265 flags = updateFlagsForApplication(flags, userId, null); 6266 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6267 6268 // writer 6269 synchronized (mPackages) { 6270 ArrayList<ApplicationInfo> list; 6271 if (listUninstalled) { 6272 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6273 for (PackageSetting ps : mSettings.mPackages.values()) { 6274 ApplicationInfo ai; 6275 if (ps.pkg != null) { 6276 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6277 ps.readUserState(userId), userId); 6278 } else { 6279 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6280 } 6281 if (ai != null) { 6282 list.add(ai); 6283 } 6284 } 6285 } else { 6286 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6287 for (PackageParser.Package p : mPackages.values()) { 6288 if (p.mExtras != null) { 6289 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6290 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6291 if (ai != null) { 6292 list.add(ai); 6293 } 6294 } 6295 } 6296 } 6297 6298 return new ParceledListSlice<ApplicationInfo>(list); 6299 } 6300 } 6301 6302 @Override 6303 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6304 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6305 return null; 6306 } 6307 6308 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6309 "getEphemeralApplications"); 6310 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6311 true /* requireFullPermission */, false /* checkShell */, 6312 "getEphemeralApplications"); 6313 synchronized (mPackages) { 6314 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6315 .getEphemeralApplicationsLPw(userId); 6316 if (ephemeralApps != null) { 6317 return new ParceledListSlice<>(ephemeralApps); 6318 } 6319 } 6320 return null; 6321 } 6322 6323 @Override 6324 public boolean isEphemeralApplication(String packageName, int userId) { 6325 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6326 true /* requireFullPermission */, false /* checkShell */, 6327 "isEphemeral"); 6328 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6329 return false; 6330 } 6331 6332 if (!isCallerSameApp(packageName)) { 6333 return false; 6334 } 6335 synchronized (mPackages) { 6336 PackageParser.Package pkg = mPackages.get(packageName); 6337 if (pkg != null) { 6338 return pkg.applicationInfo.isEphemeralApp(); 6339 } 6340 } 6341 return false; 6342 } 6343 6344 @Override 6345 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6346 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6347 return null; 6348 } 6349 6350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6351 true /* requireFullPermission */, false /* checkShell */, 6352 "getCookie"); 6353 if (!isCallerSameApp(packageName)) { 6354 return null; 6355 } 6356 synchronized (mPackages) { 6357 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6358 packageName, userId); 6359 } 6360 } 6361 6362 @Override 6363 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6364 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6365 return true; 6366 } 6367 6368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6369 true /* requireFullPermission */, true /* checkShell */, 6370 "setCookie"); 6371 if (!isCallerSameApp(packageName)) { 6372 return false; 6373 } 6374 synchronized (mPackages) { 6375 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6376 packageName, cookie, userId); 6377 } 6378 } 6379 6380 @Override 6381 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6382 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6383 return null; 6384 } 6385 6386 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6387 "getEphemeralApplicationIcon"); 6388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6389 true /* requireFullPermission */, false /* checkShell */, 6390 "getEphemeralApplicationIcon"); 6391 synchronized (mPackages) { 6392 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6393 packageName, userId); 6394 } 6395 } 6396 6397 private boolean isCallerSameApp(String packageName) { 6398 PackageParser.Package pkg = mPackages.get(packageName); 6399 return pkg != null 6400 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6401 } 6402 6403 @Override 6404 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6405 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6406 } 6407 6408 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6409 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6410 6411 // reader 6412 synchronized (mPackages) { 6413 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6414 final int userId = UserHandle.getCallingUserId(); 6415 while (i.hasNext()) { 6416 final PackageParser.Package p = i.next(); 6417 if (p.applicationInfo == null) continue; 6418 6419 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6420 && !p.applicationInfo.isDirectBootAware(); 6421 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6422 && p.applicationInfo.isDirectBootAware(); 6423 6424 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6425 && (!mSafeMode || isSystemApp(p)) 6426 && (matchesUnaware || matchesAware)) { 6427 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6428 if (ps != null) { 6429 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6430 ps.readUserState(userId), userId); 6431 if (ai != null) { 6432 finalList.add(ai); 6433 } 6434 } 6435 } 6436 } 6437 } 6438 6439 return finalList; 6440 } 6441 6442 @Override 6443 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6444 if (!sUserManager.exists(userId)) return null; 6445 flags = updateFlagsForComponent(flags, userId, name); 6446 // reader 6447 synchronized (mPackages) { 6448 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6449 PackageSetting ps = provider != null 6450 ? mSettings.mPackages.get(provider.owner.packageName) 6451 : null; 6452 return ps != null 6453 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6454 ? PackageParser.generateProviderInfo(provider, flags, 6455 ps.readUserState(userId), userId) 6456 : null; 6457 } 6458 } 6459 6460 /** 6461 * @deprecated 6462 */ 6463 @Deprecated 6464 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6465 // reader 6466 synchronized (mPackages) { 6467 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6468 .entrySet().iterator(); 6469 final int userId = UserHandle.getCallingUserId(); 6470 while (i.hasNext()) { 6471 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6472 PackageParser.Provider p = entry.getValue(); 6473 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6474 6475 if (ps != null && p.syncable 6476 && (!mSafeMode || (p.info.applicationInfo.flags 6477 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6478 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6479 ps.readUserState(userId), userId); 6480 if (info != null) { 6481 outNames.add(entry.getKey()); 6482 outInfo.add(info); 6483 } 6484 } 6485 } 6486 } 6487 } 6488 6489 @Override 6490 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6491 int uid, int flags) { 6492 final int userId = processName != null ? UserHandle.getUserId(uid) 6493 : UserHandle.getCallingUserId(); 6494 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6495 flags = updateFlagsForComponent(flags, userId, processName); 6496 6497 ArrayList<ProviderInfo> finalList = null; 6498 // reader 6499 synchronized (mPackages) { 6500 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6501 while (i.hasNext()) { 6502 final PackageParser.Provider p = i.next(); 6503 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6504 if (ps != null && p.info.authority != null 6505 && (processName == null 6506 || (p.info.processName.equals(processName) 6507 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6508 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6509 if (finalList == null) { 6510 finalList = new ArrayList<ProviderInfo>(3); 6511 } 6512 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6513 ps.readUserState(userId), userId); 6514 if (info != null) { 6515 finalList.add(info); 6516 } 6517 } 6518 } 6519 } 6520 6521 if (finalList != null) { 6522 Collections.sort(finalList, mProviderInitOrderSorter); 6523 return new ParceledListSlice<ProviderInfo>(finalList); 6524 } 6525 6526 return ParceledListSlice.emptyList(); 6527 } 6528 6529 @Override 6530 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6531 // reader 6532 synchronized (mPackages) { 6533 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6534 return PackageParser.generateInstrumentationInfo(i, flags); 6535 } 6536 } 6537 6538 @Override 6539 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6540 String targetPackage, int flags) { 6541 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6542 } 6543 6544 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6545 int flags) { 6546 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6547 6548 // reader 6549 synchronized (mPackages) { 6550 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6551 while (i.hasNext()) { 6552 final PackageParser.Instrumentation p = i.next(); 6553 if (targetPackage == null 6554 || targetPackage.equals(p.info.targetPackage)) { 6555 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6556 flags); 6557 if (ii != null) { 6558 finalList.add(ii); 6559 } 6560 } 6561 } 6562 } 6563 6564 return finalList; 6565 } 6566 6567 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6568 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6569 if (overlays == null) { 6570 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6571 return; 6572 } 6573 for (PackageParser.Package opkg : overlays.values()) { 6574 // Not much to do if idmap fails: we already logged the error 6575 // and we certainly don't want to abort installation of pkg simply 6576 // because an overlay didn't fit properly. For these reasons, 6577 // ignore the return value of createIdmapForPackagePairLI. 6578 createIdmapForPackagePairLI(pkg, opkg); 6579 } 6580 } 6581 6582 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6583 PackageParser.Package opkg) { 6584 if (!opkg.mTrustedOverlay) { 6585 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6586 opkg.baseCodePath + ": overlay not trusted"); 6587 return false; 6588 } 6589 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6590 if (overlaySet == null) { 6591 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6592 opkg.baseCodePath + " but target package has no known overlays"); 6593 return false; 6594 } 6595 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6596 // TODO: generate idmap for split APKs 6597 try { 6598 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6599 } catch (InstallerException e) { 6600 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6601 + opkg.baseCodePath); 6602 return false; 6603 } 6604 PackageParser.Package[] overlayArray = 6605 overlaySet.values().toArray(new PackageParser.Package[0]); 6606 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6607 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6608 return p1.mOverlayPriority - p2.mOverlayPriority; 6609 } 6610 }; 6611 Arrays.sort(overlayArray, cmp); 6612 6613 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6614 int i = 0; 6615 for (PackageParser.Package p : overlayArray) { 6616 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6617 } 6618 return true; 6619 } 6620 6621 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6622 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6623 try { 6624 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6625 } finally { 6626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6627 } 6628 } 6629 6630 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6631 final File[] files = dir.listFiles(); 6632 if (ArrayUtils.isEmpty(files)) { 6633 Log.d(TAG, "No files in app dir " + dir); 6634 return; 6635 } 6636 6637 if (DEBUG_PACKAGE_SCANNING) { 6638 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6639 + " flags=0x" + Integer.toHexString(parseFlags)); 6640 } 6641 6642 for (File file : files) { 6643 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6644 && !PackageInstallerService.isStageName(file.getName()); 6645 if (!isPackage) { 6646 // Ignore entries which are not packages 6647 continue; 6648 } 6649 try { 6650 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6651 scanFlags, currentTime, null); 6652 } catch (PackageManagerException e) { 6653 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6654 6655 // Delete invalid userdata apps 6656 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6657 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6658 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6659 removeCodePathLI(file); 6660 } 6661 } 6662 } 6663 } 6664 6665 private static File getSettingsProblemFile() { 6666 File dataDir = Environment.getDataDirectory(); 6667 File systemDir = new File(dataDir, "system"); 6668 File fname = new File(systemDir, "uiderrors.txt"); 6669 return fname; 6670 } 6671 6672 static void reportSettingsProblem(int priority, String msg) { 6673 logCriticalInfo(priority, msg); 6674 } 6675 6676 static void logCriticalInfo(int priority, String msg) { 6677 Slog.println(priority, TAG, msg); 6678 EventLogTags.writePmCriticalInfo(msg); 6679 try { 6680 File fname = getSettingsProblemFile(); 6681 FileOutputStream out = new FileOutputStream(fname, true); 6682 PrintWriter pw = new FastPrintWriter(out); 6683 SimpleDateFormat formatter = new SimpleDateFormat(); 6684 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6685 pw.println(dateString + ": " + msg); 6686 pw.close(); 6687 FileUtils.setPermissions( 6688 fname.toString(), 6689 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6690 -1, -1); 6691 } catch (java.io.IOException e) { 6692 } 6693 } 6694 6695 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6696 if (srcFile.isDirectory()) { 6697 final File baseFile = new File(pkg.baseCodePath); 6698 long maxModifiedTime = baseFile.lastModified(); 6699 if (pkg.splitCodePaths != null) { 6700 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6701 final File splitFile = new File(pkg.splitCodePaths[i]); 6702 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6703 } 6704 } 6705 return maxModifiedTime; 6706 } 6707 return srcFile.lastModified(); 6708 } 6709 6710 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6711 final int policyFlags) throws PackageManagerException { 6712 // When upgrading from pre-N MR1, verify the package time stamp using the package 6713 // directory and not the APK file. 6714 final long lastModifiedTime = mIsPreNMR1Upgrade 6715 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6716 if (ps != null 6717 && ps.codePath.equals(srcFile) 6718 && ps.timeStamp == lastModifiedTime 6719 && !isCompatSignatureUpdateNeeded(pkg) 6720 && !isRecoverSignatureUpdateNeeded(pkg)) { 6721 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6722 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6723 ArraySet<PublicKey> signingKs; 6724 synchronized (mPackages) { 6725 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6726 } 6727 if (ps.signatures.mSignatures != null 6728 && ps.signatures.mSignatures.length != 0 6729 && signingKs != null) { 6730 // Optimization: reuse the existing cached certificates 6731 // if the package appears to be unchanged. 6732 pkg.mSignatures = ps.signatures.mSignatures; 6733 pkg.mSigningKeys = signingKs; 6734 return; 6735 } 6736 6737 Slog.w(TAG, "PackageSetting for " + ps.name 6738 + " is missing signatures. Collecting certs again to recover them."); 6739 } else { 6740 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6741 } 6742 6743 try { 6744 PackageParser.collectCertificates(pkg, policyFlags); 6745 } catch (PackageParserException e) { 6746 throw PackageManagerException.from(e); 6747 } 6748 } 6749 6750 /** 6751 * Traces a package scan. 6752 * @see #scanPackageLI(File, int, int, long, UserHandle) 6753 */ 6754 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6755 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6756 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6757 try { 6758 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6759 } finally { 6760 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6761 } 6762 } 6763 6764 /** 6765 * Scans a package and returns the newly parsed package. 6766 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6767 */ 6768 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6769 long currentTime, UserHandle user) throws PackageManagerException { 6770 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6771 PackageParser pp = new PackageParser(); 6772 pp.setSeparateProcesses(mSeparateProcesses); 6773 pp.setOnlyCoreApps(mOnlyCore); 6774 pp.setDisplayMetrics(mMetrics); 6775 6776 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6777 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6778 } 6779 6780 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6781 final PackageParser.Package pkg; 6782 try { 6783 pkg = pp.parsePackage(scanFile, parseFlags); 6784 } catch (PackageParserException e) { 6785 throw PackageManagerException.from(e); 6786 } finally { 6787 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6788 } 6789 6790 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6791 } 6792 6793 /** 6794 * Scans a package and returns the newly parsed package. 6795 * @throws PackageManagerException on a parse error. 6796 */ 6797 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6798 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6799 throws PackageManagerException { 6800 // If the package has children and this is the first dive in the function 6801 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6802 // packages (parent and children) would be successfully scanned before the 6803 // actual scan since scanning mutates internal state and we want to atomically 6804 // install the package and its children. 6805 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6806 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6807 scanFlags |= SCAN_CHECK_ONLY; 6808 } 6809 } else { 6810 scanFlags &= ~SCAN_CHECK_ONLY; 6811 } 6812 6813 // Scan the parent 6814 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6815 scanFlags, currentTime, user); 6816 6817 // Scan the children 6818 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6819 for (int i = 0; i < childCount; i++) { 6820 PackageParser.Package childPackage = pkg.childPackages.get(i); 6821 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6822 currentTime, user); 6823 } 6824 6825 6826 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6827 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6828 } 6829 6830 return scannedPkg; 6831 } 6832 6833 /** 6834 * Scans a package and returns the newly parsed package. 6835 * @throws PackageManagerException on a parse error. 6836 */ 6837 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6838 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6839 throws PackageManagerException { 6840 PackageSetting ps = null; 6841 PackageSetting updatedPkg; 6842 // reader 6843 synchronized (mPackages) { 6844 // Look to see if we already know about this package. 6845 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6846 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6847 // This package has been renamed to its original name. Let's 6848 // use that. 6849 ps = mSettings.peekPackageLPr(oldName); 6850 } 6851 // If there was no original package, see one for the real package name. 6852 if (ps == null) { 6853 ps = mSettings.peekPackageLPr(pkg.packageName); 6854 } 6855 // Check to see if this package could be hiding/updating a system 6856 // package. Must look for it either under the original or real 6857 // package name depending on our state. 6858 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6859 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6860 6861 // If this is a package we don't know about on the system partition, we 6862 // may need to remove disabled child packages on the system partition 6863 // or may need to not add child packages if the parent apk is updated 6864 // on the data partition and no longer defines this child package. 6865 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6866 // If this is a parent package for an updated system app and this system 6867 // app got an OTA update which no longer defines some of the child packages 6868 // we have to prune them from the disabled system packages. 6869 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6870 if (disabledPs != null) { 6871 final int scannedChildCount = (pkg.childPackages != null) 6872 ? pkg.childPackages.size() : 0; 6873 final int disabledChildCount = disabledPs.childPackageNames != null 6874 ? disabledPs.childPackageNames.size() : 0; 6875 for (int i = 0; i < disabledChildCount; i++) { 6876 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6877 boolean disabledPackageAvailable = false; 6878 for (int j = 0; j < scannedChildCount; j++) { 6879 PackageParser.Package childPkg = pkg.childPackages.get(j); 6880 if (childPkg.packageName.equals(disabledChildPackageName)) { 6881 disabledPackageAvailable = true; 6882 break; 6883 } 6884 } 6885 if (!disabledPackageAvailable) { 6886 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6887 } 6888 } 6889 } 6890 } 6891 } 6892 6893 boolean updatedPkgBetter = false; 6894 // First check if this is a system package that may involve an update 6895 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6896 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6897 // it needs to drop FLAG_PRIVILEGED. 6898 if (locationIsPrivileged(scanFile)) { 6899 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6900 } else { 6901 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6902 } 6903 6904 if (ps != null && !ps.codePath.equals(scanFile)) { 6905 // The path has changed from what was last scanned... check the 6906 // version of the new path against what we have stored to determine 6907 // what to do. 6908 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6909 if (pkg.mVersionCode <= ps.versionCode) { 6910 // The system package has been updated and the code path does not match 6911 // Ignore entry. Skip it. 6912 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6913 + " ignored: updated version " + ps.versionCode 6914 + " better than this " + pkg.mVersionCode); 6915 if (!updatedPkg.codePath.equals(scanFile)) { 6916 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6917 + ps.name + " changing from " + updatedPkg.codePathString 6918 + " to " + scanFile); 6919 updatedPkg.codePath = scanFile; 6920 updatedPkg.codePathString = scanFile.toString(); 6921 updatedPkg.resourcePath = scanFile; 6922 updatedPkg.resourcePathString = scanFile.toString(); 6923 } 6924 updatedPkg.pkg = pkg; 6925 updatedPkg.versionCode = pkg.mVersionCode; 6926 6927 // Update the disabled system child packages to point to the package too. 6928 final int childCount = updatedPkg.childPackageNames != null 6929 ? updatedPkg.childPackageNames.size() : 0; 6930 for (int i = 0; i < childCount; i++) { 6931 String childPackageName = updatedPkg.childPackageNames.get(i); 6932 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6933 childPackageName); 6934 if (updatedChildPkg != null) { 6935 updatedChildPkg.pkg = pkg; 6936 updatedChildPkg.versionCode = pkg.mVersionCode; 6937 } 6938 } 6939 6940 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6941 + scanFile + " ignored: updated version " + ps.versionCode 6942 + " better than this " + pkg.mVersionCode); 6943 } else { 6944 // The current app on the system partition is better than 6945 // what we have updated to on the data partition; switch 6946 // back to the system partition version. 6947 // At this point, its safely assumed that package installation for 6948 // apps in system partition will go through. If not there won't be a working 6949 // version of the app 6950 // writer 6951 synchronized (mPackages) { 6952 // Just remove the loaded entries from package lists. 6953 mPackages.remove(ps.name); 6954 } 6955 6956 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6957 + " reverting from " + ps.codePathString 6958 + ": new version " + pkg.mVersionCode 6959 + " better than installed " + ps.versionCode); 6960 6961 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6962 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6963 synchronized (mInstallLock) { 6964 args.cleanUpResourcesLI(); 6965 } 6966 synchronized (mPackages) { 6967 mSettings.enableSystemPackageLPw(ps.name); 6968 } 6969 updatedPkgBetter = true; 6970 } 6971 } 6972 } 6973 6974 if (updatedPkg != null) { 6975 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6976 // initially 6977 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6978 6979 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6980 // flag set initially 6981 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6982 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6983 } 6984 } 6985 6986 // Verify certificates against what was last scanned 6987 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6988 6989 /* 6990 * A new system app appeared, but we already had a non-system one of the 6991 * same name installed earlier. 6992 */ 6993 boolean shouldHideSystemApp = false; 6994 if (updatedPkg == null && ps != null 6995 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6996 /* 6997 * Check to make sure the signatures match first. If they don't, 6998 * wipe the installed application and its data. 6999 */ 7000 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7001 != PackageManager.SIGNATURE_MATCH) { 7002 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7003 + " signatures don't match existing userdata copy; removing"); 7004 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7005 "scanPackageInternalLI")) { 7006 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7007 } 7008 ps = null; 7009 } else { 7010 /* 7011 * If the newly-added system app is an older version than the 7012 * already installed version, hide it. It will be scanned later 7013 * and re-added like an update. 7014 */ 7015 if (pkg.mVersionCode <= ps.versionCode) { 7016 shouldHideSystemApp = true; 7017 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7018 + " but new version " + pkg.mVersionCode + " better than installed " 7019 + ps.versionCode + "; hiding system"); 7020 } else { 7021 /* 7022 * The newly found system app is a newer version that the 7023 * one previously installed. Simply remove the 7024 * already-installed application and replace it with our own 7025 * while keeping the application data. 7026 */ 7027 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7028 + " reverting from " + ps.codePathString + ": new version " 7029 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7030 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7031 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7032 synchronized (mInstallLock) { 7033 args.cleanUpResourcesLI(); 7034 } 7035 } 7036 } 7037 } 7038 7039 // The apk is forward locked (not public) if its code and resources 7040 // are kept in different files. (except for app in either system or 7041 // vendor path). 7042 // TODO grab this value from PackageSettings 7043 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7044 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7045 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7046 } 7047 } 7048 7049 // TODO: extend to support forward-locked splits 7050 String resourcePath = null; 7051 String baseResourcePath = null; 7052 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7053 if (ps != null && ps.resourcePathString != null) { 7054 resourcePath = ps.resourcePathString; 7055 baseResourcePath = ps.resourcePathString; 7056 } else { 7057 // Should not happen at all. Just log an error. 7058 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7059 } 7060 } else { 7061 resourcePath = pkg.codePath; 7062 baseResourcePath = pkg.baseCodePath; 7063 } 7064 7065 // Set application objects path explicitly. 7066 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7067 pkg.setApplicationInfoCodePath(pkg.codePath); 7068 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7069 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7070 pkg.setApplicationInfoResourcePath(resourcePath); 7071 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7072 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7073 7074 // Note that we invoke the following method only if we are about to unpack an application 7075 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7076 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7077 7078 /* 7079 * If the system app should be overridden by a previously installed 7080 * data, hide the system app now and let the /data/app scan pick it up 7081 * again. 7082 */ 7083 if (shouldHideSystemApp) { 7084 synchronized (mPackages) { 7085 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7086 } 7087 } 7088 7089 return scannedPkg; 7090 } 7091 7092 private static String fixProcessName(String defProcessName, 7093 String processName, int uid) { 7094 if (processName == null) { 7095 return defProcessName; 7096 } 7097 return processName; 7098 } 7099 7100 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7101 throws PackageManagerException { 7102 if (pkgSetting.signatures.mSignatures != null) { 7103 // Already existing package. Make sure signatures match 7104 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7105 == PackageManager.SIGNATURE_MATCH; 7106 if (!match) { 7107 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7108 == PackageManager.SIGNATURE_MATCH; 7109 } 7110 if (!match) { 7111 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7112 == PackageManager.SIGNATURE_MATCH; 7113 } 7114 if (!match) { 7115 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7116 + pkg.packageName + " signatures do not match the " 7117 + "previously installed version; ignoring!"); 7118 } 7119 } 7120 7121 // Check for shared user signatures 7122 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7123 // Already existing package. Make sure signatures match 7124 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7125 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7126 if (!match) { 7127 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7128 == PackageManager.SIGNATURE_MATCH; 7129 } 7130 if (!match) { 7131 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7132 == PackageManager.SIGNATURE_MATCH; 7133 } 7134 if (!match) { 7135 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7136 "Package " + pkg.packageName 7137 + " has no signatures that match those in shared user " 7138 + pkgSetting.sharedUser.name + "; ignoring!"); 7139 } 7140 } 7141 } 7142 7143 /** 7144 * Enforces that only the system UID or root's UID can call a method exposed 7145 * via Binder. 7146 * 7147 * @param message used as message if SecurityException is thrown 7148 * @throws SecurityException if the caller is not system or root 7149 */ 7150 private static final void enforceSystemOrRoot(String message) { 7151 final int uid = Binder.getCallingUid(); 7152 if (uid != Process.SYSTEM_UID && uid != 0) { 7153 throw new SecurityException(message); 7154 } 7155 } 7156 7157 @Override 7158 public void performFstrimIfNeeded() { 7159 enforceSystemOrRoot("Only the system can request fstrim"); 7160 7161 // Before everything else, see whether we need to fstrim. 7162 try { 7163 IMountService ms = PackageHelper.getMountService(); 7164 if (ms != null) { 7165 boolean doTrim = false; 7166 final long interval = android.provider.Settings.Global.getLong( 7167 mContext.getContentResolver(), 7168 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7169 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7170 if (interval > 0) { 7171 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7172 if (timeSinceLast > interval) { 7173 doTrim = true; 7174 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7175 + "; running immediately"); 7176 } 7177 } 7178 if (doTrim) { 7179 final boolean dexOptDialogShown; 7180 synchronized (mPackages) { 7181 dexOptDialogShown = mDexOptDialogShown; 7182 } 7183 if (!isFirstBoot() && dexOptDialogShown) { 7184 try { 7185 ActivityManagerNative.getDefault().showBootMessage( 7186 mContext.getResources().getString( 7187 R.string.android_upgrading_fstrim), true); 7188 } catch (RemoteException e) { 7189 } 7190 } 7191 ms.runMaintenance(); 7192 } 7193 } else { 7194 Slog.e(TAG, "Mount service unavailable!"); 7195 } 7196 } catch (RemoteException e) { 7197 // Can't happen; MountService is local 7198 } 7199 } 7200 7201 @Override 7202 public void updatePackagesIfNeeded() { 7203 enforceSystemOrRoot("Only the system can request package update"); 7204 7205 // We need to re-extract after an OTA. 7206 boolean causeUpgrade = isUpgrade(); 7207 7208 // First boot or factory reset. 7209 // Note: we also handle devices that are upgrading to N right now as if it is their 7210 // first boot, as they do not have profile data. 7211 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7212 7213 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7214 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7215 7216 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7217 return; 7218 } 7219 7220 List<PackageParser.Package> pkgs; 7221 synchronized (mPackages) { 7222 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7223 } 7224 7225 final long startTime = System.nanoTime(); 7226 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7227 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7228 7229 final int elapsedTimeSeconds = 7230 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7231 7232 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7233 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7234 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7235 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7236 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7237 } 7238 7239 /** 7240 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7241 * containing statistics about the invocation. The array consists of three elements, 7242 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7243 * and {@code numberOfPackagesFailed}. 7244 */ 7245 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7246 String compilerFilter) { 7247 7248 int numberOfPackagesVisited = 0; 7249 int numberOfPackagesOptimized = 0; 7250 int numberOfPackagesSkipped = 0; 7251 int numberOfPackagesFailed = 0; 7252 final int numberOfPackagesToDexopt = pkgs.size(); 7253 7254 for (PackageParser.Package pkg : pkgs) { 7255 numberOfPackagesVisited++; 7256 7257 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7258 if (DEBUG_DEXOPT) { 7259 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7260 } 7261 numberOfPackagesSkipped++; 7262 continue; 7263 } 7264 7265 if (DEBUG_DEXOPT) { 7266 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7267 numberOfPackagesToDexopt + ": " + pkg.packageName); 7268 } 7269 7270 if (showDialog) { 7271 try { 7272 ActivityManagerNative.getDefault().showBootMessage( 7273 mContext.getResources().getString(R.string.android_upgrading_apk, 7274 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7275 } catch (RemoteException e) { 7276 } 7277 synchronized (mPackages) { 7278 mDexOptDialogShown = true; 7279 } 7280 } 7281 7282 // If the OTA updates a system app which was previously preopted to a non-preopted state 7283 // the app might end up being verified at runtime. That's because by default the apps 7284 // are verify-profile but for preopted apps there's no profile. 7285 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7286 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7287 // filter (by default interpret-only). 7288 // Note that at this stage unused apps are already filtered. 7289 if (isSystemApp(pkg) && 7290 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7291 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7292 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7293 } 7294 7295 // checkProfiles is false to avoid merging profiles during boot which 7296 // might interfere with background compilation (b/28612421). 7297 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7298 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7299 // trade-off worth doing to save boot time work. 7300 int dexOptStatus = performDexOptTraced(pkg.packageName, 7301 false /* checkProfiles */, 7302 compilerFilter, 7303 false /* force */); 7304 switch (dexOptStatus) { 7305 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7306 numberOfPackagesOptimized++; 7307 break; 7308 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7309 numberOfPackagesSkipped++; 7310 break; 7311 case PackageDexOptimizer.DEX_OPT_FAILED: 7312 numberOfPackagesFailed++; 7313 break; 7314 default: 7315 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7316 break; 7317 } 7318 } 7319 7320 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7321 numberOfPackagesFailed }; 7322 } 7323 7324 @Override 7325 public void notifyPackageUse(String packageName, int reason) { 7326 synchronized (mPackages) { 7327 PackageParser.Package p = mPackages.get(packageName); 7328 if (p == null) { 7329 return; 7330 } 7331 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7332 } 7333 } 7334 7335 // TODO: this is not used nor needed. Delete it. 7336 @Override 7337 public boolean performDexOptIfNeeded(String packageName) { 7338 int dexOptStatus = performDexOptTraced(packageName, 7339 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7340 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7341 } 7342 7343 @Override 7344 public boolean performDexOpt(String packageName, 7345 boolean checkProfiles, int compileReason, boolean force) { 7346 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7347 getCompilerFilterForReason(compileReason), force); 7348 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7349 } 7350 7351 @Override 7352 public boolean performDexOptMode(String packageName, 7353 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7354 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7355 targetCompilerFilter, force); 7356 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7357 } 7358 7359 private int performDexOptTraced(String packageName, 7360 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7361 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7362 try { 7363 return performDexOptInternal(packageName, checkProfiles, 7364 targetCompilerFilter, force); 7365 } finally { 7366 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7367 } 7368 } 7369 7370 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7371 // if the package can now be considered up to date for the given filter. 7372 private int performDexOptInternal(String packageName, 7373 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7374 PackageParser.Package p; 7375 synchronized (mPackages) { 7376 p = mPackages.get(packageName); 7377 if (p == null) { 7378 // Package could not be found. Report failure. 7379 return PackageDexOptimizer.DEX_OPT_FAILED; 7380 } 7381 mPackageUsage.maybeWriteAsync(mPackages); 7382 mCompilerStats.maybeWriteAsync(); 7383 } 7384 long callingId = Binder.clearCallingIdentity(); 7385 try { 7386 synchronized (mInstallLock) { 7387 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7388 targetCompilerFilter, force); 7389 } 7390 } finally { 7391 Binder.restoreCallingIdentity(callingId); 7392 } 7393 } 7394 7395 public ArraySet<String> getOptimizablePackages() { 7396 ArraySet<String> pkgs = new ArraySet<String>(); 7397 synchronized (mPackages) { 7398 for (PackageParser.Package p : mPackages.values()) { 7399 if (PackageDexOptimizer.canOptimizePackage(p)) { 7400 pkgs.add(p.packageName); 7401 } 7402 } 7403 } 7404 return pkgs; 7405 } 7406 7407 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7408 boolean checkProfiles, String targetCompilerFilter, 7409 boolean force) { 7410 // Select the dex optimizer based on the force parameter. 7411 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7412 // allocate an object here. 7413 PackageDexOptimizer pdo = force 7414 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7415 : mPackageDexOptimizer; 7416 7417 // Optimize all dependencies first. Note: we ignore the return value and march on 7418 // on errors. 7419 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7420 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7421 if (!deps.isEmpty()) { 7422 for (PackageParser.Package depPackage : deps) { 7423 // TODO: Analyze and investigate if we (should) profile libraries. 7424 // Currently this will do a full compilation of the library by default. 7425 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7426 false /* checkProfiles */, 7427 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7428 getOrCreateCompilerPackageStats(depPackage)); 7429 } 7430 } 7431 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7432 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7433 } 7434 7435 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7436 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7437 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7438 Set<String> collectedNames = new HashSet<>(); 7439 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7440 7441 retValue.remove(p); 7442 7443 return retValue; 7444 } else { 7445 return Collections.emptyList(); 7446 } 7447 } 7448 7449 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7450 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7451 if (!collectedNames.contains(p.packageName)) { 7452 collectedNames.add(p.packageName); 7453 collected.add(p); 7454 7455 if (p.usesLibraries != null) { 7456 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7457 } 7458 if (p.usesOptionalLibraries != null) { 7459 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7460 collectedNames); 7461 } 7462 } 7463 } 7464 7465 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7466 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7467 for (String libName : libs) { 7468 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7469 if (libPkg != null) { 7470 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7471 } 7472 } 7473 } 7474 7475 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7476 synchronized (mPackages) { 7477 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7478 if (lib != null && lib.apk != null) { 7479 return mPackages.get(lib.apk); 7480 } 7481 } 7482 return null; 7483 } 7484 7485 public void shutdown() { 7486 mPackageUsage.writeNow(mPackages); 7487 mCompilerStats.writeNow(); 7488 } 7489 7490 @Override 7491 public void dumpProfiles(String packageName) { 7492 PackageParser.Package pkg; 7493 synchronized (mPackages) { 7494 pkg = mPackages.get(packageName); 7495 if (pkg == null) { 7496 throw new IllegalArgumentException("Unknown package: " + packageName); 7497 } 7498 } 7499 /* Only the shell, root, or the app user should be able to dump profiles. */ 7500 int callingUid = Binder.getCallingUid(); 7501 if (callingUid != Process.SHELL_UID && 7502 callingUid != Process.ROOT_UID && 7503 callingUid != pkg.applicationInfo.uid) { 7504 throw new SecurityException("dumpProfiles"); 7505 } 7506 7507 synchronized (mInstallLock) { 7508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7509 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7510 try { 7511 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7512 String gid = Integer.toString(sharedGid); 7513 String codePaths = TextUtils.join(";", allCodePaths); 7514 mInstaller.dumpProfiles(gid, packageName, codePaths); 7515 } catch (InstallerException e) { 7516 Slog.w(TAG, "Failed to dump profiles", e); 7517 } 7518 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7519 } 7520 } 7521 7522 @Override 7523 public void forceDexOpt(String packageName) { 7524 enforceSystemOrRoot("forceDexOpt"); 7525 7526 PackageParser.Package pkg; 7527 synchronized (mPackages) { 7528 pkg = mPackages.get(packageName); 7529 if (pkg == null) { 7530 throw new IllegalArgumentException("Unknown package: " + packageName); 7531 } 7532 } 7533 7534 synchronized (mInstallLock) { 7535 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7536 7537 // Whoever is calling forceDexOpt wants a fully compiled package. 7538 // Don't use profiles since that may cause compilation to be skipped. 7539 final int res = performDexOptInternalWithDependenciesLI(pkg, 7540 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7541 true /* force */); 7542 7543 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7544 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7545 throw new IllegalStateException("Failed to dexopt: " + res); 7546 } 7547 } 7548 } 7549 7550 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7551 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7552 Slog.w(TAG, "Unable to update from " + oldPkg.name 7553 + " to " + newPkg.packageName 7554 + ": old package not in system partition"); 7555 return false; 7556 } else if (mPackages.get(oldPkg.name) != null) { 7557 Slog.w(TAG, "Unable to update from " + oldPkg.name 7558 + " to " + newPkg.packageName 7559 + ": old package still exists"); 7560 return false; 7561 } 7562 return true; 7563 } 7564 7565 void removeCodePathLI(File codePath) { 7566 if (codePath.isDirectory()) { 7567 try { 7568 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7569 } catch (InstallerException e) { 7570 Slog.w(TAG, "Failed to remove code path", e); 7571 } 7572 } else { 7573 codePath.delete(); 7574 } 7575 } 7576 7577 private int[] resolveUserIds(int userId) { 7578 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7579 } 7580 7581 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7582 if (pkg == null) { 7583 Slog.wtf(TAG, "Package was null!", new Throwable()); 7584 return; 7585 } 7586 clearAppDataLeafLIF(pkg, userId, flags); 7587 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7588 for (int i = 0; i < childCount; i++) { 7589 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7590 } 7591 } 7592 7593 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7594 final PackageSetting ps; 7595 synchronized (mPackages) { 7596 ps = mSettings.mPackages.get(pkg.packageName); 7597 } 7598 for (int realUserId : resolveUserIds(userId)) { 7599 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7600 try { 7601 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7602 ceDataInode); 7603 } catch (InstallerException e) { 7604 Slog.w(TAG, String.valueOf(e)); 7605 } 7606 } 7607 } 7608 7609 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7610 if (pkg == null) { 7611 Slog.wtf(TAG, "Package was null!", new Throwable()); 7612 return; 7613 } 7614 destroyAppDataLeafLIF(pkg, userId, flags); 7615 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7616 for (int i = 0; i < childCount; i++) { 7617 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7618 } 7619 } 7620 7621 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7622 final PackageSetting ps; 7623 synchronized (mPackages) { 7624 ps = mSettings.mPackages.get(pkg.packageName); 7625 } 7626 for (int realUserId : resolveUserIds(userId)) { 7627 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7628 try { 7629 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7630 ceDataInode); 7631 } catch (InstallerException e) { 7632 Slog.w(TAG, String.valueOf(e)); 7633 } 7634 } 7635 } 7636 7637 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7638 if (pkg == null) { 7639 Slog.wtf(TAG, "Package was null!", new Throwable()); 7640 return; 7641 } 7642 destroyAppProfilesLeafLIF(pkg); 7643 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7644 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7645 for (int i = 0; i < childCount; i++) { 7646 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7647 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7648 true /* removeBaseMarker */); 7649 } 7650 } 7651 7652 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7653 boolean removeBaseMarker) { 7654 if (pkg.isForwardLocked()) { 7655 return; 7656 } 7657 7658 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7659 try { 7660 path = PackageManagerServiceUtils.realpath(new File(path)); 7661 } catch (IOException e) { 7662 // TODO: Should we return early here ? 7663 Slog.w(TAG, "Failed to get canonical path", e); 7664 continue; 7665 } 7666 7667 final String useMarker = path.replace('/', '@'); 7668 for (int realUserId : resolveUserIds(userId)) { 7669 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7670 if (removeBaseMarker) { 7671 File foreignUseMark = new File(profileDir, useMarker); 7672 if (foreignUseMark.exists()) { 7673 if (!foreignUseMark.delete()) { 7674 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7675 + pkg.packageName); 7676 } 7677 } 7678 } 7679 7680 File[] markers = profileDir.listFiles(); 7681 if (markers != null) { 7682 final String searchString = "@" + pkg.packageName + "@"; 7683 // We also delete all markers that contain the package name we're 7684 // uninstalling. These are associated with secondary dex-files belonging 7685 // to the package. Reconstructing the path of these dex files is messy 7686 // in general. 7687 for (File marker : markers) { 7688 if (marker.getName().indexOf(searchString) > 0) { 7689 if (!marker.delete()) { 7690 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7691 + pkg.packageName); 7692 } 7693 } 7694 } 7695 } 7696 } 7697 } 7698 } 7699 7700 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7701 try { 7702 mInstaller.destroyAppProfiles(pkg.packageName); 7703 } catch (InstallerException e) { 7704 Slog.w(TAG, String.valueOf(e)); 7705 } 7706 } 7707 7708 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7709 if (pkg == null) { 7710 Slog.wtf(TAG, "Package was null!", new Throwable()); 7711 return; 7712 } 7713 clearAppProfilesLeafLIF(pkg); 7714 // We don't remove the base foreign use marker when clearing profiles because 7715 // we will rename it when the app is updated. Unlike the actual profile contents, 7716 // the foreign use marker is good across installs. 7717 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7719 for (int i = 0; i < childCount; i++) { 7720 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7721 } 7722 } 7723 7724 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7725 try { 7726 mInstaller.clearAppProfiles(pkg.packageName); 7727 } catch (InstallerException e) { 7728 Slog.w(TAG, String.valueOf(e)); 7729 } 7730 } 7731 7732 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7733 long lastUpdateTime) { 7734 // Set parent install/update time 7735 PackageSetting ps = (PackageSetting) pkg.mExtras; 7736 if (ps != null) { 7737 ps.firstInstallTime = firstInstallTime; 7738 ps.lastUpdateTime = lastUpdateTime; 7739 } 7740 // Set children install/update time 7741 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7742 for (int i = 0; i < childCount; i++) { 7743 PackageParser.Package childPkg = pkg.childPackages.get(i); 7744 ps = (PackageSetting) childPkg.mExtras; 7745 if (ps != null) { 7746 ps.firstInstallTime = firstInstallTime; 7747 ps.lastUpdateTime = lastUpdateTime; 7748 } 7749 } 7750 } 7751 7752 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7753 PackageParser.Package changingLib) { 7754 if (file.path != null) { 7755 usesLibraryFiles.add(file.path); 7756 return; 7757 } 7758 PackageParser.Package p = mPackages.get(file.apk); 7759 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7760 // If we are doing this while in the middle of updating a library apk, 7761 // then we need to make sure to use that new apk for determining the 7762 // dependencies here. (We haven't yet finished committing the new apk 7763 // to the package manager state.) 7764 if (p == null || p.packageName.equals(changingLib.packageName)) { 7765 p = changingLib; 7766 } 7767 } 7768 if (p != null) { 7769 usesLibraryFiles.addAll(p.getAllCodePaths()); 7770 } 7771 } 7772 7773 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7774 PackageParser.Package changingLib) throws PackageManagerException { 7775 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7776 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7777 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7778 for (int i=0; i<N; i++) { 7779 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7780 if (file == null) { 7781 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7782 "Package " + pkg.packageName + " requires unavailable shared library " 7783 + pkg.usesLibraries.get(i) + "; failing!"); 7784 } 7785 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7786 } 7787 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7788 for (int i=0; i<N; i++) { 7789 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7790 if (file == null) { 7791 Slog.w(TAG, "Package " + pkg.packageName 7792 + " desires unavailable shared library " 7793 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7794 } else { 7795 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7796 } 7797 } 7798 N = usesLibraryFiles.size(); 7799 if (N > 0) { 7800 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7801 } else { 7802 pkg.usesLibraryFiles = null; 7803 } 7804 } 7805 } 7806 7807 private static boolean hasString(List<String> list, List<String> which) { 7808 if (list == null) { 7809 return false; 7810 } 7811 for (int i=list.size()-1; i>=0; i--) { 7812 for (int j=which.size()-1; j>=0; j--) { 7813 if (which.get(j).equals(list.get(i))) { 7814 return true; 7815 } 7816 } 7817 } 7818 return false; 7819 } 7820 7821 private void updateAllSharedLibrariesLPw() { 7822 for (PackageParser.Package pkg : mPackages.values()) { 7823 try { 7824 updateSharedLibrariesLPw(pkg, null); 7825 } catch (PackageManagerException e) { 7826 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7827 } 7828 } 7829 } 7830 7831 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7832 PackageParser.Package changingPkg) { 7833 ArrayList<PackageParser.Package> res = null; 7834 for (PackageParser.Package pkg : mPackages.values()) { 7835 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7836 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7837 if (res == null) { 7838 res = new ArrayList<PackageParser.Package>(); 7839 } 7840 res.add(pkg); 7841 try { 7842 updateSharedLibrariesLPw(pkg, changingPkg); 7843 } catch (PackageManagerException e) { 7844 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7845 } 7846 } 7847 } 7848 return res; 7849 } 7850 7851 /** 7852 * Derive the value of the {@code cpuAbiOverride} based on the provided 7853 * value and an optional stored value from the package settings. 7854 */ 7855 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7856 String cpuAbiOverride = null; 7857 7858 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7859 cpuAbiOverride = null; 7860 } else if (abiOverride != null) { 7861 cpuAbiOverride = abiOverride; 7862 } else if (settings != null) { 7863 cpuAbiOverride = settings.cpuAbiOverrideString; 7864 } 7865 7866 return cpuAbiOverride; 7867 } 7868 7869 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7870 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7871 throws PackageManagerException { 7872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7873 // If the package has children and this is the first dive in the function 7874 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7875 // whether all packages (parent and children) would be successfully scanned 7876 // before the actual scan since scanning mutates internal state and we want 7877 // to atomically install the package and its children. 7878 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7879 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7880 scanFlags |= SCAN_CHECK_ONLY; 7881 } 7882 } else { 7883 scanFlags &= ~SCAN_CHECK_ONLY; 7884 } 7885 7886 final PackageParser.Package scannedPkg; 7887 try { 7888 // Scan the parent 7889 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7890 // Scan the children 7891 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7892 for (int i = 0; i < childCount; i++) { 7893 PackageParser.Package childPkg = pkg.childPackages.get(i); 7894 scanPackageLI(childPkg, policyFlags, 7895 scanFlags, currentTime, user); 7896 } 7897 } finally { 7898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7899 } 7900 7901 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7902 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7903 } 7904 7905 return scannedPkg; 7906 } 7907 7908 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7909 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7910 boolean success = false; 7911 try { 7912 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7913 currentTime, user); 7914 success = true; 7915 return res; 7916 } finally { 7917 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7918 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7919 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7920 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7921 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7922 } 7923 } 7924 } 7925 7926 /** 7927 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7928 */ 7929 private static boolean apkHasCode(String fileName) { 7930 StrictJarFile jarFile = null; 7931 try { 7932 jarFile = new StrictJarFile(fileName, 7933 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7934 return jarFile.findEntry("classes.dex") != null; 7935 } catch (IOException ignore) { 7936 } finally { 7937 try { 7938 if (jarFile != null) { 7939 jarFile.close(); 7940 } 7941 } catch (IOException ignore) {} 7942 } 7943 return false; 7944 } 7945 7946 /** 7947 * Enforces code policy for the package. This ensures that if an APK has 7948 * declared hasCode="true" in its manifest that the APK actually contains 7949 * code. 7950 * 7951 * @throws PackageManagerException If bytecode could not be found when it should exist 7952 */ 7953 private static void enforceCodePolicy(PackageParser.Package pkg) 7954 throws PackageManagerException { 7955 final boolean shouldHaveCode = 7956 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7957 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7958 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7959 "Package " + pkg.baseCodePath + " code is missing"); 7960 } 7961 7962 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7963 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7964 final boolean splitShouldHaveCode = 7965 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7966 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7967 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7968 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7969 } 7970 } 7971 } 7972 } 7973 7974 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7975 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7976 throws PackageManagerException { 7977 final File scanFile = new File(pkg.codePath); 7978 if (pkg.applicationInfo.getCodePath() == null || 7979 pkg.applicationInfo.getResourcePath() == null) { 7980 // Bail out. The resource and code paths haven't been set. 7981 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7982 "Code and resource paths haven't been set correctly"); 7983 } 7984 7985 // Apply policy 7986 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7987 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7988 if (pkg.applicationInfo.isDirectBootAware()) { 7989 // we're direct boot aware; set for all components 7990 for (PackageParser.Service s : pkg.services) { 7991 s.info.encryptionAware = s.info.directBootAware = true; 7992 } 7993 for (PackageParser.Provider p : pkg.providers) { 7994 p.info.encryptionAware = p.info.directBootAware = true; 7995 } 7996 for (PackageParser.Activity a : pkg.activities) { 7997 a.info.encryptionAware = a.info.directBootAware = true; 7998 } 7999 for (PackageParser.Activity r : pkg.receivers) { 8000 r.info.encryptionAware = r.info.directBootAware = true; 8001 } 8002 } 8003 } else { 8004 // Only allow system apps to be flagged as core apps. 8005 pkg.coreApp = false; 8006 // clear flags not applicable to regular apps 8007 pkg.applicationInfo.privateFlags &= 8008 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8009 pkg.applicationInfo.privateFlags &= 8010 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8011 } 8012 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8013 8014 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8015 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8016 } 8017 8018 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8019 enforceCodePolicy(pkg); 8020 } 8021 8022 if (mCustomResolverComponentName != null && 8023 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8024 setUpCustomResolverActivity(pkg); 8025 } 8026 8027 if (pkg.packageName.equals("android")) { 8028 synchronized (mPackages) { 8029 if (mAndroidApplication != null) { 8030 Slog.w(TAG, "*************************************************"); 8031 Slog.w(TAG, "Core android package being redefined. Skipping."); 8032 Slog.w(TAG, " file=" + scanFile); 8033 Slog.w(TAG, "*************************************************"); 8034 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8035 "Core android package being redefined. Skipping."); 8036 } 8037 8038 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8039 // Set up information for our fall-back user intent resolution activity. 8040 mPlatformPackage = pkg; 8041 pkg.mVersionCode = mSdkVersion; 8042 mAndroidApplication = pkg.applicationInfo; 8043 8044 if (!mResolverReplaced) { 8045 mResolveActivity.applicationInfo = mAndroidApplication; 8046 mResolveActivity.name = ResolverActivity.class.getName(); 8047 mResolveActivity.packageName = mAndroidApplication.packageName; 8048 mResolveActivity.processName = "system:ui"; 8049 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8050 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8051 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8052 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8053 mResolveActivity.exported = true; 8054 mResolveActivity.enabled = true; 8055 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8056 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8057 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8058 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8059 | ActivityInfo.CONFIG_ORIENTATION 8060 | ActivityInfo.CONFIG_KEYBOARD 8061 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8062 mResolveInfo.activityInfo = mResolveActivity; 8063 mResolveInfo.priority = 0; 8064 mResolveInfo.preferredOrder = 0; 8065 mResolveInfo.match = 0; 8066 mResolveComponentName = new ComponentName( 8067 mAndroidApplication.packageName, mResolveActivity.name); 8068 } 8069 } 8070 } 8071 } 8072 8073 if (DEBUG_PACKAGE_SCANNING) { 8074 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8075 Log.d(TAG, "Scanning package " + pkg.packageName); 8076 } 8077 8078 synchronized (mPackages) { 8079 if (mPackages.containsKey(pkg.packageName) 8080 || mSharedLibraries.containsKey(pkg.packageName)) { 8081 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8082 "Application package " + pkg.packageName 8083 + " already installed. Skipping duplicate."); 8084 } 8085 8086 // If we're only installing presumed-existing packages, require that the 8087 // scanned APK is both already known and at the path previously established 8088 // for it. Previously unknown packages we pick up normally, but if we have an 8089 // a priori expectation about this package's install presence, enforce it. 8090 // With a singular exception for new system packages. When an OTA contains 8091 // a new system package, we allow the codepath to change from a system location 8092 // to the user-installed location. If we don't allow this change, any newer, 8093 // user-installed version of the application will be ignored. 8094 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8095 if (mExpectingBetter.containsKey(pkg.packageName)) { 8096 logCriticalInfo(Log.WARN, 8097 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8098 } else { 8099 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8100 if (known != null) { 8101 if (DEBUG_PACKAGE_SCANNING) { 8102 Log.d(TAG, "Examining " + pkg.codePath 8103 + " and requiring known paths " + known.codePathString 8104 + " & " + known.resourcePathString); 8105 } 8106 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8107 || !pkg.applicationInfo.getResourcePath().equals( 8108 known.resourcePathString)) { 8109 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8110 "Application package " + pkg.packageName 8111 + " found at " + pkg.applicationInfo.getCodePath() 8112 + " but expected at " + known.codePathString 8113 + "; ignoring."); 8114 } 8115 } 8116 } 8117 } 8118 } 8119 8120 // Initialize package source and resource directories 8121 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8122 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8123 8124 SharedUserSetting suid = null; 8125 PackageSetting pkgSetting = null; 8126 8127 if (!isSystemApp(pkg)) { 8128 // Only system apps can use these features. 8129 pkg.mOriginalPackages = null; 8130 pkg.mRealPackage = null; 8131 pkg.mAdoptPermissions = null; 8132 } 8133 8134 // Getting the package setting may have a side-effect, so if we 8135 // are only checking if scan would succeed, stash a copy of the 8136 // old setting to restore at the end. 8137 PackageSetting nonMutatedPs = null; 8138 8139 // writer 8140 synchronized (mPackages) { 8141 if (pkg.mSharedUserId != null) { 8142 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8143 if (suid == null) { 8144 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8145 "Creating application package " + pkg.packageName 8146 + " for shared user failed"); 8147 } 8148 if (DEBUG_PACKAGE_SCANNING) { 8149 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8150 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8151 + "): packages=" + suid.packages); 8152 } 8153 } 8154 8155 // Check if we are renaming from an original package name. 8156 PackageSetting origPackage = null; 8157 String realName = null; 8158 if (pkg.mOriginalPackages != null) { 8159 // This package may need to be renamed to a previously 8160 // installed name. Let's check on that... 8161 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8162 if (pkg.mOriginalPackages.contains(renamed)) { 8163 // This package had originally been installed as the 8164 // original name, and we have already taken care of 8165 // transitioning to the new one. Just update the new 8166 // one to continue using the old name. 8167 realName = pkg.mRealPackage; 8168 if (!pkg.packageName.equals(renamed)) { 8169 // Callers into this function may have already taken 8170 // care of renaming the package; only do it here if 8171 // it is not already done. 8172 pkg.setPackageName(renamed); 8173 } 8174 8175 } else { 8176 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8177 if ((origPackage = mSettings.peekPackageLPr( 8178 pkg.mOriginalPackages.get(i))) != null) { 8179 // We do have the package already installed under its 8180 // original name... should we use it? 8181 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8182 // New package is not compatible with original. 8183 origPackage = null; 8184 continue; 8185 } else if (origPackage.sharedUser != null) { 8186 // Make sure uid is compatible between packages. 8187 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8188 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8189 + " to " + pkg.packageName + ": old uid " 8190 + origPackage.sharedUser.name 8191 + " differs from " + pkg.mSharedUserId); 8192 origPackage = null; 8193 continue; 8194 } 8195 // TODO: Add case when shared user id is added [b/28144775] 8196 } else { 8197 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8198 + pkg.packageName + " to old name " + origPackage.name); 8199 } 8200 break; 8201 } 8202 } 8203 } 8204 } 8205 8206 if (mTransferedPackages.contains(pkg.packageName)) { 8207 Slog.w(TAG, "Package " + pkg.packageName 8208 + " was transferred to another, but its .apk remains"); 8209 } 8210 8211 // See comments in nonMutatedPs declaration 8212 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8213 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8214 if (foundPs != null) { 8215 nonMutatedPs = new PackageSetting(foundPs); 8216 } 8217 } 8218 8219 // Just create the setting, don't add it yet. For already existing packages 8220 // the PkgSetting exists already and doesn't have to be created. 8221 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8222 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8223 pkg.applicationInfo.primaryCpuAbi, 8224 pkg.applicationInfo.secondaryCpuAbi, 8225 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8226 user, false); 8227 if (pkgSetting == null) { 8228 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8229 "Creating application package " + pkg.packageName + " failed"); 8230 } 8231 8232 if (pkgSetting.origPackage != null) { 8233 // If we are first transitioning from an original package, 8234 // fix up the new package's name now. We need to do this after 8235 // looking up the package under its new name, so getPackageLP 8236 // can take care of fiddling things correctly. 8237 pkg.setPackageName(origPackage.name); 8238 8239 // File a report about this. 8240 String msg = "New package " + pkgSetting.realName 8241 + " renamed to replace old package " + pkgSetting.name; 8242 reportSettingsProblem(Log.WARN, msg); 8243 8244 // Make a note of it. 8245 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8246 mTransferedPackages.add(origPackage.name); 8247 } 8248 8249 // No longer need to retain this. 8250 pkgSetting.origPackage = null; 8251 } 8252 8253 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8254 // Make a note of it. 8255 mTransferedPackages.add(pkg.packageName); 8256 } 8257 8258 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8259 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8260 } 8261 8262 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8263 // Check all shared libraries and map to their actual file path. 8264 // We only do this here for apps not on a system dir, because those 8265 // are the only ones that can fail an install due to this. We 8266 // will take care of the system apps by updating all of their 8267 // library paths after the scan is done. 8268 updateSharedLibrariesLPw(pkg, null); 8269 } 8270 8271 if (mFoundPolicyFile) { 8272 SELinuxMMAC.assignSeinfoValue(pkg); 8273 } 8274 8275 pkg.applicationInfo.uid = pkgSetting.appId; 8276 pkg.mExtras = pkgSetting; 8277 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8278 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8279 // We just determined the app is signed correctly, so bring 8280 // over the latest parsed certs. 8281 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8282 } else { 8283 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8284 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8285 "Package " + pkg.packageName + " upgrade keys do not match the " 8286 + "previously installed version"); 8287 } else { 8288 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8289 String msg = "System package " + pkg.packageName 8290 + " signature changed; retaining data."; 8291 reportSettingsProblem(Log.WARN, msg); 8292 } 8293 } 8294 } else { 8295 try { 8296 verifySignaturesLP(pkgSetting, pkg); 8297 // We just determined the app is signed correctly, so bring 8298 // over the latest parsed certs. 8299 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8300 } catch (PackageManagerException e) { 8301 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8302 throw e; 8303 } 8304 // The signature has changed, but this package is in the system 8305 // image... let's recover! 8306 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8307 // However... if this package is part of a shared user, but it 8308 // doesn't match the signature of the shared user, let's fail. 8309 // What this means is that you can't change the signatures 8310 // associated with an overall shared user, which doesn't seem all 8311 // that unreasonable. 8312 if (pkgSetting.sharedUser != null) { 8313 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8314 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8315 throw new PackageManagerException( 8316 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8317 "Signature mismatch for shared user: " 8318 + pkgSetting.sharedUser); 8319 } 8320 } 8321 // File a report about this. 8322 String msg = "System package " + pkg.packageName 8323 + " signature changed; retaining data."; 8324 reportSettingsProblem(Log.WARN, msg); 8325 } 8326 } 8327 // Verify that this new package doesn't have any content providers 8328 // that conflict with existing packages. Only do this if the 8329 // package isn't already installed, since we don't want to break 8330 // things that are installed. 8331 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8332 final int N = pkg.providers.size(); 8333 int i; 8334 for (i=0; i<N; i++) { 8335 PackageParser.Provider p = pkg.providers.get(i); 8336 if (p.info.authority != null) { 8337 String names[] = p.info.authority.split(";"); 8338 for (int j = 0; j < names.length; j++) { 8339 if (mProvidersByAuthority.containsKey(names[j])) { 8340 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8341 final String otherPackageName = 8342 ((other != null && other.getComponentName() != null) ? 8343 other.getComponentName().getPackageName() : "?"); 8344 throw new PackageManagerException( 8345 INSTALL_FAILED_CONFLICTING_PROVIDER, 8346 "Can't install because provider name " + names[j] 8347 + " (in package " + pkg.applicationInfo.packageName 8348 + ") is already used by " + otherPackageName); 8349 } 8350 } 8351 } 8352 } 8353 } 8354 8355 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8356 // This package wants to adopt ownership of permissions from 8357 // another package. 8358 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8359 final String origName = pkg.mAdoptPermissions.get(i); 8360 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8361 if (orig != null) { 8362 if (verifyPackageUpdateLPr(orig, pkg)) { 8363 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8364 + pkg.packageName); 8365 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8366 } 8367 } 8368 } 8369 } 8370 } 8371 8372 final String pkgName = pkg.packageName; 8373 8374 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8375 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8376 pkg.applicationInfo.processName = fixProcessName( 8377 pkg.applicationInfo.packageName, 8378 pkg.applicationInfo.processName, 8379 pkg.applicationInfo.uid); 8380 8381 if (pkg != mPlatformPackage) { 8382 // Get all of our default paths setup 8383 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8384 } 8385 8386 final String path = scanFile.getPath(); 8387 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8388 8389 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8390 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8391 8392 // Some system apps still use directory structure for native libraries 8393 // in which case we might end up not detecting abi solely based on apk 8394 // structure. Try to detect abi based on directory structure. 8395 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8396 pkg.applicationInfo.primaryCpuAbi == null) { 8397 setBundledAppAbisAndRoots(pkg, pkgSetting); 8398 setNativeLibraryPaths(pkg); 8399 } 8400 8401 } else { 8402 if ((scanFlags & SCAN_MOVE) != 0) { 8403 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8404 // but we already have this packages package info in the PackageSetting. We just 8405 // use that and derive the native library path based on the new codepath. 8406 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8407 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8408 } 8409 8410 // Set native library paths again. For moves, the path will be updated based on the 8411 // ABIs we've determined above. For non-moves, the path will be updated based on the 8412 // ABIs we determined during compilation, but the path will depend on the final 8413 // package path (after the rename away from the stage path). 8414 setNativeLibraryPaths(pkg); 8415 } 8416 8417 // This is a special case for the "system" package, where the ABI is 8418 // dictated by the zygote configuration (and init.rc). We should keep track 8419 // of this ABI so that we can deal with "normal" applications that run under 8420 // the same UID correctly. 8421 if (mPlatformPackage == pkg) { 8422 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8423 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8424 } 8425 8426 // If there's a mismatch between the abi-override in the package setting 8427 // and the abiOverride specified for the install. Warn about this because we 8428 // would've already compiled the app without taking the package setting into 8429 // account. 8430 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8431 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8432 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8433 " for package " + pkg.packageName); 8434 } 8435 } 8436 8437 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8438 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8439 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8440 8441 // Copy the derived override back to the parsed package, so that we can 8442 // update the package settings accordingly. 8443 pkg.cpuAbiOverride = cpuAbiOverride; 8444 8445 if (DEBUG_ABI_SELECTION) { 8446 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8447 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8448 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8449 } 8450 8451 // Push the derived path down into PackageSettings so we know what to 8452 // clean up at uninstall time. 8453 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8454 8455 if (DEBUG_ABI_SELECTION) { 8456 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8457 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8458 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8459 } 8460 8461 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8462 // We don't do this here during boot because we can do it all 8463 // at once after scanning all existing packages. 8464 // 8465 // We also do this *before* we perform dexopt on this package, so that 8466 // we can avoid redundant dexopts, and also to make sure we've got the 8467 // code and package path correct. 8468 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8469 pkg, true /* boot complete */); 8470 } 8471 8472 if (mFactoryTest && pkg.requestedPermissions.contains( 8473 android.Manifest.permission.FACTORY_TEST)) { 8474 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8475 } 8476 8477 if (isSystemApp(pkg)) { 8478 pkgSetting.isOrphaned = true; 8479 } 8480 8481 ArrayList<PackageParser.Package> clientLibPkgs = null; 8482 8483 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8484 if (nonMutatedPs != null) { 8485 synchronized (mPackages) { 8486 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8487 } 8488 } 8489 return pkg; 8490 } 8491 8492 // Only privileged apps and updated privileged apps can add child packages. 8493 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8494 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8495 throw new PackageManagerException("Only privileged apps and updated " 8496 + "privileged apps can add child packages. Ignoring package " 8497 + pkg.packageName); 8498 } 8499 final int childCount = pkg.childPackages.size(); 8500 for (int i = 0; i < childCount; i++) { 8501 PackageParser.Package childPkg = pkg.childPackages.get(i); 8502 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8503 childPkg.packageName)) { 8504 throw new PackageManagerException("Cannot override a child package of " 8505 + "another disabled system app. Ignoring package " + pkg.packageName); 8506 } 8507 } 8508 } 8509 8510 // writer 8511 synchronized (mPackages) { 8512 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8513 // Only system apps can add new shared libraries. 8514 if (pkg.libraryNames != null) { 8515 for (int i=0; i<pkg.libraryNames.size(); i++) { 8516 String name = pkg.libraryNames.get(i); 8517 boolean allowed = false; 8518 if (pkg.isUpdatedSystemApp()) { 8519 // New library entries can only be added through the 8520 // system image. This is important to get rid of a lot 8521 // of nasty edge cases: for example if we allowed a non- 8522 // system update of the app to add a library, then uninstalling 8523 // the update would make the library go away, and assumptions 8524 // we made such as through app install filtering would now 8525 // have allowed apps on the device which aren't compatible 8526 // with it. Better to just have the restriction here, be 8527 // conservative, and create many fewer cases that can negatively 8528 // impact the user experience. 8529 final PackageSetting sysPs = mSettings 8530 .getDisabledSystemPkgLPr(pkg.packageName); 8531 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8532 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8533 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8534 allowed = true; 8535 break; 8536 } 8537 } 8538 } 8539 } else { 8540 allowed = true; 8541 } 8542 if (allowed) { 8543 if (!mSharedLibraries.containsKey(name)) { 8544 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8545 } else if (!name.equals(pkg.packageName)) { 8546 Slog.w(TAG, "Package " + pkg.packageName + " library " 8547 + name + " already exists; skipping"); 8548 } 8549 } else { 8550 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8551 + name + " that is not declared on system image; skipping"); 8552 } 8553 } 8554 if ((scanFlags & SCAN_BOOTING) == 0) { 8555 // If we are not booting, we need to update any applications 8556 // that are clients of our shared library. If we are booting, 8557 // this will all be done once the scan is complete. 8558 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8559 } 8560 } 8561 } 8562 } 8563 8564 if ((scanFlags & SCAN_BOOTING) != 0) { 8565 // No apps can run during boot scan, so they don't need to be frozen 8566 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8567 // Caller asked to not kill app, so it's probably not frozen 8568 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8569 // Caller asked us to ignore frozen check for some reason; they 8570 // probably didn't know the package name 8571 } else { 8572 // We're doing major surgery on this package, so it better be frozen 8573 // right now to keep it from launching 8574 checkPackageFrozen(pkgName); 8575 } 8576 8577 // Also need to kill any apps that are dependent on the library. 8578 if (clientLibPkgs != null) { 8579 for (int i=0; i<clientLibPkgs.size(); i++) { 8580 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8581 killApplication(clientPkg.applicationInfo.packageName, 8582 clientPkg.applicationInfo.uid, "update lib"); 8583 } 8584 } 8585 8586 // Make sure we're not adding any bogus keyset info 8587 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8588 ksms.assertScannedPackageValid(pkg); 8589 8590 // writer 8591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8592 8593 boolean createIdmapFailed = false; 8594 synchronized (mPackages) { 8595 // We don't expect installation to fail beyond this point 8596 8597 if (pkgSetting.pkg != null) { 8598 // Note that |user| might be null during the initial boot scan. If a codePath 8599 // for an app has changed during a boot scan, it's due to an app update that's 8600 // part of the system partition and marker changes must be applied to all users. 8601 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8602 (user != null) ? user : UserHandle.ALL); 8603 } 8604 8605 // Add the new setting to mSettings 8606 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8607 // Add the new setting to mPackages 8608 mPackages.put(pkg.applicationInfo.packageName, pkg); 8609 // Make sure we don't accidentally delete its data. 8610 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8611 while (iter.hasNext()) { 8612 PackageCleanItem item = iter.next(); 8613 if (pkgName.equals(item.packageName)) { 8614 iter.remove(); 8615 } 8616 } 8617 8618 // Take care of first install / last update times. 8619 if (currentTime != 0) { 8620 if (pkgSetting.firstInstallTime == 0) { 8621 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8622 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8623 pkgSetting.lastUpdateTime = currentTime; 8624 } 8625 } else if (pkgSetting.firstInstallTime == 0) { 8626 // We need *something*. Take time time stamp of the file. 8627 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8628 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8629 if (scanFileTime != pkgSetting.timeStamp) { 8630 // A package on the system image has changed; consider this 8631 // to be an update. 8632 pkgSetting.lastUpdateTime = scanFileTime; 8633 } 8634 } 8635 8636 // Add the package's KeySets to the global KeySetManagerService 8637 ksms.addScannedPackageLPw(pkg); 8638 8639 int N = pkg.providers.size(); 8640 StringBuilder r = null; 8641 int i; 8642 for (i=0; i<N; i++) { 8643 PackageParser.Provider p = pkg.providers.get(i); 8644 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8645 p.info.processName, pkg.applicationInfo.uid); 8646 mProviders.addProvider(p); 8647 p.syncable = p.info.isSyncable; 8648 if (p.info.authority != null) { 8649 String names[] = p.info.authority.split(";"); 8650 p.info.authority = null; 8651 for (int j = 0; j < names.length; j++) { 8652 if (j == 1 && p.syncable) { 8653 // We only want the first authority for a provider to possibly be 8654 // syncable, so if we already added this provider using a different 8655 // authority clear the syncable flag. We copy the provider before 8656 // changing it because the mProviders object contains a reference 8657 // to a provider that we don't want to change. 8658 // Only do this for the second authority since the resulting provider 8659 // object can be the same for all future authorities for this provider. 8660 p = new PackageParser.Provider(p); 8661 p.syncable = false; 8662 } 8663 if (!mProvidersByAuthority.containsKey(names[j])) { 8664 mProvidersByAuthority.put(names[j], p); 8665 if (p.info.authority == null) { 8666 p.info.authority = names[j]; 8667 } else { 8668 p.info.authority = p.info.authority + ";" + names[j]; 8669 } 8670 if (DEBUG_PACKAGE_SCANNING) { 8671 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8672 Log.d(TAG, "Registered content provider: " + names[j] 8673 + ", className = " + p.info.name + ", isSyncable = " 8674 + p.info.isSyncable); 8675 } 8676 } else { 8677 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8678 Slog.w(TAG, "Skipping provider name " + names[j] + 8679 " (in package " + pkg.applicationInfo.packageName + 8680 "): name already used by " 8681 + ((other != null && other.getComponentName() != null) 8682 ? other.getComponentName().getPackageName() : "?")); 8683 } 8684 } 8685 } 8686 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8687 if (r == null) { 8688 r = new StringBuilder(256); 8689 } else { 8690 r.append(' '); 8691 } 8692 r.append(p.info.name); 8693 } 8694 } 8695 if (r != null) { 8696 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8697 } 8698 8699 N = pkg.services.size(); 8700 r = null; 8701 for (i=0; i<N; i++) { 8702 PackageParser.Service s = pkg.services.get(i); 8703 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8704 s.info.processName, pkg.applicationInfo.uid); 8705 mServices.addService(s); 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(s.info.name); 8713 } 8714 } 8715 if (r != null) { 8716 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8717 } 8718 8719 N = pkg.receivers.size(); 8720 r = null; 8721 for (i=0; i<N; i++) { 8722 PackageParser.Activity a = pkg.receivers.get(i); 8723 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8724 a.info.processName, pkg.applicationInfo.uid); 8725 mReceivers.addActivity(a, "receiver"); 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(a.info.name); 8733 } 8734 } 8735 if (r != null) { 8736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8737 } 8738 8739 N = pkg.activities.size(); 8740 r = null; 8741 for (i=0; i<N; i++) { 8742 PackageParser.Activity a = pkg.activities.get(i); 8743 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8744 a.info.processName, pkg.applicationInfo.uid); 8745 mActivities.addActivity(a, "activity"); 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, " Activities: " + r); 8757 } 8758 8759 N = pkg.permissionGroups.size(); 8760 r = null; 8761 for (i=0; i<N; i++) { 8762 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8763 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8764 final String curPackageName = cur == null ? null : cur.info.packageName; 8765 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8766 if (cur == null || isPackageUpdate) { 8767 mPermissionGroups.put(pg.info.name, pg); 8768 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8769 if (r == null) { 8770 r = new StringBuilder(256); 8771 } else { 8772 r.append(' '); 8773 } 8774 if (isPackageUpdate) { 8775 r.append("UPD:"); 8776 } 8777 r.append(pg.info.name); 8778 } 8779 } else { 8780 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8781 + pg.info.packageName + " ignored: original from " 8782 + cur.info.packageName); 8783 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8784 if (r == null) { 8785 r = new StringBuilder(256); 8786 } else { 8787 r.append(' '); 8788 } 8789 r.append("DUP:"); 8790 r.append(pg.info.name); 8791 } 8792 } 8793 } 8794 if (r != null) { 8795 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8796 } 8797 8798 N = pkg.permissions.size(); 8799 r = null; 8800 for (i=0; i<N; i++) { 8801 PackageParser.Permission p = pkg.permissions.get(i); 8802 8803 // Assume by default that we did not install this permission into the system. 8804 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8805 8806 // Now that permission groups have a special meaning, we ignore permission 8807 // groups for legacy apps to prevent unexpected behavior. In particular, 8808 // permissions for one app being granted to someone just becase they happen 8809 // to be in a group defined by another app (before this had no implications). 8810 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8811 p.group = mPermissionGroups.get(p.info.group); 8812 // Warn for a permission in an unknown group. 8813 if (p.info.group != null && p.group == null) { 8814 Slog.w(TAG, "Permission " + p.info.name + " from package " 8815 + p.info.packageName + " in an unknown group " + p.info.group); 8816 } 8817 } 8818 8819 ArrayMap<String, BasePermission> permissionMap = 8820 p.tree ? mSettings.mPermissionTrees 8821 : mSettings.mPermissions; 8822 BasePermission bp = permissionMap.get(p.info.name); 8823 8824 // Allow system apps to redefine non-system permissions 8825 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8826 final boolean currentOwnerIsSystem = (bp.perm != null 8827 && isSystemApp(bp.perm.owner)); 8828 if (isSystemApp(p.owner)) { 8829 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8830 // It's a built-in permission and no owner, take ownership now 8831 bp.packageSetting = pkgSetting; 8832 bp.perm = p; 8833 bp.uid = pkg.applicationInfo.uid; 8834 bp.sourcePackage = p.info.packageName; 8835 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8836 } else if (!currentOwnerIsSystem) { 8837 String msg = "New decl " + p.owner + " of permission " 8838 + p.info.name + " is system; overriding " + bp.sourcePackage; 8839 reportSettingsProblem(Log.WARN, msg); 8840 bp = null; 8841 } 8842 } 8843 } 8844 8845 if (bp == null) { 8846 bp = new BasePermission(p.info.name, p.info.packageName, 8847 BasePermission.TYPE_NORMAL); 8848 permissionMap.put(p.info.name, bp); 8849 } 8850 8851 if (bp.perm == null) { 8852 if (bp.sourcePackage == null 8853 || bp.sourcePackage.equals(p.info.packageName)) { 8854 BasePermission tree = findPermissionTreeLP(p.info.name); 8855 if (tree == null 8856 || tree.sourcePackage.equals(p.info.packageName)) { 8857 bp.packageSetting = pkgSetting; 8858 bp.perm = p; 8859 bp.uid = pkg.applicationInfo.uid; 8860 bp.sourcePackage = p.info.packageName; 8861 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8862 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8863 if (r == null) { 8864 r = new StringBuilder(256); 8865 } else { 8866 r.append(' '); 8867 } 8868 r.append(p.info.name); 8869 } 8870 } else { 8871 Slog.w(TAG, "Permission " + p.info.name + " from package " 8872 + p.info.packageName + " ignored: base tree " 8873 + tree.name + " is from package " 8874 + tree.sourcePackage); 8875 } 8876 } else { 8877 Slog.w(TAG, "Permission " + p.info.name + " from package " 8878 + p.info.packageName + " ignored: original from " 8879 + bp.sourcePackage); 8880 } 8881 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8882 if (r == null) { 8883 r = new StringBuilder(256); 8884 } else { 8885 r.append(' '); 8886 } 8887 r.append("DUP:"); 8888 r.append(p.info.name); 8889 } 8890 if (bp.perm == p) { 8891 bp.protectionLevel = p.info.protectionLevel; 8892 } 8893 } 8894 8895 if (r != null) { 8896 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8897 } 8898 8899 N = pkg.instrumentation.size(); 8900 r = null; 8901 for (i=0; i<N; i++) { 8902 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8903 a.info.packageName = pkg.applicationInfo.packageName; 8904 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8905 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8906 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8907 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8908 a.info.dataDir = pkg.applicationInfo.dataDir; 8909 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8910 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8911 8912 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8913 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8914 mInstrumentation.put(a.getComponentName(), a); 8915 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8916 if (r == null) { 8917 r = new StringBuilder(256); 8918 } else { 8919 r.append(' '); 8920 } 8921 r.append(a.info.name); 8922 } 8923 } 8924 if (r != null) { 8925 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8926 } 8927 8928 if (pkg.protectedBroadcasts != null) { 8929 N = pkg.protectedBroadcasts.size(); 8930 for (i=0; i<N; i++) { 8931 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8932 } 8933 } 8934 8935 pkgSetting.setTimeStamp(scanFileTime); 8936 8937 // Create idmap files for pairs of (packages, overlay packages). 8938 // Note: "android", ie framework-res.apk, is handled by native layers. 8939 if (pkg.mOverlayTarget != null) { 8940 // This is an overlay package. 8941 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8942 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8943 mOverlays.put(pkg.mOverlayTarget, 8944 new ArrayMap<String, PackageParser.Package>()); 8945 } 8946 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8947 map.put(pkg.packageName, pkg); 8948 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8949 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8950 createIdmapFailed = true; 8951 } 8952 } 8953 } else if (mOverlays.containsKey(pkg.packageName) && 8954 !pkg.packageName.equals("android")) { 8955 // This is a regular package, with one or more known overlay packages. 8956 createIdmapsForPackageLI(pkg); 8957 } 8958 } 8959 8960 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8961 8962 if (createIdmapFailed) { 8963 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8964 "scanPackageLI failed to createIdmap"); 8965 } 8966 return pkg; 8967 } 8968 8969 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8970 PackageParser.Package update, UserHandle user) { 8971 if (existing.applicationInfo == null || update.applicationInfo == null) { 8972 // This isn't due to an app installation. 8973 return; 8974 } 8975 8976 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8977 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8978 8979 // The codePath hasn't changed, so there's nothing for us to do. 8980 if (Objects.equals(oldCodePath, newCodePath)) { 8981 return; 8982 } 8983 8984 File canonicalNewCodePath; 8985 try { 8986 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8987 } catch (IOException e) { 8988 Slog.w(TAG, "Failed to get canonical path.", e); 8989 return; 8990 } 8991 8992 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8993 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8994 // that the last component of the path (i.e, the name) doesn't need canonicalization 8995 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8996 // but may change in the future. Hopefully this function won't exist at that point. 8997 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8998 oldCodePath.getName()); 8999 9000 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9001 // with "@". 9002 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9003 if (!oldMarkerPrefix.endsWith("@")) { 9004 oldMarkerPrefix += "@"; 9005 } 9006 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9007 if (!newMarkerPrefix.endsWith("@")) { 9008 newMarkerPrefix += "@"; 9009 } 9010 9011 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9012 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9013 for (String updatedPath : updatedPaths) { 9014 String updatedPathName = new File(updatedPath).getName(); 9015 markerSuffixes.add(updatedPathName.replace('/', '@')); 9016 } 9017 9018 for (int userId : resolveUserIds(user.getIdentifier())) { 9019 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9020 9021 for (String markerSuffix : markerSuffixes) { 9022 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9023 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9024 if (oldForeignUseMark.exists()) { 9025 try { 9026 Os.rename(oldForeignUseMark.getAbsolutePath(), 9027 newForeignUseMark.getAbsolutePath()); 9028 } catch (ErrnoException e) { 9029 Slog.w(TAG, "Failed to rename foreign use marker", e); 9030 oldForeignUseMark.delete(); 9031 } 9032 } 9033 } 9034 } 9035 } 9036 9037 /** 9038 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9039 * is derived purely on the basis of the contents of {@code scanFile} and 9040 * {@code cpuAbiOverride}. 9041 * 9042 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9043 */ 9044 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9045 String cpuAbiOverride, boolean extractLibs) 9046 throws PackageManagerException { 9047 // TODO: We can probably be smarter about this stuff. For installed apps, 9048 // we can calculate this information at install time once and for all. For 9049 // system apps, we can probably assume that this information doesn't change 9050 // after the first boot scan. As things stand, we do lots of unnecessary work. 9051 9052 // Give ourselves some initial paths; we'll come back for another 9053 // pass once we've determined ABI below. 9054 setNativeLibraryPaths(pkg); 9055 9056 // We would never need to extract libs for forward-locked and external packages, 9057 // since the container service will do it for us. We shouldn't attempt to 9058 // extract libs from system app when it was not updated. 9059 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9060 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9061 extractLibs = false; 9062 } 9063 9064 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9065 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9066 9067 NativeLibraryHelper.Handle handle = null; 9068 try { 9069 handle = NativeLibraryHelper.Handle.create(pkg); 9070 // TODO(multiArch): This can be null for apps that didn't go through the 9071 // usual installation process. We can calculate it again, like we 9072 // do during install time. 9073 // 9074 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9075 // unnecessary. 9076 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9077 9078 // Null out the abis so that they can be recalculated. 9079 pkg.applicationInfo.primaryCpuAbi = null; 9080 pkg.applicationInfo.secondaryCpuAbi = null; 9081 if (isMultiArch(pkg.applicationInfo)) { 9082 // Warn if we've set an abiOverride for multi-lib packages.. 9083 // By definition, we need to copy both 32 and 64 bit libraries for 9084 // such packages. 9085 if (pkg.cpuAbiOverride != null 9086 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9087 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9088 } 9089 9090 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9091 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9092 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9093 if (extractLibs) { 9094 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9095 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9096 useIsaSpecificSubdirs); 9097 } else { 9098 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9099 } 9100 } 9101 9102 maybeThrowExceptionForMultiArchCopy( 9103 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9104 9105 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9106 if (extractLibs) { 9107 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9108 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9109 useIsaSpecificSubdirs); 9110 } else { 9111 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9112 } 9113 } 9114 9115 maybeThrowExceptionForMultiArchCopy( 9116 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9117 9118 if (abi64 >= 0) { 9119 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9120 } 9121 9122 if (abi32 >= 0) { 9123 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9124 if (abi64 >= 0) { 9125 if (pkg.use32bitAbi) { 9126 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9127 pkg.applicationInfo.primaryCpuAbi = abi; 9128 } else { 9129 pkg.applicationInfo.secondaryCpuAbi = abi; 9130 } 9131 } else { 9132 pkg.applicationInfo.primaryCpuAbi = abi; 9133 } 9134 } 9135 9136 } else { 9137 String[] abiList = (cpuAbiOverride != null) ? 9138 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9139 9140 // Enable gross and lame hacks for apps that are built with old 9141 // SDK tools. We must scan their APKs for renderscript bitcode and 9142 // not launch them if it's present. Don't bother checking on devices 9143 // that don't have 64 bit support. 9144 boolean needsRenderScriptOverride = false; 9145 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9146 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9147 abiList = Build.SUPPORTED_32_BIT_ABIS; 9148 needsRenderScriptOverride = true; 9149 } 9150 9151 final int copyRet; 9152 if (extractLibs) { 9153 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9154 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9155 } else { 9156 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9157 } 9158 9159 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9160 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9161 "Error unpackaging native libs for app, errorCode=" + copyRet); 9162 } 9163 9164 if (copyRet >= 0) { 9165 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9166 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9167 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9168 } else if (needsRenderScriptOverride) { 9169 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9170 } 9171 } 9172 } catch (IOException ioe) { 9173 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9174 } finally { 9175 IoUtils.closeQuietly(handle); 9176 } 9177 9178 // Now that we've calculated the ABIs and determined if it's an internal app, 9179 // we will go ahead and populate the nativeLibraryPath. 9180 setNativeLibraryPaths(pkg); 9181 } 9182 9183 /** 9184 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9185 * i.e, so that all packages can be run inside a single process if required. 9186 * 9187 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9188 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9189 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9190 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9191 * updating a package that belongs to a shared user. 9192 * 9193 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9194 * adds unnecessary complexity. 9195 */ 9196 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9197 PackageParser.Package scannedPackage, boolean bootComplete) { 9198 String requiredInstructionSet = null; 9199 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9200 requiredInstructionSet = VMRuntime.getInstructionSet( 9201 scannedPackage.applicationInfo.primaryCpuAbi); 9202 } 9203 9204 PackageSetting requirer = null; 9205 for (PackageSetting ps : packagesForUser) { 9206 // If packagesForUser contains scannedPackage, we skip it. This will happen 9207 // when scannedPackage is an update of an existing package. Without this check, 9208 // we will never be able to change the ABI of any package belonging to a shared 9209 // user, even if it's compatible with other packages. 9210 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9211 if (ps.primaryCpuAbiString == null) { 9212 continue; 9213 } 9214 9215 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9216 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9217 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9218 // this but there's not much we can do. 9219 String errorMessage = "Instruction set mismatch, " 9220 + ((requirer == null) ? "[caller]" : requirer) 9221 + " requires " + requiredInstructionSet + " whereas " + ps 9222 + " requires " + instructionSet; 9223 Slog.w(TAG, errorMessage); 9224 } 9225 9226 if (requiredInstructionSet == null) { 9227 requiredInstructionSet = instructionSet; 9228 requirer = ps; 9229 } 9230 } 9231 } 9232 9233 if (requiredInstructionSet != null) { 9234 String adjustedAbi; 9235 if (requirer != null) { 9236 // requirer != null implies that either scannedPackage was null or that scannedPackage 9237 // did not require an ABI, in which case we have to adjust scannedPackage to match 9238 // the ABI of the set (which is the same as requirer's ABI) 9239 adjustedAbi = requirer.primaryCpuAbiString; 9240 if (scannedPackage != null) { 9241 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9242 } 9243 } else { 9244 // requirer == null implies that we're updating all ABIs in the set to 9245 // match scannedPackage. 9246 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9247 } 9248 9249 for (PackageSetting ps : packagesForUser) { 9250 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9251 if (ps.primaryCpuAbiString != null) { 9252 continue; 9253 } 9254 9255 ps.primaryCpuAbiString = adjustedAbi; 9256 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9257 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9258 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9259 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9260 + " (requirer=" 9261 + (requirer == null ? "null" : requirer.pkg.packageName) 9262 + ", scannedPackage=" 9263 + (scannedPackage != null ? scannedPackage.packageName : "null") 9264 + ")"); 9265 try { 9266 mInstaller.rmdex(ps.codePathString, 9267 getDexCodeInstructionSet(getPreferredInstructionSet())); 9268 } catch (InstallerException ignored) { 9269 } 9270 } 9271 } 9272 } 9273 } 9274 } 9275 9276 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9277 synchronized (mPackages) { 9278 mResolverReplaced = true; 9279 // Set up information for custom user intent resolution activity. 9280 mResolveActivity.applicationInfo = pkg.applicationInfo; 9281 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9282 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9283 mResolveActivity.processName = pkg.applicationInfo.packageName; 9284 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9285 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9286 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9287 mResolveActivity.theme = 0; 9288 mResolveActivity.exported = true; 9289 mResolveActivity.enabled = true; 9290 mResolveInfo.activityInfo = mResolveActivity; 9291 mResolveInfo.priority = 0; 9292 mResolveInfo.preferredOrder = 0; 9293 mResolveInfo.match = 0; 9294 mResolveComponentName = mCustomResolverComponentName; 9295 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9296 mResolveComponentName); 9297 } 9298 } 9299 9300 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9301 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9302 9303 // Set up information for ephemeral installer activity 9304 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9305 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9306 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9307 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9308 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9309 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9310 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9311 mEphemeralInstallerActivity.theme = 0; 9312 mEphemeralInstallerActivity.exported = true; 9313 mEphemeralInstallerActivity.enabled = true; 9314 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9315 mEphemeralInstallerInfo.priority = 0; 9316 mEphemeralInstallerInfo.preferredOrder = 1; 9317 mEphemeralInstallerInfo.isDefault = true; 9318 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9319 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9320 9321 if (DEBUG_EPHEMERAL) { 9322 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9323 } 9324 } 9325 9326 private static String calculateBundledApkRoot(final String codePathString) { 9327 final File codePath = new File(codePathString); 9328 final File codeRoot; 9329 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9330 codeRoot = Environment.getRootDirectory(); 9331 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9332 codeRoot = Environment.getOemDirectory(); 9333 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9334 codeRoot = Environment.getVendorDirectory(); 9335 } else { 9336 // Unrecognized code path; take its top real segment as the apk root: 9337 // e.g. /something/app/blah.apk => /something 9338 try { 9339 File f = codePath.getCanonicalFile(); 9340 File parent = f.getParentFile(); // non-null because codePath is a file 9341 File tmp; 9342 while ((tmp = parent.getParentFile()) != null) { 9343 f = parent; 9344 parent = tmp; 9345 } 9346 codeRoot = f; 9347 Slog.w(TAG, "Unrecognized code path " 9348 + codePath + " - using " + codeRoot); 9349 } catch (IOException e) { 9350 // Can't canonicalize the code path -- shenanigans? 9351 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9352 return Environment.getRootDirectory().getPath(); 9353 } 9354 } 9355 return codeRoot.getPath(); 9356 } 9357 9358 /** 9359 * Derive and set the location of native libraries for the given package, 9360 * which varies depending on where and how the package was installed. 9361 */ 9362 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9363 final ApplicationInfo info = pkg.applicationInfo; 9364 final String codePath = pkg.codePath; 9365 final File codeFile = new File(codePath); 9366 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9367 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9368 9369 info.nativeLibraryRootDir = null; 9370 info.nativeLibraryRootRequiresIsa = false; 9371 info.nativeLibraryDir = null; 9372 info.secondaryNativeLibraryDir = null; 9373 9374 if (isApkFile(codeFile)) { 9375 // Monolithic install 9376 if (bundledApp) { 9377 // If "/system/lib64/apkname" exists, assume that is the per-package 9378 // native library directory to use; otherwise use "/system/lib/apkname". 9379 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9380 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9381 getPrimaryInstructionSet(info)); 9382 9383 // This is a bundled system app so choose the path based on the ABI. 9384 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9385 // is just the default path. 9386 final String apkName = deriveCodePathName(codePath); 9387 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9388 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9389 apkName).getAbsolutePath(); 9390 9391 if (info.secondaryCpuAbi != null) { 9392 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9393 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9394 secondaryLibDir, apkName).getAbsolutePath(); 9395 } 9396 } else if (asecApp) { 9397 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9398 .getAbsolutePath(); 9399 } else { 9400 final String apkName = deriveCodePathName(codePath); 9401 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9402 .getAbsolutePath(); 9403 } 9404 9405 info.nativeLibraryRootRequiresIsa = false; 9406 info.nativeLibraryDir = info.nativeLibraryRootDir; 9407 } else { 9408 // Cluster install 9409 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9410 info.nativeLibraryRootRequiresIsa = true; 9411 9412 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9413 getPrimaryInstructionSet(info)).getAbsolutePath(); 9414 9415 if (info.secondaryCpuAbi != null) { 9416 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9417 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9418 } 9419 } 9420 } 9421 9422 /** 9423 * Calculate the abis and roots for a bundled app. These can uniquely 9424 * be determined from the contents of the system partition, i.e whether 9425 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9426 * of this information, and instead assume that the system was built 9427 * sensibly. 9428 */ 9429 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9430 PackageSetting pkgSetting) { 9431 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9432 9433 // If "/system/lib64/apkname" exists, assume that is the per-package 9434 // native library directory to use; otherwise use "/system/lib/apkname". 9435 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9436 setBundledAppAbi(pkg, apkRoot, apkName); 9437 // pkgSetting might be null during rescan following uninstall of updates 9438 // to a bundled app, so accommodate that possibility. The settings in 9439 // that case will be established later from the parsed package. 9440 // 9441 // If the settings aren't null, sync them up with what we've just derived. 9442 // note that apkRoot isn't stored in the package settings. 9443 if (pkgSetting != null) { 9444 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9445 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9446 } 9447 } 9448 9449 /** 9450 * Deduces the ABI of a bundled app and sets the relevant fields on the 9451 * parsed pkg object. 9452 * 9453 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9454 * under which system libraries are installed. 9455 * @param apkName the name of the installed package. 9456 */ 9457 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9458 final File codeFile = new File(pkg.codePath); 9459 9460 final boolean has64BitLibs; 9461 final boolean has32BitLibs; 9462 if (isApkFile(codeFile)) { 9463 // Monolithic install 9464 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9465 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9466 } else { 9467 // Cluster install 9468 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9469 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9470 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9471 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9472 has64BitLibs = (new File(rootDir, isa)).exists(); 9473 } else { 9474 has64BitLibs = false; 9475 } 9476 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9477 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9478 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9479 has32BitLibs = (new File(rootDir, isa)).exists(); 9480 } else { 9481 has32BitLibs = false; 9482 } 9483 } 9484 9485 if (has64BitLibs && !has32BitLibs) { 9486 // The package has 64 bit libs, but not 32 bit libs. Its primary 9487 // ABI should be 64 bit. We can safely assume here that the bundled 9488 // native libraries correspond to the most preferred ABI in the list. 9489 9490 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9491 pkg.applicationInfo.secondaryCpuAbi = null; 9492 } else if (has32BitLibs && !has64BitLibs) { 9493 // The package has 32 bit libs but not 64 bit libs. Its primary 9494 // ABI should be 32 bit. 9495 9496 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9497 pkg.applicationInfo.secondaryCpuAbi = null; 9498 } else if (has32BitLibs && has64BitLibs) { 9499 // The application has both 64 and 32 bit bundled libraries. We check 9500 // here that the app declares multiArch support, and warn if it doesn't. 9501 // 9502 // We will be lenient here and record both ABIs. The primary will be the 9503 // ABI that's higher on the list, i.e, a device that's configured to prefer 9504 // 64 bit apps will see a 64 bit primary ABI, 9505 9506 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9507 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9508 } 9509 9510 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9511 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9512 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9513 } else { 9514 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9515 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9516 } 9517 } else { 9518 pkg.applicationInfo.primaryCpuAbi = null; 9519 pkg.applicationInfo.secondaryCpuAbi = null; 9520 } 9521 } 9522 9523 private void killApplication(String pkgName, int appId, String reason) { 9524 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9525 } 9526 9527 private void killApplication(String pkgName, int appId, int userId, String reason) { 9528 // Request the ActivityManager to kill the process(only for existing packages) 9529 // so that we do not end up in a confused state while the user is still using the older 9530 // version of the application while the new one gets installed. 9531 final long token = Binder.clearCallingIdentity(); 9532 try { 9533 IActivityManager am = ActivityManagerNative.getDefault(); 9534 if (am != null) { 9535 try { 9536 am.killApplication(pkgName, appId, userId, reason); 9537 } catch (RemoteException e) { 9538 } 9539 } 9540 } finally { 9541 Binder.restoreCallingIdentity(token); 9542 } 9543 } 9544 9545 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9546 // Remove the parent package setting 9547 PackageSetting ps = (PackageSetting) pkg.mExtras; 9548 if (ps != null) { 9549 removePackageLI(ps, chatty); 9550 } 9551 // Remove the child package setting 9552 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9553 for (int i = 0; i < childCount; i++) { 9554 PackageParser.Package childPkg = pkg.childPackages.get(i); 9555 ps = (PackageSetting) childPkg.mExtras; 9556 if (ps != null) { 9557 removePackageLI(ps, chatty); 9558 } 9559 } 9560 } 9561 9562 void removePackageLI(PackageSetting ps, boolean chatty) { 9563 if (DEBUG_INSTALL) { 9564 if (chatty) 9565 Log.d(TAG, "Removing package " + ps.name); 9566 } 9567 9568 // writer 9569 synchronized (mPackages) { 9570 mPackages.remove(ps.name); 9571 final PackageParser.Package pkg = ps.pkg; 9572 if (pkg != null) { 9573 cleanPackageDataStructuresLILPw(pkg, chatty); 9574 } 9575 } 9576 } 9577 9578 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9579 if (DEBUG_INSTALL) { 9580 if (chatty) 9581 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9582 } 9583 9584 // writer 9585 synchronized (mPackages) { 9586 // Remove the parent package 9587 mPackages.remove(pkg.applicationInfo.packageName); 9588 cleanPackageDataStructuresLILPw(pkg, chatty); 9589 9590 // Remove the child packages 9591 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9592 for (int i = 0; i < childCount; i++) { 9593 PackageParser.Package childPkg = pkg.childPackages.get(i); 9594 mPackages.remove(childPkg.applicationInfo.packageName); 9595 cleanPackageDataStructuresLILPw(childPkg, chatty); 9596 } 9597 } 9598 } 9599 9600 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9601 int N = pkg.providers.size(); 9602 StringBuilder r = null; 9603 int i; 9604 for (i=0; i<N; i++) { 9605 PackageParser.Provider p = pkg.providers.get(i); 9606 mProviders.removeProvider(p); 9607 if (p.info.authority == null) { 9608 9609 /* There was another ContentProvider with this authority when 9610 * this app was installed so this authority is null, 9611 * Ignore it as we don't have to unregister the provider. 9612 */ 9613 continue; 9614 } 9615 String names[] = p.info.authority.split(";"); 9616 for (int j = 0; j < names.length; j++) { 9617 if (mProvidersByAuthority.get(names[j]) == p) { 9618 mProvidersByAuthority.remove(names[j]); 9619 if (DEBUG_REMOVE) { 9620 if (chatty) 9621 Log.d(TAG, "Unregistered content provider: " + names[j] 9622 + ", className = " + p.info.name + ", isSyncable = " 9623 + p.info.isSyncable); 9624 } 9625 } 9626 } 9627 if (DEBUG_REMOVE && chatty) { 9628 if (r == null) { 9629 r = new StringBuilder(256); 9630 } else { 9631 r.append(' '); 9632 } 9633 r.append(p.info.name); 9634 } 9635 } 9636 if (r != null) { 9637 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9638 } 9639 9640 N = pkg.services.size(); 9641 r = null; 9642 for (i=0; i<N; i++) { 9643 PackageParser.Service s = pkg.services.get(i); 9644 mServices.removeService(s); 9645 if (chatty) { 9646 if (r == null) { 9647 r = new StringBuilder(256); 9648 } else { 9649 r.append(' '); 9650 } 9651 r.append(s.info.name); 9652 } 9653 } 9654 if (r != null) { 9655 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9656 } 9657 9658 N = pkg.receivers.size(); 9659 r = null; 9660 for (i=0; i<N; i++) { 9661 PackageParser.Activity a = pkg.receivers.get(i); 9662 mReceivers.removeActivity(a, "receiver"); 9663 if (DEBUG_REMOVE && chatty) { 9664 if (r == null) { 9665 r = new StringBuilder(256); 9666 } else { 9667 r.append(' '); 9668 } 9669 r.append(a.info.name); 9670 } 9671 } 9672 if (r != null) { 9673 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9674 } 9675 9676 N = pkg.activities.size(); 9677 r = null; 9678 for (i=0; i<N; i++) { 9679 PackageParser.Activity a = pkg.activities.get(i); 9680 mActivities.removeActivity(a, "activity"); 9681 if (DEBUG_REMOVE && chatty) { 9682 if (r == null) { 9683 r = new StringBuilder(256); 9684 } else { 9685 r.append(' '); 9686 } 9687 r.append(a.info.name); 9688 } 9689 } 9690 if (r != null) { 9691 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9692 } 9693 9694 N = pkg.permissions.size(); 9695 r = null; 9696 for (i=0; i<N; i++) { 9697 PackageParser.Permission p = pkg.permissions.get(i); 9698 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9699 if (bp == null) { 9700 bp = mSettings.mPermissionTrees.get(p.info.name); 9701 } 9702 if (bp != null && bp.perm == p) { 9703 bp.perm = null; 9704 if (DEBUG_REMOVE && chatty) { 9705 if (r == null) { 9706 r = new StringBuilder(256); 9707 } else { 9708 r.append(' '); 9709 } 9710 r.append(p.info.name); 9711 } 9712 } 9713 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9714 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9715 if (appOpPkgs != null) { 9716 appOpPkgs.remove(pkg.packageName); 9717 } 9718 } 9719 } 9720 if (r != null) { 9721 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9722 } 9723 9724 N = pkg.requestedPermissions.size(); 9725 r = null; 9726 for (i=0; i<N; i++) { 9727 String perm = pkg.requestedPermissions.get(i); 9728 BasePermission bp = mSettings.mPermissions.get(perm); 9729 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9730 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9731 if (appOpPkgs != null) { 9732 appOpPkgs.remove(pkg.packageName); 9733 if (appOpPkgs.isEmpty()) { 9734 mAppOpPermissionPackages.remove(perm); 9735 } 9736 } 9737 } 9738 } 9739 if (r != null) { 9740 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9741 } 9742 9743 N = pkg.instrumentation.size(); 9744 r = null; 9745 for (i=0; i<N; i++) { 9746 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9747 mInstrumentation.remove(a.getComponentName()); 9748 if (DEBUG_REMOVE && chatty) { 9749 if (r == null) { 9750 r = new StringBuilder(256); 9751 } else { 9752 r.append(' '); 9753 } 9754 r.append(a.info.name); 9755 } 9756 } 9757 if (r != null) { 9758 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9759 } 9760 9761 r = null; 9762 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9763 // Only system apps can hold shared libraries. 9764 if (pkg.libraryNames != null) { 9765 for (i=0; i<pkg.libraryNames.size(); i++) { 9766 String name = pkg.libraryNames.get(i); 9767 SharedLibraryEntry cur = mSharedLibraries.get(name); 9768 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9769 mSharedLibraries.remove(name); 9770 if (DEBUG_REMOVE && chatty) { 9771 if (r == null) { 9772 r = new StringBuilder(256); 9773 } else { 9774 r.append(' '); 9775 } 9776 r.append(name); 9777 } 9778 } 9779 } 9780 } 9781 } 9782 if (r != null) { 9783 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9784 } 9785 } 9786 9787 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9788 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9789 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9790 return true; 9791 } 9792 } 9793 return false; 9794 } 9795 9796 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9797 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9798 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9799 9800 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9801 // Update the parent permissions 9802 updatePermissionsLPw(pkg.packageName, pkg, flags); 9803 // Update the child permissions 9804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9805 for (int i = 0; i < childCount; i++) { 9806 PackageParser.Package childPkg = pkg.childPackages.get(i); 9807 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9808 } 9809 } 9810 9811 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9812 int flags) { 9813 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9814 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9815 } 9816 9817 private void updatePermissionsLPw(String changingPkg, 9818 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9819 // Make sure there are no dangling permission trees. 9820 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9821 while (it.hasNext()) { 9822 final BasePermission bp = it.next(); 9823 if (bp.packageSetting == null) { 9824 // We may not yet have parsed the package, so just see if 9825 // we still know about its settings. 9826 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9827 } 9828 if (bp.packageSetting == null) { 9829 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9830 + " from package " + bp.sourcePackage); 9831 it.remove(); 9832 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9833 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9834 Slog.i(TAG, "Removing old permission tree: " + bp.name 9835 + " from package " + bp.sourcePackage); 9836 flags |= UPDATE_PERMISSIONS_ALL; 9837 it.remove(); 9838 } 9839 } 9840 } 9841 9842 // Make sure all dynamic permissions have been assigned to a package, 9843 // and make sure there are no dangling permissions. 9844 it = mSettings.mPermissions.values().iterator(); 9845 while (it.hasNext()) { 9846 final BasePermission bp = it.next(); 9847 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9848 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9849 + bp.name + " pkg=" + bp.sourcePackage 9850 + " info=" + bp.pendingInfo); 9851 if (bp.packageSetting == null && bp.pendingInfo != null) { 9852 final BasePermission tree = findPermissionTreeLP(bp.name); 9853 if (tree != null && tree.perm != null) { 9854 bp.packageSetting = tree.packageSetting; 9855 bp.perm = new PackageParser.Permission(tree.perm.owner, 9856 new PermissionInfo(bp.pendingInfo)); 9857 bp.perm.info.packageName = tree.perm.info.packageName; 9858 bp.perm.info.name = bp.name; 9859 bp.uid = tree.uid; 9860 } 9861 } 9862 } 9863 if (bp.packageSetting == null) { 9864 // We may not yet have parsed the package, so just see if 9865 // we still know about its settings. 9866 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9867 } 9868 if (bp.packageSetting == null) { 9869 Slog.w(TAG, "Removing dangling permission: " + bp.name 9870 + " from package " + bp.sourcePackage); 9871 it.remove(); 9872 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9873 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9874 Slog.i(TAG, "Removing old permission: " + bp.name 9875 + " from package " + bp.sourcePackage); 9876 flags |= UPDATE_PERMISSIONS_ALL; 9877 it.remove(); 9878 } 9879 } 9880 } 9881 9882 // Now update the permissions for all packages, in particular 9883 // replace the granted permissions of the system packages. 9884 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9885 for (PackageParser.Package pkg : mPackages.values()) { 9886 if (pkg != pkgInfo) { 9887 // Only replace for packages on requested volume 9888 final String volumeUuid = getVolumeUuidForPackage(pkg); 9889 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9890 && Objects.equals(replaceVolumeUuid, volumeUuid); 9891 grantPermissionsLPw(pkg, replace, changingPkg); 9892 } 9893 } 9894 } 9895 9896 if (pkgInfo != null) { 9897 // Only replace for packages on requested volume 9898 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9899 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9900 && Objects.equals(replaceVolumeUuid, volumeUuid); 9901 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9902 } 9903 } 9904 9905 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9906 String packageOfInterest) { 9907 // IMPORTANT: There are two types of permissions: install and runtime. 9908 // Install time permissions are granted when the app is installed to 9909 // all device users and users added in the future. Runtime permissions 9910 // are granted at runtime explicitly to specific users. Normal and signature 9911 // protected permissions are install time permissions. Dangerous permissions 9912 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9913 // otherwise they are runtime permissions. This function does not manage 9914 // runtime permissions except for the case an app targeting Lollipop MR1 9915 // being upgraded to target a newer SDK, in which case dangerous permissions 9916 // are transformed from install time to runtime ones. 9917 9918 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9919 if (ps == null) { 9920 return; 9921 } 9922 9923 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9924 9925 PermissionsState permissionsState = ps.getPermissionsState(); 9926 PermissionsState origPermissions = permissionsState; 9927 9928 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9929 9930 boolean runtimePermissionsRevoked = false; 9931 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9932 9933 boolean changedInstallPermission = false; 9934 9935 if (replace) { 9936 ps.installPermissionsFixed = false; 9937 if (!ps.isSharedUser()) { 9938 origPermissions = new PermissionsState(permissionsState); 9939 permissionsState.reset(); 9940 } else { 9941 // We need to know only about runtime permission changes since the 9942 // calling code always writes the install permissions state but 9943 // the runtime ones are written only if changed. The only cases of 9944 // changed runtime permissions here are promotion of an install to 9945 // runtime and revocation of a runtime from a shared user. 9946 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9947 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9948 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9949 runtimePermissionsRevoked = true; 9950 } 9951 } 9952 } 9953 9954 permissionsState.setGlobalGids(mGlobalGids); 9955 9956 final int N = pkg.requestedPermissions.size(); 9957 for (int i=0; i<N; i++) { 9958 final String name = pkg.requestedPermissions.get(i); 9959 final BasePermission bp = mSettings.mPermissions.get(name); 9960 9961 if (DEBUG_INSTALL) { 9962 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9963 } 9964 9965 if (bp == null || bp.packageSetting == null) { 9966 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9967 Slog.w(TAG, "Unknown permission " + name 9968 + " in package " + pkg.packageName); 9969 } 9970 continue; 9971 } 9972 9973 final String perm = bp.name; 9974 boolean allowedSig = false; 9975 int grant = GRANT_DENIED; 9976 9977 // Keep track of app op permissions. 9978 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9979 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9980 if (pkgs == null) { 9981 pkgs = new ArraySet<>(); 9982 mAppOpPermissionPackages.put(bp.name, pkgs); 9983 } 9984 pkgs.add(pkg.packageName); 9985 } 9986 9987 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9988 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9989 >= Build.VERSION_CODES.M; 9990 switch (level) { 9991 case PermissionInfo.PROTECTION_NORMAL: { 9992 // For all apps normal permissions are install time ones. 9993 grant = GRANT_INSTALL; 9994 } break; 9995 9996 case PermissionInfo.PROTECTION_DANGEROUS: { 9997 // If a permission review is required for legacy apps we represent 9998 // their permissions as always granted runtime ones since we need 9999 // to keep the review required permission flag per user while an 10000 // install permission's state is shared across all users. 10001 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10002 // For legacy apps dangerous permissions are install time ones. 10003 grant = GRANT_INSTALL; 10004 } else if (origPermissions.hasInstallPermission(bp.name)) { 10005 // For legacy apps that became modern, install becomes runtime. 10006 grant = GRANT_UPGRADE; 10007 } else if (mPromoteSystemApps 10008 && isSystemApp(ps) 10009 && mExistingSystemPackages.contains(ps.name)) { 10010 // For legacy system apps, install becomes runtime. 10011 // We cannot check hasInstallPermission() for system apps since those 10012 // permissions were granted implicitly and not persisted pre-M. 10013 grant = GRANT_UPGRADE; 10014 } else { 10015 // For modern apps keep runtime permissions unchanged. 10016 grant = GRANT_RUNTIME; 10017 } 10018 } break; 10019 10020 case PermissionInfo.PROTECTION_SIGNATURE: { 10021 // For all apps signature permissions are install time ones. 10022 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10023 if (allowedSig) { 10024 grant = GRANT_INSTALL; 10025 } 10026 } break; 10027 } 10028 10029 if (DEBUG_INSTALL) { 10030 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10031 } 10032 10033 if (grant != GRANT_DENIED) { 10034 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10035 // If this is an existing, non-system package, then 10036 // we can't add any new permissions to it. 10037 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10038 // Except... if this is a permission that was added 10039 // to the platform (note: need to only do this when 10040 // updating the platform). 10041 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10042 grant = GRANT_DENIED; 10043 } 10044 } 10045 } 10046 10047 switch (grant) { 10048 case GRANT_INSTALL: { 10049 // Revoke this as runtime permission to handle the case of 10050 // a runtime permission being downgraded to an install one. 10051 // Also in permission review mode we keep dangerous permissions 10052 // for legacy apps 10053 for (int userId : UserManagerService.getInstance().getUserIds()) { 10054 if (origPermissions.getRuntimePermissionState( 10055 bp.name, userId) != null) { 10056 // Revoke the runtime permission and clear the flags. 10057 origPermissions.revokeRuntimePermission(bp, userId); 10058 origPermissions.updatePermissionFlags(bp, userId, 10059 PackageManager.MASK_PERMISSION_FLAGS, 0); 10060 // If we revoked a permission permission, we have to write. 10061 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10062 changedRuntimePermissionUserIds, userId); 10063 } 10064 } 10065 // Grant an install permission. 10066 if (permissionsState.grantInstallPermission(bp) != 10067 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10068 changedInstallPermission = true; 10069 } 10070 } break; 10071 10072 case GRANT_RUNTIME: { 10073 // Grant previously granted runtime permissions. 10074 for (int userId : UserManagerService.getInstance().getUserIds()) { 10075 PermissionState permissionState = origPermissions 10076 .getRuntimePermissionState(bp.name, userId); 10077 int flags = permissionState != null 10078 ? permissionState.getFlags() : 0; 10079 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10080 if (permissionsState.grantRuntimePermission(bp, userId) == 10081 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10082 // If we cannot put the permission as it was, we have to write. 10083 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10084 changedRuntimePermissionUserIds, userId); 10085 } 10086 // If the app supports runtime permissions no need for a review. 10087 if (Build.PERMISSIONS_REVIEW_REQUIRED 10088 && appSupportsRuntimePermissions 10089 && (flags & PackageManager 10090 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10091 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10092 // Since we changed the flags, we have to write. 10093 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10094 changedRuntimePermissionUserIds, userId); 10095 } 10096 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10097 && !appSupportsRuntimePermissions) { 10098 // For legacy apps that need a permission review, every new 10099 // runtime permission is granted but it is pending a review. 10100 // We also need to review only platform defined runtime 10101 // permissions as these are the only ones the platform knows 10102 // how to disable the API to simulate revocation as legacy 10103 // apps don't expect to run with revoked permissions. 10104 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10105 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10106 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10107 // We changed the flags, hence have to write. 10108 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10109 changedRuntimePermissionUserIds, userId); 10110 } 10111 } 10112 if (permissionsState.grantRuntimePermission(bp, userId) 10113 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10114 // We changed the permission, hence have to write. 10115 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10116 changedRuntimePermissionUserIds, userId); 10117 } 10118 } 10119 // Propagate the permission flags. 10120 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10121 } 10122 } break; 10123 10124 case GRANT_UPGRADE: { 10125 // Grant runtime permissions for a previously held install permission. 10126 PermissionState permissionState = origPermissions 10127 .getInstallPermissionState(bp.name); 10128 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10129 10130 if (origPermissions.revokeInstallPermission(bp) 10131 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10132 // We will be transferring the permission flags, so clear them. 10133 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10134 PackageManager.MASK_PERMISSION_FLAGS, 0); 10135 changedInstallPermission = true; 10136 } 10137 10138 // If the permission is not to be promoted to runtime we ignore it and 10139 // also its other flags as they are not applicable to install permissions. 10140 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10141 for (int userId : currentUserIds) { 10142 if (permissionsState.grantRuntimePermission(bp, userId) != 10143 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10144 // Transfer the permission flags. 10145 permissionsState.updatePermissionFlags(bp, userId, 10146 flags, flags); 10147 // If we granted the permission, we have to write. 10148 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10149 changedRuntimePermissionUserIds, userId); 10150 } 10151 } 10152 } 10153 } break; 10154 10155 default: { 10156 if (packageOfInterest == null 10157 || packageOfInterest.equals(pkg.packageName)) { 10158 Slog.w(TAG, "Not granting permission " + perm 10159 + " to package " + pkg.packageName 10160 + " because it was previously installed without"); 10161 } 10162 } break; 10163 } 10164 } else { 10165 if (permissionsState.revokeInstallPermission(bp) != 10166 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10167 // Also drop the permission flags. 10168 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10169 PackageManager.MASK_PERMISSION_FLAGS, 0); 10170 changedInstallPermission = true; 10171 Slog.i(TAG, "Un-granting permission " + perm 10172 + " from package " + pkg.packageName 10173 + " (protectionLevel=" + bp.protectionLevel 10174 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10175 + ")"); 10176 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10177 // Don't print warning for app op permissions, since it is fine for them 10178 // not to be granted, there is a UI for the user to decide. 10179 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10180 Slog.w(TAG, "Not granting permission " + perm 10181 + " to package " + pkg.packageName 10182 + " (protectionLevel=" + bp.protectionLevel 10183 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10184 + ")"); 10185 } 10186 } 10187 } 10188 } 10189 10190 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10191 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10192 // This is the first that we have heard about this package, so the 10193 // permissions we have now selected are fixed until explicitly 10194 // changed. 10195 ps.installPermissionsFixed = true; 10196 } 10197 10198 // Persist the runtime permissions state for users with changes. If permissions 10199 // were revoked because no app in the shared user declares them we have to 10200 // write synchronously to avoid losing runtime permissions state. 10201 for (int userId : changedRuntimePermissionUserIds) { 10202 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10203 } 10204 10205 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10206 } 10207 10208 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10209 boolean allowed = false; 10210 final int NP = PackageParser.NEW_PERMISSIONS.length; 10211 for (int ip=0; ip<NP; ip++) { 10212 final PackageParser.NewPermissionInfo npi 10213 = PackageParser.NEW_PERMISSIONS[ip]; 10214 if (npi.name.equals(perm) 10215 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10216 allowed = true; 10217 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10218 + pkg.packageName); 10219 break; 10220 } 10221 } 10222 return allowed; 10223 } 10224 10225 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10226 BasePermission bp, PermissionsState origPermissions) { 10227 boolean allowed; 10228 allowed = (compareSignatures( 10229 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10230 == PackageManager.SIGNATURE_MATCH) 10231 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10232 == PackageManager.SIGNATURE_MATCH); 10233 if (!allowed && (bp.protectionLevel 10234 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10235 if (isSystemApp(pkg)) { 10236 // For updated system applications, a system permission 10237 // is granted only if it had been defined by the original application. 10238 if (pkg.isUpdatedSystemApp()) { 10239 final PackageSetting sysPs = mSettings 10240 .getDisabledSystemPkgLPr(pkg.packageName); 10241 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10242 // If the original was granted this permission, we take 10243 // that grant decision as read and propagate it to the 10244 // update. 10245 if (sysPs.isPrivileged()) { 10246 allowed = true; 10247 } 10248 } else { 10249 // The system apk may have been updated with an older 10250 // version of the one on the data partition, but which 10251 // granted a new system permission that it didn't have 10252 // before. In this case we do want to allow the app to 10253 // now get the new permission if the ancestral apk is 10254 // privileged to get it. 10255 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10256 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10257 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10258 allowed = true; 10259 break; 10260 } 10261 } 10262 } 10263 // Also if a privileged parent package on the system image or any of 10264 // its children requested a privileged permission, the updated child 10265 // packages can also get the permission. 10266 if (pkg.parentPackage != null) { 10267 final PackageSetting disabledSysParentPs = mSettings 10268 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10269 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10270 && disabledSysParentPs.isPrivileged()) { 10271 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10272 allowed = true; 10273 } else if (disabledSysParentPs.pkg.childPackages != null) { 10274 final int count = disabledSysParentPs.pkg.childPackages.size(); 10275 for (int i = 0; i < count; i++) { 10276 PackageParser.Package disabledSysChildPkg = 10277 disabledSysParentPs.pkg.childPackages.get(i); 10278 if (isPackageRequestingPermission(disabledSysChildPkg, 10279 perm)) { 10280 allowed = true; 10281 break; 10282 } 10283 } 10284 } 10285 } 10286 } 10287 } 10288 } else { 10289 allowed = isPrivilegedApp(pkg); 10290 } 10291 } 10292 } 10293 if (!allowed) { 10294 if (!allowed && (bp.protectionLevel 10295 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10296 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10297 // If this was a previously normal/dangerous permission that got moved 10298 // to a system permission as part of the runtime permission redesign, then 10299 // we still want to blindly grant it to old apps. 10300 allowed = true; 10301 } 10302 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10303 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10304 // If this permission is to be granted to the system installer and 10305 // this app is an installer, then it gets the permission. 10306 allowed = true; 10307 } 10308 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10309 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10310 // If this permission is to be granted to the system verifier and 10311 // this app is a verifier, then it gets the permission. 10312 allowed = true; 10313 } 10314 if (!allowed && (bp.protectionLevel 10315 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10316 && isSystemApp(pkg)) { 10317 // Any pre-installed system app is allowed to get this permission. 10318 allowed = true; 10319 } 10320 if (!allowed && (bp.protectionLevel 10321 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10322 // For development permissions, a development permission 10323 // is granted only if it was already granted. 10324 allowed = origPermissions.hasInstallPermission(perm); 10325 } 10326 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10327 && pkg.packageName.equals(mSetupWizardPackage)) { 10328 // If this permission is to be granted to the system setup wizard and 10329 // this app is a setup wizard, then it gets the permission. 10330 allowed = true; 10331 } 10332 } 10333 return allowed; 10334 } 10335 10336 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10337 final int permCount = pkg.requestedPermissions.size(); 10338 for (int j = 0; j < permCount; j++) { 10339 String requestedPermission = pkg.requestedPermissions.get(j); 10340 if (permission.equals(requestedPermission)) { 10341 return true; 10342 } 10343 } 10344 return false; 10345 } 10346 10347 final class ActivityIntentResolver 10348 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10349 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10350 boolean defaultOnly, int userId) { 10351 if (!sUserManager.exists(userId)) return null; 10352 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10353 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10354 } 10355 10356 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10357 int userId) { 10358 if (!sUserManager.exists(userId)) return null; 10359 mFlags = flags; 10360 return super.queryIntent(intent, resolvedType, 10361 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10362 } 10363 10364 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10365 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10366 if (!sUserManager.exists(userId)) return null; 10367 if (packageActivities == null) { 10368 return null; 10369 } 10370 mFlags = flags; 10371 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10372 final int N = packageActivities.size(); 10373 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10374 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10375 10376 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10377 for (int i = 0; i < N; ++i) { 10378 intentFilters = packageActivities.get(i).intents; 10379 if (intentFilters != null && intentFilters.size() > 0) { 10380 PackageParser.ActivityIntentInfo[] array = 10381 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10382 intentFilters.toArray(array); 10383 listCut.add(array); 10384 } 10385 } 10386 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10387 } 10388 10389 /** 10390 * Finds a privileged activity that matches the specified activity names. 10391 */ 10392 private PackageParser.Activity findMatchingActivity( 10393 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10394 for (PackageParser.Activity sysActivity : activityList) { 10395 if (sysActivity.info.name.equals(activityInfo.name)) { 10396 return sysActivity; 10397 } 10398 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10399 return sysActivity; 10400 } 10401 if (sysActivity.info.targetActivity != null) { 10402 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10403 return sysActivity; 10404 } 10405 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10406 return sysActivity; 10407 } 10408 } 10409 } 10410 return null; 10411 } 10412 10413 public class IterGenerator<E> { 10414 public Iterator<E> generate(ActivityIntentInfo info) { 10415 return null; 10416 } 10417 } 10418 10419 public class ActionIterGenerator extends IterGenerator<String> { 10420 @Override 10421 public Iterator<String> generate(ActivityIntentInfo info) { 10422 return info.actionsIterator(); 10423 } 10424 } 10425 10426 public class CategoriesIterGenerator extends IterGenerator<String> { 10427 @Override 10428 public Iterator<String> generate(ActivityIntentInfo info) { 10429 return info.categoriesIterator(); 10430 } 10431 } 10432 10433 public class SchemesIterGenerator extends IterGenerator<String> { 10434 @Override 10435 public Iterator<String> generate(ActivityIntentInfo info) { 10436 return info.schemesIterator(); 10437 } 10438 } 10439 10440 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10441 @Override 10442 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10443 return info.authoritiesIterator(); 10444 } 10445 } 10446 10447 /** 10448 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10449 * MODIFIED. Do not pass in a list that should not be changed. 10450 */ 10451 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10452 IterGenerator<T> generator, Iterator<T> searchIterator) { 10453 // loop through the set of actions; every one must be found in the intent filter 10454 while (searchIterator.hasNext()) { 10455 // we must have at least one filter in the list to consider a match 10456 if (intentList.size() == 0) { 10457 break; 10458 } 10459 10460 final T searchAction = searchIterator.next(); 10461 10462 // loop through the set of intent filters 10463 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10464 while (intentIter.hasNext()) { 10465 final ActivityIntentInfo intentInfo = intentIter.next(); 10466 boolean selectionFound = false; 10467 10468 // loop through the intent filter's selection criteria; at least one 10469 // of them must match the searched criteria 10470 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10471 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10472 final T intentSelection = intentSelectionIter.next(); 10473 if (intentSelection != null && intentSelection.equals(searchAction)) { 10474 selectionFound = true; 10475 break; 10476 } 10477 } 10478 10479 // the selection criteria wasn't found in this filter's set; this filter 10480 // is not a potential match 10481 if (!selectionFound) { 10482 intentIter.remove(); 10483 } 10484 } 10485 } 10486 } 10487 10488 private boolean isProtectedAction(ActivityIntentInfo filter) { 10489 final Iterator<String> actionsIter = filter.actionsIterator(); 10490 while (actionsIter != null && actionsIter.hasNext()) { 10491 final String filterAction = actionsIter.next(); 10492 if (PROTECTED_ACTIONS.contains(filterAction)) { 10493 return true; 10494 } 10495 } 10496 return false; 10497 } 10498 10499 /** 10500 * Adjusts the priority of the given intent filter according to policy. 10501 * <p> 10502 * <ul> 10503 * <li>The priority for non privileged applications is capped to '0'</li> 10504 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10505 * <li>The priority for unbundled updates to privileged applications is capped to the 10506 * priority defined on the system partition</li> 10507 * </ul> 10508 * <p> 10509 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10510 * allowed to obtain any priority on any action. 10511 */ 10512 private void adjustPriority( 10513 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10514 // nothing to do; priority is fine as-is 10515 if (intent.getPriority() <= 0) { 10516 return; 10517 } 10518 10519 final ActivityInfo activityInfo = intent.activity.info; 10520 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10521 10522 final boolean privilegedApp = 10523 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10524 if (!privilegedApp) { 10525 // non-privileged applications can never define a priority >0 10526 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10527 + " package: " + applicationInfo.packageName 10528 + " activity: " + intent.activity.className 10529 + " origPrio: " + intent.getPriority()); 10530 intent.setPriority(0); 10531 return; 10532 } 10533 10534 if (systemActivities == null) { 10535 // the system package is not disabled; we're parsing the system partition 10536 if (isProtectedAction(intent)) { 10537 if (mDeferProtectedFilters) { 10538 // We can't deal with these just yet. No component should ever obtain a 10539 // >0 priority for a protected actions, with ONE exception -- the setup 10540 // wizard. The setup wizard, however, cannot be known until we're able to 10541 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10542 // until all intent filters have been processed. Chicken, meet egg. 10543 // Let the filter temporarily have a high priority and rectify the 10544 // priorities after all system packages have been scanned. 10545 mProtectedFilters.add(intent); 10546 if (DEBUG_FILTERS) { 10547 Slog.i(TAG, "Protected action; save for later;" 10548 + " package: " + applicationInfo.packageName 10549 + " activity: " + intent.activity.className 10550 + " origPrio: " + intent.getPriority()); 10551 } 10552 return; 10553 } else { 10554 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10555 Slog.i(TAG, "No setup wizard;" 10556 + " All protected intents capped to priority 0"); 10557 } 10558 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10559 if (DEBUG_FILTERS) { 10560 Slog.i(TAG, "Found setup wizard;" 10561 + " allow priority " + intent.getPriority() + ";" 10562 + " package: " + intent.activity.info.packageName 10563 + " activity: " + intent.activity.className 10564 + " priority: " + intent.getPriority()); 10565 } 10566 // setup wizard gets whatever it wants 10567 return; 10568 } 10569 Slog.w(TAG, "Protected action; cap priority to 0;" 10570 + " package: " + intent.activity.info.packageName 10571 + " activity: " + intent.activity.className 10572 + " origPrio: " + intent.getPriority()); 10573 intent.setPriority(0); 10574 return; 10575 } 10576 } 10577 // privileged apps on the system image get whatever priority they request 10578 return; 10579 } 10580 10581 // privileged app unbundled update ... try to find the same activity 10582 final PackageParser.Activity foundActivity = 10583 findMatchingActivity(systemActivities, activityInfo); 10584 if (foundActivity == null) { 10585 // this is a new activity; it cannot obtain >0 priority 10586 if (DEBUG_FILTERS) { 10587 Slog.i(TAG, "New activity; cap priority to 0;" 10588 + " package: " + applicationInfo.packageName 10589 + " activity: " + intent.activity.className 10590 + " origPrio: " + intent.getPriority()); 10591 } 10592 intent.setPriority(0); 10593 return; 10594 } 10595 10596 // found activity, now check for filter equivalence 10597 10598 // a shallow copy is enough; we modify the list, not its contents 10599 final List<ActivityIntentInfo> intentListCopy = 10600 new ArrayList<>(foundActivity.intents); 10601 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10602 10603 // find matching action subsets 10604 final Iterator<String> actionsIterator = intent.actionsIterator(); 10605 if (actionsIterator != null) { 10606 getIntentListSubset( 10607 intentListCopy, new ActionIterGenerator(), actionsIterator); 10608 if (intentListCopy.size() == 0) { 10609 // no more intents to match; we're not equivalent 10610 if (DEBUG_FILTERS) { 10611 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10612 + " package: " + applicationInfo.packageName 10613 + " activity: " + intent.activity.className 10614 + " origPrio: " + intent.getPriority()); 10615 } 10616 intent.setPriority(0); 10617 return; 10618 } 10619 } 10620 10621 // find matching category subsets 10622 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10623 if (categoriesIterator != null) { 10624 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10625 categoriesIterator); 10626 if (intentListCopy.size() == 0) { 10627 // no more intents to match; we're not equivalent 10628 if (DEBUG_FILTERS) { 10629 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10630 + " package: " + applicationInfo.packageName 10631 + " activity: " + intent.activity.className 10632 + " origPrio: " + intent.getPriority()); 10633 } 10634 intent.setPriority(0); 10635 return; 10636 } 10637 } 10638 10639 // find matching schemes subsets 10640 final Iterator<String> schemesIterator = intent.schemesIterator(); 10641 if (schemesIterator != null) { 10642 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10643 schemesIterator); 10644 if (intentListCopy.size() == 0) { 10645 // no more intents to match; we're not equivalent 10646 if (DEBUG_FILTERS) { 10647 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10648 + " package: " + applicationInfo.packageName 10649 + " activity: " + intent.activity.className 10650 + " origPrio: " + intent.getPriority()); 10651 } 10652 intent.setPriority(0); 10653 return; 10654 } 10655 } 10656 10657 // find matching authorities subsets 10658 final Iterator<IntentFilter.AuthorityEntry> 10659 authoritiesIterator = intent.authoritiesIterator(); 10660 if (authoritiesIterator != null) { 10661 getIntentListSubset(intentListCopy, 10662 new AuthoritiesIterGenerator(), 10663 authoritiesIterator); 10664 if (intentListCopy.size() == 0) { 10665 // no more intents to match; we're not equivalent 10666 if (DEBUG_FILTERS) { 10667 Slog.i(TAG, "Mismatched authority; 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 // we found matching filter(s); app gets the max priority of all intents 10678 int cappedPriority = 0; 10679 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10680 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10681 } 10682 if (intent.getPriority() > cappedPriority) { 10683 if (DEBUG_FILTERS) { 10684 Slog.i(TAG, "Found matching filter(s);" 10685 + " cap priority to " + cappedPriority + ";" 10686 + " package: " + applicationInfo.packageName 10687 + " activity: " + intent.activity.className 10688 + " origPrio: " + intent.getPriority()); 10689 } 10690 intent.setPriority(cappedPriority); 10691 return; 10692 } 10693 // all this for nothing; the requested priority was <= what was on the system 10694 } 10695 10696 public final void addActivity(PackageParser.Activity a, String type) { 10697 mActivities.put(a.getComponentName(), a); 10698 if (DEBUG_SHOW_INFO) 10699 Log.v( 10700 TAG, " " + type + " " + 10701 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10702 if (DEBUG_SHOW_INFO) 10703 Log.v(TAG, " Class=" + a.info.name); 10704 final int NI = a.intents.size(); 10705 for (int j=0; j<NI; j++) { 10706 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10707 if ("activity".equals(type)) { 10708 final PackageSetting ps = 10709 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10710 final List<PackageParser.Activity> systemActivities = 10711 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10712 adjustPriority(systemActivities, intent); 10713 } 10714 if (DEBUG_SHOW_INFO) { 10715 Log.v(TAG, " IntentFilter:"); 10716 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10717 } 10718 if (!intent.debugCheck()) { 10719 Log.w(TAG, "==> For Activity " + a.info.name); 10720 } 10721 addFilter(intent); 10722 } 10723 } 10724 10725 public final void removeActivity(PackageParser.Activity a, String type) { 10726 mActivities.remove(a.getComponentName()); 10727 if (DEBUG_SHOW_INFO) { 10728 Log.v(TAG, " " + type + " " 10729 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10730 : a.info.name) + ":"); 10731 Log.v(TAG, " Class=" + a.info.name); 10732 } 10733 final int NI = a.intents.size(); 10734 for (int j=0; j<NI; j++) { 10735 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10736 if (DEBUG_SHOW_INFO) { 10737 Log.v(TAG, " IntentFilter:"); 10738 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10739 } 10740 removeFilter(intent); 10741 } 10742 } 10743 10744 @Override 10745 protected boolean allowFilterResult( 10746 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10747 ActivityInfo filterAi = filter.activity.info; 10748 for (int i=dest.size()-1; i>=0; i--) { 10749 ActivityInfo destAi = dest.get(i).activityInfo; 10750 if (destAi.name == filterAi.name 10751 && destAi.packageName == filterAi.packageName) { 10752 return false; 10753 } 10754 } 10755 return true; 10756 } 10757 10758 @Override 10759 protected ActivityIntentInfo[] newArray(int size) { 10760 return new ActivityIntentInfo[size]; 10761 } 10762 10763 @Override 10764 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10765 if (!sUserManager.exists(userId)) return true; 10766 PackageParser.Package p = filter.activity.owner; 10767 if (p != null) { 10768 PackageSetting ps = (PackageSetting)p.mExtras; 10769 if (ps != null) { 10770 // System apps are never considered stopped for purposes of 10771 // filtering, because there may be no way for the user to 10772 // actually re-launch them. 10773 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10774 && ps.getStopped(userId); 10775 } 10776 } 10777 return false; 10778 } 10779 10780 @Override 10781 protected boolean isPackageForFilter(String packageName, 10782 PackageParser.ActivityIntentInfo info) { 10783 return packageName.equals(info.activity.owner.packageName); 10784 } 10785 10786 @Override 10787 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10788 int match, int userId) { 10789 if (!sUserManager.exists(userId)) return null; 10790 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10791 return null; 10792 } 10793 final PackageParser.Activity activity = info.activity; 10794 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10795 if (ps == null) { 10796 return null; 10797 } 10798 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10799 ps.readUserState(userId), userId); 10800 if (ai == null) { 10801 return null; 10802 } 10803 final ResolveInfo res = new ResolveInfo(); 10804 res.activityInfo = ai; 10805 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10806 res.filter = info; 10807 } 10808 if (info != null) { 10809 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10810 } 10811 res.priority = info.getPriority(); 10812 res.preferredOrder = activity.owner.mPreferredOrder; 10813 //System.out.println("Result: " + res.activityInfo.className + 10814 // " = " + res.priority); 10815 res.match = match; 10816 res.isDefault = info.hasDefault; 10817 res.labelRes = info.labelRes; 10818 res.nonLocalizedLabel = info.nonLocalizedLabel; 10819 if (userNeedsBadging(userId)) { 10820 res.noResourceId = true; 10821 } else { 10822 res.icon = info.icon; 10823 } 10824 res.iconResourceId = info.icon; 10825 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10826 return res; 10827 } 10828 10829 @Override 10830 protected void sortResults(List<ResolveInfo> results) { 10831 Collections.sort(results, mResolvePrioritySorter); 10832 } 10833 10834 @Override 10835 protected void dumpFilter(PrintWriter out, String prefix, 10836 PackageParser.ActivityIntentInfo filter) { 10837 out.print(prefix); out.print( 10838 Integer.toHexString(System.identityHashCode(filter.activity))); 10839 out.print(' '); 10840 filter.activity.printComponentShortName(out); 10841 out.print(" filter "); 10842 out.println(Integer.toHexString(System.identityHashCode(filter))); 10843 } 10844 10845 @Override 10846 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10847 return filter.activity; 10848 } 10849 10850 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10851 PackageParser.Activity activity = (PackageParser.Activity)label; 10852 out.print(prefix); out.print( 10853 Integer.toHexString(System.identityHashCode(activity))); 10854 out.print(' '); 10855 activity.printComponentShortName(out); 10856 if (count > 1) { 10857 out.print(" ("); out.print(count); out.print(" filters)"); 10858 } 10859 out.println(); 10860 } 10861 10862 // Keys are String (activity class name), values are Activity. 10863 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10864 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10865 private int mFlags; 10866 } 10867 10868 private final class ServiceIntentResolver 10869 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10870 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10871 boolean defaultOnly, int userId) { 10872 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10873 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10874 } 10875 10876 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10877 int userId) { 10878 if (!sUserManager.exists(userId)) return null; 10879 mFlags = flags; 10880 return super.queryIntent(intent, resolvedType, 10881 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10882 } 10883 10884 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10885 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10886 if (!sUserManager.exists(userId)) return null; 10887 if (packageServices == null) { 10888 return null; 10889 } 10890 mFlags = flags; 10891 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10892 final int N = packageServices.size(); 10893 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10894 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10895 10896 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10897 for (int i = 0; i < N; ++i) { 10898 intentFilters = packageServices.get(i).intents; 10899 if (intentFilters != null && intentFilters.size() > 0) { 10900 PackageParser.ServiceIntentInfo[] array = 10901 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10902 intentFilters.toArray(array); 10903 listCut.add(array); 10904 } 10905 } 10906 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10907 } 10908 10909 public final void addService(PackageParser.Service s) { 10910 mServices.put(s.getComponentName(), s); 10911 if (DEBUG_SHOW_INFO) { 10912 Log.v(TAG, " " 10913 + (s.info.nonLocalizedLabel != null 10914 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10915 Log.v(TAG, " Class=" + s.info.name); 10916 } 10917 final int NI = s.intents.size(); 10918 int j; 10919 for (j=0; j<NI; j++) { 10920 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10921 if (DEBUG_SHOW_INFO) { 10922 Log.v(TAG, " IntentFilter:"); 10923 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10924 } 10925 if (!intent.debugCheck()) { 10926 Log.w(TAG, "==> For Service " + s.info.name); 10927 } 10928 addFilter(intent); 10929 } 10930 } 10931 10932 public final void removeService(PackageParser.Service s) { 10933 mServices.remove(s.getComponentName()); 10934 if (DEBUG_SHOW_INFO) { 10935 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10936 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10937 Log.v(TAG, " Class=" + s.info.name); 10938 } 10939 final int NI = s.intents.size(); 10940 int j; 10941 for (j=0; j<NI; j++) { 10942 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10943 if (DEBUG_SHOW_INFO) { 10944 Log.v(TAG, " IntentFilter:"); 10945 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10946 } 10947 removeFilter(intent); 10948 } 10949 } 10950 10951 @Override 10952 protected boolean allowFilterResult( 10953 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10954 ServiceInfo filterSi = filter.service.info; 10955 for (int i=dest.size()-1; i>=0; i--) { 10956 ServiceInfo destAi = dest.get(i).serviceInfo; 10957 if (destAi.name == filterSi.name 10958 && destAi.packageName == filterSi.packageName) { 10959 return false; 10960 } 10961 } 10962 return true; 10963 } 10964 10965 @Override 10966 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10967 return new PackageParser.ServiceIntentInfo[size]; 10968 } 10969 10970 @Override 10971 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10972 if (!sUserManager.exists(userId)) return true; 10973 PackageParser.Package p = filter.service.owner; 10974 if (p != null) { 10975 PackageSetting ps = (PackageSetting)p.mExtras; 10976 if (ps != null) { 10977 // System apps are never considered stopped for purposes of 10978 // filtering, because there may be no way for the user to 10979 // actually re-launch them. 10980 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10981 && ps.getStopped(userId); 10982 } 10983 } 10984 return false; 10985 } 10986 10987 @Override 10988 protected boolean isPackageForFilter(String packageName, 10989 PackageParser.ServiceIntentInfo info) { 10990 return packageName.equals(info.service.owner.packageName); 10991 } 10992 10993 @Override 10994 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10995 int match, int userId) { 10996 if (!sUserManager.exists(userId)) return null; 10997 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10998 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10999 return null; 11000 } 11001 final PackageParser.Service service = info.service; 11002 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11003 if (ps == null) { 11004 return null; 11005 } 11006 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11007 ps.readUserState(userId), userId); 11008 if (si == null) { 11009 return null; 11010 } 11011 final ResolveInfo res = new ResolveInfo(); 11012 res.serviceInfo = si; 11013 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11014 res.filter = filter; 11015 } 11016 res.priority = info.getPriority(); 11017 res.preferredOrder = service.owner.mPreferredOrder; 11018 res.match = match; 11019 res.isDefault = info.hasDefault; 11020 res.labelRes = info.labelRes; 11021 res.nonLocalizedLabel = info.nonLocalizedLabel; 11022 res.icon = info.icon; 11023 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11024 return res; 11025 } 11026 11027 @Override 11028 protected void sortResults(List<ResolveInfo> results) { 11029 Collections.sort(results, mResolvePrioritySorter); 11030 } 11031 11032 @Override 11033 protected void dumpFilter(PrintWriter out, String prefix, 11034 PackageParser.ServiceIntentInfo filter) { 11035 out.print(prefix); out.print( 11036 Integer.toHexString(System.identityHashCode(filter.service))); 11037 out.print(' '); 11038 filter.service.printComponentShortName(out); 11039 out.print(" filter "); 11040 out.println(Integer.toHexString(System.identityHashCode(filter))); 11041 } 11042 11043 @Override 11044 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11045 return filter.service; 11046 } 11047 11048 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11049 PackageParser.Service service = (PackageParser.Service)label; 11050 out.print(prefix); out.print( 11051 Integer.toHexString(System.identityHashCode(service))); 11052 out.print(' '); 11053 service.printComponentShortName(out); 11054 if (count > 1) { 11055 out.print(" ("); out.print(count); out.print(" filters)"); 11056 } 11057 out.println(); 11058 } 11059 11060// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11061// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11062// final List<ResolveInfo> retList = Lists.newArrayList(); 11063// while (i.hasNext()) { 11064// final ResolveInfo resolveInfo = (ResolveInfo) i; 11065// if (isEnabledLP(resolveInfo.serviceInfo)) { 11066// retList.add(resolveInfo); 11067// } 11068// } 11069// return retList; 11070// } 11071 11072 // Keys are String (activity class name), values are Activity. 11073 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11074 = new ArrayMap<ComponentName, PackageParser.Service>(); 11075 private int mFlags; 11076 }; 11077 11078 private final class ProviderIntentResolver 11079 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11080 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11081 boolean defaultOnly, int userId) { 11082 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11083 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11084 } 11085 11086 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11087 int userId) { 11088 if (!sUserManager.exists(userId)) 11089 return null; 11090 mFlags = flags; 11091 return super.queryIntent(intent, resolvedType, 11092 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11093 } 11094 11095 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11096 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11097 if (!sUserManager.exists(userId)) 11098 return null; 11099 if (packageProviders == null) { 11100 return null; 11101 } 11102 mFlags = flags; 11103 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11104 final int N = packageProviders.size(); 11105 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11106 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11107 11108 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11109 for (int i = 0; i < N; ++i) { 11110 intentFilters = packageProviders.get(i).intents; 11111 if (intentFilters != null && intentFilters.size() > 0) { 11112 PackageParser.ProviderIntentInfo[] array = 11113 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11114 intentFilters.toArray(array); 11115 listCut.add(array); 11116 } 11117 } 11118 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11119 } 11120 11121 public final void addProvider(PackageParser.Provider p) { 11122 if (mProviders.containsKey(p.getComponentName())) { 11123 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11124 return; 11125 } 11126 11127 mProviders.put(p.getComponentName(), p); 11128 if (DEBUG_SHOW_INFO) { 11129 Log.v(TAG, " " 11130 + (p.info.nonLocalizedLabel != null 11131 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11132 Log.v(TAG, " Class=" + p.info.name); 11133 } 11134 final int NI = p.intents.size(); 11135 int j; 11136 for (j = 0; j < NI; j++) { 11137 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11138 if (DEBUG_SHOW_INFO) { 11139 Log.v(TAG, " IntentFilter:"); 11140 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11141 } 11142 if (!intent.debugCheck()) { 11143 Log.w(TAG, "==> For Provider " + p.info.name); 11144 } 11145 addFilter(intent); 11146 } 11147 } 11148 11149 public final void removeProvider(PackageParser.Provider p) { 11150 mProviders.remove(p.getComponentName()); 11151 if (DEBUG_SHOW_INFO) { 11152 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11153 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11154 Log.v(TAG, " Class=" + p.info.name); 11155 } 11156 final int NI = p.intents.size(); 11157 int j; 11158 for (j = 0; j < NI; j++) { 11159 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11160 if (DEBUG_SHOW_INFO) { 11161 Log.v(TAG, " IntentFilter:"); 11162 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11163 } 11164 removeFilter(intent); 11165 } 11166 } 11167 11168 @Override 11169 protected boolean allowFilterResult( 11170 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11171 ProviderInfo filterPi = filter.provider.info; 11172 for (int i = dest.size() - 1; i >= 0; i--) { 11173 ProviderInfo destPi = dest.get(i).providerInfo; 11174 if (destPi.name == filterPi.name 11175 && destPi.packageName == filterPi.packageName) { 11176 return false; 11177 } 11178 } 11179 return true; 11180 } 11181 11182 @Override 11183 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11184 return new PackageParser.ProviderIntentInfo[size]; 11185 } 11186 11187 @Override 11188 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11189 if (!sUserManager.exists(userId)) 11190 return true; 11191 PackageParser.Package p = filter.provider.owner; 11192 if (p != null) { 11193 PackageSetting ps = (PackageSetting) p.mExtras; 11194 if (ps != null) { 11195 // System apps are never considered stopped for purposes of 11196 // filtering, because there may be no way for the user to 11197 // actually re-launch them. 11198 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11199 && ps.getStopped(userId); 11200 } 11201 } 11202 return false; 11203 } 11204 11205 @Override 11206 protected boolean isPackageForFilter(String packageName, 11207 PackageParser.ProviderIntentInfo info) { 11208 return packageName.equals(info.provider.owner.packageName); 11209 } 11210 11211 @Override 11212 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11213 int match, int userId) { 11214 if (!sUserManager.exists(userId)) 11215 return null; 11216 final PackageParser.ProviderIntentInfo info = filter; 11217 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11218 return null; 11219 } 11220 final PackageParser.Provider provider = info.provider; 11221 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11222 if (ps == null) { 11223 return null; 11224 } 11225 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11226 ps.readUserState(userId), userId); 11227 if (pi == null) { 11228 return null; 11229 } 11230 final ResolveInfo res = new ResolveInfo(); 11231 res.providerInfo = pi; 11232 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11233 res.filter = filter; 11234 } 11235 res.priority = info.getPriority(); 11236 res.preferredOrder = provider.owner.mPreferredOrder; 11237 res.match = match; 11238 res.isDefault = info.hasDefault; 11239 res.labelRes = info.labelRes; 11240 res.nonLocalizedLabel = info.nonLocalizedLabel; 11241 res.icon = info.icon; 11242 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11243 return res; 11244 } 11245 11246 @Override 11247 protected void sortResults(List<ResolveInfo> results) { 11248 Collections.sort(results, mResolvePrioritySorter); 11249 } 11250 11251 @Override 11252 protected void dumpFilter(PrintWriter out, String prefix, 11253 PackageParser.ProviderIntentInfo filter) { 11254 out.print(prefix); 11255 out.print( 11256 Integer.toHexString(System.identityHashCode(filter.provider))); 11257 out.print(' '); 11258 filter.provider.printComponentShortName(out); 11259 out.print(" filter "); 11260 out.println(Integer.toHexString(System.identityHashCode(filter))); 11261 } 11262 11263 @Override 11264 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11265 return filter.provider; 11266 } 11267 11268 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11269 PackageParser.Provider provider = (PackageParser.Provider)label; 11270 out.print(prefix); out.print( 11271 Integer.toHexString(System.identityHashCode(provider))); 11272 out.print(' '); 11273 provider.printComponentShortName(out); 11274 if (count > 1) { 11275 out.print(" ("); out.print(count); out.print(" filters)"); 11276 } 11277 out.println(); 11278 } 11279 11280 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11281 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11282 private int mFlags; 11283 } 11284 11285 private static final class EphemeralIntentResolver 11286 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11287 /** 11288 * The result that has the highest defined order. Ordering applies on a 11289 * per-package basis. Mapping is from package name to Pair of order and 11290 * EphemeralResolveInfo. 11291 * <p> 11292 * NOTE: This is implemented as a field variable for convenience and efficiency. 11293 * By having a field variable, we're able to track filter ordering as soon as 11294 * a non-zero order is defined. Otherwise, multiple loops across the result set 11295 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11296 * this needs to be contained entirely within {@link #filterResults()}. 11297 */ 11298 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11299 11300 @Override 11301 protected EphemeralResolveIntentInfo[] newArray(int size) { 11302 return new EphemeralResolveIntentInfo[size]; 11303 } 11304 11305 @Override 11306 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11307 return true; 11308 } 11309 11310 @Override 11311 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11312 int userId) { 11313 if (!sUserManager.exists(userId)) { 11314 return null; 11315 } 11316 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11317 final Integer order = info.getOrder(); 11318 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11319 mOrderResult.get(packageName); 11320 // ordering is enabled and this item's order isn't high enough 11321 if (lastOrderResult != null && lastOrderResult.first >= order) { 11322 return null; 11323 } 11324 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11325 if (order > 0) { 11326 // non-zero order, enable ordering 11327 mOrderResult.put(packageName, new Pair<>(order, res)); 11328 } 11329 return res; 11330 } 11331 11332 @Override 11333 protected void filterResults(List<EphemeralResolveInfo> results) { 11334 // only do work if ordering is enabled [most of the time it won't be] 11335 if (mOrderResult.size() == 0) { 11336 return; 11337 } 11338 int resultSize = results.size(); 11339 for (int i = 0; i < resultSize; i++) { 11340 final EphemeralResolveInfo info = results.get(i); 11341 final String packageName = info.getPackageName(); 11342 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11343 if (savedInfo == null) { 11344 // package doesn't having ordering 11345 continue; 11346 } 11347 if (savedInfo.second == info) { 11348 // circled back to the highest ordered item; remove from order list 11349 mOrderResult.remove(savedInfo); 11350 if (mOrderResult.size() == 0) { 11351 // no more ordered items 11352 break; 11353 } 11354 continue; 11355 } 11356 // item has a worse order, remove it from the result list 11357 results.remove(i); 11358 resultSize--; 11359 i--; 11360 } 11361 } 11362 } 11363 11364 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11365 new Comparator<ResolveInfo>() { 11366 public int compare(ResolveInfo r1, ResolveInfo r2) { 11367 int v1 = r1.priority; 11368 int v2 = r2.priority; 11369 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11370 if (v1 != v2) { 11371 return (v1 > v2) ? -1 : 1; 11372 } 11373 v1 = r1.preferredOrder; 11374 v2 = r2.preferredOrder; 11375 if (v1 != v2) { 11376 return (v1 > v2) ? -1 : 1; 11377 } 11378 if (r1.isDefault != r2.isDefault) { 11379 return r1.isDefault ? -1 : 1; 11380 } 11381 v1 = r1.match; 11382 v2 = r2.match; 11383 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11384 if (v1 != v2) { 11385 return (v1 > v2) ? -1 : 1; 11386 } 11387 if (r1.system != r2.system) { 11388 return r1.system ? -1 : 1; 11389 } 11390 if (r1.activityInfo != null) { 11391 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11392 } 11393 if (r1.serviceInfo != null) { 11394 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11395 } 11396 if (r1.providerInfo != null) { 11397 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11398 } 11399 return 0; 11400 } 11401 }; 11402 11403 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11404 new Comparator<ProviderInfo>() { 11405 public int compare(ProviderInfo p1, ProviderInfo p2) { 11406 final int v1 = p1.initOrder; 11407 final int v2 = p2.initOrder; 11408 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11409 } 11410 }; 11411 11412 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11413 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11414 final int[] userIds) { 11415 mHandler.post(new Runnable() { 11416 @Override 11417 public void run() { 11418 try { 11419 final IActivityManager am = ActivityManagerNative.getDefault(); 11420 if (am == null) return; 11421 final int[] resolvedUserIds; 11422 if (userIds == null) { 11423 resolvedUserIds = am.getRunningUserIds(); 11424 } else { 11425 resolvedUserIds = userIds; 11426 } 11427 for (int id : resolvedUserIds) { 11428 final Intent intent = new Intent(action, 11429 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11430 if (extras != null) { 11431 intent.putExtras(extras); 11432 } 11433 if (targetPkg != null) { 11434 intent.setPackage(targetPkg); 11435 } 11436 // Modify the UID when posting to other users 11437 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11438 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11439 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11440 intent.putExtra(Intent.EXTRA_UID, uid); 11441 } 11442 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11443 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11444 if (DEBUG_BROADCASTS) { 11445 RuntimeException here = new RuntimeException("here"); 11446 here.fillInStackTrace(); 11447 Slog.d(TAG, "Sending to user " + id + ": " 11448 + intent.toShortString(false, true, false, false) 11449 + " " + intent.getExtras(), here); 11450 } 11451 am.broadcastIntent(null, intent, null, finishedReceiver, 11452 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11453 null, finishedReceiver != null, false, id); 11454 } 11455 } catch (RemoteException ex) { 11456 } 11457 } 11458 }); 11459 } 11460 11461 /** 11462 * Check if the external storage media is available. This is true if there 11463 * is a mounted external storage medium or if the external storage is 11464 * emulated. 11465 */ 11466 private boolean isExternalMediaAvailable() { 11467 return mMediaMounted || Environment.isExternalStorageEmulated(); 11468 } 11469 11470 @Override 11471 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11472 // writer 11473 synchronized (mPackages) { 11474 if (!isExternalMediaAvailable()) { 11475 // If the external storage is no longer mounted at this point, 11476 // the caller may not have been able to delete all of this 11477 // packages files and can not delete any more. Bail. 11478 return null; 11479 } 11480 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11481 if (lastPackage != null) { 11482 pkgs.remove(lastPackage); 11483 } 11484 if (pkgs.size() > 0) { 11485 return pkgs.get(0); 11486 } 11487 } 11488 return null; 11489 } 11490 11491 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11492 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11493 userId, andCode ? 1 : 0, packageName); 11494 if (mSystemReady) { 11495 msg.sendToTarget(); 11496 } else { 11497 if (mPostSystemReadyMessages == null) { 11498 mPostSystemReadyMessages = new ArrayList<>(); 11499 } 11500 mPostSystemReadyMessages.add(msg); 11501 } 11502 } 11503 11504 void startCleaningPackages() { 11505 // reader 11506 if (!isExternalMediaAvailable()) { 11507 return; 11508 } 11509 synchronized (mPackages) { 11510 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11511 return; 11512 } 11513 } 11514 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11515 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11516 IActivityManager am = ActivityManagerNative.getDefault(); 11517 if (am != null) { 11518 try { 11519 am.startService(null, intent, null, mContext.getOpPackageName(), 11520 UserHandle.USER_SYSTEM); 11521 } catch (RemoteException e) { 11522 } 11523 } 11524 } 11525 11526 @Override 11527 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11528 int installFlags, String installerPackageName, int userId) { 11529 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11530 11531 final int callingUid = Binder.getCallingUid(); 11532 enforceCrossUserPermission(callingUid, userId, 11533 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11534 11535 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11536 try { 11537 if (observer != null) { 11538 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11539 } 11540 } catch (RemoteException re) { 11541 } 11542 return; 11543 } 11544 11545 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11546 installFlags |= PackageManager.INSTALL_FROM_ADB; 11547 11548 } else { 11549 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11550 // about installerPackageName. 11551 11552 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11553 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11554 } 11555 11556 UserHandle user; 11557 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11558 user = UserHandle.ALL; 11559 } else { 11560 user = new UserHandle(userId); 11561 } 11562 11563 // Only system components can circumvent runtime permissions when installing. 11564 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11565 && mContext.checkCallingOrSelfPermission(Manifest.permission 11566 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11567 throw new SecurityException("You need the " 11568 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11569 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11570 } 11571 11572 final File originFile = new File(originPath); 11573 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11574 11575 final Message msg = mHandler.obtainMessage(INIT_COPY); 11576 final VerificationInfo verificationInfo = new VerificationInfo( 11577 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11578 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11579 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11580 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11581 null /*certificates*/); 11582 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11583 msg.obj = params; 11584 11585 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11586 System.identityHashCode(msg.obj)); 11587 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11588 System.identityHashCode(msg.obj)); 11589 11590 mHandler.sendMessage(msg); 11591 } 11592 11593 void installStage(String packageName, File stagedDir, String stagedCid, 11594 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11595 String installerPackageName, int installerUid, UserHandle user, 11596 Certificate[][] certificates) { 11597 if (DEBUG_EPHEMERAL) { 11598 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11599 Slog.d(TAG, "Ephemeral install of " + packageName); 11600 } 11601 } 11602 final VerificationInfo verificationInfo = new VerificationInfo( 11603 sessionParams.originatingUri, sessionParams.referrerUri, 11604 sessionParams.originatingUid, installerUid); 11605 11606 final OriginInfo origin; 11607 if (stagedDir != null) { 11608 origin = OriginInfo.fromStagedFile(stagedDir); 11609 } else { 11610 origin = OriginInfo.fromStagedContainer(stagedCid); 11611 } 11612 11613 final Message msg = mHandler.obtainMessage(INIT_COPY); 11614 final InstallParams params = new InstallParams(origin, null, observer, 11615 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11616 verificationInfo, user, sessionParams.abiOverride, 11617 sessionParams.grantedRuntimePermissions, certificates); 11618 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11619 msg.obj = params; 11620 11621 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11622 System.identityHashCode(msg.obj)); 11623 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11624 System.identityHashCode(msg.obj)); 11625 11626 mHandler.sendMessage(msg); 11627 } 11628 11629 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11630 int userId) { 11631 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11632 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11633 } 11634 11635 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11636 int appId, int userId) { 11637 Bundle extras = new Bundle(1); 11638 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11639 11640 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11641 packageName, extras, 0, null, null, new int[] {userId}); 11642 try { 11643 IActivityManager am = ActivityManagerNative.getDefault(); 11644 if (isSystem && am.isUserRunning(userId, 0)) { 11645 // The just-installed/enabled app is bundled on the system, so presumed 11646 // to be able to run automatically without needing an explicit launch. 11647 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11648 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11649 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11650 .setPackage(packageName); 11651 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11652 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11653 } 11654 } catch (RemoteException e) { 11655 // shouldn't happen 11656 Slog.w(TAG, "Unable to bootstrap installed package", e); 11657 } 11658 } 11659 11660 @Override 11661 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11662 int userId) { 11663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11664 PackageSetting pkgSetting; 11665 final int uid = Binder.getCallingUid(); 11666 enforceCrossUserPermission(uid, userId, 11667 true /* requireFullPermission */, true /* checkShell */, 11668 "setApplicationHiddenSetting for user " + userId); 11669 11670 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11671 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11672 return false; 11673 } 11674 11675 long callingId = Binder.clearCallingIdentity(); 11676 try { 11677 boolean sendAdded = false; 11678 boolean sendRemoved = false; 11679 // writer 11680 synchronized (mPackages) { 11681 pkgSetting = mSettings.mPackages.get(packageName); 11682 if (pkgSetting == null) { 11683 return false; 11684 } 11685 // Do not allow "android" is being disabled 11686 if ("android".equals(packageName)) { 11687 Slog.w(TAG, "Cannot hide package: android"); 11688 return false; 11689 } 11690 // Only allow protected packages to hide themselves. 11691 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11692 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11693 Slog.w(TAG, "Not hiding protected package: " + packageName); 11694 return false; 11695 } 11696 11697 if (pkgSetting.getHidden(userId) != hidden) { 11698 pkgSetting.setHidden(hidden, userId); 11699 mSettings.writePackageRestrictionsLPr(userId); 11700 if (hidden) { 11701 sendRemoved = true; 11702 } else { 11703 sendAdded = true; 11704 } 11705 } 11706 } 11707 if (sendAdded) { 11708 sendPackageAddedForUser(packageName, pkgSetting, userId); 11709 return true; 11710 } 11711 if (sendRemoved) { 11712 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11713 "hiding pkg"); 11714 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11715 return true; 11716 } 11717 } finally { 11718 Binder.restoreCallingIdentity(callingId); 11719 } 11720 return false; 11721 } 11722 11723 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11724 int userId) { 11725 final PackageRemovedInfo info = new PackageRemovedInfo(); 11726 info.removedPackage = packageName; 11727 info.removedUsers = new int[] {userId}; 11728 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11729 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11730 } 11731 11732 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11733 if (pkgList.length > 0) { 11734 Bundle extras = new Bundle(1); 11735 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11736 11737 sendPackageBroadcast( 11738 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11739 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11740 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11741 new int[] {userId}); 11742 } 11743 } 11744 11745 /** 11746 * Returns true if application is not found or there was an error. Otherwise it returns 11747 * the hidden state of the package for the given user. 11748 */ 11749 @Override 11750 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11751 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11752 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11753 true /* requireFullPermission */, false /* checkShell */, 11754 "getApplicationHidden for user " + userId); 11755 PackageSetting pkgSetting; 11756 long callingId = Binder.clearCallingIdentity(); 11757 try { 11758 // writer 11759 synchronized (mPackages) { 11760 pkgSetting = mSettings.mPackages.get(packageName); 11761 if (pkgSetting == null) { 11762 return true; 11763 } 11764 return pkgSetting.getHidden(userId); 11765 } 11766 } finally { 11767 Binder.restoreCallingIdentity(callingId); 11768 } 11769 } 11770 11771 /** 11772 * @hide 11773 */ 11774 @Override 11775 public int installExistingPackageAsUser(String packageName, int userId) { 11776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11777 null); 11778 PackageSetting pkgSetting; 11779 final int uid = Binder.getCallingUid(); 11780 enforceCrossUserPermission(uid, userId, 11781 true /* requireFullPermission */, true /* checkShell */, 11782 "installExistingPackage for user " + userId); 11783 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11784 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11785 } 11786 11787 long callingId = Binder.clearCallingIdentity(); 11788 try { 11789 boolean installed = false; 11790 11791 // writer 11792 synchronized (mPackages) { 11793 pkgSetting = mSettings.mPackages.get(packageName); 11794 if (pkgSetting == null) { 11795 return PackageManager.INSTALL_FAILED_INVALID_URI; 11796 } 11797 if (!pkgSetting.getInstalled(userId)) { 11798 pkgSetting.setInstalled(true, userId); 11799 pkgSetting.setHidden(false, userId); 11800 mSettings.writePackageRestrictionsLPr(userId); 11801 installed = true; 11802 } 11803 } 11804 11805 if (installed) { 11806 if (pkgSetting.pkg != null) { 11807 synchronized (mInstallLock) { 11808 // We don't need to freeze for a brand new install 11809 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11810 } 11811 } 11812 sendPackageAddedForUser(packageName, pkgSetting, userId); 11813 } 11814 } finally { 11815 Binder.restoreCallingIdentity(callingId); 11816 } 11817 11818 return PackageManager.INSTALL_SUCCEEDED; 11819 } 11820 11821 boolean isUserRestricted(int userId, String restrictionKey) { 11822 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11823 if (restrictions.getBoolean(restrictionKey, false)) { 11824 Log.w(TAG, "User is restricted: " + restrictionKey); 11825 return true; 11826 } 11827 return false; 11828 } 11829 11830 @Override 11831 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11832 int userId) { 11833 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11834 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11835 true /* requireFullPermission */, true /* checkShell */, 11836 "setPackagesSuspended for user " + userId); 11837 11838 if (ArrayUtils.isEmpty(packageNames)) { 11839 return packageNames; 11840 } 11841 11842 // List of package names for whom the suspended state has changed. 11843 List<String> changedPackages = new ArrayList<>(packageNames.length); 11844 // List of package names for whom the suspended state is not set as requested in this 11845 // method. 11846 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11847 long callingId = Binder.clearCallingIdentity(); 11848 try { 11849 for (int i = 0; i < packageNames.length; i++) { 11850 String packageName = packageNames[i]; 11851 boolean changed = false; 11852 final int appId; 11853 synchronized (mPackages) { 11854 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11855 if (pkgSetting == null) { 11856 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11857 + "\". Skipping suspending/un-suspending."); 11858 unactionedPackages.add(packageName); 11859 continue; 11860 } 11861 appId = pkgSetting.appId; 11862 if (pkgSetting.getSuspended(userId) != suspended) { 11863 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11864 unactionedPackages.add(packageName); 11865 continue; 11866 } 11867 pkgSetting.setSuspended(suspended, userId); 11868 mSettings.writePackageRestrictionsLPr(userId); 11869 changed = true; 11870 changedPackages.add(packageName); 11871 } 11872 } 11873 11874 if (changed && suspended) { 11875 killApplication(packageName, UserHandle.getUid(userId, appId), 11876 "suspending package"); 11877 } 11878 } 11879 } finally { 11880 Binder.restoreCallingIdentity(callingId); 11881 } 11882 11883 if (!changedPackages.isEmpty()) { 11884 sendPackagesSuspendedForUser(changedPackages.toArray( 11885 new String[changedPackages.size()]), userId, suspended); 11886 } 11887 11888 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11889 } 11890 11891 @Override 11892 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11893 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11894 true /* requireFullPermission */, false /* checkShell */, 11895 "isPackageSuspendedForUser for user " + userId); 11896 synchronized (mPackages) { 11897 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11898 if (pkgSetting == null) { 11899 throw new IllegalArgumentException("Unknown target package: " + packageName); 11900 } 11901 return pkgSetting.getSuspended(userId); 11902 } 11903 } 11904 11905 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11906 if (isPackageDeviceAdmin(packageName, userId)) { 11907 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11908 + "\": has an active device admin"); 11909 return false; 11910 } 11911 11912 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11913 if (packageName.equals(activeLauncherPackageName)) { 11914 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11915 + "\": contains the active launcher"); 11916 return false; 11917 } 11918 11919 if (packageName.equals(mRequiredInstallerPackage)) { 11920 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11921 + "\": required for package installation"); 11922 return false; 11923 } 11924 11925 if (packageName.equals(mRequiredUninstallerPackage)) { 11926 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11927 + "\": required for package uninstallation"); 11928 return false; 11929 } 11930 11931 if (packageName.equals(mRequiredVerifierPackage)) { 11932 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11933 + "\": required for package verification"); 11934 return false; 11935 } 11936 11937 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11938 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11939 + "\": is the default dialer"); 11940 return false; 11941 } 11942 11943 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11944 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11945 + "\": protected package"); 11946 return false; 11947 } 11948 11949 return true; 11950 } 11951 11952 private String getActiveLauncherPackageName(int userId) { 11953 Intent intent = new Intent(Intent.ACTION_MAIN); 11954 intent.addCategory(Intent.CATEGORY_HOME); 11955 ResolveInfo resolveInfo = resolveIntent( 11956 intent, 11957 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11958 PackageManager.MATCH_DEFAULT_ONLY, 11959 userId); 11960 11961 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11962 } 11963 11964 private String getDefaultDialerPackageName(int userId) { 11965 synchronized (mPackages) { 11966 return mSettings.getDefaultDialerPackageNameLPw(userId); 11967 } 11968 } 11969 11970 @Override 11971 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11972 mContext.enforceCallingOrSelfPermission( 11973 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11974 "Only package verification agents can verify applications"); 11975 11976 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11977 final PackageVerificationResponse response = new PackageVerificationResponse( 11978 verificationCode, Binder.getCallingUid()); 11979 msg.arg1 = id; 11980 msg.obj = response; 11981 mHandler.sendMessage(msg); 11982 } 11983 11984 @Override 11985 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11986 long millisecondsToDelay) { 11987 mContext.enforceCallingOrSelfPermission( 11988 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11989 "Only package verification agents can extend verification timeouts"); 11990 11991 final PackageVerificationState state = mPendingVerification.get(id); 11992 final PackageVerificationResponse response = new PackageVerificationResponse( 11993 verificationCodeAtTimeout, Binder.getCallingUid()); 11994 11995 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11996 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11997 } 11998 if (millisecondsToDelay < 0) { 11999 millisecondsToDelay = 0; 12000 } 12001 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12002 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12003 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12004 } 12005 12006 if ((state != null) && !state.timeoutExtended()) { 12007 state.extendTimeout(); 12008 12009 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12010 msg.arg1 = id; 12011 msg.obj = response; 12012 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12013 } 12014 } 12015 12016 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12017 int verificationCode, UserHandle user) { 12018 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12019 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12020 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12022 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12023 12024 mContext.sendBroadcastAsUser(intent, user, 12025 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12026 } 12027 12028 private ComponentName matchComponentForVerifier(String packageName, 12029 List<ResolveInfo> receivers) { 12030 ActivityInfo targetReceiver = null; 12031 12032 final int NR = receivers.size(); 12033 for (int i = 0; i < NR; i++) { 12034 final ResolveInfo info = receivers.get(i); 12035 if (info.activityInfo == null) { 12036 continue; 12037 } 12038 12039 if (packageName.equals(info.activityInfo.packageName)) { 12040 targetReceiver = info.activityInfo; 12041 break; 12042 } 12043 } 12044 12045 if (targetReceiver == null) { 12046 return null; 12047 } 12048 12049 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12050 } 12051 12052 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12053 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12054 if (pkgInfo.verifiers.length == 0) { 12055 return null; 12056 } 12057 12058 final int N = pkgInfo.verifiers.length; 12059 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12060 for (int i = 0; i < N; i++) { 12061 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12062 12063 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12064 receivers); 12065 if (comp == null) { 12066 continue; 12067 } 12068 12069 final int verifierUid = getUidForVerifier(verifierInfo); 12070 if (verifierUid == -1) { 12071 continue; 12072 } 12073 12074 if (DEBUG_VERIFY) { 12075 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12076 + " with the correct signature"); 12077 } 12078 sufficientVerifiers.add(comp); 12079 verificationState.addSufficientVerifier(verifierUid); 12080 } 12081 12082 return sufficientVerifiers; 12083 } 12084 12085 private int getUidForVerifier(VerifierInfo verifierInfo) { 12086 synchronized (mPackages) { 12087 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12088 if (pkg == null) { 12089 return -1; 12090 } else if (pkg.mSignatures.length != 1) { 12091 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12092 + " has more than one signature; ignoring"); 12093 return -1; 12094 } 12095 12096 /* 12097 * If the public key of the package's signature does not match 12098 * our expected public key, then this is a different package and 12099 * we should skip. 12100 */ 12101 12102 final byte[] expectedPublicKey; 12103 try { 12104 final Signature verifierSig = pkg.mSignatures[0]; 12105 final PublicKey publicKey = verifierSig.getPublicKey(); 12106 expectedPublicKey = publicKey.getEncoded(); 12107 } catch (CertificateException e) { 12108 return -1; 12109 } 12110 12111 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12112 12113 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12114 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12115 + " does not have the expected public key; ignoring"); 12116 return -1; 12117 } 12118 12119 return pkg.applicationInfo.uid; 12120 } 12121 } 12122 12123 @Override 12124 public void finishPackageInstall(int token, boolean didLaunch) { 12125 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12126 12127 if (DEBUG_INSTALL) { 12128 Slog.v(TAG, "BM finishing package install for " + token); 12129 } 12130 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12131 12132 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12133 mHandler.sendMessage(msg); 12134 } 12135 12136 /** 12137 * Get the verification agent timeout. 12138 * 12139 * @return verification timeout in milliseconds 12140 */ 12141 private long getVerificationTimeout() { 12142 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12143 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12144 DEFAULT_VERIFICATION_TIMEOUT); 12145 } 12146 12147 /** 12148 * Get the default verification agent response code. 12149 * 12150 * @return default verification response code 12151 */ 12152 private int getDefaultVerificationResponse() { 12153 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12154 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12155 DEFAULT_VERIFICATION_RESPONSE); 12156 } 12157 12158 /** 12159 * Check whether or not package verification has been enabled. 12160 * 12161 * @return true if verification should be performed 12162 */ 12163 private boolean isVerificationEnabled(int userId, int installFlags) { 12164 if (!DEFAULT_VERIFY_ENABLE) { 12165 return false; 12166 } 12167 // Ephemeral apps don't get the full verification treatment 12168 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12169 if (DEBUG_EPHEMERAL) { 12170 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12171 } 12172 return false; 12173 } 12174 12175 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12176 12177 // Check if installing from ADB 12178 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12179 // Do not run verification in a test harness environment 12180 if (ActivityManager.isRunningInTestHarness()) { 12181 return false; 12182 } 12183 if (ensureVerifyAppsEnabled) { 12184 return true; 12185 } 12186 // Check if the developer does not want package verification for ADB installs 12187 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12188 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12189 return false; 12190 } 12191 } 12192 12193 if (ensureVerifyAppsEnabled) { 12194 return true; 12195 } 12196 12197 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12198 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12199 } 12200 12201 @Override 12202 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12203 throws RemoteException { 12204 mContext.enforceCallingOrSelfPermission( 12205 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12206 "Only intentfilter verification agents can verify applications"); 12207 12208 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12209 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12210 Binder.getCallingUid(), verificationCode, failedDomains); 12211 msg.arg1 = id; 12212 msg.obj = response; 12213 mHandler.sendMessage(msg); 12214 } 12215 12216 @Override 12217 public int getIntentVerificationStatus(String packageName, int userId) { 12218 synchronized (mPackages) { 12219 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12220 } 12221 } 12222 12223 @Override 12224 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12225 mContext.enforceCallingOrSelfPermission( 12226 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12227 12228 boolean result = false; 12229 synchronized (mPackages) { 12230 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12231 } 12232 if (result) { 12233 scheduleWritePackageRestrictionsLocked(userId); 12234 } 12235 return result; 12236 } 12237 12238 @Override 12239 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12240 String packageName) { 12241 synchronized (mPackages) { 12242 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12243 } 12244 } 12245 12246 @Override 12247 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12248 if (TextUtils.isEmpty(packageName)) { 12249 return ParceledListSlice.emptyList(); 12250 } 12251 synchronized (mPackages) { 12252 PackageParser.Package pkg = mPackages.get(packageName); 12253 if (pkg == null || pkg.activities == null) { 12254 return ParceledListSlice.emptyList(); 12255 } 12256 final int count = pkg.activities.size(); 12257 ArrayList<IntentFilter> result = new ArrayList<>(); 12258 for (int n=0; n<count; n++) { 12259 PackageParser.Activity activity = pkg.activities.get(n); 12260 if (activity.intents != null && activity.intents.size() > 0) { 12261 result.addAll(activity.intents); 12262 } 12263 } 12264 return new ParceledListSlice<>(result); 12265 } 12266 } 12267 12268 @Override 12269 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12270 mContext.enforceCallingOrSelfPermission( 12271 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12272 12273 synchronized (mPackages) { 12274 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12275 if (packageName != null) { 12276 result |= updateIntentVerificationStatus(packageName, 12277 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12278 userId); 12279 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12280 packageName, userId); 12281 } 12282 return result; 12283 } 12284 } 12285 12286 @Override 12287 public String getDefaultBrowserPackageName(int userId) { 12288 synchronized (mPackages) { 12289 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12290 } 12291 } 12292 12293 /** 12294 * Get the "allow unknown sources" setting. 12295 * 12296 * @return the current "allow unknown sources" setting 12297 */ 12298 private int getUnknownSourcesSettings() { 12299 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12300 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12301 -1); 12302 } 12303 12304 @Override 12305 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12306 final int uid = Binder.getCallingUid(); 12307 // writer 12308 synchronized (mPackages) { 12309 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12310 if (targetPackageSetting == null) { 12311 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12312 } 12313 12314 PackageSetting installerPackageSetting; 12315 if (installerPackageName != null) { 12316 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12317 if (installerPackageSetting == null) { 12318 throw new IllegalArgumentException("Unknown installer package: " 12319 + installerPackageName); 12320 } 12321 } else { 12322 installerPackageSetting = null; 12323 } 12324 12325 Signature[] callerSignature; 12326 Object obj = mSettings.getUserIdLPr(uid); 12327 if (obj != null) { 12328 if (obj instanceof SharedUserSetting) { 12329 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12330 } else if (obj instanceof PackageSetting) { 12331 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12332 } else { 12333 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12334 } 12335 } else { 12336 throw new SecurityException("Unknown calling UID: " + uid); 12337 } 12338 12339 // Verify: can't set installerPackageName to a package that is 12340 // not signed with the same cert as the caller. 12341 if (installerPackageSetting != null) { 12342 if (compareSignatures(callerSignature, 12343 installerPackageSetting.signatures.mSignatures) 12344 != PackageManager.SIGNATURE_MATCH) { 12345 throw new SecurityException( 12346 "Caller does not have same cert as new installer package " 12347 + installerPackageName); 12348 } 12349 } 12350 12351 // Verify: if target already has an installer package, it must 12352 // be signed with the same cert as the caller. 12353 if (targetPackageSetting.installerPackageName != null) { 12354 PackageSetting setting = mSettings.mPackages.get( 12355 targetPackageSetting.installerPackageName); 12356 // If the currently set package isn't valid, then it's always 12357 // okay to change it. 12358 if (setting != null) { 12359 if (compareSignatures(callerSignature, 12360 setting.signatures.mSignatures) 12361 != PackageManager.SIGNATURE_MATCH) { 12362 throw new SecurityException( 12363 "Caller does not have same cert as old installer package " 12364 + targetPackageSetting.installerPackageName); 12365 } 12366 } 12367 } 12368 12369 // Okay! 12370 targetPackageSetting.installerPackageName = installerPackageName; 12371 if (installerPackageName != null) { 12372 mSettings.mInstallerPackages.add(installerPackageName); 12373 } 12374 scheduleWriteSettingsLocked(); 12375 } 12376 } 12377 12378 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12379 // Queue up an async operation since the package installation may take a little while. 12380 mHandler.post(new Runnable() { 12381 public void run() { 12382 mHandler.removeCallbacks(this); 12383 // Result object to be returned 12384 PackageInstalledInfo res = new PackageInstalledInfo(); 12385 res.setReturnCode(currentStatus); 12386 res.uid = -1; 12387 res.pkg = null; 12388 res.removedInfo = null; 12389 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12390 args.doPreInstall(res.returnCode); 12391 synchronized (mInstallLock) { 12392 installPackageTracedLI(args, res); 12393 } 12394 args.doPostInstall(res.returnCode, res.uid); 12395 } 12396 12397 // A restore should be performed at this point if (a) the install 12398 // succeeded, (b) the operation is not an update, and (c) the new 12399 // package has not opted out of backup participation. 12400 final boolean update = res.removedInfo != null 12401 && res.removedInfo.removedPackage != null; 12402 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12403 boolean doRestore = !update 12404 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12405 12406 // Set up the post-install work request bookkeeping. This will be used 12407 // and cleaned up by the post-install event handling regardless of whether 12408 // there's a restore pass performed. Token values are >= 1. 12409 int token; 12410 if (mNextInstallToken < 0) mNextInstallToken = 1; 12411 token = mNextInstallToken++; 12412 12413 PostInstallData data = new PostInstallData(args, res); 12414 mRunningInstalls.put(token, data); 12415 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12416 12417 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12418 // Pass responsibility to the Backup Manager. It will perform a 12419 // restore if appropriate, then pass responsibility back to the 12420 // Package Manager to run the post-install observer callbacks 12421 // and broadcasts. 12422 IBackupManager bm = IBackupManager.Stub.asInterface( 12423 ServiceManager.getService(Context.BACKUP_SERVICE)); 12424 if (bm != null) { 12425 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12426 + " to BM for possible restore"); 12427 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12428 try { 12429 // TODO: http://b/22388012 12430 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12431 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12432 } else { 12433 doRestore = false; 12434 } 12435 } catch (RemoteException e) { 12436 // can't happen; the backup manager is local 12437 } catch (Exception e) { 12438 Slog.e(TAG, "Exception trying to enqueue restore", e); 12439 doRestore = false; 12440 } 12441 } else { 12442 Slog.e(TAG, "Backup Manager not found!"); 12443 doRestore = false; 12444 } 12445 } 12446 12447 if (!doRestore) { 12448 // No restore possible, or the Backup Manager was mysteriously not 12449 // available -- just fire the post-install work request directly. 12450 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12451 12452 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12453 12454 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12455 mHandler.sendMessage(msg); 12456 } 12457 } 12458 }); 12459 } 12460 12461 /** 12462 * Callback from PackageSettings whenever an app is first transitioned out of the 12463 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12464 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12465 * here whether the app is the target of an ongoing install, and only send the 12466 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12467 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12468 * handling. 12469 */ 12470 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12471 // Serialize this with the rest of the install-process message chain. In the 12472 // restore-at-install case, this Runnable will necessarily run before the 12473 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12474 // are coherent. In the non-restore case, the app has already completed install 12475 // and been launched through some other means, so it is not in a problematic 12476 // state for observers to see the FIRST_LAUNCH signal. 12477 mHandler.post(new Runnable() { 12478 @Override 12479 public void run() { 12480 for (int i = 0; i < mRunningInstalls.size(); i++) { 12481 final PostInstallData data = mRunningInstalls.valueAt(i); 12482 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12483 continue; 12484 } 12485 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12486 // right package; but is it for the right user? 12487 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12488 if (userId == data.res.newUsers[uIndex]) { 12489 if (DEBUG_BACKUP) { 12490 Slog.i(TAG, "Package " + pkgName 12491 + " being restored so deferring FIRST_LAUNCH"); 12492 } 12493 return; 12494 } 12495 } 12496 } 12497 } 12498 // didn't find it, so not being restored 12499 if (DEBUG_BACKUP) { 12500 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12501 } 12502 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12503 } 12504 }); 12505 } 12506 12507 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12508 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12509 installerPkg, null, userIds); 12510 } 12511 12512 private abstract class HandlerParams { 12513 private static final int MAX_RETRIES = 4; 12514 12515 /** 12516 * Number of times startCopy() has been attempted and had a non-fatal 12517 * error. 12518 */ 12519 private int mRetries = 0; 12520 12521 /** User handle for the user requesting the information or installation. */ 12522 private final UserHandle mUser; 12523 String traceMethod; 12524 int traceCookie; 12525 12526 HandlerParams(UserHandle user) { 12527 mUser = user; 12528 } 12529 12530 UserHandle getUser() { 12531 return mUser; 12532 } 12533 12534 HandlerParams setTraceMethod(String traceMethod) { 12535 this.traceMethod = traceMethod; 12536 return this; 12537 } 12538 12539 HandlerParams setTraceCookie(int traceCookie) { 12540 this.traceCookie = traceCookie; 12541 return this; 12542 } 12543 12544 final boolean startCopy() { 12545 boolean res; 12546 try { 12547 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12548 12549 if (++mRetries > MAX_RETRIES) { 12550 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12551 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12552 handleServiceError(); 12553 return false; 12554 } else { 12555 handleStartCopy(); 12556 res = true; 12557 } 12558 } catch (RemoteException e) { 12559 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12560 mHandler.sendEmptyMessage(MCS_RECONNECT); 12561 res = false; 12562 } 12563 handleReturnCode(); 12564 return res; 12565 } 12566 12567 final void serviceError() { 12568 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12569 handleServiceError(); 12570 handleReturnCode(); 12571 } 12572 12573 abstract void handleStartCopy() throws RemoteException; 12574 abstract void handleServiceError(); 12575 abstract void handleReturnCode(); 12576 } 12577 12578 class MeasureParams extends HandlerParams { 12579 private final PackageStats mStats; 12580 private boolean mSuccess; 12581 12582 private final IPackageStatsObserver mObserver; 12583 12584 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12585 super(new UserHandle(stats.userHandle)); 12586 mObserver = observer; 12587 mStats = stats; 12588 } 12589 12590 @Override 12591 public String toString() { 12592 return "MeasureParams{" 12593 + Integer.toHexString(System.identityHashCode(this)) 12594 + " " + mStats.packageName + "}"; 12595 } 12596 12597 @Override 12598 void handleStartCopy() throws RemoteException { 12599 synchronized (mInstallLock) { 12600 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12601 } 12602 12603 if (mSuccess) { 12604 boolean mounted = false; 12605 try { 12606 final String status = Environment.getExternalStorageState(); 12607 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12608 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12609 } catch (Exception e) { 12610 } 12611 12612 if (mounted) { 12613 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12614 12615 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12616 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12617 12618 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12619 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12620 12621 // Always subtract cache size, since it's a subdirectory 12622 mStats.externalDataSize -= mStats.externalCacheSize; 12623 12624 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12625 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12626 12627 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12628 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12629 } 12630 } 12631 } 12632 12633 @Override 12634 void handleReturnCode() { 12635 if (mObserver != null) { 12636 try { 12637 mObserver.onGetStatsCompleted(mStats, mSuccess); 12638 } catch (RemoteException e) { 12639 Slog.i(TAG, "Observer no longer exists."); 12640 } 12641 } 12642 } 12643 12644 @Override 12645 void handleServiceError() { 12646 Slog.e(TAG, "Could not measure application " + mStats.packageName 12647 + " external storage"); 12648 } 12649 } 12650 12651 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12652 throws RemoteException { 12653 long result = 0; 12654 for (File path : paths) { 12655 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12656 } 12657 return result; 12658 } 12659 12660 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12661 for (File path : paths) { 12662 try { 12663 mcs.clearDirectory(path.getAbsolutePath()); 12664 } catch (RemoteException e) { 12665 } 12666 } 12667 } 12668 12669 static class OriginInfo { 12670 /** 12671 * Location where install is coming from, before it has been 12672 * copied/renamed into place. This could be a single monolithic APK 12673 * file, or a cluster directory. This location may be untrusted. 12674 */ 12675 final File file; 12676 final String cid; 12677 12678 /** 12679 * Flag indicating that {@link #file} or {@link #cid} has already been 12680 * staged, meaning downstream users don't need to defensively copy the 12681 * contents. 12682 */ 12683 final boolean staged; 12684 12685 /** 12686 * Flag indicating that {@link #file} or {@link #cid} is an already 12687 * installed app that is being moved. 12688 */ 12689 final boolean existing; 12690 12691 final String resolvedPath; 12692 final File resolvedFile; 12693 12694 static OriginInfo fromNothing() { 12695 return new OriginInfo(null, null, false, false); 12696 } 12697 12698 static OriginInfo fromUntrustedFile(File file) { 12699 return new OriginInfo(file, null, false, false); 12700 } 12701 12702 static OriginInfo fromExistingFile(File file) { 12703 return new OriginInfo(file, null, false, true); 12704 } 12705 12706 static OriginInfo fromStagedFile(File file) { 12707 return new OriginInfo(file, null, true, false); 12708 } 12709 12710 static OriginInfo fromStagedContainer(String cid) { 12711 return new OriginInfo(null, cid, true, false); 12712 } 12713 12714 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12715 this.file = file; 12716 this.cid = cid; 12717 this.staged = staged; 12718 this.existing = existing; 12719 12720 if (cid != null) { 12721 resolvedPath = PackageHelper.getSdDir(cid); 12722 resolvedFile = new File(resolvedPath); 12723 } else if (file != null) { 12724 resolvedPath = file.getAbsolutePath(); 12725 resolvedFile = file; 12726 } else { 12727 resolvedPath = null; 12728 resolvedFile = null; 12729 } 12730 } 12731 } 12732 12733 static class MoveInfo { 12734 final int moveId; 12735 final String fromUuid; 12736 final String toUuid; 12737 final String packageName; 12738 final String dataAppName; 12739 final int appId; 12740 final String seinfo; 12741 final int targetSdkVersion; 12742 12743 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12744 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12745 this.moveId = moveId; 12746 this.fromUuid = fromUuid; 12747 this.toUuid = toUuid; 12748 this.packageName = packageName; 12749 this.dataAppName = dataAppName; 12750 this.appId = appId; 12751 this.seinfo = seinfo; 12752 this.targetSdkVersion = targetSdkVersion; 12753 } 12754 } 12755 12756 static class VerificationInfo { 12757 /** A constant used to indicate that a uid value is not present. */ 12758 public static final int NO_UID = -1; 12759 12760 /** URI referencing where the package was downloaded from. */ 12761 final Uri originatingUri; 12762 12763 /** HTTP referrer URI associated with the originatingURI. */ 12764 final Uri referrer; 12765 12766 /** UID of the application that the install request originated from. */ 12767 final int originatingUid; 12768 12769 /** UID of application requesting the install */ 12770 final int installerUid; 12771 12772 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12773 this.originatingUri = originatingUri; 12774 this.referrer = referrer; 12775 this.originatingUid = originatingUid; 12776 this.installerUid = installerUid; 12777 } 12778 } 12779 12780 class InstallParams extends HandlerParams { 12781 final OriginInfo origin; 12782 final MoveInfo move; 12783 final IPackageInstallObserver2 observer; 12784 int installFlags; 12785 final String installerPackageName; 12786 final String volumeUuid; 12787 private InstallArgs mArgs; 12788 private int mRet; 12789 final String packageAbiOverride; 12790 final String[] grantedRuntimePermissions; 12791 final VerificationInfo verificationInfo; 12792 final Certificate[][] certificates; 12793 12794 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12795 int installFlags, String installerPackageName, String volumeUuid, 12796 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12797 String[] grantedPermissions, Certificate[][] certificates) { 12798 super(user); 12799 this.origin = origin; 12800 this.move = move; 12801 this.observer = observer; 12802 this.installFlags = installFlags; 12803 this.installerPackageName = installerPackageName; 12804 this.volumeUuid = volumeUuid; 12805 this.verificationInfo = verificationInfo; 12806 this.packageAbiOverride = packageAbiOverride; 12807 this.grantedRuntimePermissions = grantedPermissions; 12808 this.certificates = certificates; 12809 } 12810 12811 @Override 12812 public String toString() { 12813 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12814 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12815 } 12816 12817 private int installLocationPolicy(PackageInfoLite pkgLite) { 12818 String packageName = pkgLite.packageName; 12819 int installLocation = pkgLite.installLocation; 12820 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12821 // reader 12822 synchronized (mPackages) { 12823 // Currently installed package which the new package is attempting to replace or 12824 // null if no such package is installed. 12825 PackageParser.Package installedPkg = mPackages.get(packageName); 12826 // Package which currently owns the data which the new package will own if installed. 12827 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12828 // will be null whereas dataOwnerPkg will contain information about the package 12829 // which was uninstalled while keeping its data. 12830 PackageParser.Package dataOwnerPkg = installedPkg; 12831 if (dataOwnerPkg == null) { 12832 PackageSetting ps = mSettings.mPackages.get(packageName); 12833 if (ps != null) { 12834 dataOwnerPkg = ps.pkg; 12835 } 12836 } 12837 12838 if (dataOwnerPkg != null) { 12839 // If installed, the package will get access to data left on the device by its 12840 // predecessor. As a security measure, this is permited only if this is not a 12841 // version downgrade or if the predecessor package is marked as debuggable and 12842 // a downgrade is explicitly requested. 12843 // 12844 // On debuggable platform builds, downgrades are permitted even for 12845 // non-debuggable packages to make testing easier. Debuggable platform builds do 12846 // not offer security guarantees and thus it's OK to disable some security 12847 // mechanisms to make debugging/testing easier on those builds. However, even on 12848 // debuggable builds downgrades of packages are permitted only if requested via 12849 // installFlags. This is because we aim to keep the behavior of debuggable 12850 // platform builds as close as possible to the behavior of non-debuggable 12851 // platform builds. 12852 final boolean downgradeRequested = 12853 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12854 final boolean packageDebuggable = 12855 (dataOwnerPkg.applicationInfo.flags 12856 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12857 final boolean downgradePermitted = 12858 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12859 if (!downgradePermitted) { 12860 try { 12861 checkDowngrade(dataOwnerPkg, pkgLite); 12862 } catch (PackageManagerException e) { 12863 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12864 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12865 } 12866 } 12867 } 12868 12869 if (installedPkg != null) { 12870 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12871 // Check for updated system application. 12872 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12873 if (onSd) { 12874 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12875 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12876 } 12877 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12878 } else { 12879 if (onSd) { 12880 // Install flag overrides everything. 12881 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12882 } 12883 // If current upgrade specifies particular preference 12884 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12885 // Application explicitly specified internal. 12886 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12887 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12888 // App explictly prefers external. Let policy decide 12889 } else { 12890 // Prefer previous location 12891 if (isExternal(installedPkg)) { 12892 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12893 } 12894 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12895 } 12896 } 12897 } else { 12898 // Invalid install. Return error code 12899 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12900 } 12901 } 12902 } 12903 // All the special cases have been taken care of. 12904 // Return result based on recommended install location. 12905 if (onSd) { 12906 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12907 } 12908 return pkgLite.recommendedInstallLocation; 12909 } 12910 12911 /* 12912 * Invoke remote method to get package information and install 12913 * location values. Override install location based on default 12914 * policy if needed and then create install arguments based 12915 * on the install location. 12916 */ 12917 public void handleStartCopy() throws RemoteException { 12918 int ret = PackageManager.INSTALL_SUCCEEDED; 12919 12920 // If we're already staged, we've firmly committed to an install location 12921 if (origin.staged) { 12922 if (origin.file != null) { 12923 installFlags |= PackageManager.INSTALL_INTERNAL; 12924 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12925 } else if (origin.cid != null) { 12926 installFlags |= PackageManager.INSTALL_EXTERNAL; 12927 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12928 } else { 12929 throw new IllegalStateException("Invalid stage location"); 12930 } 12931 } 12932 12933 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12934 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12935 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12936 PackageInfoLite pkgLite = null; 12937 12938 if (onInt && onSd) { 12939 // Check if both bits are set. 12940 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12941 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12942 } else if (onSd && ephemeral) { 12943 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12944 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12945 } else { 12946 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12947 packageAbiOverride); 12948 12949 if (DEBUG_EPHEMERAL && ephemeral) { 12950 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12951 } 12952 12953 /* 12954 * If we have too little free space, try to free cache 12955 * before giving up. 12956 */ 12957 if (!origin.staged && pkgLite.recommendedInstallLocation 12958 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12959 // TODO: focus freeing disk space on the target device 12960 final StorageManager storage = StorageManager.from(mContext); 12961 final long lowThreshold = storage.getStorageLowBytes( 12962 Environment.getDataDirectory()); 12963 12964 final long sizeBytes = mContainerService.calculateInstalledSize( 12965 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12966 12967 try { 12968 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12969 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12970 installFlags, packageAbiOverride); 12971 } catch (InstallerException e) { 12972 Slog.w(TAG, "Failed to free cache", e); 12973 } 12974 12975 /* 12976 * The cache free must have deleted the file we 12977 * downloaded to install. 12978 * 12979 * TODO: fix the "freeCache" call to not delete 12980 * the file we care about. 12981 */ 12982 if (pkgLite.recommendedInstallLocation 12983 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12984 pkgLite.recommendedInstallLocation 12985 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12986 } 12987 } 12988 } 12989 12990 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12991 int loc = pkgLite.recommendedInstallLocation; 12992 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12993 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12994 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12995 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12996 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12997 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12998 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12999 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13000 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13001 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13002 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13003 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13004 } else { 13005 // Override with defaults if needed. 13006 loc = installLocationPolicy(pkgLite); 13007 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13008 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13009 } else if (!onSd && !onInt) { 13010 // Override install location with flags 13011 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13012 // Set the flag to install on external media. 13013 installFlags |= PackageManager.INSTALL_EXTERNAL; 13014 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13015 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13016 if (DEBUG_EPHEMERAL) { 13017 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13018 } 13019 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13020 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13021 |PackageManager.INSTALL_INTERNAL); 13022 } else { 13023 // Make sure the flag for installing on external 13024 // media is unset 13025 installFlags |= PackageManager.INSTALL_INTERNAL; 13026 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13027 } 13028 } 13029 } 13030 } 13031 13032 final InstallArgs args = createInstallArgs(this); 13033 mArgs = args; 13034 13035 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13036 // TODO: http://b/22976637 13037 // Apps installed for "all" users use the device owner to verify the app 13038 UserHandle verifierUser = getUser(); 13039 if (verifierUser == UserHandle.ALL) { 13040 verifierUser = UserHandle.SYSTEM; 13041 } 13042 13043 /* 13044 * Determine if we have any installed package verifiers. If we 13045 * do, then we'll defer to them to verify the packages. 13046 */ 13047 final int requiredUid = mRequiredVerifierPackage == null ? -1 13048 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13049 verifierUser.getIdentifier()); 13050 if (!origin.existing && requiredUid != -1 13051 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13052 final Intent verification = new Intent( 13053 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13054 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13055 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13056 PACKAGE_MIME_TYPE); 13057 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13058 13059 // Query all live verifiers based on current user state 13060 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13061 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13062 13063 if (DEBUG_VERIFY) { 13064 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13065 + verification.toString() + " with " + pkgLite.verifiers.length 13066 + " optional verifiers"); 13067 } 13068 13069 final int verificationId = mPendingVerificationToken++; 13070 13071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13072 13073 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13074 installerPackageName); 13075 13076 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13077 installFlags); 13078 13079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13080 pkgLite.packageName); 13081 13082 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13083 pkgLite.versionCode); 13084 13085 if (verificationInfo != null) { 13086 if (verificationInfo.originatingUri != null) { 13087 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13088 verificationInfo.originatingUri); 13089 } 13090 if (verificationInfo.referrer != null) { 13091 verification.putExtra(Intent.EXTRA_REFERRER, 13092 verificationInfo.referrer); 13093 } 13094 if (verificationInfo.originatingUid >= 0) { 13095 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13096 verificationInfo.originatingUid); 13097 } 13098 if (verificationInfo.installerUid >= 0) { 13099 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13100 verificationInfo.installerUid); 13101 } 13102 } 13103 13104 final PackageVerificationState verificationState = new PackageVerificationState( 13105 requiredUid, args); 13106 13107 mPendingVerification.append(verificationId, verificationState); 13108 13109 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13110 receivers, verificationState); 13111 13112 /* 13113 * If any sufficient verifiers were listed in the package 13114 * manifest, attempt to ask them. 13115 */ 13116 if (sufficientVerifiers != null) { 13117 final int N = sufficientVerifiers.size(); 13118 if (N == 0) { 13119 Slog.i(TAG, "Additional verifiers required, but none installed."); 13120 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13121 } else { 13122 for (int i = 0; i < N; i++) { 13123 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13124 13125 final Intent sufficientIntent = new Intent(verification); 13126 sufficientIntent.setComponent(verifierComponent); 13127 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13128 } 13129 } 13130 } 13131 13132 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13133 mRequiredVerifierPackage, receivers); 13134 if (ret == PackageManager.INSTALL_SUCCEEDED 13135 && mRequiredVerifierPackage != null) { 13136 Trace.asyncTraceBegin( 13137 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13138 /* 13139 * Send the intent to the required verification agent, 13140 * but only start the verification timeout after the 13141 * target BroadcastReceivers have run. 13142 */ 13143 verification.setComponent(requiredVerifierComponent); 13144 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13145 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13146 new BroadcastReceiver() { 13147 @Override 13148 public void onReceive(Context context, Intent intent) { 13149 final Message msg = mHandler 13150 .obtainMessage(CHECK_PENDING_VERIFICATION); 13151 msg.arg1 = verificationId; 13152 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13153 } 13154 }, null, 0, null, null); 13155 13156 /* 13157 * We don't want the copy to proceed until verification 13158 * succeeds, so null out this field. 13159 */ 13160 mArgs = null; 13161 } 13162 } else { 13163 /* 13164 * No package verification is enabled, so immediately start 13165 * the remote call to initiate copy using temporary file. 13166 */ 13167 ret = args.copyApk(mContainerService, true); 13168 } 13169 } 13170 13171 mRet = ret; 13172 } 13173 13174 @Override 13175 void handleReturnCode() { 13176 // If mArgs is null, then MCS couldn't be reached. When it 13177 // reconnects, it will try again to install. At that point, this 13178 // will succeed. 13179 if (mArgs != null) { 13180 processPendingInstall(mArgs, mRet); 13181 } 13182 } 13183 13184 @Override 13185 void handleServiceError() { 13186 mArgs = createInstallArgs(this); 13187 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13188 } 13189 13190 public boolean isForwardLocked() { 13191 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13192 } 13193 } 13194 13195 /** 13196 * Used during creation of InstallArgs 13197 * 13198 * @param installFlags package installation flags 13199 * @return true if should be installed on external storage 13200 */ 13201 private static boolean installOnExternalAsec(int installFlags) { 13202 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13203 return false; 13204 } 13205 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13206 return true; 13207 } 13208 return false; 13209 } 13210 13211 /** 13212 * Used during creation of InstallArgs 13213 * 13214 * @param installFlags package installation flags 13215 * @return true if should be installed as forward locked 13216 */ 13217 private static boolean installForwardLocked(int installFlags) { 13218 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13219 } 13220 13221 private InstallArgs createInstallArgs(InstallParams params) { 13222 if (params.move != null) { 13223 return new MoveInstallArgs(params); 13224 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13225 return new AsecInstallArgs(params); 13226 } else { 13227 return new FileInstallArgs(params); 13228 } 13229 } 13230 13231 /** 13232 * Create args that describe an existing installed package. Typically used 13233 * when cleaning up old installs, or used as a move source. 13234 */ 13235 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13236 String resourcePath, String[] instructionSets) { 13237 final boolean isInAsec; 13238 if (installOnExternalAsec(installFlags)) { 13239 /* Apps on SD card are always in ASEC containers. */ 13240 isInAsec = true; 13241 } else if (installForwardLocked(installFlags) 13242 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13243 /* 13244 * Forward-locked apps are only in ASEC containers if they're the 13245 * new style 13246 */ 13247 isInAsec = true; 13248 } else { 13249 isInAsec = false; 13250 } 13251 13252 if (isInAsec) { 13253 return new AsecInstallArgs(codePath, instructionSets, 13254 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13255 } else { 13256 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13257 } 13258 } 13259 13260 static abstract class InstallArgs { 13261 /** @see InstallParams#origin */ 13262 final OriginInfo origin; 13263 /** @see InstallParams#move */ 13264 final MoveInfo move; 13265 13266 final IPackageInstallObserver2 observer; 13267 // Always refers to PackageManager flags only 13268 final int installFlags; 13269 final String installerPackageName; 13270 final String volumeUuid; 13271 final UserHandle user; 13272 final String abiOverride; 13273 final String[] installGrantPermissions; 13274 /** If non-null, drop an async trace when the install completes */ 13275 final String traceMethod; 13276 final int traceCookie; 13277 final Certificate[][] certificates; 13278 13279 // The list of instruction sets supported by this app. This is currently 13280 // only used during the rmdex() phase to clean up resources. We can get rid of this 13281 // if we move dex files under the common app path. 13282 /* nullable */ String[] instructionSets; 13283 13284 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13285 int installFlags, String installerPackageName, String volumeUuid, 13286 UserHandle user, String[] instructionSets, 13287 String abiOverride, String[] installGrantPermissions, 13288 String traceMethod, int traceCookie, Certificate[][] certificates) { 13289 this.origin = origin; 13290 this.move = move; 13291 this.installFlags = installFlags; 13292 this.observer = observer; 13293 this.installerPackageName = installerPackageName; 13294 this.volumeUuid = volumeUuid; 13295 this.user = user; 13296 this.instructionSets = instructionSets; 13297 this.abiOverride = abiOverride; 13298 this.installGrantPermissions = installGrantPermissions; 13299 this.traceMethod = traceMethod; 13300 this.traceCookie = traceCookie; 13301 this.certificates = certificates; 13302 } 13303 13304 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13305 abstract int doPreInstall(int status); 13306 13307 /** 13308 * Rename package into final resting place. All paths on the given 13309 * scanned package should be updated to reflect the rename. 13310 */ 13311 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13312 abstract int doPostInstall(int status, int uid); 13313 13314 /** @see PackageSettingBase#codePathString */ 13315 abstract String getCodePath(); 13316 /** @see PackageSettingBase#resourcePathString */ 13317 abstract String getResourcePath(); 13318 13319 // Need installer lock especially for dex file removal. 13320 abstract void cleanUpResourcesLI(); 13321 abstract boolean doPostDeleteLI(boolean delete); 13322 13323 /** 13324 * Called before the source arguments are copied. This is used mostly 13325 * for MoveParams when it needs to read the source file to put it in the 13326 * destination. 13327 */ 13328 int doPreCopy() { 13329 return PackageManager.INSTALL_SUCCEEDED; 13330 } 13331 13332 /** 13333 * Called after the source arguments are copied. This is used mostly for 13334 * MoveParams when it needs to read the source file to put it in the 13335 * destination. 13336 */ 13337 int doPostCopy(int uid) { 13338 return PackageManager.INSTALL_SUCCEEDED; 13339 } 13340 13341 protected boolean isFwdLocked() { 13342 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13343 } 13344 13345 protected boolean isExternalAsec() { 13346 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13347 } 13348 13349 protected boolean isEphemeral() { 13350 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13351 } 13352 13353 UserHandle getUser() { 13354 return user; 13355 } 13356 } 13357 13358 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13359 if (!allCodePaths.isEmpty()) { 13360 if (instructionSets == null) { 13361 throw new IllegalStateException("instructionSet == null"); 13362 } 13363 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13364 for (String codePath : allCodePaths) { 13365 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13366 try { 13367 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13368 } catch (InstallerException ignored) { 13369 } 13370 } 13371 } 13372 } 13373 } 13374 13375 /** 13376 * Logic to handle installation of non-ASEC applications, including copying 13377 * and renaming logic. 13378 */ 13379 class FileInstallArgs extends InstallArgs { 13380 private File codeFile; 13381 private File resourceFile; 13382 13383 // Example topology: 13384 // /data/app/com.example/base.apk 13385 // /data/app/com.example/split_foo.apk 13386 // /data/app/com.example/lib/arm/libfoo.so 13387 // /data/app/com.example/lib/arm64/libfoo.so 13388 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13389 13390 /** New install */ 13391 FileInstallArgs(InstallParams params) { 13392 super(params.origin, params.move, params.observer, params.installFlags, 13393 params.installerPackageName, params.volumeUuid, 13394 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13395 params.grantedRuntimePermissions, 13396 params.traceMethod, params.traceCookie, params.certificates); 13397 if (isFwdLocked()) { 13398 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13399 } 13400 } 13401 13402 /** Existing install */ 13403 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13404 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13405 null, null, null, 0, null /*certificates*/); 13406 this.codeFile = (codePath != null) ? new File(codePath) : null; 13407 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13408 } 13409 13410 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13412 try { 13413 return doCopyApk(imcs, temp); 13414 } finally { 13415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13416 } 13417 } 13418 13419 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13420 if (origin.staged) { 13421 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13422 codeFile = origin.file; 13423 resourceFile = origin.file; 13424 return PackageManager.INSTALL_SUCCEEDED; 13425 } 13426 13427 try { 13428 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13429 final File tempDir = 13430 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13431 codeFile = tempDir; 13432 resourceFile = tempDir; 13433 } catch (IOException e) { 13434 Slog.w(TAG, "Failed to create copy file: " + e); 13435 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13436 } 13437 13438 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13439 @Override 13440 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13441 if (!FileUtils.isValidExtFilename(name)) { 13442 throw new IllegalArgumentException("Invalid filename: " + name); 13443 } 13444 try { 13445 final File file = new File(codeFile, name); 13446 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13447 O_RDWR | O_CREAT, 0644); 13448 Os.chmod(file.getAbsolutePath(), 0644); 13449 return new ParcelFileDescriptor(fd); 13450 } catch (ErrnoException e) { 13451 throw new RemoteException("Failed to open: " + e.getMessage()); 13452 } 13453 } 13454 }; 13455 13456 int ret = PackageManager.INSTALL_SUCCEEDED; 13457 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13458 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13459 Slog.e(TAG, "Failed to copy package"); 13460 return ret; 13461 } 13462 13463 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13464 NativeLibraryHelper.Handle handle = null; 13465 try { 13466 handle = NativeLibraryHelper.Handle.create(codeFile); 13467 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13468 abiOverride); 13469 } catch (IOException e) { 13470 Slog.e(TAG, "Copying native libraries failed", e); 13471 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13472 } finally { 13473 IoUtils.closeQuietly(handle); 13474 } 13475 13476 return ret; 13477 } 13478 13479 int doPreInstall(int status) { 13480 if (status != PackageManager.INSTALL_SUCCEEDED) { 13481 cleanUp(); 13482 } 13483 return status; 13484 } 13485 13486 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13487 if (status != PackageManager.INSTALL_SUCCEEDED) { 13488 cleanUp(); 13489 return false; 13490 } 13491 13492 final File targetDir = codeFile.getParentFile(); 13493 final File beforeCodeFile = codeFile; 13494 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13495 13496 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13497 try { 13498 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13499 } catch (ErrnoException e) { 13500 Slog.w(TAG, "Failed to rename", e); 13501 return false; 13502 } 13503 13504 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13505 Slog.w(TAG, "Failed to restorecon"); 13506 return false; 13507 } 13508 13509 // Reflect the rename internally 13510 codeFile = afterCodeFile; 13511 resourceFile = afterCodeFile; 13512 13513 // Reflect the rename in scanned details 13514 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13515 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13516 afterCodeFile, pkg.baseCodePath)); 13517 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13518 afterCodeFile, pkg.splitCodePaths)); 13519 13520 // Reflect the rename in app info 13521 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13522 pkg.setApplicationInfoCodePath(pkg.codePath); 13523 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13524 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13525 pkg.setApplicationInfoResourcePath(pkg.codePath); 13526 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13527 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13528 13529 return true; 13530 } 13531 13532 int doPostInstall(int status, int uid) { 13533 if (status != PackageManager.INSTALL_SUCCEEDED) { 13534 cleanUp(); 13535 } 13536 return status; 13537 } 13538 13539 @Override 13540 String getCodePath() { 13541 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13542 } 13543 13544 @Override 13545 String getResourcePath() { 13546 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13547 } 13548 13549 private boolean cleanUp() { 13550 if (codeFile == null || !codeFile.exists()) { 13551 return false; 13552 } 13553 13554 removeCodePathLI(codeFile); 13555 13556 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13557 resourceFile.delete(); 13558 } 13559 13560 return true; 13561 } 13562 13563 void cleanUpResourcesLI() { 13564 // Try enumerating all code paths before deleting 13565 List<String> allCodePaths = Collections.EMPTY_LIST; 13566 if (codeFile != null && codeFile.exists()) { 13567 try { 13568 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13569 allCodePaths = pkg.getAllCodePaths(); 13570 } catch (PackageParserException e) { 13571 // Ignored; we tried our best 13572 } 13573 } 13574 13575 cleanUp(); 13576 removeDexFiles(allCodePaths, instructionSets); 13577 } 13578 13579 boolean doPostDeleteLI(boolean delete) { 13580 // XXX err, shouldn't we respect the delete flag? 13581 cleanUpResourcesLI(); 13582 return true; 13583 } 13584 } 13585 13586 private boolean isAsecExternal(String cid) { 13587 final String asecPath = PackageHelper.getSdFilesystem(cid); 13588 return !asecPath.startsWith(mAsecInternalPath); 13589 } 13590 13591 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13592 PackageManagerException { 13593 if (copyRet < 0) { 13594 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13595 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13596 throw new PackageManagerException(copyRet, message); 13597 } 13598 } 13599 } 13600 13601 /** 13602 * Extract the MountService "container ID" from the full code path of an 13603 * .apk. 13604 */ 13605 static String cidFromCodePath(String fullCodePath) { 13606 int eidx = fullCodePath.lastIndexOf("/"); 13607 String subStr1 = fullCodePath.substring(0, eidx); 13608 int sidx = subStr1.lastIndexOf("/"); 13609 return subStr1.substring(sidx+1, eidx); 13610 } 13611 13612 /** 13613 * Logic to handle installation of ASEC applications, including copying and 13614 * renaming logic. 13615 */ 13616 class AsecInstallArgs extends InstallArgs { 13617 static final String RES_FILE_NAME = "pkg.apk"; 13618 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13619 13620 String cid; 13621 String packagePath; 13622 String resourcePath; 13623 13624 /** New install */ 13625 AsecInstallArgs(InstallParams params) { 13626 super(params.origin, params.move, params.observer, params.installFlags, 13627 params.installerPackageName, params.volumeUuid, 13628 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13629 params.grantedRuntimePermissions, 13630 params.traceMethod, params.traceCookie, params.certificates); 13631 } 13632 13633 /** Existing install */ 13634 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13635 boolean isExternal, boolean isForwardLocked) { 13636 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13637 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13638 instructionSets, null, null, null, 0, null /*certificates*/); 13639 // Hackily pretend we're still looking at a full code path 13640 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13641 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13642 } 13643 13644 // Extract cid from fullCodePath 13645 int eidx = fullCodePath.lastIndexOf("/"); 13646 String subStr1 = fullCodePath.substring(0, eidx); 13647 int sidx = subStr1.lastIndexOf("/"); 13648 cid = subStr1.substring(sidx+1, eidx); 13649 setMountPath(subStr1); 13650 } 13651 13652 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13653 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13654 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13655 instructionSets, null, null, null, 0, null /*certificates*/); 13656 this.cid = cid; 13657 setMountPath(PackageHelper.getSdDir(cid)); 13658 } 13659 13660 void createCopyFile() { 13661 cid = mInstallerService.allocateExternalStageCidLegacy(); 13662 } 13663 13664 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13665 if (origin.staged && origin.cid != null) { 13666 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13667 cid = origin.cid; 13668 setMountPath(PackageHelper.getSdDir(cid)); 13669 return PackageManager.INSTALL_SUCCEEDED; 13670 } 13671 13672 if (temp) { 13673 createCopyFile(); 13674 } else { 13675 /* 13676 * Pre-emptively destroy the container since it's destroyed if 13677 * copying fails due to it existing anyway. 13678 */ 13679 PackageHelper.destroySdDir(cid); 13680 } 13681 13682 final String newMountPath = imcs.copyPackageToContainer( 13683 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13684 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13685 13686 if (newMountPath != null) { 13687 setMountPath(newMountPath); 13688 return PackageManager.INSTALL_SUCCEEDED; 13689 } else { 13690 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13691 } 13692 } 13693 13694 @Override 13695 String getCodePath() { 13696 return packagePath; 13697 } 13698 13699 @Override 13700 String getResourcePath() { 13701 return resourcePath; 13702 } 13703 13704 int doPreInstall(int status) { 13705 if (status != PackageManager.INSTALL_SUCCEEDED) { 13706 // Destroy container 13707 PackageHelper.destroySdDir(cid); 13708 } else { 13709 boolean mounted = PackageHelper.isContainerMounted(cid); 13710 if (!mounted) { 13711 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13712 Process.SYSTEM_UID); 13713 if (newMountPath != null) { 13714 setMountPath(newMountPath); 13715 } else { 13716 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13717 } 13718 } 13719 } 13720 return status; 13721 } 13722 13723 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13724 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13725 String newMountPath = null; 13726 if (PackageHelper.isContainerMounted(cid)) { 13727 // Unmount the container 13728 if (!PackageHelper.unMountSdDir(cid)) { 13729 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13730 return false; 13731 } 13732 } 13733 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13734 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13735 " which might be stale. Will try to clean up."); 13736 // Clean up the stale container and proceed to recreate. 13737 if (!PackageHelper.destroySdDir(newCacheId)) { 13738 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13739 return false; 13740 } 13741 // Successfully cleaned up stale container. Try to rename again. 13742 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13743 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13744 + " inspite of cleaning it up."); 13745 return false; 13746 } 13747 } 13748 if (!PackageHelper.isContainerMounted(newCacheId)) { 13749 Slog.w(TAG, "Mounting container " + newCacheId); 13750 newMountPath = PackageHelper.mountSdDir(newCacheId, 13751 getEncryptKey(), Process.SYSTEM_UID); 13752 } else { 13753 newMountPath = PackageHelper.getSdDir(newCacheId); 13754 } 13755 if (newMountPath == null) { 13756 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13757 return false; 13758 } 13759 Log.i(TAG, "Succesfully renamed " + cid + 13760 " to " + newCacheId + 13761 " at new path: " + newMountPath); 13762 cid = newCacheId; 13763 13764 final File beforeCodeFile = new File(packagePath); 13765 setMountPath(newMountPath); 13766 final File afterCodeFile = new File(packagePath); 13767 13768 // Reflect the rename in scanned details 13769 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13770 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13771 afterCodeFile, pkg.baseCodePath)); 13772 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13773 afterCodeFile, pkg.splitCodePaths)); 13774 13775 // Reflect the rename in app info 13776 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13777 pkg.setApplicationInfoCodePath(pkg.codePath); 13778 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13779 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13780 pkg.setApplicationInfoResourcePath(pkg.codePath); 13781 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13782 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13783 13784 return true; 13785 } 13786 13787 private void setMountPath(String mountPath) { 13788 final File mountFile = new File(mountPath); 13789 13790 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13791 if (monolithicFile.exists()) { 13792 packagePath = monolithicFile.getAbsolutePath(); 13793 if (isFwdLocked()) { 13794 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13795 } else { 13796 resourcePath = packagePath; 13797 } 13798 } else { 13799 packagePath = mountFile.getAbsolutePath(); 13800 resourcePath = packagePath; 13801 } 13802 } 13803 13804 int doPostInstall(int status, int uid) { 13805 if (status != PackageManager.INSTALL_SUCCEEDED) { 13806 cleanUp(); 13807 } else { 13808 final int groupOwner; 13809 final String protectedFile; 13810 if (isFwdLocked()) { 13811 groupOwner = UserHandle.getSharedAppGid(uid); 13812 protectedFile = RES_FILE_NAME; 13813 } else { 13814 groupOwner = -1; 13815 protectedFile = null; 13816 } 13817 13818 if (uid < Process.FIRST_APPLICATION_UID 13819 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13820 Slog.e(TAG, "Failed to finalize " + cid); 13821 PackageHelper.destroySdDir(cid); 13822 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13823 } 13824 13825 boolean mounted = PackageHelper.isContainerMounted(cid); 13826 if (!mounted) { 13827 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13828 } 13829 } 13830 return status; 13831 } 13832 13833 private void cleanUp() { 13834 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13835 13836 // Destroy secure container 13837 PackageHelper.destroySdDir(cid); 13838 } 13839 13840 private List<String> getAllCodePaths() { 13841 final File codeFile = new File(getCodePath()); 13842 if (codeFile != null && codeFile.exists()) { 13843 try { 13844 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13845 return pkg.getAllCodePaths(); 13846 } catch (PackageParserException e) { 13847 // Ignored; we tried our best 13848 } 13849 } 13850 return Collections.EMPTY_LIST; 13851 } 13852 13853 void cleanUpResourcesLI() { 13854 // Enumerate all code paths before deleting 13855 cleanUpResourcesLI(getAllCodePaths()); 13856 } 13857 13858 private void cleanUpResourcesLI(List<String> allCodePaths) { 13859 cleanUp(); 13860 removeDexFiles(allCodePaths, instructionSets); 13861 } 13862 13863 String getPackageName() { 13864 return getAsecPackageName(cid); 13865 } 13866 13867 boolean doPostDeleteLI(boolean delete) { 13868 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13869 final List<String> allCodePaths = getAllCodePaths(); 13870 boolean mounted = PackageHelper.isContainerMounted(cid); 13871 if (mounted) { 13872 // Unmount first 13873 if (PackageHelper.unMountSdDir(cid)) { 13874 mounted = false; 13875 } 13876 } 13877 if (!mounted && delete) { 13878 cleanUpResourcesLI(allCodePaths); 13879 } 13880 return !mounted; 13881 } 13882 13883 @Override 13884 int doPreCopy() { 13885 if (isFwdLocked()) { 13886 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13887 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13888 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13889 } 13890 } 13891 13892 return PackageManager.INSTALL_SUCCEEDED; 13893 } 13894 13895 @Override 13896 int doPostCopy(int uid) { 13897 if (isFwdLocked()) { 13898 if (uid < Process.FIRST_APPLICATION_UID 13899 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13900 RES_FILE_NAME)) { 13901 Slog.e(TAG, "Failed to finalize " + cid); 13902 PackageHelper.destroySdDir(cid); 13903 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13904 } 13905 } 13906 13907 return PackageManager.INSTALL_SUCCEEDED; 13908 } 13909 } 13910 13911 /** 13912 * Logic to handle movement of existing installed applications. 13913 */ 13914 class MoveInstallArgs extends InstallArgs { 13915 private File codeFile; 13916 private File resourceFile; 13917 13918 /** New install */ 13919 MoveInstallArgs(InstallParams params) { 13920 super(params.origin, params.move, params.observer, params.installFlags, 13921 params.installerPackageName, params.volumeUuid, 13922 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13923 params.grantedRuntimePermissions, 13924 params.traceMethod, params.traceCookie, params.certificates); 13925 } 13926 13927 int copyApk(IMediaContainerService imcs, boolean temp) { 13928 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13929 + move.fromUuid + " to " + move.toUuid); 13930 synchronized (mInstaller) { 13931 try { 13932 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13933 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13934 } catch (InstallerException e) { 13935 Slog.w(TAG, "Failed to move app", e); 13936 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13937 } 13938 } 13939 13940 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13941 resourceFile = codeFile; 13942 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13943 13944 return PackageManager.INSTALL_SUCCEEDED; 13945 } 13946 13947 int doPreInstall(int status) { 13948 if (status != PackageManager.INSTALL_SUCCEEDED) { 13949 cleanUp(move.toUuid); 13950 } 13951 return status; 13952 } 13953 13954 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13955 if (status != PackageManager.INSTALL_SUCCEEDED) { 13956 cleanUp(move.toUuid); 13957 return false; 13958 } 13959 13960 // Reflect the move in app info 13961 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13962 pkg.setApplicationInfoCodePath(pkg.codePath); 13963 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13964 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13965 pkg.setApplicationInfoResourcePath(pkg.codePath); 13966 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13967 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13968 13969 return true; 13970 } 13971 13972 int doPostInstall(int status, int uid) { 13973 if (status == PackageManager.INSTALL_SUCCEEDED) { 13974 cleanUp(move.fromUuid); 13975 } else { 13976 cleanUp(move.toUuid); 13977 } 13978 return status; 13979 } 13980 13981 @Override 13982 String getCodePath() { 13983 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13984 } 13985 13986 @Override 13987 String getResourcePath() { 13988 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13989 } 13990 13991 private boolean cleanUp(String volumeUuid) { 13992 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13993 move.dataAppName); 13994 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13995 final int[] userIds = sUserManager.getUserIds(); 13996 synchronized (mInstallLock) { 13997 // Clean up both app data and code 13998 // All package moves are frozen until finished 13999 for (int userId : userIds) { 14000 try { 14001 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14002 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14003 } catch (InstallerException e) { 14004 Slog.w(TAG, String.valueOf(e)); 14005 } 14006 } 14007 removeCodePathLI(codeFile); 14008 } 14009 return true; 14010 } 14011 14012 void cleanUpResourcesLI() { 14013 throw new UnsupportedOperationException(); 14014 } 14015 14016 boolean doPostDeleteLI(boolean delete) { 14017 throw new UnsupportedOperationException(); 14018 } 14019 } 14020 14021 static String getAsecPackageName(String packageCid) { 14022 int idx = packageCid.lastIndexOf("-"); 14023 if (idx == -1) { 14024 return packageCid; 14025 } 14026 return packageCid.substring(0, idx); 14027 } 14028 14029 // Utility method used to create code paths based on package name and available index. 14030 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14031 String idxStr = ""; 14032 int idx = 1; 14033 // Fall back to default value of idx=1 if prefix is not 14034 // part of oldCodePath 14035 if (oldCodePath != null) { 14036 String subStr = oldCodePath; 14037 // Drop the suffix right away 14038 if (suffix != null && subStr.endsWith(suffix)) { 14039 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14040 } 14041 // If oldCodePath already contains prefix find out the 14042 // ending index to either increment or decrement. 14043 int sidx = subStr.lastIndexOf(prefix); 14044 if (sidx != -1) { 14045 subStr = subStr.substring(sidx + prefix.length()); 14046 if (subStr != null) { 14047 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14048 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14049 } 14050 try { 14051 idx = Integer.parseInt(subStr); 14052 if (idx <= 1) { 14053 idx++; 14054 } else { 14055 idx--; 14056 } 14057 } catch(NumberFormatException e) { 14058 } 14059 } 14060 } 14061 } 14062 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14063 return prefix + idxStr; 14064 } 14065 14066 private File getNextCodePath(File targetDir, String packageName) { 14067 int suffix = 1; 14068 File result; 14069 do { 14070 result = new File(targetDir, packageName + "-" + suffix); 14071 suffix++; 14072 } while (result.exists()); 14073 return result; 14074 } 14075 14076 // Utility method that returns the relative package path with respect 14077 // to the installation directory. Like say for /data/data/com.test-1.apk 14078 // string com.test-1 is returned. 14079 static String deriveCodePathName(String codePath) { 14080 if (codePath == null) { 14081 return null; 14082 } 14083 final File codeFile = new File(codePath); 14084 final String name = codeFile.getName(); 14085 if (codeFile.isDirectory()) { 14086 return name; 14087 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14088 final int lastDot = name.lastIndexOf('.'); 14089 return name.substring(0, lastDot); 14090 } else { 14091 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14092 return null; 14093 } 14094 } 14095 14096 static class PackageInstalledInfo { 14097 String name; 14098 int uid; 14099 // The set of users that originally had this package installed. 14100 int[] origUsers; 14101 // The set of users that now have this package installed. 14102 int[] newUsers; 14103 PackageParser.Package pkg; 14104 int returnCode; 14105 String returnMsg; 14106 PackageRemovedInfo removedInfo; 14107 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14108 14109 public void setError(int code, String msg) { 14110 setReturnCode(code); 14111 setReturnMessage(msg); 14112 Slog.w(TAG, msg); 14113 } 14114 14115 public void setError(String msg, PackageParserException e) { 14116 setReturnCode(e.error); 14117 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14118 Slog.w(TAG, msg, e); 14119 } 14120 14121 public void setError(String msg, PackageManagerException e) { 14122 returnCode = e.error; 14123 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14124 Slog.w(TAG, msg, e); 14125 } 14126 14127 public void setReturnCode(int returnCode) { 14128 this.returnCode = returnCode; 14129 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14130 for (int i = 0; i < childCount; i++) { 14131 addedChildPackages.valueAt(i).returnCode = returnCode; 14132 } 14133 } 14134 14135 private void setReturnMessage(String returnMsg) { 14136 this.returnMsg = returnMsg; 14137 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14138 for (int i = 0; i < childCount; i++) { 14139 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14140 } 14141 } 14142 14143 // In some error cases we want to convey more info back to the observer 14144 String origPackage; 14145 String origPermission; 14146 } 14147 14148 /* 14149 * Install a non-existing package. 14150 */ 14151 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14152 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14153 PackageInstalledInfo res) { 14154 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14155 14156 // Remember this for later, in case we need to rollback this install 14157 String pkgName = pkg.packageName; 14158 14159 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14160 14161 synchronized(mPackages) { 14162 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14163 // A package with the same name is already installed, though 14164 // it has been renamed to an older name. The package we 14165 // are trying to install should be installed as an update to 14166 // the existing one, but that has not been requested, so bail. 14167 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14168 + " without first uninstalling package running as " 14169 + mSettings.mRenamedPackages.get(pkgName)); 14170 return; 14171 } 14172 if (mPackages.containsKey(pkgName)) { 14173 // Don't allow installation over an existing package with the same name. 14174 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14175 + " without first uninstalling."); 14176 return; 14177 } 14178 } 14179 14180 try { 14181 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14182 System.currentTimeMillis(), user); 14183 14184 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14185 14186 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14187 prepareAppDataAfterInstallLIF(newPackage); 14188 14189 } else { 14190 // Remove package from internal structures, but keep around any 14191 // data that might have already existed 14192 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14193 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14194 } 14195 } catch (PackageManagerException e) { 14196 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14197 } 14198 14199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14200 } 14201 14202 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14203 // Can't rotate keys during boot or if sharedUser. 14204 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14205 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14206 return false; 14207 } 14208 // app is using upgradeKeySets; make sure all are valid 14209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14210 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14211 for (int i = 0; i < upgradeKeySets.length; i++) { 14212 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14213 Slog.wtf(TAG, "Package " 14214 + (oldPs.name != null ? oldPs.name : "<null>") 14215 + " contains upgrade-key-set reference to unknown key-set: " 14216 + upgradeKeySets[i] 14217 + " reverting to signatures check."); 14218 return false; 14219 } 14220 } 14221 return true; 14222 } 14223 14224 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14225 // Upgrade keysets are being used. Determine if new package has a superset of the 14226 // required keys. 14227 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14228 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14229 for (int i = 0; i < upgradeKeySets.length; i++) { 14230 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14231 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14232 return true; 14233 } 14234 } 14235 return false; 14236 } 14237 14238 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14239 try (DigestInputStream digestStream = 14240 new DigestInputStream(new FileInputStream(file), digest)) { 14241 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14242 } 14243 } 14244 14245 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14246 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14247 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14248 14249 final PackageParser.Package oldPackage; 14250 final String pkgName = pkg.packageName; 14251 final int[] allUsers; 14252 final int[] installedUsers; 14253 14254 synchronized(mPackages) { 14255 oldPackage = mPackages.get(pkgName); 14256 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14257 14258 // don't allow upgrade to target a release SDK from a pre-release SDK 14259 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14260 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14261 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14262 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14263 if (oldTargetsPreRelease 14264 && !newTargetsPreRelease 14265 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14266 Slog.w(TAG, "Can't install package targeting released sdk"); 14267 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14268 return; 14269 } 14270 14271 // don't allow an upgrade from full to ephemeral 14272 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14273 if (isEphemeral && !oldIsEphemeral) { 14274 // can't downgrade from full to ephemeral 14275 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14276 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14277 return; 14278 } 14279 14280 // verify signatures are valid 14281 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14282 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14283 if (!checkUpgradeKeySetLP(ps, pkg)) { 14284 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14285 "New package not signed by keys specified by upgrade-keysets: " 14286 + pkgName); 14287 return; 14288 } 14289 } else { 14290 // default to original signature matching 14291 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14292 != PackageManager.SIGNATURE_MATCH) { 14293 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14294 "New package has a different signature: " + pkgName); 14295 return; 14296 } 14297 } 14298 14299 // don't allow a system upgrade unless the upgrade hash matches 14300 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14301 byte[] digestBytes = null; 14302 try { 14303 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14304 updateDigest(digest, new File(pkg.baseCodePath)); 14305 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14306 for (String path : pkg.splitCodePaths) { 14307 updateDigest(digest, new File(path)); 14308 } 14309 } 14310 digestBytes = digest.digest(); 14311 } catch (NoSuchAlgorithmException | IOException e) { 14312 res.setError(INSTALL_FAILED_INVALID_APK, 14313 "Could not compute hash: " + pkgName); 14314 return; 14315 } 14316 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14317 res.setError(INSTALL_FAILED_INVALID_APK, 14318 "New package fails restrict-update check: " + pkgName); 14319 return; 14320 } 14321 // retain upgrade restriction 14322 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14323 } 14324 14325 // Check for shared user id changes 14326 String invalidPackageName = 14327 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14328 if (invalidPackageName != null) { 14329 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14330 "Package " + invalidPackageName + " tried to change user " 14331 + oldPackage.mSharedUserId); 14332 return; 14333 } 14334 14335 // In case of rollback, remember per-user/profile install state 14336 allUsers = sUserManager.getUserIds(); 14337 installedUsers = ps.queryInstalledUsers(allUsers, true); 14338 } 14339 14340 // Update what is removed 14341 res.removedInfo = new PackageRemovedInfo(); 14342 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14343 res.removedInfo.removedPackage = oldPackage.packageName; 14344 res.removedInfo.isUpdate = true; 14345 res.removedInfo.origUsers = installedUsers; 14346 final int childCount = (oldPackage.childPackages != null) 14347 ? oldPackage.childPackages.size() : 0; 14348 for (int i = 0; i < childCount; i++) { 14349 boolean childPackageUpdated = false; 14350 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14351 if (res.addedChildPackages != null) { 14352 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14353 if (childRes != null) { 14354 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14355 childRes.removedInfo.removedPackage = childPkg.packageName; 14356 childRes.removedInfo.isUpdate = true; 14357 childPackageUpdated = true; 14358 } 14359 } 14360 if (!childPackageUpdated) { 14361 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14362 childRemovedRes.removedPackage = childPkg.packageName; 14363 childRemovedRes.isUpdate = false; 14364 childRemovedRes.dataRemoved = true; 14365 synchronized (mPackages) { 14366 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14367 if (childPs != null) { 14368 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14369 } 14370 } 14371 if (res.removedInfo.removedChildPackages == null) { 14372 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14373 } 14374 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14375 } 14376 } 14377 14378 boolean sysPkg = (isSystemApp(oldPackage)); 14379 if (sysPkg) { 14380 // Set the system/privileged flags as needed 14381 final boolean privileged = 14382 (oldPackage.applicationInfo.privateFlags 14383 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14384 final int systemPolicyFlags = policyFlags 14385 | PackageParser.PARSE_IS_SYSTEM 14386 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14387 14388 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14389 user, allUsers, installerPackageName, res); 14390 } else { 14391 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14392 user, allUsers, installerPackageName, res); 14393 } 14394 } 14395 14396 public List<String> getPreviousCodePaths(String packageName) { 14397 final PackageSetting ps = mSettings.mPackages.get(packageName); 14398 final List<String> result = new ArrayList<String>(); 14399 if (ps != null && ps.oldCodePaths != null) { 14400 result.addAll(ps.oldCodePaths); 14401 } 14402 return result; 14403 } 14404 14405 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14406 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14407 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14408 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14409 + deletedPackage); 14410 14411 String pkgName = deletedPackage.packageName; 14412 boolean deletedPkg = true; 14413 boolean addedPkg = false; 14414 boolean updatedSettings = false; 14415 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14416 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14417 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14418 14419 final long origUpdateTime = (pkg.mExtras != null) 14420 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14421 14422 // First delete the existing package while retaining the data directory 14423 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14424 res.removedInfo, true, pkg)) { 14425 // If the existing package wasn't successfully deleted 14426 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14427 deletedPkg = false; 14428 } else { 14429 // Successfully deleted the old package; proceed with replace. 14430 14431 // If deleted package lived in a container, give users a chance to 14432 // relinquish resources before killing. 14433 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14434 if (DEBUG_INSTALL) { 14435 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14436 } 14437 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14438 final ArrayList<String> pkgList = new ArrayList<String>(1); 14439 pkgList.add(deletedPackage.applicationInfo.packageName); 14440 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14441 } 14442 14443 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14444 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14445 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14446 14447 try { 14448 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14449 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14450 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14451 14452 // Update the in-memory copy of the previous code paths. 14453 PackageSetting ps = mSettings.mPackages.get(pkgName); 14454 if (!killApp) { 14455 if (ps.oldCodePaths == null) { 14456 ps.oldCodePaths = new ArraySet<>(); 14457 } 14458 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14459 if (deletedPackage.splitCodePaths != null) { 14460 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14461 } 14462 } else { 14463 ps.oldCodePaths = null; 14464 } 14465 if (ps.childPackageNames != null) { 14466 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14467 final String childPkgName = ps.childPackageNames.get(i); 14468 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14469 childPs.oldCodePaths = ps.oldCodePaths; 14470 } 14471 } 14472 prepareAppDataAfterInstallLIF(newPackage); 14473 addedPkg = true; 14474 } catch (PackageManagerException e) { 14475 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14476 } 14477 } 14478 14479 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14480 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14481 14482 // Revert all internal state mutations and added folders for the failed install 14483 if (addedPkg) { 14484 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14485 res.removedInfo, true, null); 14486 } 14487 14488 // Restore the old package 14489 if (deletedPkg) { 14490 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14491 File restoreFile = new File(deletedPackage.codePath); 14492 // Parse old package 14493 boolean oldExternal = isExternal(deletedPackage); 14494 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14495 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14496 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14497 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14498 try { 14499 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14500 null); 14501 } catch (PackageManagerException e) { 14502 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14503 + e.getMessage()); 14504 return; 14505 } 14506 14507 synchronized (mPackages) { 14508 // Ensure the installer package name up to date 14509 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14510 14511 // Update permissions for restored package 14512 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14513 14514 mSettings.writeLPr(); 14515 } 14516 14517 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14518 } 14519 } else { 14520 synchronized (mPackages) { 14521 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14522 if (ps != null) { 14523 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14524 if (res.removedInfo.removedChildPackages != null) { 14525 final int childCount = res.removedInfo.removedChildPackages.size(); 14526 // Iterate in reverse as we may modify the collection 14527 for (int i = childCount - 1; i >= 0; i--) { 14528 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14529 if (res.addedChildPackages.containsKey(childPackageName)) { 14530 res.removedInfo.removedChildPackages.removeAt(i); 14531 } else { 14532 PackageRemovedInfo childInfo = res.removedInfo 14533 .removedChildPackages.valueAt(i); 14534 childInfo.removedForAllUsers = mPackages.get( 14535 childInfo.removedPackage) == null; 14536 } 14537 } 14538 } 14539 } 14540 } 14541 } 14542 } 14543 14544 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14545 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14546 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14547 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14548 + ", old=" + deletedPackage); 14549 14550 final boolean disabledSystem; 14551 14552 // Remove existing system package 14553 removePackageLI(deletedPackage, true); 14554 14555 synchronized (mPackages) { 14556 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14557 } 14558 if (!disabledSystem) { 14559 // We didn't need to disable the .apk as a current system package, 14560 // which means we are replacing another update that is already 14561 // installed. We need to make sure to delete the older one's .apk. 14562 res.removedInfo.args = createInstallArgsForExisting(0, 14563 deletedPackage.applicationInfo.getCodePath(), 14564 deletedPackage.applicationInfo.getResourcePath(), 14565 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14566 } else { 14567 res.removedInfo.args = null; 14568 } 14569 14570 // Successfully disabled the old package. Now proceed with re-installation 14571 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14572 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14573 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14574 14575 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14576 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14577 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14578 14579 PackageParser.Package newPackage = null; 14580 try { 14581 // Add the package to the internal data structures 14582 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14583 14584 // Set the update and install times 14585 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14586 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14587 System.currentTimeMillis()); 14588 14589 // Update the package dynamic state if succeeded 14590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14591 // Now that the install succeeded make sure we remove data 14592 // directories for any child package the update removed. 14593 final int deletedChildCount = (deletedPackage.childPackages != null) 14594 ? deletedPackage.childPackages.size() : 0; 14595 final int newChildCount = (newPackage.childPackages != null) 14596 ? newPackage.childPackages.size() : 0; 14597 for (int i = 0; i < deletedChildCount; i++) { 14598 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14599 boolean childPackageDeleted = true; 14600 for (int j = 0; j < newChildCount; j++) { 14601 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14602 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14603 childPackageDeleted = false; 14604 break; 14605 } 14606 } 14607 if (childPackageDeleted) { 14608 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14609 deletedChildPkg.packageName); 14610 if (ps != null && res.removedInfo.removedChildPackages != null) { 14611 PackageRemovedInfo removedChildRes = res.removedInfo 14612 .removedChildPackages.get(deletedChildPkg.packageName); 14613 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14614 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14615 } 14616 } 14617 } 14618 14619 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14620 prepareAppDataAfterInstallLIF(newPackage); 14621 } 14622 } catch (PackageManagerException e) { 14623 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14624 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14625 } 14626 14627 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14628 // Re installation failed. Restore old information 14629 // Remove new pkg information 14630 if (newPackage != null) { 14631 removeInstalledPackageLI(newPackage, true); 14632 } 14633 // Add back the old system package 14634 try { 14635 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14636 } catch (PackageManagerException e) { 14637 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14638 } 14639 14640 synchronized (mPackages) { 14641 if (disabledSystem) { 14642 enableSystemPackageLPw(deletedPackage); 14643 } 14644 14645 // Ensure the installer package name up to date 14646 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14647 14648 // Update permissions for restored package 14649 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14650 14651 mSettings.writeLPr(); 14652 } 14653 14654 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14655 + " after failed upgrade"); 14656 } 14657 } 14658 14659 /** 14660 * Checks whether the parent or any of the child packages have a change shared 14661 * user. For a package to be a valid update the shred users of the parent and 14662 * the children should match. We may later support changing child shared users. 14663 * @param oldPkg The updated package. 14664 * @param newPkg The update package. 14665 * @return The shared user that change between the versions. 14666 */ 14667 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14668 PackageParser.Package newPkg) { 14669 // Check parent shared user 14670 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14671 return newPkg.packageName; 14672 } 14673 // Check child shared users 14674 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14675 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14676 for (int i = 0; i < newChildCount; i++) { 14677 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14678 // If this child was present, did it have the same shared user? 14679 for (int j = 0; j < oldChildCount; j++) { 14680 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14681 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14682 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14683 return newChildPkg.packageName; 14684 } 14685 } 14686 } 14687 return null; 14688 } 14689 14690 private void removeNativeBinariesLI(PackageSetting ps) { 14691 // Remove the lib path for the parent package 14692 if (ps != null) { 14693 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14694 // Remove the lib path for the child packages 14695 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14696 for (int i = 0; i < childCount; i++) { 14697 PackageSetting childPs = null; 14698 synchronized (mPackages) { 14699 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14700 } 14701 if (childPs != null) { 14702 NativeLibraryHelper.removeNativeBinariesLI(childPs 14703 .legacyNativeLibraryPathString); 14704 } 14705 } 14706 } 14707 } 14708 14709 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14710 // Enable the parent package 14711 mSettings.enableSystemPackageLPw(pkg.packageName); 14712 // Enable the child packages 14713 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14714 for (int i = 0; i < childCount; i++) { 14715 PackageParser.Package childPkg = pkg.childPackages.get(i); 14716 mSettings.enableSystemPackageLPw(childPkg.packageName); 14717 } 14718 } 14719 14720 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14721 PackageParser.Package newPkg) { 14722 // Disable the parent package (parent always replaced) 14723 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14724 // Disable the child packages 14725 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14726 for (int i = 0; i < childCount; i++) { 14727 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14728 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14729 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14730 } 14731 return disabled; 14732 } 14733 14734 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14735 String installerPackageName) { 14736 // Enable the parent package 14737 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14738 // Enable the child packages 14739 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14740 for (int i = 0; i < childCount; i++) { 14741 PackageParser.Package childPkg = pkg.childPackages.get(i); 14742 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14743 } 14744 } 14745 14746 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14747 // Collect all used permissions in the UID 14748 ArraySet<String> usedPermissions = new ArraySet<>(); 14749 final int packageCount = su.packages.size(); 14750 for (int i = 0; i < packageCount; i++) { 14751 PackageSetting ps = su.packages.valueAt(i); 14752 if (ps.pkg == null) { 14753 continue; 14754 } 14755 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14756 for (int j = 0; j < requestedPermCount; j++) { 14757 String permission = ps.pkg.requestedPermissions.get(j); 14758 BasePermission bp = mSettings.mPermissions.get(permission); 14759 if (bp != null) { 14760 usedPermissions.add(permission); 14761 } 14762 } 14763 } 14764 14765 PermissionsState permissionsState = su.getPermissionsState(); 14766 // Prune install permissions 14767 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14768 final int installPermCount = installPermStates.size(); 14769 for (int i = installPermCount - 1; i >= 0; i--) { 14770 PermissionState permissionState = installPermStates.get(i); 14771 if (!usedPermissions.contains(permissionState.getName())) { 14772 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14773 if (bp != null) { 14774 permissionsState.revokeInstallPermission(bp); 14775 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14776 PackageManager.MASK_PERMISSION_FLAGS, 0); 14777 } 14778 } 14779 } 14780 14781 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14782 14783 // Prune runtime permissions 14784 for (int userId : allUserIds) { 14785 List<PermissionState> runtimePermStates = permissionsState 14786 .getRuntimePermissionStates(userId); 14787 final int runtimePermCount = runtimePermStates.size(); 14788 for (int i = runtimePermCount - 1; i >= 0; i--) { 14789 PermissionState permissionState = runtimePermStates.get(i); 14790 if (!usedPermissions.contains(permissionState.getName())) { 14791 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14792 if (bp != null) { 14793 permissionsState.revokeRuntimePermission(bp, userId); 14794 permissionsState.updatePermissionFlags(bp, userId, 14795 PackageManager.MASK_PERMISSION_FLAGS, 0); 14796 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14797 runtimePermissionChangedUserIds, userId); 14798 } 14799 } 14800 } 14801 } 14802 14803 return runtimePermissionChangedUserIds; 14804 } 14805 14806 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14807 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14808 // Update the parent package setting 14809 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14810 res, user); 14811 // Update the child packages setting 14812 final int childCount = (newPackage.childPackages != null) 14813 ? newPackage.childPackages.size() : 0; 14814 for (int i = 0; i < childCount; i++) { 14815 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14816 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14817 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14818 childRes.origUsers, childRes, user); 14819 } 14820 } 14821 14822 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14823 String installerPackageName, int[] allUsers, int[] installedForUsers, 14824 PackageInstalledInfo res, UserHandle user) { 14825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14826 14827 String pkgName = newPackage.packageName; 14828 synchronized (mPackages) { 14829 //write settings. the installStatus will be incomplete at this stage. 14830 //note that the new package setting would have already been 14831 //added to mPackages. It hasn't been persisted yet. 14832 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14834 mSettings.writeLPr(); 14835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14836 } 14837 14838 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14839 synchronized (mPackages) { 14840 updatePermissionsLPw(newPackage.packageName, newPackage, 14841 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14842 ? UPDATE_PERMISSIONS_ALL : 0)); 14843 // For system-bundled packages, we assume that installing an upgraded version 14844 // of the package implies that the user actually wants to run that new code, 14845 // so we enable the package. 14846 PackageSetting ps = mSettings.mPackages.get(pkgName); 14847 final int userId = user.getIdentifier(); 14848 if (ps != null) { 14849 if (isSystemApp(newPackage)) { 14850 if (DEBUG_INSTALL) { 14851 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14852 } 14853 // Enable system package for requested users 14854 if (res.origUsers != null) { 14855 for (int origUserId : res.origUsers) { 14856 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14857 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14858 origUserId, installerPackageName); 14859 } 14860 } 14861 } 14862 // Also convey the prior install/uninstall state 14863 if (allUsers != null && installedForUsers != null) { 14864 for (int currentUserId : allUsers) { 14865 final boolean installed = ArrayUtils.contains( 14866 installedForUsers, currentUserId); 14867 if (DEBUG_INSTALL) { 14868 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14869 } 14870 ps.setInstalled(installed, currentUserId); 14871 } 14872 // these install state changes will be persisted in the 14873 // upcoming call to mSettings.writeLPr(). 14874 } 14875 } 14876 // It's implied that when a user requests installation, they want the app to be 14877 // installed and enabled. 14878 if (userId != UserHandle.USER_ALL) { 14879 ps.setInstalled(true, userId); 14880 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14881 } 14882 } 14883 res.name = pkgName; 14884 res.uid = newPackage.applicationInfo.uid; 14885 res.pkg = newPackage; 14886 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14887 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14888 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14889 //to update install status 14890 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14891 mSettings.writeLPr(); 14892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14893 } 14894 14895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14896 } 14897 14898 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14899 try { 14900 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14901 installPackageLI(args, res); 14902 } finally { 14903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14904 } 14905 } 14906 14907 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14908 final int installFlags = args.installFlags; 14909 final String installerPackageName = args.installerPackageName; 14910 final String volumeUuid = args.volumeUuid; 14911 final File tmpPackageFile = new File(args.getCodePath()); 14912 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14913 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14914 || (args.volumeUuid != null)); 14915 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14916 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14917 boolean replace = false; 14918 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14919 if (args.move != null) { 14920 // moving a complete application; perform an initial scan on the new install location 14921 scanFlags |= SCAN_INITIAL; 14922 } 14923 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14924 scanFlags |= SCAN_DONT_KILL_APP; 14925 } 14926 14927 // Result object to be returned 14928 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14929 14930 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14931 14932 // Sanity check 14933 if (ephemeral && (forwardLocked || onExternal)) { 14934 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14935 + " external=" + onExternal); 14936 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14937 return; 14938 } 14939 14940 // Retrieve PackageSettings and parse package 14941 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14942 | PackageParser.PARSE_ENFORCE_CODE 14943 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14944 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14945 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14946 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14947 PackageParser pp = new PackageParser(); 14948 pp.setSeparateProcesses(mSeparateProcesses); 14949 pp.setDisplayMetrics(mMetrics); 14950 14951 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14952 final PackageParser.Package pkg; 14953 try { 14954 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14955 } catch (PackageParserException e) { 14956 res.setError("Failed parse during installPackageLI", e); 14957 return; 14958 } finally { 14959 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14960 } 14961 14962 // If we are installing a clustered package add results for the children 14963 if (pkg.childPackages != null) { 14964 synchronized (mPackages) { 14965 final int childCount = pkg.childPackages.size(); 14966 for (int i = 0; i < childCount; i++) { 14967 PackageParser.Package childPkg = pkg.childPackages.get(i); 14968 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14969 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14970 childRes.pkg = childPkg; 14971 childRes.name = childPkg.packageName; 14972 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14973 if (childPs != null) { 14974 childRes.origUsers = childPs.queryInstalledUsers( 14975 sUserManager.getUserIds(), true); 14976 } 14977 if ((mPackages.containsKey(childPkg.packageName))) { 14978 childRes.removedInfo = new PackageRemovedInfo(); 14979 childRes.removedInfo.removedPackage = childPkg.packageName; 14980 } 14981 if (res.addedChildPackages == null) { 14982 res.addedChildPackages = new ArrayMap<>(); 14983 } 14984 res.addedChildPackages.put(childPkg.packageName, childRes); 14985 } 14986 } 14987 } 14988 14989 // If package doesn't declare API override, mark that we have an install 14990 // time CPU ABI override. 14991 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14992 pkg.cpuAbiOverride = args.abiOverride; 14993 } 14994 14995 String pkgName = res.name = pkg.packageName; 14996 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14997 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14998 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14999 return; 15000 } 15001 } 15002 15003 try { 15004 // either use what we've been given or parse directly from the APK 15005 if (args.certificates != null) { 15006 try { 15007 PackageParser.populateCertificates(pkg, args.certificates); 15008 } catch (PackageParserException e) { 15009 // there was something wrong with the certificates we were given; 15010 // try to pull them from the APK 15011 PackageParser.collectCertificates(pkg, parseFlags); 15012 } 15013 } else { 15014 PackageParser.collectCertificates(pkg, parseFlags); 15015 } 15016 } catch (PackageParserException e) { 15017 res.setError("Failed collect during installPackageLI", e); 15018 return; 15019 } 15020 15021 // Get rid of all references to package scan path via parser. 15022 pp = null; 15023 String oldCodePath = null; 15024 boolean systemApp = false; 15025 synchronized (mPackages) { 15026 // Check if installing already existing package 15027 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15028 String oldName = mSettings.mRenamedPackages.get(pkgName); 15029 if (pkg.mOriginalPackages != null 15030 && pkg.mOriginalPackages.contains(oldName) 15031 && mPackages.containsKey(oldName)) { 15032 // This package is derived from an original package, 15033 // and this device has been updating from that original 15034 // name. We must continue using the original name, so 15035 // rename the new package here. 15036 pkg.setPackageName(oldName); 15037 pkgName = pkg.packageName; 15038 replace = true; 15039 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15040 + oldName + " pkgName=" + pkgName); 15041 } else if (mPackages.containsKey(pkgName)) { 15042 // This package, under its official name, already exists 15043 // on the device; we should replace it. 15044 replace = true; 15045 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15046 } 15047 15048 // Child packages are installed through the parent package 15049 if (pkg.parentPackage != null) { 15050 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15051 "Package " + pkg.packageName + " is child of package " 15052 + pkg.parentPackage.parentPackage + ". Child packages " 15053 + "can be updated only through the parent package."); 15054 return; 15055 } 15056 15057 if (replace) { 15058 // Prevent apps opting out from runtime permissions 15059 PackageParser.Package oldPackage = mPackages.get(pkgName); 15060 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15061 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15062 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15063 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15064 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15065 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15066 + " doesn't support runtime permissions but the old" 15067 + " target SDK " + oldTargetSdk + " does."); 15068 return; 15069 } 15070 15071 // Prevent installing of child packages 15072 if (oldPackage.parentPackage != null) { 15073 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15074 "Package " + pkg.packageName + " is child of package " 15075 + oldPackage.parentPackage + ". Child packages " 15076 + "can be updated only through the parent package."); 15077 return; 15078 } 15079 } 15080 } 15081 15082 PackageSetting ps = mSettings.mPackages.get(pkgName); 15083 if (ps != null) { 15084 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15085 15086 // Quick sanity check that we're signed correctly if updating; 15087 // we'll check this again later when scanning, but we want to 15088 // bail early here before tripping over redefined permissions. 15089 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15090 if (!checkUpgradeKeySetLP(ps, pkg)) { 15091 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15092 + pkg.packageName + " upgrade keys do not match the " 15093 + "previously installed version"); 15094 return; 15095 } 15096 } else { 15097 try { 15098 verifySignaturesLP(ps, pkg); 15099 } catch (PackageManagerException e) { 15100 res.setError(e.error, e.getMessage()); 15101 return; 15102 } 15103 } 15104 15105 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15106 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15107 systemApp = (ps.pkg.applicationInfo.flags & 15108 ApplicationInfo.FLAG_SYSTEM) != 0; 15109 } 15110 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15111 } 15112 15113 // Check whether the newly-scanned package wants to define an already-defined perm 15114 int N = pkg.permissions.size(); 15115 for (int i = N-1; i >= 0; i--) { 15116 PackageParser.Permission perm = pkg.permissions.get(i); 15117 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15118 if (bp != null) { 15119 // If the defining package is signed with our cert, it's okay. This 15120 // also includes the "updating the same package" case, of course. 15121 // "updating same package" could also involve key-rotation. 15122 final boolean sigsOk; 15123 if (bp.sourcePackage.equals(pkg.packageName) 15124 && (bp.packageSetting instanceof PackageSetting) 15125 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15126 scanFlags))) { 15127 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15128 } else { 15129 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15130 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15131 } 15132 if (!sigsOk) { 15133 // If the owning package is the system itself, we log but allow 15134 // install to proceed; we fail the install on all other permission 15135 // redefinitions. 15136 if (!bp.sourcePackage.equals("android")) { 15137 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15138 + pkg.packageName + " attempting to redeclare permission " 15139 + perm.info.name + " already owned by " + bp.sourcePackage); 15140 res.origPermission = perm.info.name; 15141 res.origPackage = bp.sourcePackage; 15142 return; 15143 } else { 15144 Slog.w(TAG, "Package " + pkg.packageName 15145 + " attempting to redeclare system permission " 15146 + perm.info.name + "; ignoring new declaration"); 15147 pkg.permissions.remove(i); 15148 } 15149 } 15150 } 15151 } 15152 } 15153 15154 if (systemApp) { 15155 if (onExternal) { 15156 // Abort update; system app can't be replaced with app on sdcard 15157 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15158 "Cannot install updates to system apps on sdcard"); 15159 return; 15160 } else if (ephemeral) { 15161 // Abort update; system app can't be replaced with an ephemeral app 15162 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15163 "Cannot update a system app with an ephemeral app"); 15164 return; 15165 } 15166 } 15167 15168 if (args.move != null) { 15169 // We did an in-place move, so dex is ready to roll 15170 scanFlags |= SCAN_NO_DEX; 15171 scanFlags |= SCAN_MOVE; 15172 15173 synchronized (mPackages) { 15174 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15175 if (ps == null) { 15176 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15177 "Missing settings for moved package " + pkgName); 15178 } 15179 15180 // We moved the entire application as-is, so bring over the 15181 // previously derived ABI information. 15182 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15183 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15184 } 15185 15186 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15187 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15188 scanFlags |= SCAN_NO_DEX; 15189 15190 try { 15191 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15192 args.abiOverride : pkg.cpuAbiOverride); 15193 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15194 true /* extract libs */); 15195 } catch (PackageManagerException pme) { 15196 Slog.e(TAG, "Error deriving application ABI", pme); 15197 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15198 return; 15199 } 15200 15201 // Shared libraries for the package need to be updated. 15202 synchronized (mPackages) { 15203 try { 15204 updateSharedLibrariesLPw(pkg, null); 15205 } catch (PackageManagerException e) { 15206 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15207 } 15208 } 15209 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15210 // Do not run PackageDexOptimizer through the local performDexOpt 15211 // method because `pkg` may not be in `mPackages` yet. 15212 // 15213 // Also, don't fail application installs if the dexopt step fails. 15214 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15215 null /* instructionSets */, false /* checkProfiles */, 15216 getCompilerFilterForReason(REASON_INSTALL), 15217 getOrCreateCompilerPackageStats(pkg)); 15218 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15219 15220 // Notify BackgroundDexOptService that the package has been changed. 15221 // If this is an update of a package which used to fail to compile, 15222 // BDOS will remove it from its blacklist. 15223 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15224 } 15225 15226 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15227 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15228 return; 15229 } 15230 15231 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15232 15233 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15234 "installPackageLI")) { 15235 if (replace) { 15236 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15237 installerPackageName, res); 15238 } else { 15239 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15240 args.user, installerPackageName, volumeUuid, res); 15241 } 15242 } 15243 synchronized (mPackages) { 15244 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15245 if (ps != null) { 15246 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15247 } 15248 15249 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15250 for (int i = 0; i < childCount; i++) { 15251 PackageParser.Package childPkg = pkg.childPackages.get(i); 15252 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15253 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15254 if (childPs != null) { 15255 childRes.newUsers = childPs.queryInstalledUsers( 15256 sUserManager.getUserIds(), true); 15257 } 15258 } 15259 } 15260 } 15261 15262 private void startIntentFilterVerifications(int userId, boolean replacing, 15263 PackageParser.Package pkg) { 15264 if (mIntentFilterVerifierComponent == null) { 15265 Slog.w(TAG, "No IntentFilter verification will not be done as " 15266 + "there is no IntentFilterVerifier available!"); 15267 return; 15268 } 15269 15270 final int verifierUid = getPackageUid( 15271 mIntentFilterVerifierComponent.getPackageName(), 15272 MATCH_DEBUG_TRIAGED_MISSING, 15273 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15274 15275 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15276 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15277 mHandler.sendMessage(msg); 15278 15279 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15280 for (int i = 0; i < childCount; i++) { 15281 PackageParser.Package childPkg = pkg.childPackages.get(i); 15282 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15283 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15284 mHandler.sendMessage(msg); 15285 } 15286 } 15287 15288 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15289 PackageParser.Package pkg) { 15290 int size = pkg.activities.size(); 15291 if (size == 0) { 15292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15293 "No activity, so no need to verify any IntentFilter!"); 15294 return; 15295 } 15296 15297 final boolean hasDomainURLs = hasDomainURLs(pkg); 15298 if (!hasDomainURLs) { 15299 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15300 "No domain URLs, so no need to verify any IntentFilter!"); 15301 return; 15302 } 15303 15304 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15305 + " if any IntentFilter from the " + size 15306 + " Activities needs verification ..."); 15307 15308 int count = 0; 15309 final String packageName = pkg.packageName; 15310 15311 synchronized (mPackages) { 15312 // If this is a new install and we see that we've already run verification for this 15313 // package, we have nothing to do: it means the state was restored from backup. 15314 if (!replacing) { 15315 IntentFilterVerificationInfo ivi = 15316 mSettings.getIntentFilterVerificationLPr(packageName); 15317 if (ivi != null) { 15318 if (DEBUG_DOMAIN_VERIFICATION) { 15319 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15320 + ivi.getStatusString()); 15321 } 15322 return; 15323 } 15324 } 15325 15326 // If any filters need to be verified, then all need to be. 15327 boolean needToVerify = false; 15328 for (PackageParser.Activity a : pkg.activities) { 15329 for (ActivityIntentInfo filter : a.intents) { 15330 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15331 if (DEBUG_DOMAIN_VERIFICATION) { 15332 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15333 } 15334 needToVerify = true; 15335 break; 15336 } 15337 } 15338 } 15339 15340 if (needToVerify) { 15341 final int verificationId = mIntentFilterVerificationToken++; 15342 for (PackageParser.Activity a : pkg.activities) { 15343 for (ActivityIntentInfo filter : a.intents) { 15344 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15345 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15346 "Verification needed for IntentFilter:" + filter.toString()); 15347 mIntentFilterVerifier.addOneIntentFilterVerification( 15348 verifierUid, userId, verificationId, filter, packageName); 15349 count++; 15350 } 15351 } 15352 } 15353 } 15354 } 15355 15356 if (count > 0) { 15357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15358 + " IntentFilter verification" + (count > 1 ? "s" : "") 15359 + " for userId:" + userId); 15360 mIntentFilterVerifier.startVerifications(userId); 15361 } else { 15362 if (DEBUG_DOMAIN_VERIFICATION) { 15363 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15364 } 15365 } 15366 } 15367 15368 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15369 final ComponentName cn = filter.activity.getComponentName(); 15370 final String packageName = cn.getPackageName(); 15371 15372 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15373 packageName); 15374 if (ivi == null) { 15375 return true; 15376 } 15377 int status = ivi.getStatus(); 15378 switch (status) { 15379 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15380 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15381 return true; 15382 15383 default: 15384 // Nothing to do 15385 return false; 15386 } 15387 } 15388 15389 private static boolean isMultiArch(ApplicationInfo info) { 15390 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15391 } 15392 15393 private static boolean isExternal(PackageParser.Package pkg) { 15394 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15395 } 15396 15397 private static boolean isExternal(PackageSetting ps) { 15398 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15399 } 15400 15401 private static boolean isEphemeral(PackageParser.Package pkg) { 15402 return pkg.applicationInfo.isEphemeralApp(); 15403 } 15404 15405 private static boolean isEphemeral(PackageSetting ps) { 15406 return ps.pkg != null && isEphemeral(ps.pkg); 15407 } 15408 15409 private static boolean isSystemApp(PackageParser.Package pkg) { 15410 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15411 } 15412 15413 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15414 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15415 } 15416 15417 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15418 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15419 } 15420 15421 private static boolean isSystemApp(PackageSetting ps) { 15422 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15423 } 15424 15425 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15426 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15427 } 15428 15429 private int packageFlagsToInstallFlags(PackageSetting ps) { 15430 int installFlags = 0; 15431 if (isEphemeral(ps)) { 15432 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15433 } 15434 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15435 // This existing package was an external ASEC install when we have 15436 // the external flag without a UUID 15437 installFlags |= PackageManager.INSTALL_EXTERNAL; 15438 } 15439 if (ps.isForwardLocked()) { 15440 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15441 } 15442 return installFlags; 15443 } 15444 15445 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15446 if (isExternal(pkg)) { 15447 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15448 return StorageManager.UUID_PRIMARY_PHYSICAL; 15449 } else { 15450 return pkg.volumeUuid; 15451 } 15452 } else { 15453 return StorageManager.UUID_PRIVATE_INTERNAL; 15454 } 15455 } 15456 15457 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15458 if (isExternal(pkg)) { 15459 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15460 return mSettings.getExternalVersion(); 15461 } else { 15462 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15463 } 15464 } else { 15465 return mSettings.getInternalVersion(); 15466 } 15467 } 15468 15469 private void deleteTempPackageFiles() { 15470 final FilenameFilter filter = new FilenameFilter() { 15471 public boolean accept(File dir, String name) { 15472 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15473 } 15474 }; 15475 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15476 file.delete(); 15477 } 15478 } 15479 15480 @Override 15481 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15482 int flags) { 15483 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15484 flags); 15485 } 15486 15487 @Override 15488 public void deletePackage(final String packageName, 15489 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15490 mContext.enforceCallingOrSelfPermission( 15491 android.Manifest.permission.DELETE_PACKAGES, null); 15492 Preconditions.checkNotNull(packageName); 15493 Preconditions.checkNotNull(observer); 15494 final int uid = Binder.getCallingUid(); 15495 if (!isOrphaned(packageName) 15496 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15497 try { 15498 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15499 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15500 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15501 observer.onUserActionRequired(intent); 15502 } catch (RemoteException re) { 15503 } 15504 return; 15505 } 15506 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15507 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15508 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15509 mContext.enforceCallingOrSelfPermission( 15510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15511 "deletePackage for user " + userId); 15512 } 15513 15514 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15515 try { 15516 observer.onPackageDeleted(packageName, 15517 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15518 } catch (RemoteException re) { 15519 } 15520 return; 15521 } 15522 15523 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15524 try { 15525 observer.onPackageDeleted(packageName, 15526 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15527 } catch (RemoteException re) { 15528 } 15529 return; 15530 } 15531 15532 if (DEBUG_REMOVE) { 15533 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15534 + " deleteAllUsers: " + deleteAllUsers ); 15535 } 15536 // Queue up an async operation since the package deletion may take a little while. 15537 mHandler.post(new Runnable() { 15538 public void run() { 15539 mHandler.removeCallbacks(this); 15540 int returnCode; 15541 if (!deleteAllUsers) { 15542 returnCode = deletePackageX(packageName, userId, deleteFlags); 15543 } else { 15544 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15545 // If nobody is blocking uninstall, proceed with delete for all users 15546 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15547 returnCode = deletePackageX(packageName, userId, deleteFlags); 15548 } else { 15549 // Otherwise uninstall individually for users with blockUninstalls=false 15550 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15551 for (int userId : users) { 15552 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15553 returnCode = deletePackageX(packageName, userId, userFlags); 15554 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15555 Slog.w(TAG, "Package delete failed for user " + userId 15556 + ", returnCode " + returnCode); 15557 } 15558 } 15559 } 15560 // The app has only been marked uninstalled for certain users. 15561 // We still need to report that delete was blocked 15562 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15563 } 15564 } 15565 try { 15566 observer.onPackageDeleted(packageName, returnCode, null); 15567 } catch (RemoteException e) { 15568 Log.i(TAG, "Observer no longer exists."); 15569 } //end catch 15570 } //end run 15571 }); 15572 } 15573 15574 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15575 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15576 || callingUid == Process.SYSTEM_UID) { 15577 return true; 15578 } 15579 final int callingUserId = UserHandle.getUserId(callingUid); 15580 // If the caller installed the pkgName, then allow it to silently uninstall. 15581 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15582 return true; 15583 } 15584 15585 // Allow package verifier to silently uninstall. 15586 if (mRequiredVerifierPackage != null && 15587 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15588 return true; 15589 } 15590 15591 // Allow package uninstaller to silently uninstall. 15592 if (mRequiredUninstallerPackage != null && 15593 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15594 return true; 15595 } 15596 15597 // Allow storage manager to silently uninstall. 15598 if (mStorageManagerPackage != null && 15599 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15600 return true; 15601 } 15602 return false; 15603 } 15604 15605 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15606 int[] result = EMPTY_INT_ARRAY; 15607 for (int userId : userIds) { 15608 if (getBlockUninstallForUser(packageName, userId)) { 15609 result = ArrayUtils.appendInt(result, userId); 15610 } 15611 } 15612 return result; 15613 } 15614 15615 @Override 15616 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15617 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15618 } 15619 15620 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15621 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15622 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15623 try { 15624 if (dpm != null) { 15625 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15626 /* callingUserOnly =*/ false); 15627 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15628 : deviceOwnerComponentName.getPackageName(); 15629 // Does the package contains the device owner? 15630 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15631 // this check is probably not needed, since DO should be registered as a device 15632 // admin on some user too. (Original bug for this: b/17657954) 15633 if (packageName.equals(deviceOwnerPackageName)) { 15634 return true; 15635 } 15636 // Does it contain a device admin for any user? 15637 int[] users; 15638 if (userId == UserHandle.USER_ALL) { 15639 users = sUserManager.getUserIds(); 15640 } else { 15641 users = new int[]{userId}; 15642 } 15643 for (int i = 0; i < users.length; ++i) { 15644 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15645 return true; 15646 } 15647 } 15648 } 15649 } catch (RemoteException e) { 15650 } 15651 return false; 15652 } 15653 15654 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15655 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15656 } 15657 15658 /** 15659 * This method is an internal method that could be get invoked either 15660 * to delete an installed package or to clean up a failed installation. 15661 * After deleting an installed package, a broadcast is sent to notify any 15662 * listeners that the package has been removed. For cleaning up a failed 15663 * installation, the broadcast is not necessary since the package's 15664 * installation wouldn't have sent the initial broadcast either 15665 * The key steps in deleting a package are 15666 * deleting the package information in internal structures like mPackages, 15667 * deleting the packages base directories through installd 15668 * updating mSettings to reflect current status 15669 * persisting settings for later use 15670 * sending a broadcast if necessary 15671 */ 15672 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15673 final PackageRemovedInfo info = new PackageRemovedInfo(); 15674 final boolean res; 15675 15676 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15677 ? UserHandle.USER_ALL : userId; 15678 15679 if (isPackageDeviceAdmin(packageName, removeUser)) { 15680 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15681 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15682 } 15683 15684 PackageSetting uninstalledPs = null; 15685 15686 // for the uninstall-updates case and restricted profiles, remember the per- 15687 // user handle installed state 15688 int[] allUsers; 15689 synchronized (mPackages) { 15690 uninstalledPs = mSettings.mPackages.get(packageName); 15691 if (uninstalledPs == null) { 15692 Slog.w(TAG, "Not removing non-existent package " + packageName); 15693 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15694 } 15695 allUsers = sUserManager.getUserIds(); 15696 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15697 } 15698 15699 final int freezeUser; 15700 if (isUpdatedSystemApp(uninstalledPs) 15701 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15702 // We're downgrading a system app, which will apply to all users, so 15703 // freeze them all during the downgrade 15704 freezeUser = UserHandle.USER_ALL; 15705 } else { 15706 freezeUser = removeUser; 15707 } 15708 15709 synchronized (mInstallLock) { 15710 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15711 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15712 deleteFlags, "deletePackageX")) { 15713 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15714 deleteFlags | REMOVE_CHATTY, info, true, null); 15715 } 15716 synchronized (mPackages) { 15717 if (res) { 15718 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15719 } 15720 } 15721 } 15722 15723 if (res) { 15724 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15725 info.sendPackageRemovedBroadcasts(killApp); 15726 info.sendSystemPackageUpdatedBroadcasts(); 15727 info.sendSystemPackageAppearedBroadcasts(); 15728 } 15729 // Force a gc here. 15730 Runtime.getRuntime().gc(); 15731 // Delete the resources here after sending the broadcast to let 15732 // other processes clean up before deleting resources. 15733 if (info.args != null) { 15734 synchronized (mInstallLock) { 15735 info.args.doPostDeleteLI(true); 15736 } 15737 } 15738 15739 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15740 } 15741 15742 class PackageRemovedInfo { 15743 String removedPackage; 15744 int uid = -1; 15745 int removedAppId = -1; 15746 int[] origUsers; 15747 int[] removedUsers = null; 15748 boolean isRemovedPackageSystemUpdate = false; 15749 boolean isUpdate; 15750 boolean dataRemoved; 15751 boolean removedForAllUsers; 15752 // Clean up resources deleted packages. 15753 InstallArgs args = null; 15754 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15755 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15756 15757 void sendPackageRemovedBroadcasts(boolean killApp) { 15758 sendPackageRemovedBroadcastInternal(killApp); 15759 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15760 for (int i = 0; i < childCount; i++) { 15761 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15762 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15763 } 15764 } 15765 15766 void sendSystemPackageUpdatedBroadcasts() { 15767 if (isRemovedPackageSystemUpdate) { 15768 sendSystemPackageUpdatedBroadcastsInternal(); 15769 final int childCount = (removedChildPackages != null) 15770 ? removedChildPackages.size() : 0; 15771 for (int i = 0; i < childCount; i++) { 15772 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15773 if (childInfo.isRemovedPackageSystemUpdate) { 15774 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15775 } 15776 } 15777 } 15778 } 15779 15780 void sendSystemPackageAppearedBroadcasts() { 15781 final int packageCount = (appearedChildPackages != null) 15782 ? appearedChildPackages.size() : 0; 15783 for (int i = 0; i < packageCount; i++) { 15784 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15785 for (int userId : installedInfo.newUsers) { 15786 sendPackageAddedForUser(installedInfo.name, true, 15787 UserHandle.getAppId(installedInfo.uid), userId); 15788 } 15789 } 15790 } 15791 15792 private void sendSystemPackageUpdatedBroadcastsInternal() { 15793 Bundle extras = new Bundle(2); 15794 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15795 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15796 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15797 extras, 0, null, null, null); 15798 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15799 extras, 0, null, null, null); 15800 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15801 null, 0, removedPackage, null, null); 15802 } 15803 15804 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15805 Bundle extras = new Bundle(2); 15806 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15807 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15808 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15809 if (isUpdate || isRemovedPackageSystemUpdate) { 15810 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15811 } 15812 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15813 if (removedPackage != null) { 15814 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15815 extras, 0, null, null, removedUsers); 15816 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15817 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15818 removedPackage, extras, 0, null, null, removedUsers); 15819 } 15820 } 15821 if (removedAppId >= 0) { 15822 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15823 removedUsers); 15824 } 15825 } 15826 } 15827 15828 /* 15829 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15830 * flag is not set, the data directory is removed as well. 15831 * make sure this flag is set for partially installed apps. If not its meaningless to 15832 * delete a partially installed application. 15833 */ 15834 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15835 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15836 String packageName = ps.name; 15837 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15838 // Retrieve object to delete permissions for shared user later on 15839 final PackageParser.Package deletedPkg; 15840 final PackageSetting deletedPs; 15841 // reader 15842 synchronized (mPackages) { 15843 deletedPkg = mPackages.get(packageName); 15844 deletedPs = mSettings.mPackages.get(packageName); 15845 if (outInfo != null) { 15846 outInfo.removedPackage = packageName; 15847 outInfo.removedUsers = deletedPs != null 15848 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15849 : null; 15850 } 15851 } 15852 15853 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15854 15855 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15856 final PackageParser.Package resolvedPkg; 15857 if (deletedPkg != null) { 15858 resolvedPkg = deletedPkg; 15859 } else { 15860 // We don't have a parsed package when it lives on an ejected 15861 // adopted storage device, so fake something together 15862 resolvedPkg = new PackageParser.Package(ps.name); 15863 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15864 } 15865 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15866 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15867 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15868 if (outInfo != null) { 15869 outInfo.dataRemoved = true; 15870 } 15871 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15872 } 15873 15874 // writer 15875 synchronized (mPackages) { 15876 if (deletedPs != null) { 15877 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15878 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15879 clearDefaultBrowserIfNeeded(packageName); 15880 if (outInfo != null) { 15881 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15882 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15883 } 15884 updatePermissionsLPw(deletedPs.name, null, 0); 15885 if (deletedPs.sharedUser != null) { 15886 // Remove permissions associated with package. Since runtime 15887 // permissions are per user we have to kill the removed package 15888 // or packages running under the shared user of the removed 15889 // package if revoking the permissions requested only by the removed 15890 // package is successful and this causes a change in gids. 15891 for (int userId : UserManagerService.getInstance().getUserIds()) { 15892 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15893 userId); 15894 if (userIdToKill == UserHandle.USER_ALL 15895 || userIdToKill >= UserHandle.USER_SYSTEM) { 15896 // If gids changed for this user, kill all affected packages. 15897 mHandler.post(new Runnable() { 15898 @Override 15899 public void run() { 15900 // This has to happen with no lock held. 15901 killApplication(deletedPs.name, deletedPs.appId, 15902 KILL_APP_REASON_GIDS_CHANGED); 15903 } 15904 }); 15905 break; 15906 } 15907 } 15908 } 15909 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15910 } 15911 // make sure to preserve per-user disabled state if this removal was just 15912 // a downgrade of a system app to the factory package 15913 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15914 if (DEBUG_REMOVE) { 15915 Slog.d(TAG, "Propagating install state across downgrade"); 15916 } 15917 for (int userId : allUserHandles) { 15918 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15919 if (DEBUG_REMOVE) { 15920 Slog.d(TAG, " user " + userId + " => " + installed); 15921 } 15922 ps.setInstalled(installed, userId); 15923 } 15924 } 15925 } 15926 // can downgrade to reader 15927 if (writeSettings) { 15928 // Save settings now 15929 mSettings.writeLPr(); 15930 } 15931 } 15932 if (outInfo != null) { 15933 // A user ID was deleted here. Go through all users and remove it 15934 // from KeyStore. 15935 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15936 } 15937 } 15938 15939 static boolean locationIsPrivileged(File path) { 15940 try { 15941 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15942 .getCanonicalPath(); 15943 return path.getCanonicalPath().startsWith(privilegedAppDir); 15944 } catch (IOException e) { 15945 Slog.e(TAG, "Unable to access code path " + path); 15946 } 15947 return false; 15948 } 15949 15950 /* 15951 * Tries to delete system package. 15952 */ 15953 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15954 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15955 boolean writeSettings) { 15956 if (deletedPs.parentPackageName != null) { 15957 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15958 return false; 15959 } 15960 15961 final boolean applyUserRestrictions 15962 = (allUserHandles != null) && (outInfo.origUsers != null); 15963 final PackageSetting disabledPs; 15964 // Confirm if the system package has been updated 15965 // An updated system app can be deleted. This will also have to restore 15966 // the system pkg from system partition 15967 // reader 15968 synchronized (mPackages) { 15969 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15970 } 15971 15972 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15973 + " disabledPs=" + disabledPs); 15974 15975 if (disabledPs == null) { 15976 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15977 return false; 15978 } else if (DEBUG_REMOVE) { 15979 Slog.d(TAG, "Deleting system pkg from data partition"); 15980 } 15981 15982 if (DEBUG_REMOVE) { 15983 if (applyUserRestrictions) { 15984 Slog.d(TAG, "Remembering install states:"); 15985 for (int userId : allUserHandles) { 15986 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15987 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15988 } 15989 } 15990 } 15991 15992 // Delete the updated package 15993 outInfo.isRemovedPackageSystemUpdate = true; 15994 if (outInfo.removedChildPackages != null) { 15995 final int childCount = (deletedPs.childPackageNames != null) 15996 ? deletedPs.childPackageNames.size() : 0; 15997 for (int i = 0; i < childCount; i++) { 15998 String childPackageName = deletedPs.childPackageNames.get(i); 15999 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16000 .contains(childPackageName)) { 16001 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16002 childPackageName); 16003 if (childInfo != null) { 16004 childInfo.isRemovedPackageSystemUpdate = true; 16005 } 16006 } 16007 } 16008 } 16009 16010 if (disabledPs.versionCode < deletedPs.versionCode) { 16011 // Delete data for downgrades 16012 flags &= ~PackageManager.DELETE_KEEP_DATA; 16013 } else { 16014 // Preserve data by setting flag 16015 flags |= PackageManager.DELETE_KEEP_DATA; 16016 } 16017 16018 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16019 outInfo, writeSettings, disabledPs.pkg); 16020 if (!ret) { 16021 return false; 16022 } 16023 16024 // writer 16025 synchronized (mPackages) { 16026 // Reinstate the old system package 16027 enableSystemPackageLPw(disabledPs.pkg); 16028 // Remove any native libraries from the upgraded package. 16029 removeNativeBinariesLI(deletedPs); 16030 } 16031 16032 // Install the system package 16033 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16034 int parseFlags = mDefParseFlags 16035 | PackageParser.PARSE_MUST_BE_APK 16036 | PackageParser.PARSE_IS_SYSTEM 16037 | PackageParser.PARSE_IS_SYSTEM_DIR; 16038 if (locationIsPrivileged(disabledPs.codePath)) { 16039 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16040 } 16041 16042 final PackageParser.Package newPkg; 16043 try { 16044 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16045 } catch (PackageManagerException e) { 16046 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16047 + e.getMessage()); 16048 return false; 16049 } 16050 try { 16051 // update shared libraries for the newly re-installed system package 16052 updateSharedLibrariesLPw(newPkg, null); 16053 } catch (PackageManagerException e) { 16054 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16055 } 16056 16057 prepareAppDataAfterInstallLIF(newPkg); 16058 16059 // writer 16060 synchronized (mPackages) { 16061 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16062 16063 // Propagate the permissions state as we do not want to drop on the floor 16064 // runtime permissions. The update permissions method below will take 16065 // care of removing obsolete permissions and grant install permissions. 16066 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16067 updatePermissionsLPw(newPkg.packageName, newPkg, 16068 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16069 16070 if (applyUserRestrictions) { 16071 if (DEBUG_REMOVE) { 16072 Slog.d(TAG, "Propagating install state across reinstall"); 16073 } 16074 for (int userId : allUserHandles) { 16075 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16076 if (DEBUG_REMOVE) { 16077 Slog.d(TAG, " user " + userId + " => " + installed); 16078 } 16079 ps.setInstalled(installed, userId); 16080 16081 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16082 } 16083 // Regardless of writeSettings we need to ensure that this restriction 16084 // state propagation is persisted 16085 mSettings.writeAllUsersPackageRestrictionsLPr(); 16086 } 16087 // can downgrade to reader here 16088 if (writeSettings) { 16089 mSettings.writeLPr(); 16090 } 16091 } 16092 return true; 16093 } 16094 16095 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16096 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16097 PackageRemovedInfo outInfo, boolean writeSettings, 16098 PackageParser.Package replacingPackage) { 16099 synchronized (mPackages) { 16100 if (outInfo != null) { 16101 outInfo.uid = ps.appId; 16102 } 16103 16104 if (outInfo != null && outInfo.removedChildPackages != null) { 16105 final int childCount = (ps.childPackageNames != null) 16106 ? ps.childPackageNames.size() : 0; 16107 for (int i = 0; i < childCount; i++) { 16108 String childPackageName = ps.childPackageNames.get(i); 16109 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16110 if (childPs == null) { 16111 return false; 16112 } 16113 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16114 childPackageName); 16115 if (childInfo != null) { 16116 childInfo.uid = childPs.appId; 16117 } 16118 } 16119 } 16120 } 16121 16122 // Delete package data from internal structures and also remove data if flag is set 16123 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16124 16125 // Delete the child packages data 16126 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16127 for (int i = 0; i < childCount; i++) { 16128 PackageSetting childPs; 16129 synchronized (mPackages) { 16130 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16131 } 16132 if (childPs != null) { 16133 PackageRemovedInfo childOutInfo = (outInfo != null 16134 && outInfo.removedChildPackages != null) 16135 ? outInfo.removedChildPackages.get(childPs.name) : null; 16136 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16137 && (replacingPackage != null 16138 && !replacingPackage.hasChildPackage(childPs.name)) 16139 ? flags & ~DELETE_KEEP_DATA : flags; 16140 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16141 deleteFlags, writeSettings); 16142 } 16143 } 16144 16145 // Delete application code and resources only for parent packages 16146 if (ps.parentPackageName == null) { 16147 if (deleteCodeAndResources && (outInfo != null)) { 16148 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16149 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16150 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16151 } 16152 } 16153 16154 return true; 16155 } 16156 16157 @Override 16158 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16159 int userId) { 16160 mContext.enforceCallingOrSelfPermission( 16161 android.Manifest.permission.DELETE_PACKAGES, null); 16162 synchronized (mPackages) { 16163 PackageSetting ps = mSettings.mPackages.get(packageName); 16164 if (ps == null) { 16165 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16166 return false; 16167 } 16168 if (!ps.getInstalled(userId)) { 16169 // Can't block uninstall for an app that is not installed or enabled. 16170 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16171 return false; 16172 } 16173 ps.setBlockUninstall(blockUninstall, userId); 16174 mSettings.writePackageRestrictionsLPr(userId); 16175 } 16176 return true; 16177 } 16178 16179 @Override 16180 public boolean getBlockUninstallForUser(String packageName, int userId) { 16181 synchronized (mPackages) { 16182 PackageSetting ps = mSettings.mPackages.get(packageName); 16183 if (ps == null) { 16184 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16185 return false; 16186 } 16187 return ps.getBlockUninstall(userId); 16188 } 16189 } 16190 16191 @Override 16192 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16193 int callingUid = Binder.getCallingUid(); 16194 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16195 throw new SecurityException( 16196 "setRequiredForSystemUser can only be run by the system or root"); 16197 } 16198 synchronized (mPackages) { 16199 PackageSetting ps = mSettings.mPackages.get(packageName); 16200 if (ps == null) { 16201 Log.w(TAG, "Package doesn't exist: " + packageName); 16202 return false; 16203 } 16204 if (systemUserApp) { 16205 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16206 } else { 16207 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16208 } 16209 mSettings.writeLPr(); 16210 } 16211 return true; 16212 } 16213 16214 /* 16215 * This method handles package deletion in general 16216 */ 16217 private boolean deletePackageLIF(String packageName, UserHandle user, 16218 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16219 PackageRemovedInfo outInfo, boolean writeSettings, 16220 PackageParser.Package replacingPackage) { 16221 if (packageName == null) { 16222 Slog.w(TAG, "Attempt to delete null packageName."); 16223 return false; 16224 } 16225 16226 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16227 16228 PackageSetting ps; 16229 16230 synchronized (mPackages) { 16231 ps = mSettings.mPackages.get(packageName); 16232 if (ps == null) { 16233 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16234 return false; 16235 } 16236 16237 if (ps.parentPackageName != null && (!isSystemApp(ps) 16238 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16239 if (DEBUG_REMOVE) { 16240 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16241 + ((user == null) ? UserHandle.USER_ALL : user)); 16242 } 16243 final int removedUserId = (user != null) ? user.getIdentifier() 16244 : UserHandle.USER_ALL; 16245 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16246 return false; 16247 } 16248 markPackageUninstalledForUserLPw(ps, user); 16249 scheduleWritePackageRestrictionsLocked(user); 16250 return true; 16251 } 16252 } 16253 16254 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16255 && user.getIdentifier() != UserHandle.USER_ALL)) { 16256 // The caller is asking that the package only be deleted for a single 16257 // user. To do this, we just mark its uninstalled state and delete 16258 // its data. If this is a system app, we only allow this to happen if 16259 // they have set the special DELETE_SYSTEM_APP which requests different 16260 // semantics than normal for uninstalling system apps. 16261 markPackageUninstalledForUserLPw(ps, user); 16262 16263 if (!isSystemApp(ps)) { 16264 // Do not uninstall the APK if an app should be cached 16265 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16266 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16267 // Other user still have this package installed, so all 16268 // we need to do is clear this user's data and save that 16269 // it is uninstalled. 16270 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16271 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16272 return false; 16273 } 16274 scheduleWritePackageRestrictionsLocked(user); 16275 return true; 16276 } else { 16277 // We need to set it back to 'installed' so the uninstall 16278 // broadcasts will be sent correctly. 16279 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16280 ps.setInstalled(true, user.getIdentifier()); 16281 } 16282 } else { 16283 // This is a system app, so we assume that the 16284 // other users still have this package installed, so all 16285 // we need to do is clear this user's data and save that 16286 // it is uninstalled. 16287 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16288 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16289 return false; 16290 } 16291 scheduleWritePackageRestrictionsLocked(user); 16292 return true; 16293 } 16294 } 16295 16296 // If we are deleting a composite package for all users, keep track 16297 // of result for each child. 16298 if (ps.childPackageNames != null && outInfo != null) { 16299 synchronized (mPackages) { 16300 final int childCount = ps.childPackageNames.size(); 16301 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16302 for (int i = 0; i < childCount; i++) { 16303 String childPackageName = ps.childPackageNames.get(i); 16304 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16305 childInfo.removedPackage = childPackageName; 16306 outInfo.removedChildPackages.put(childPackageName, childInfo); 16307 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16308 if (childPs != null) { 16309 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16310 } 16311 } 16312 } 16313 } 16314 16315 boolean ret = false; 16316 if (isSystemApp(ps)) { 16317 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16318 // When an updated system application is deleted we delete the existing resources 16319 // as well and fall back to existing code in system partition 16320 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16321 } else { 16322 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16323 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16324 outInfo, writeSettings, replacingPackage); 16325 } 16326 16327 // Take a note whether we deleted the package for all users 16328 if (outInfo != null) { 16329 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16330 if (outInfo.removedChildPackages != null) { 16331 synchronized (mPackages) { 16332 final int childCount = outInfo.removedChildPackages.size(); 16333 for (int i = 0; i < childCount; i++) { 16334 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16335 if (childInfo != null) { 16336 childInfo.removedForAllUsers = mPackages.get( 16337 childInfo.removedPackage) == null; 16338 } 16339 } 16340 } 16341 } 16342 // If we uninstalled an update to a system app there may be some 16343 // child packages that appeared as they are declared in the system 16344 // app but were not declared in the update. 16345 if (isSystemApp(ps)) { 16346 synchronized (mPackages) { 16347 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16348 final int childCount = (updatedPs.childPackageNames != null) 16349 ? updatedPs.childPackageNames.size() : 0; 16350 for (int i = 0; i < childCount; i++) { 16351 String childPackageName = updatedPs.childPackageNames.get(i); 16352 if (outInfo.removedChildPackages == null 16353 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16354 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16355 if (childPs == null) { 16356 continue; 16357 } 16358 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16359 installRes.name = childPackageName; 16360 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16361 installRes.pkg = mPackages.get(childPackageName); 16362 installRes.uid = childPs.pkg.applicationInfo.uid; 16363 if (outInfo.appearedChildPackages == null) { 16364 outInfo.appearedChildPackages = new ArrayMap<>(); 16365 } 16366 outInfo.appearedChildPackages.put(childPackageName, installRes); 16367 } 16368 } 16369 } 16370 } 16371 } 16372 16373 return ret; 16374 } 16375 16376 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16377 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16378 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16379 for (int nextUserId : userIds) { 16380 if (DEBUG_REMOVE) { 16381 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16382 } 16383 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16384 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16385 false /*hidden*/, false /*suspended*/, null, null, null, 16386 false /*blockUninstall*/, 16387 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16388 } 16389 } 16390 16391 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16392 PackageRemovedInfo outInfo) { 16393 final PackageParser.Package pkg; 16394 synchronized (mPackages) { 16395 pkg = mPackages.get(ps.name); 16396 } 16397 16398 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16399 : new int[] {userId}; 16400 for (int nextUserId : userIds) { 16401 if (DEBUG_REMOVE) { 16402 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16403 + nextUserId); 16404 } 16405 16406 destroyAppDataLIF(pkg, userId, 16407 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16408 destroyAppProfilesLIF(pkg, userId); 16409 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16410 schedulePackageCleaning(ps.name, nextUserId, false); 16411 synchronized (mPackages) { 16412 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16413 scheduleWritePackageRestrictionsLocked(nextUserId); 16414 } 16415 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16416 } 16417 } 16418 16419 if (outInfo != null) { 16420 outInfo.removedPackage = ps.name; 16421 outInfo.removedAppId = ps.appId; 16422 outInfo.removedUsers = userIds; 16423 } 16424 16425 return true; 16426 } 16427 16428 private final class ClearStorageConnection implements ServiceConnection { 16429 IMediaContainerService mContainerService; 16430 16431 @Override 16432 public void onServiceConnected(ComponentName name, IBinder service) { 16433 synchronized (this) { 16434 mContainerService = IMediaContainerService.Stub.asInterface(service); 16435 notifyAll(); 16436 } 16437 } 16438 16439 @Override 16440 public void onServiceDisconnected(ComponentName name) { 16441 } 16442 } 16443 16444 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16445 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16446 16447 final boolean mounted; 16448 if (Environment.isExternalStorageEmulated()) { 16449 mounted = true; 16450 } else { 16451 final String status = Environment.getExternalStorageState(); 16452 16453 mounted = status.equals(Environment.MEDIA_MOUNTED) 16454 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16455 } 16456 16457 if (!mounted) { 16458 return; 16459 } 16460 16461 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16462 int[] users; 16463 if (userId == UserHandle.USER_ALL) { 16464 users = sUserManager.getUserIds(); 16465 } else { 16466 users = new int[] { userId }; 16467 } 16468 final ClearStorageConnection conn = new ClearStorageConnection(); 16469 if (mContext.bindServiceAsUser( 16470 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16471 try { 16472 for (int curUser : users) { 16473 long timeout = SystemClock.uptimeMillis() + 5000; 16474 synchronized (conn) { 16475 long now; 16476 while (conn.mContainerService == null && 16477 (now = SystemClock.uptimeMillis()) < timeout) { 16478 try { 16479 conn.wait(timeout - now); 16480 } catch (InterruptedException e) { 16481 } 16482 } 16483 } 16484 if (conn.mContainerService == null) { 16485 return; 16486 } 16487 16488 final UserEnvironment userEnv = new UserEnvironment(curUser); 16489 clearDirectory(conn.mContainerService, 16490 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16491 if (allData) { 16492 clearDirectory(conn.mContainerService, 16493 userEnv.buildExternalStorageAppDataDirs(packageName)); 16494 clearDirectory(conn.mContainerService, 16495 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16496 } 16497 } 16498 } finally { 16499 mContext.unbindService(conn); 16500 } 16501 } 16502 } 16503 16504 @Override 16505 public void clearApplicationProfileData(String packageName) { 16506 enforceSystemOrRoot("Only the system can clear all profile data"); 16507 16508 final PackageParser.Package pkg; 16509 synchronized (mPackages) { 16510 pkg = mPackages.get(packageName); 16511 } 16512 16513 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16514 synchronized (mInstallLock) { 16515 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16516 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16517 true /* removeBaseMarker */); 16518 } 16519 } 16520 } 16521 16522 @Override 16523 public void clearApplicationUserData(final String packageName, 16524 final IPackageDataObserver observer, final int userId) { 16525 mContext.enforceCallingOrSelfPermission( 16526 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16527 16528 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16529 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16530 16531 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16532 throw new SecurityException("Cannot clear data for a protected package: " 16533 + packageName); 16534 } 16535 // Queue up an async operation since the package deletion may take a little while. 16536 mHandler.post(new Runnable() { 16537 public void run() { 16538 mHandler.removeCallbacks(this); 16539 final boolean succeeded; 16540 try (PackageFreezer freezer = freezePackage(packageName, 16541 "clearApplicationUserData")) { 16542 synchronized (mInstallLock) { 16543 succeeded = clearApplicationUserDataLIF(packageName, userId); 16544 } 16545 clearExternalStorageDataSync(packageName, userId, true); 16546 } 16547 if (succeeded) { 16548 // invoke DeviceStorageMonitor's update method to clear any notifications 16549 DeviceStorageMonitorInternal dsm = LocalServices 16550 .getService(DeviceStorageMonitorInternal.class); 16551 if (dsm != null) { 16552 dsm.checkMemory(); 16553 } 16554 } 16555 if(observer != null) { 16556 try { 16557 observer.onRemoveCompleted(packageName, succeeded); 16558 } catch (RemoteException e) { 16559 Log.i(TAG, "Observer no longer exists."); 16560 } 16561 } //end if observer 16562 } //end run 16563 }); 16564 } 16565 16566 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16567 if (packageName == null) { 16568 Slog.w(TAG, "Attempt to delete null packageName."); 16569 return false; 16570 } 16571 16572 // Try finding details about the requested package 16573 PackageParser.Package pkg; 16574 synchronized (mPackages) { 16575 pkg = mPackages.get(packageName); 16576 if (pkg == null) { 16577 final PackageSetting ps = mSettings.mPackages.get(packageName); 16578 if (ps != null) { 16579 pkg = ps.pkg; 16580 } 16581 } 16582 16583 if (pkg == null) { 16584 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16585 return false; 16586 } 16587 16588 PackageSetting ps = (PackageSetting) pkg.mExtras; 16589 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16590 } 16591 16592 clearAppDataLIF(pkg, userId, 16593 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16594 16595 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16596 removeKeystoreDataIfNeeded(userId, appId); 16597 16598 UserManagerInternal umInternal = getUserManagerInternal(); 16599 final int flags; 16600 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16601 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16602 } else if (umInternal.isUserRunning(userId)) { 16603 flags = StorageManager.FLAG_STORAGE_DE; 16604 } else { 16605 flags = 0; 16606 } 16607 prepareAppDataContentsLIF(pkg, userId, flags); 16608 16609 return true; 16610 } 16611 16612 /** 16613 * Reverts user permission state changes (permissions and flags) in 16614 * all packages for a given user. 16615 * 16616 * @param userId The device user for which to do a reset. 16617 */ 16618 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16619 final int packageCount = mPackages.size(); 16620 for (int i = 0; i < packageCount; i++) { 16621 PackageParser.Package pkg = mPackages.valueAt(i); 16622 PackageSetting ps = (PackageSetting) pkg.mExtras; 16623 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16624 } 16625 } 16626 16627 private void resetNetworkPolicies(int userId) { 16628 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16629 } 16630 16631 /** 16632 * Reverts user permission state changes (permissions and flags). 16633 * 16634 * @param ps The package for which to reset. 16635 * @param userId The device user for which to do a reset. 16636 */ 16637 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16638 final PackageSetting ps, final int userId) { 16639 if (ps.pkg == null) { 16640 return; 16641 } 16642 16643 // These are flags that can change base on user actions. 16644 final int userSettableMask = FLAG_PERMISSION_USER_SET 16645 | FLAG_PERMISSION_USER_FIXED 16646 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16647 | FLAG_PERMISSION_REVIEW_REQUIRED; 16648 16649 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16650 | FLAG_PERMISSION_POLICY_FIXED; 16651 16652 boolean writeInstallPermissions = false; 16653 boolean writeRuntimePermissions = false; 16654 16655 final int permissionCount = ps.pkg.requestedPermissions.size(); 16656 for (int i = 0; i < permissionCount; i++) { 16657 String permission = ps.pkg.requestedPermissions.get(i); 16658 16659 BasePermission bp = mSettings.mPermissions.get(permission); 16660 if (bp == null) { 16661 continue; 16662 } 16663 16664 // If shared user we just reset the state to which only this app contributed. 16665 if (ps.sharedUser != null) { 16666 boolean used = false; 16667 final int packageCount = ps.sharedUser.packages.size(); 16668 for (int j = 0; j < packageCount; j++) { 16669 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16670 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16671 && pkg.pkg.requestedPermissions.contains(permission)) { 16672 used = true; 16673 break; 16674 } 16675 } 16676 if (used) { 16677 continue; 16678 } 16679 } 16680 16681 PermissionsState permissionsState = ps.getPermissionsState(); 16682 16683 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16684 16685 // Always clear the user settable flags. 16686 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16687 bp.name) != null; 16688 // If permission review is enabled and this is a legacy app, mark the 16689 // permission as requiring a review as this is the initial state. 16690 int flags = 0; 16691 if (Build.PERMISSIONS_REVIEW_REQUIRED 16692 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16693 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16694 } 16695 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16696 if (hasInstallState) { 16697 writeInstallPermissions = true; 16698 } else { 16699 writeRuntimePermissions = true; 16700 } 16701 } 16702 16703 // Below is only runtime permission handling. 16704 if (!bp.isRuntime()) { 16705 continue; 16706 } 16707 16708 // Never clobber system or policy. 16709 if ((oldFlags & policyOrSystemFlags) != 0) { 16710 continue; 16711 } 16712 16713 // If this permission was granted by default, make sure it is. 16714 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16715 if (permissionsState.grantRuntimePermission(bp, userId) 16716 != PERMISSION_OPERATION_FAILURE) { 16717 writeRuntimePermissions = true; 16718 } 16719 // If permission review is enabled the permissions for a legacy apps 16720 // are represented as constantly granted runtime ones, so don't revoke. 16721 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16722 // Otherwise, reset the permission. 16723 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16724 switch (revokeResult) { 16725 case PERMISSION_OPERATION_SUCCESS: 16726 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16727 writeRuntimePermissions = true; 16728 final int appId = ps.appId; 16729 mHandler.post(new Runnable() { 16730 @Override 16731 public void run() { 16732 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16733 } 16734 }); 16735 } break; 16736 } 16737 } 16738 } 16739 16740 // Synchronously write as we are taking permissions away. 16741 if (writeRuntimePermissions) { 16742 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16743 } 16744 16745 // Synchronously write as we are taking permissions away. 16746 if (writeInstallPermissions) { 16747 mSettings.writeLPr(); 16748 } 16749 } 16750 16751 /** 16752 * Remove entries from the keystore daemon. Will only remove it if the 16753 * {@code appId} is valid. 16754 */ 16755 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16756 if (appId < 0) { 16757 return; 16758 } 16759 16760 final KeyStore keyStore = KeyStore.getInstance(); 16761 if (keyStore != null) { 16762 if (userId == UserHandle.USER_ALL) { 16763 for (final int individual : sUserManager.getUserIds()) { 16764 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16765 } 16766 } else { 16767 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16768 } 16769 } else { 16770 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16771 } 16772 } 16773 16774 @Override 16775 public void deleteApplicationCacheFiles(final String packageName, 16776 final IPackageDataObserver observer) { 16777 final int userId = UserHandle.getCallingUserId(); 16778 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16779 } 16780 16781 @Override 16782 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16783 final IPackageDataObserver observer) { 16784 mContext.enforceCallingOrSelfPermission( 16785 android.Manifest.permission.DELETE_CACHE_FILES, null); 16786 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16787 /* requireFullPermission= */ true, /* checkShell= */ false, 16788 "delete application cache files"); 16789 16790 final PackageParser.Package pkg; 16791 synchronized (mPackages) { 16792 pkg = mPackages.get(packageName); 16793 } 16794 16795 // Queue up an async operation since the package deletion may take a little while. 16796 mHandler.post(new Runnable() { 16797 public void run() { 16798 synchronized (mInstallLock) { 16799 final int flags = StorageManager.FLAG_STORAGE_DE 16800 | StorageManager.FLAG_STORAGE_CE; 16801 // We're only clearing cache files, so we don't care if the 16802 // app is unfrozen and still able to run 16803 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16804 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16805 } 16806 clearExternalStorageDataSync(packageName, userId, false); 16807 if (observer != null) { 16808 try { 16809 observer.onRemoveCompleted(packageName, true); 16810 } catch (RemoteException e) { 16811 Log.i(TAG, "Observer no longer exists."); 16812 } 16813 } 16814 } 16815 }); 16816 } 16817 16818 @Override 16819 public void getPackageSizeInfo(final String packageName, int userHandle, 16820 final IPackageStatsObserver observer) { 16821 mContext.enforceCallingOrSelfPermission( 16822 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16823 if (packageName == null) { 16824 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16825 } 16826 16827 PackageStats stats = new PackageStats(packageName, userHandle); 16828 16829 /* 16830 * Queue up an async operation since the package measurement may take a 16831 * little while. 16832 */ 16833 Message msg = mHandler.obtainMessage(INIT_COPY); 16834 msg.obj = new MeasureParams(stats, observer); 16835 mHandler.sendMessage(msg); 16836 } 16837 16838 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16839 final PackageSetting ps; 16840 synchronized (mPackages) { 16841 ps = mSettings.mPackages.get(packageName); 16842 if (ps == null) { 16843 Slog.w(TAG, "Failed to find settings for " + packageName); 16844 return false; 16845 } 16846 } 16847 try { 16848 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16849 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16850 ps.getCeDataInode(userId), ps.codePathString, stats); 16851 } catch (InstallerException e) { 16852 Slog.w(TAG, String.valueOf(e)); 16853 return false; 16854 } 16855 16856 // For now, ignore code size of packages on system partition 16857 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16858 stats.codeSize = 0; 16859 } 16860 16861 return true; 16862 } 16863 16864 private int getUidTargetSdkVersionLockedLPr(int uid) { 16865 Object obj = mSettings.getUserIdLPr(uid); 16866 if (obj instanceof SharedUserSetting) { 16867 final SharedUserSetting sus = (SharedUserSetting) obj; 16868 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16869 final Iterator<PackageSetting> it = sus.packages.iterator(); 16870 while (it.hasNext()) { 16871 final PackageSetting ps = it.next(); 16872 if (ps.pkg != null) { 16873 int v = ps.pkg.applicationInfo.targetSdkVersion; 16874 if (v < vers) vers = v; 16875 } 16876 } 16877 return vers; 16878 } else if (obj instanceof PackageSetting) { 16879 final PackageSetting ps = (PackageSetting) obj; 16880 if (ps.pkg != null) { 16881 return ps.pkg.applicationInfo.targetSdkVersion; 16882 } 16883 } 16884 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16885 } 16886 16887 @Override 16888 public void addPreferredActivity(IntentFilter filter, int match, 16889 ComponentName[] set, ComponentName activity, int userId) { 16890 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16891 "Adding preferred"); 16892 } 16893 16894 private void addPreferredActivityInternal(IntentFilter filter, int match, 16895 ComponentName[] set, ComponentName activity, boolean always, int userId, 16896 String opname) { 16897 // writer 16898 int callingUid = Binder.getCallingUid(); 16899 enforceCrossUserPermission(callingUid, userId, 16900 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16901 if (filter.countActions() == 0) { 16902 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16903 return; 16904 } 16905 synchronized (mPackages) { 16906 if (mContext.checkCallingOrSelfPermission( 16907 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16908 != PackageManager.PERMISSION_GRANTED) { 16909 if (getUidTargetSdkVersionLockedLPr(callingUid) 16910 < Build.VERSION_CODES.FROYO) { 16911 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16912 + callingUid); 16913 return; 16914 } 16915 mContext.enforceCallingOrSelfPermission( 16916 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16917 } 16918 16919 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16920 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16921 + userId + ":"); 16922 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16923 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16924 scheduleWritePackageRestrictionsLocked(userId); 16925 postPreferredActivityChangedBroadcast(userId); 16926 } 16927 } 16928 16929 private void postPreferredActivityChangedBroadcast(int userId) { 16930 mHandler.post(() -> { 16931 final IActivityManager am = ActivityManagerNative.getDefault(); 16932 if (am == null) { 16933 return; 16934 } 16935 16936 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16937 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16938 try { 16939 am.broadcastIntent(null, intent, null, null, 16940 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16941 null, false, false, userId); 16942 } catch (RemoteException e) { 16943 } 16944 }); 16945 } 16946 16947 @Override 16948 public void replacePreferredActivity(IntentFilter filter, int match, 16949 ComponentName[] set, ComponentName activity, int userId) { 16950 if (filter.countActions() != 1) { 16951 throw new IllegalArgumentException( 16952 "replacePreferredActivity expects filter to have only 1 action."); 16953 } 16954 if (filter.countDataAuthorities() != 0 16955 || filter.countDataPaths() != 0 16956 || filter.countDataSchemes() > 1 16957 || filter.countDataTypes() != 0) { 16958 throw new IllegalArgumentException( 16959 "replacePreferredActivity expects filter to have no data authorities, " + 16960 "paths, or types; and at most one scheme."); 16961 } 16962 16963 final int callingUid = Binder.getCallingUid(); 16964 enforceCrossUserPermission(callingUid, userId, 16965 true /* requireFullPermission */, false /* checkShell */, 16966 "replace preferred activity"); 16967 synchronized (mPackages) { 16968 if (mContext.checkCallingOrSelfPermission( 16969 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16970 != PackageManager.PERMISSION_GRANTED) { 16971 if (getUidTargetSdkVersionLockedLPr(callingUid) 16972 < Build.VERSION_CODES.FROYO) { 16973 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16974 + Binder.getCallingUid()); 16975 return; 16976 } 16977 mContext.enforceCallingOrSelfPermission( 16978 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16979 } 16980 16981 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16982 if (pir != null) { 16983 // Get all of the existing entries that exactly match this filter. 16984 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16985 if (existing != null && existing.size() == 1) { 16986 PreferredActivity cur = existing.get(0); 16987 if (DEBUG_PREFERRED) { 16988 Slog.i(TAG, "Checking replace of preferred:"); 16989 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16990 if (!cur.mPref.mAlways) { 16991 Slog.i(TAG, " -- CUR; not mAlways!"); 16992 } else { 16993 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16994 Slog.i(TAG, " -- CUR: mSet=" 16995 + Arrays.toString(cur.mPref.mSetComponents)); 16996 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16997 Slog.i(TAG, " -- NEW: mMatch=" 16998 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16999 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17000 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17001 } 17002 } 17003 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17004 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17005 && cur.mPref.sameSet(set)) { 17006 // Setting the preferred activity to what it happens to be already 17007 if (DEBUG_PREFERRED) { 17008 Slog.i(TAG, "Replacing with same preferred activity " 17009 + cur.mPref.mShortComponent + " for user " 17010 + userId + ":"); 17011 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17012 } 17013 return; 17014 } 17015 } 17016 17017 if (existing != null) { 17018 if (DEBUG_PREFERRED) { 17019 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17020 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17021 } 17022 for (int i = 0; i < existing.size(); i++) { 17023 PreferredActivity pa = existing.get(i); 17024 if (DEBUG_PREFERRED) { 17025 Slog.i(TAG, "Removing existing preferred activity " 17026 + pa.mPref.mComponent + ":"); 17027 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17028 } 17029 pir.removeFilter(pa); 17030 } 17031 } 17032 } 17033 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17034 "Replacing preferred"); 17035 } 17036 } 17037 17038 @Override 17039 public void clearPackagePreferredActivities(String packageName) { 17040 final int uid = Binder.getCallingUid(); 17041 // writer 17042 synchronized (mPackages) { 17043 PackageParser.Package pkg = mPackages.get(packageName); 17044 if (pkg == null || pkg.applicationInfo.uid != uid) { 17045 if (mContext.checkCallingOrSelfPermission( 17046 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17047 != PackageManager.PERMISSION_GRANTED) { 17048 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17049 < Build.VERSION_CODES.FROYO) { 17050 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17051 + Binder.getCallingUid()); 17052 return; 17053 } 17054 mContext.enforceCallingOrSelfPermission( 17055 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17056 } 17057 } 17058 17059 int user = UserHandle.getCallingUserId(); 17060 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17061 scheduleWritePackageRestrictionsLocked(user); 17062 } 17063 } 17064 } 17065 17066 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17067 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17068 ArrayList<PreferredActivity> removed = null; 17069 boolean changed = false; 17070 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17071 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17072 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17073 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17074 continue; 17075 } 17076 Iterator<PreferredActivity> it = pir.filterIterator(); 17077 while (it.hasNext()) { 17078 PreferredActivity pa = it.next(); 17079 // Mark entry for removal only if it matches the package name 17080 // and the entry is of type "always". 17081 if (packageName == null || 17082 (pa.mPref.mComponent.getPackageName().equals(packageName) 17083 && pa.mPref.mAlways)) { 17084 if (removed == null) { 17085 removed = new ArrayList<PreferredActivity>(); 17086 } 17087 removed.add(pa); 17088 } 17089 } 17090 if (removed != null) { 17091 for (int j=0; j<removed.size(); j++) { 17092 PreferredActivity pa = removed.get(j); 17093 pir.removeFilter(pa); 17094 } 17095 changed = true; 17096 } 17097 } 17098 if (changed) { 17099 postPreferredActivityChangedBroadcast(userId); 17100 } 17101 return changed; 17102 } 17103 17104 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17105 private void clearIntentFilterVerificationsLPw(int userId) { 17106 final int packageCount = mPackages.size(); 17107 for (int i = 0; i < packageCount; i++) { 17108 PackageParser.Package pkg = mPackages.valueAt(i); 17109 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17110 } 17111 } 17112 17113 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17114 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17115 if (userId == UserHandle.USER_ALL) { 17116 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17117 sUserManager.getUserIds())) { 17118 for (int oneUserId : sUserManager.getUserIds()) { 17119 scheduleWritePackageRestrictionsLocked(oneUserId); 17120 } 17121 } 17122 } else { 17123 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17124 scheduleWritePackageRestrictionsLocked(userId); 17125 } 17126 } 17127 } 17128 17129 void clearDefaultBrowserIfNeeded(String packageName) { 17130 for (int oneUserId : sUserManager.getUserIds()) { 17131 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17132 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17133 if (packageName.equals(defaultBrowserPackageName)) { 17134 setDefaultBrowserPackageName(null, oneUserId); 17135 } 17136 } 17137 } 17138 17139 @Override 17140 public void resetApplicationPreferences(int userId) { 17141 mContext.enforceCallingOrSelfPermission( 17142 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17143 final long identity = Binder.clearCallingIdentity(); 17144 // writer 17145 try { 17146 synchronized (mPackages) { 17147 clearPackagePreferredActivitiesLPw(null, userId); 17148 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17149 // TODO: We have to reset the default SMS and Phone. This requires 17150 // significant refactoring to keep all default apps in the package 17151 // manager (cleaner but more work) or have the services provide 17152 // callbacks to the package manager to request a default app reset. 17153 applyFactoryDefaultBrowserLPw(userId); 17154 clearIntentFilterVerificationsLPw(userId); 17155 primeDomainVerificationsLPw(userId); 17156 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17157 scheduleWritePackageRestrictionsLocked(userId); 17158 } 17159 resetNetworkPolicies(userId); 17160 } finally { 17161 Binder.restoreCallingIdentity(identity); 17162 } 17163 } 17164 17165 @Override 17166 public int getPreferredActivities(List<IntentFilter> outFilters, 17167 List<ComponentName> outActivities, String packageName) { 17168 17169 int num = 0; 17170 final int userId = UserHandle.getCallingUserId(); 17171 // reader 17172 synchronized (mPackages) { 17173 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17174 if (pir != null) { 17175 final Iterator<PreferredActivity> it = pir.filterIterator(); 17176 while (it.hasNext()) { 17177 final PreferredActivity pa = it.next(); 17178 if (packageName == null 17179 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17180 && pa.mPref.mAlways)) { 17181 if (outFilters != null) { 17182 outFilters.add(new IntentFilter(pa)); 17183 } 17184 if (outActivities != null) { 17185 outActivities.add(pa.mPref.mComponent); 17186 } 17187 } 17188 } 17189 } 17190 } 17191 17192 return num; 17193 } 17194 17195 @Override 17196 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17197 int userId) { 17198 int callingUid = Binder.getCallingUid(); 17199 if (callingUid != Process.SYSTEM_UID) { 17200 throw new SecurityException( 17201 "addPersistentPreferredActivity can only be run by the system"); 17202 } 17203 if (filter.countActions() == 0) { 17204 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17205 return; 17206 } 17207 synchronized (mPackages) { 17208 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17209 ":"); 17210 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17211 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17212 new PersistentPreferredActivity(filter, activity)); 17213 scheduleWritePackageRestrictionsLocked(userId); 17214 postPreferredActivityChangedBroadcast(userId); 17215 } 17216 } 17217 17218 @Override 17219 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17220 int callingUid = Binder.getCallingUid(); 17221 if (callingUid != Process.SYSTEM_UID) { 17222 throw new SecurityException( 17223 "clearPackagePersistentPreferredActivities can only be run by the system"); 17224 } 17225 ArrayList<PersistentPreferredActivity> removed = null; 17226 boolean changed = false; 17227 synchronized (mPackages) { 17228 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17229 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17230 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17231 .valueAt(i); 17232 if (userId != thisUserId) { 17233 continue; 17234 } 17235 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17236 while (it.hasNext()) { 17237 PersistentPreferredActivity ppa = it.next(); 17238 // Mark entry for removal only if it matches the package name. 17239 if (ppa.mComponent.getPackageName().equals(packageName)) { 17240 if (removed == null) { 17241 removed = new ArrayList<PersistentPreferredActivity>(); 17242 } 17243 removed.add(ppa); 17244 } 17245 } 17246 if (removed != null) { 17247 for (int j=0; j<removed.size(); j++) { 17248 PersistentPreferredActivity ppa = removed.get(j); 17249 ppir.removeFilter(ppa); 17250 } 17251 changed = true; 17252 } 17253 } 17254 17255 if (changed) { 17256 scheduleWritePackageRestrictionsLocked(userId); 17257 postPreferredActivityChangedBroadcast(userId); 17258 } 17259 } 17260 } 17261 17262 /** 17263 * Common machinery for picking apart a restored XML blob and passing 17264 * it to a caller-supplied functor to be applied to the running system. 17265 */ 17266 private void restoreFromXml(XmlPullParser parser, int userId, 17267 String expectedStartTag, BlobXmlRestorer functor) 17268 throws IOException, XmlPullParserException { 17269 int type; 17270 while ((type = parser.next()) != XmlPullParser.START_TAG 17271 && type != XmlPullParser.END_DOCUMENT) { 17272 } 17273 if (type != XmlPullParser.START_TAG) { 17274 // oops didn't find a start tag?! 17275 if (DEBUG_BACKUP) { 17276 Slog.e(TAG, "Didn't find start tag during restore"); 17277 } 17278 return; 17279 } 17280Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17281 // this is supposed to be TAG_PREFERRED_BACKUP 17282 if (!expectedStartTag.equals(parser.getName())) { 17283 if (DEBUG_BACKUP) { 17284 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17285 } 17286 return; 17287 } 17288 17289 // skip interfering stuff, then we're aligned with the backing implementation 17290 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17291Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17292 functor.apply(parser, userId); 17293 } 17294 17295 private interface BlobXmlRestorer { 17296 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17297 } 17298 17299 /** 17300 * Non-Binder method, support for the backup/restore mechanism: write the 17301 * full set of preferred activities in its canonical XML format. Returns the 17302 * XML output as a byte array, or null if there is none. 17303 */ 17304 @Override 17305 public byte[] getPreferredActivityBackup(int userId) { 17306 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17307 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17308 } 17309 17310 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17311 try { 17312 final XmlSerializer serializer = new FastXmlSerializer(); 17313 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17314 serializer.startDocument(null, true); 17315 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17316 17317 synchronized (mPackages) { 17318 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17319 } 17320 17321 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17322 serializer.endDocument(); 17323 serializer.flush(); 17324 } catch (Exception e) { 17325 if (DEBUG_BACKUP) { 17326 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17327 } 17328 return null; 17329 } 17330 17331 return dataStream.toByteArray(); 17332 } 17333 17334 @Override 17335 public void restorePreferredActivities(byte[] backup, int userId) { 17336 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17337 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17338 } 17339 17340 try { 17341 final XmlPullParser parser = Xml.newPullParser(); 17342 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17343 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17344 new BlobXmlRestorer() { 17345 @Override 17346 public void apply(XmlPullParser parser, int userId) 17347 throws XmlPullParserException, IOException { 17348 synchronized (mPackages) { 17349 mSettings.readPreferredActivitiesLPw(parser, userId); 17350 } 17351 } 17352 } ); 17353 } catch (Exception e) { 17354 if (DEBUG_BACKUP) { 17355 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17356 } 17357 } 17358 } 17359 17360 /** 17361 * Non-Binder method, support for the backup/restore mechanism: write the 17362 * default browser (etc) settings in its canonical XML format. Returns the default 17363 * browser XML representation as a byte array, or null if there is none. 17364 */ 17365 @Override 17366 public byte[] getDefaultAppsBackup(int userId) { 17367 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17368 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17369 } 17370 17371 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17372 try { 17373 final XmlSerializer serializer = new FastXmlSerializer(); 17374 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17375 serializer.startDocument(null, true); 17376 serializer.startTag(null, TAG_DEFAULT_APPS); 17377 17378 synchronized (mPackages) { 17379 mSettings.writeDefaultAppsLPr(serializer, userId); 17380 } 17381 17382 serializer.endTag(null, TAG_DEFAULT_APPS); 17383 serializer.endDocument(); 17384 serializer.flush(); 17385 } catch (Exception e) { 17386 if (DEBUG_BACKUP) { 17387 Slog.e(TAG, "Unable to write default apps for backup", e); 17388 } 17389 return null; 17390 } 17391 17392 return dataStream.toByteArray(); 17393 } 17394 17395 @Override 17396 public void restoreDefaultApps(byte[] backup, int userId) { 17397 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17398 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17399 } 17400 17401 try { 17402 final XmlPullParser parser = Xml.newPullParser(); 17403 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17404 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17405 new BlobXmlRestorer() { 17406 @Override 17407 public void apply(XmlPullParser parser, int userId) 17408 throws XmlPullParserException, IOException { 17409 synchronized (mPackages) { 17410 mSettings.readDefaultAppsLPw(parser, userId); 17411 } 17412 } 17413 } ); 17414 } catch (Exception e) { 17415 if (DEBUG_BACKUP) { 17416 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17417 } 17418 } 17419 } 17420 17421 @Override 17422 public byte[] getIntentFilterVerificationBackup(int userId) { 17423 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17424 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17425 } 17426 17427 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17428 try { 17429 final XmlSerializer serializer = new FastXmlSerializer(); 17430 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17431 serializer.startDocument(null, true); 17432 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17433 17434 synchronized (mPackages) { 17435 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17436 } 17437 17438 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17439 serializer.endDocument(); 17440 serializer.flush(); 17441 } catch (Exception e) { 17442 if (DEBUG_BACKUP) { 17443 Slog.e(TAG, "Unable to write default apps for backup", e); 17444 } 17445 return null; 17446 } 17447 17448 return dataStream.toByteArray(); 17449 } 17450 17451 @Override 17452 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17453 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17454 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17455 } 17456 17457 try { 17458 final XmlPullParser parser = Xml.newPullParser(); 17459 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17460 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17461 new BlobXmlRestorer() { 17462 @Override 17463 public void apply(XmlPullParser parser, int userId) 17464 throws XmlPullParserException, IOException { 17465 synchronized (mPackages) { 17466 mSettings.readAllDomainVerificationsLPr(parser, userId); 17467 mSettings.writeLPr(); 17468 } 17469 } 17470 } ); 17471 } catch (Exception e) { 17472 if (DEBUG_BACKUP) { 17473 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17474 } 17475 } 17476 } 17477 17478 @Override 17479 public byte[] getPermissionGrantBackup(int userId) { 17480 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17481 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17482 } 17483 17484 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17485 try { 17486 final XmlSerializer serializer = new FastXmlSerializer(); 17487 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17488 serializer.startDocument(null, true); 17489 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17490 17491 synchronized (mPackages) { 17492 serializeRuntimePermissionGrantsLPr(serializer, userId); 17493 } 17494 17495 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17496 serializer.endDocument(); 17497 serializer.flush(); 17498 } catch (Exception e) { 17499 if (DEBUG_BACKUP) { 17500 Slog.e(TAG, "Unable to write default apps for backup", e); 17501 } 17502 return null; 17503 } 17504 17505 return dataStream.toByteArray(); 17506 } 17507 17508 @Override 17509 public void restorePermissionGrants(byte[] backup, int userId) { 17510 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17511 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17512 } 17513 17514 try { 17515 final XmlPullParser parser = Xml.newPullParser(); 17516 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17517 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17518 new BlobXmlRestorer() { 17519 @Override 17520 public void apply(XmlPullParser parser, int userId) 17521 throws XmlPullParserException, IOException { 17522 synchronized (mPackages) { 17523 processRestoredPermissionGrantsLPr(parser, userId); 17524 } 17525 } 17526 } ); 17527 } catch (Exception e) { 17528 if (DEBUG_BACKUP) { 17529 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17530 } 17531 } 17532 } 17533 17534 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17535 throws IOException { 17536 serializer.startTag(null, TAG_ALL_GRANTS); 17537 17538 final int N = mSettings.mPackages.size(); 17539 for (int i = 0; i < N; i++) { 17540 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17541 boolean pkgGrantsKnown = false; 17542 17543 PermissionsState packagePerms = ps.getPermissionsState(); 17544 17545 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17546 final int grantFlags = state.getFlags(); 17547 // only look at grants that are not system/policy fixed 17548 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17549 final boolean isGranted = state.isGranted(); 17550 // And only back up the user-twiddled state bits 17551 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17552 final String packageName = mSettings.mPackages.keyAt(i); 17553 if (!pkgGrantsKnown) { 17554 serializer.startTag(null, TAG_GRANT); 17555 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17556 pkgGrantsKnown = true; 17557 } 17558 17559 final boolean userSet = 17560 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17561 final boolean userFixed = 17562 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17563 final boolean revoke = 17564 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17565 17566 serializer.startTag(null, TAG_PERMISSION); 17567 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17568 if (isGranted) { 17569 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17570 } 17571 if (userSet) { 17572 serializer.attribute(null, ATTR_USER_SET, "true"); 17573 } 17574 if (userFixed) { 17575 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17576 } 17577 if (revoke) { 17578 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17579 } 17580 serializer.endTag(null, TAG_PERMISSION); 17581 } 17582 } 17583 } 17584 17585 if (pkgGrantsKnown) { 17586 serializer.endTag(null, TAG_GRANT); 17587 } 17588 } 17589 17590 serializer.endTag(null, TAG_ALL_GRANTS); 17591 } 17592 17593 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17594 throws XmlPullParserException, IOException { 17595 String pkgName = null; 17596 int outerDepth = parser.getDepth(); 17597 int type; 17598 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17599 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17600 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17601 continue; 17602 } 17603 17604 final String tagName = parser.getName(); 17605 if (tagName.equals(TAG_GRANT)) { 17606 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17607 if (DEBUG_BACKUP) { 17608 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17609 } 17610 } else if (tagName.equals(TAG_PERMISSION)) { 17611 17612 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17613 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17614 17615 int newFlagSet = 0; 17616 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17617 newFlagSet |= FLAG_PERMISSION_USER_SET; 17618 } 17619 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17620 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17621 } 17622 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17623 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17624 } 17625 if (DEBUG_BACKUP) { 17626 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17627 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17628 } 17629 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17630 if (ps != null) { 17631 // Already installed so we apply the grant immediately 17632 if (DEBUG_BACKUP) { 17633 Slog.v(TAG, " + already installed; applying"); 17634 } 17635 PermissionsState perms = ps.getPermissionsState(); 17636 BasePermission bp = mSettings.mPermissions.get(permName); 17637 if (bp != null) { 17638 if (isGranted) { 17639 perms.grantRuntimePermission(bp, userId); 17640 } 17641 if (newFlagSet != 0) { 17642 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17643 } 17644 } 17645 } else { 17646 // Need to wait for post-restore install to apply the grant 17647 if (DEBUG_BACKUP) { 17648 Slog.v(TAG, " - not yet installed; saving for later"); 17649 } 17650 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17651 isGranted, newFlagSet, userId); 17652 } 17653 } else { 17654 PackageManagerService.reportSettingsProblem(Log.WARN, 17655 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17656 XmlUtils.skipCurrentTag(parser); 17657 } 17658 } 17659 17660 scheduleWriteSettingsLocked(); 17661 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17662 } 17663 17664 @Override 17665 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17666 int sourceUserId, int targetUserId, int flags) { 17667 mContext.enforceCallingOrSelfPermission( 17668 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17669 int callingUid = Binder.getCallingUid(); 17670 enforceOwnerRights(ownerPackage, callingUid); 17671 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17672 if (intentFilter.countActions() == 0) { 17673 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17674 return; 17675 } 17676 synchronized (mPackages) { 17677 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17678 ownerPackage, targetUserId, flags); 17679 CrossProfileIntentResolver resolver = 17680 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17681 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17682 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17683 if (existing != null) { 17684 int size = existing.size(); 17685 for (int i = 0; i < size; i++) { 17686 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17687 return; 17688 } 17689 } 17690 } 17691 resolver.addFilter(newFilter); 17692 scheduleWritePackageRestrictionsLocked(sourceUserId); 17693 } 17694 } 17695 17696 @Override 17697 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17698 mContext.enforceCallingOrSelfPermission( 17699 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17700 int callingUid = Binder.getCallingUid(); 17701 enforceOwnerRights(ownerPackage, callingUid); 17702 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17703 synchronized (mPackages) { 17704 CrossProfileIntentResolver resolver = 17705 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17706 ArraySet<CrossProfileIntentFilter> set = 17707 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17708 for (CrossProfileIntentFilter filter : set) { 17709 if (filter.getOwnerPackage().equals(ownerPackage)) { 17710 resolver.removeFilter(filter); 17711 } 17712 } 17713 scheduleWritePackageRestrictionsLocked(sourceUserId); 17714 } 17715 } 17716 17717 // Enforcing that callingUid is owning pkg on userId 17718 private void enforceOwnerRights(String pkg, int callingUid) { 17719 // The system owns everything. 17720 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17721 return; 17722 } 17723 int callingUserId = UserHandle.getUserId(callingUid); 17724 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17725 if (pi == null) { 17726 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17727 + callingUserId); 17728 } 17729 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17730 throw new SecurityException("Calling uid " + callingUid 17731 + " does not own package " + pkg); 17732 } 17733 } 17734 17735 @Override 17736 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17737 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17738 } 17739 17740 private Intent getHomeIntent() { 17741 Intent intent = new Intent(Intent.ACTION_MAIN); 17742 intent.addCategory(Intent.CATEGORY_HOME); 17743 intent.addCategory(Intent.CATEGORY_DEFAULT); 17744 return intent; 17745 } 17746 17747 private IntentFilter getHomeFilter() { 17748 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17749 filter.addCategory(Intent.CATEGORY_HOME); 17750 filter.addCategory(Intent.CATEGORY_DEFAULT); 17751 return filter; 17752 } 17753 17754 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17755 int userId) { 17756 Intent intent = getHomeIntent(); 17757 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17758 PackageManager.GET_META_DATA, userId); 17759 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17760 true, false, false, userId); 17761 17762 allHomeCandidates.clear(); 17763 if (list != null) { 17764 for (ResolveInfo ri : list) { 17765 allHomeCandidates.add(ri); 17766 } 17767 } 17768 return (preferred == null || preferred.activityInfo == null) 17769 ? null 17770 : new ComponentName(preferred.activityInfo.packageName, 17771 preferred.activityInfo.name); 17772 } 17773 17774 @Override 17775 public void setHomeActivity(ComponentName comp, int userId) { 17776 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17777 getHomeActivitiesAsUser(homeActivities, userId); 17778 17779 boolean found = false; 17780 17781 final int size = homeActivities.size(); 17782 final ComponentName[] set = new ComponentName[size]; 17783 for (int i = 0; i < size; i++) { 17784 final ResolveInfo candidate = homeActivities.get(i); 17785 final ActivityInfo info = candidate.activityInfo; 17786 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17787 set[i] = activityName; 17788 if (!found && activityName.equals(comp)) { 17789 found = true; 17790 } 17791 } 17792 if (!found) { 17793 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17794 + userId); 17795 } 17796 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17797 set, comp, userId); 17798 } 17799 17800 private @Nullable String getSetupWizardPackageName() { 17801 final Intent intent = new Intent(Intent.ACTION_MAIN); 17802 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17803 17804 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17805 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17806 | MATCH_DISABLED_COMPONENTS, 17807 UserHandle.myUserId()); 17808 if (matches.size() == 1) { 17809 return matches.get(0).getComponentInfo().packageName; 17810 } else { 17811 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17812 + ": matches=" + matches); 17813 return null; 17814 } 17815 } 17816 17817 private @Nullable String getStorageManagerPackageName() { 17818 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17819 17820 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17821 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17822 | MATCH_DISABLED_COMPONENTS, 17823 UserHandle.myUserId()); 17824 if (matches.size() == 1) { 17825 return matches.get(0).getComponentInfo().packageName; 17826 } else { 17827 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17828 + matches.size() + ": matches=" + matches); 17829 return null; 17830 } 17831 } 17832 17833 @Override 17834 public void setApplicationEnabledSetting(String appPackageName, 17835 int newState, int flags, int userId, String callingPackage) { 17836 if (!sUserManager.exists(userId)) return; 17837 if (callingPackage == null) { 17838 callingPackage = Integer.toString(Binder.getCallingUid()); 17839 } 17840 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17841 } 17842 17843 @Override 17844 public void setComponentEnabledSetting(ComponentName componentName, 17845 int newState, int flags, int userId) { 17846 if (!sUserManager.exists(userId)) return; 17847 setEnabledSetting(componentName.getPackageName(), 17848 componentName.getClassName(), newState, flags, userId, null); 17849 } 17850 17851 private void setEnabledSetting(final String packageName, String className, int newState, 17852 final int flags, int userId, String callingPackage) { 17853 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17854 || newState == COMPONENT_ENABLED_STATE_ENABLED 17855 || newState == COMPONENT_ENABLED_STATE_DISABLED 17856 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17857 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17858 throw new IllegalArgumentException("Invalid new component state: " 17859 + newState); 17860 } 17861 PackageSetting pkgSetting; 17862 final int uid = Binder.getCallingUid(); 17863 final int permission; 17864 if (uid == Process.SYSTEM_UID) { 17865 permission = PackageManager.PERMISSION_GRANTED; 17866 } else { 17867 permission = mContext.checkCallingOrSelfPermission( 17868 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17869 } 17870 enforceCrossUserPermission(uid, userId, 17871 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17872 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17873 boolean sendNow = false; 17874 boolean isApp = (className == null); 17875 String componentName = isApp ? packageName : className; 17876 int packageUid = -1; 17877 ArrayList<String> components; 17878 17879 // writer 17880 synchronized (mPackages) { 17881 pkgSetting = mSettings.mPackages.get(packageName); 17882 if (pkgSetting == null) { 17883 if (className == null) { 17884 throw new IllegalArgumentException("Unknown package: " + packageName); 17885 } 17886 throw new IllegalArgumentException( 17887 "Unknown component: " + packageName + "/" + className); 17888 } 17889 } 17890 17891 // Limit who can change which apps 17892 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17893 // Don't allow apps that don't have permission to modify other apps 17894 if (!allowedByPermission) { 17895 throw new SecurityException( 17896 "Permission Denial: attempt to change component state from pid=" 17897 + Binder.getCallingPid() 17898 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17899 } 17900 // Don't allow changing protected packages. 17901 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17902 throw new SecurityException("Cannot disable a protected package: " + packageName); 17903 } 17904 } 17905 17906 synchronized (mPackages) { 17907 if (uid == Process.SHELL_UID) { 17908 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17909 int oldState = pkgSetting.getEnabled(userId); 17910 if (className == null 17911 && 17912 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17913 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17914 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17915 && 17916 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17917 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17918 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17919 // ok 17920 } else { 17921 throw new SecurityException( 17922 "Shell cannot change component state for " + packageName + "/" 17923 + className + " to " + newState); 17924 } 17925 } 17926 if (className == null) { 17927 // We're dealing with an application/package level state change 17928 if (pkgSetting.getEnabled(userId) == newState) { 17929 // Nothing to do 17930 return; 17931 } 17932 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17933 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17934 // Don't care about who enables an app. 17935 callingPackage = null; 17936 } 17937 pkgSetting.setEnabled(newState, userId, callingPackage); 17938 // pkgSetting.pkg.mSetEnabled = newState; 17939 } else { 17940 // We're dealing with a component level state change 17941 // First, verify that this is a valid class name. 17942 PackageParser.Package pkg = pkgSetting.pkg; 17943 if (pkg == null || !pkg.hasComponentClassName(className)) { 17944 if (pkg != null && 17945 pkg.applicationInfo.targetSdkVersion >= 17946 Build.VERSION_CODES.JELLY_BEAN) { 17947 throw new IllegalArgumentException("Component class " + className 17948 + " does not exist in " + packageName); 17949 } else { 17950 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17951 + className + " does not exist in " + packageName); 17952 } 17953 } 17954 switch (newState) { 17955 case COMPONENT_ENABLED_STATE_ENABLED: 17956 if (!pkgSetting.enableComponentLPw(className, userId)) { 17957 return; 17958 } 17959 break; 17960 case COMPONENT_ENABLED_STATE_DISABLED: 17961 if (!pkgSetting.disableComponentLPw(className, userId)) { 17962 return; 17963 } 17964 break; 17965 case COMPONENT_ENABLED_STATE_DEFAULT: 17966 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17967 return; 17968 } 17969 break; 17970 default: 17971 Slog.e(TAG, "Invalid new component state: " + newState); 17972 return; 17973 } 17974 } 17975 scheduleWritePackageRestrictionsLocked(userId); 17976 components = mPendingBroadcasts.get(userId, packageName); 17977 final boolean newPackage = components == null; 17978 if (newPackage) { 17979 components = new ArrayList<String>(); 17980 } 17981 if (!components.contains(componentName)) { 17982 components.add(componentName); 17983 } 17984 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17985 sendNow = true; 17986 // Purge entry from pending broadcast list if another one exists already 17987 // since we are sending one right away. 17988 mPendingBroadcasts.remove(userId, packageName); 17989 } else { 17990 if (newPackage) { 17991 mPendingBroadcasts.put(userId, packageName, components); 17992 } 17993 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17994 // Schedule a message 17995 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17996 } 17997 } 17998 } 17999 18000 long callingId = Binder.clearCallingIdentity(); 18001 try { 18002 if (sendNow) { 18003 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18004 sendPackageChangedBroadcast(packageName, 18005 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18006 } 18007 } finally { 18008 Binder.restoreCallingIdentity(callingId); 18009 } 18010 } 18011 18012 @Override 18013 public void flushPackageRestrictionsAsUser(int userId) { 18014 if (!sUserManager.exists(userId)) { 18015 return; 18016 } 18017 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18018 false /* checkShell */, "flushPackageRestrictions"); 18019 synchronized (mPackages) { 18020 mSettings.writePackageRestrictionsLPr(userId); 18021 mDirtyUsers.remove(userId); 18022 if (mDirtyUsers.isEmpty()) { 18023 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18024 } 18025 } 18026 } 18027 18028 private void sendPackageChangedBroadcast(String packageName, 18029 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18030 if (DEBUG_INSTALL) 18031 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18032 + componentNames); 18033 Bundle extras = new Bundle(4); 18034 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18035 String nameList[] = new String[componentNames.size()]; 18036 componentNames.toArray(nameList); 18037 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18038 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18039 extras.putInt(Intent.EXTRA_UID, packageUid); 18040 // If this is not reporting a change of the overall package, then only send it 18041 // to registered receivers. We don't want to launch a swath of apps for every 18042 // little component state change. 18043 final int flags = !componentNames.contains(packageName) 18044 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18045 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18046 new int[] {UserHandle.getUserId(packageUid)}); 18047 } 18048 18049 @Override 18050 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18051 if (!sUserManager.exists(userId)) return; 18052 final int uid = Binder.getCallingUid(); 18053 final int permission = mContext.checkCallingOrSelfPermission( 18054 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18055 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18056 enforceCrossUserPermission(uid, userId, 18057 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18058 // writer 18059 synchronized (mPackages) { 18060 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18061 allowedByPermission, uid, userId)) { 18062 scheduleWritePackageRestrictionsLocked(userId); 18063 } 18064 } 18065 } 18066 18067 @Override 18068 public String getInstallerPackageName(String packageName) { 18069 // reader 18070 synchronized (mPackages) { 18071 return mSettings.getInstallerPackageNameLPr(packageName); 18072 } 18073 } 18074 18075 public boolean isOrphaned(String packageName) { 18076 // reader 18077 synchronized (mPackages) { 18078 return mSettings.isOrphaned(packageName); 18079 } 18080 } 18081 18082 @Override 18083 public int getApplicationEnabledSetting(String packageName, int userId) { 18084 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18085 int uid = Binder.getCallingUid(); 18086 enforceCrossUserPermission(uid, userId, 18087 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18088 // reader 18089 synchronized (mPackages) { 18090 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18091 } 18092 } 18093 18094 @Override 18095 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18096 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18097 int uid = Binder.getCallingUid(); 18098 enforceCrossUserPermission(uid, userId, 18099 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18100 // reader 18101 synchronized (mPackages) { 18102 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18103 } 18104 } 18105 18106 @Override 18107 public void enterSafeMode() { 18108 enforceSystemOrRoot("Only the system can request entering safe mode"); 18109 18110 if (!mSystemReady) { 18111 mSafeMode = true; 18112 } 18113 } 18114 18115 @Override 18116 public void systemReady() { 18117 mSystemReady = true; 18118 18119 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18120 // disabled after already being started. 18121 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18122 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18123 18124 // Read the compatibilty setting when the system is ready. 18125 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18126 mContext.getContentResolver(), 18127 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18128 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18129 if (DEBUG_SETTINGS) { 18130 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18131 } 18132 18133 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18134 18135 synchronized (mPackages) { 18136 // Verify that all of the preferred activity components actually 18137 // exist. It is possible for applications to be updated and at 18138 // that point remove a previously declared activity component that 18139 // had been set as a preferred activity. We try to clean this up 18140 // the next time we encounter that preferred activity, but it is 18141 // possible for the user flow to never be able to return to that 18142 // situation so here we do a sanity check to make sure we haven't 18143 // left any junk around. 18144 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18145 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18146 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18147 removed.clear(); 18148 for (PreferredActivity pa : pir.filterSet()) { 18149 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18150 removed.add(pa); 18151 } 18152 } 18153 if (removed.size() > 0) { 18154 for (int r=0; r<removed.size(); r++) { 18155 PreferredActivity pa = removed.get(r); 18156 Slog.w(TAG, "Removing dangling preferred activity: " 18157 + pa.mPref.mComponent); 18158 pir.removeFilter(pa); 18159 } 18160 mSettings.writePackageRestrictionsLPr( 18161 mSettings.mPreferredActivities.keyAt(i)); 18162 } 18163 } 18164 18165 for (int userId : UserManagerService.getInstance().getUserIds()) { 18166 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18167 grantPermissionsUserIds = ArrayUtils.appendInt( 18168 grantPermissionsUserIds, userId); 18169 } 18170 } 18171 } 18172 sUserManager.systemReady(); 18173 18174 // If we upgraded grant all default permissions before kicking off. 18175 for (int userId : grantPermissionsUserIds) { 18176 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18177 } 18178 18179 // If we did not grant default permissions, we preload from this the 18180 // default permission exceptions lazily to ensure we don't hit the 18181 // disk on a new user creation. 18182 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18183 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18184 } 18185 18186 // Kick off any messages waiting for system ready 18187 if (mPostSystemReadyMessages != null) { 18188 for (Message msg : mPostSystemReadyMessages) { 18189 msg.sendToTarget(); 18190 } 18191 mPostSystemReadyMessages = null; 18192 } 18193 18194 // Watch for external volumes that come and go over time 18195 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18196 storage.registerListener(mStorageListener); 18197 18198 mInstallerService.systemReady(); 18199 mPackageDexOptimizer.systemReady(); 18200 18201 MountServiceInternal mountServiceInternal = LocalServices.getService( 18202 MountServiceInternal.class); 18203 mountServiceInternal.addExternalStoragePolicy( 18204 new MountServiceInternal.ExternalStorageMountPolicy() { 18205 @Override 18206 public int getMountMode(int uid, String packageName) { 18207 if (Process.isIsolated(uid)) { 18208 return Zygote.MOUNT_EXTERNAL_NONE; 18209 } 18210 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18211 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18212 } 18213 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18214 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18215 } 18216 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18217 return Zygote.MOUNT_EXTERNAL_READ; 18218 } 18219 return Zygote.MOUNT_EXTERNAL_WRITE; 18220 } 18221 18222 @Override 18223 public boolean hasExternalStorage(int uid, String packageName) { 18224 return true; 18225 } 18226 }); 18227 18228 // Now that we're mostly running, clean up stale users and apps 18229 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18230 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18231 } 18232 18233 @Override 18234 public boolean isSafeMode() { 18235 return mSafeMode; 18236 } 18237 18238 @Override 18239 public boolean hasSystemUidErrors() { 18240 return mHasSystemUidErrors; 18241 } 18242 18243 static String arrayToString(int[] array) { 18244 StringBuffer buf = new StringBuffer(128); 18245 buf.append('['); 18246 if (array != null) { 18247 for (int i=0; i<array.length; i++) { 18248 if (i > 0) buf.append(", "); 18249 buf.append(array[i]); 18250 } 18251 } 18252 buf.append(']'); 18253 return buf.toString(); 18254 } 18255 18256 static class DumpState { 18257 public static final int DUMP_LIBS = 1 << 0; 18258 public static final int DUMP_FEATURES = 1 << 1; 18259 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18260 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18261 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18262 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18263 public static final int DUMP_PERMISSIONS = 1 << 6; 18264 public static final int DUMP_PACKAGES = 1 << 7; 18265 public static final int DUMP_SHARED_USERS = 1 << 8; 18266 public static final int DUMP_MESSAGES = 1 << 9; 18267 public static final int DUMP_PROVIDERS = 1 << 10; 18268 public static final int DUMP_VERIFIERS = 1 << 11; 18269 public static final int DUMP_PREFERRED = 1 << 12; 18270 public static final int DUMP_PREFERRED_XML = 1 << 13; 18271 public static final int DUMP_KEYSETS = 1 << 14; 18272 public static final int DUMP_VERSION = 1 << 15; 18273 public static final int DUMP_INSTALLS = 1 << 16; 18274 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18275 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18276 public static final int DUMP_FROZEN = 1 << 19; 18277 public static final int DUMP_DEXOPT = 1 << 20; 18278 public static final int DUMP_COMPILER_STATS = 1 << 21; 18279 18280 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18281 18282 private int mTypes; 18283 18284 private int mOptions; 18285 18286 private boolean mTitlePrinted; 18287 18288 private SharedUserSetting mSharedUser; 18289 18290 public boolean isDumping(int type) { 18291 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18292 return true; 18293 } 18294 18295 return (mTypes & type) != 0; 18296 } 18297 18298 public void setDump(int type) { 18299 mTypes |= type; 18300 } 18301 18302 public boolean isOptionEnabled(int option) { 18303 return (mOptions & option) != 0; 18304 } 18305 18306 public void setOptionEnabled(int option) { 18307 mOptions |= option; 18308 } 18309 18310 public boolean onTitlePrinted() { 18311 final boolean printed = mTitlePrinted; 18312 mTitlePrinted = true; 18313 return printed; 18314 } 18315 18316 public boolean getTitlePrinted() { 18317 return mTitlePrinted; 18318 } 18319 18320 public void setTitlePrinted(boolean enabled) { 18321 mTitlePrinted = enabled; 18322 } 18323 18324 public SharedUserSetting getSharedUser() { 18325 return mSharedUser; 18326 } 18327 18328 public void setSharedUser(SharedUserSetting user) { 18329 mSharedUser = user; 18330 } 18331 } 18332 18333 @Override 18334 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18335 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18336 (new PackageManagerShellCommand(this)).exec( 18337 this, in, out, err, args, resultReceiver); 18338 } 18339 18340 @Override 18341 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18342 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18343 != PackageManager.PERMISSION_GRANTED) { 18344 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18345 + Binder.getCallingPid() 18346 + ", uid=" + Binder.getCallingUid() 18347 + " without permission " 18348 + android.Manifest.permission.DUMP); 18349 return; 18350 } 18351 18352 DumpState dumpState = new DumpState(); 18353 boolean fullPreferred = false; 18354 boolean checkin = false; 18355 18356 String packageName = null; 18357 ArraySet<String> permissionNames = null; 18358 18359 int opti = 0; 18360 while (opti < args.length) { 18361 String opt = args[opti]; 18362 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18363 break; 18364 } 18365 opti++; 18366 18367 if ("-a".equals(opt)) { 18368 // Right now we only know how to print all. 18369 } else if ("-h".equals(opt)) { 18370 pw.println("Package manager dump options:"); 18371 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18372 pw.println(" --checkin: dump for a checkin"); 18373 pw.println(" -f: print details of intent filters"); 18374 pw.println(" -h: print this help"); 18375 pw.println(" cmd may be one of:"); 18376 pw.println(" l[ibraries]: list known shared libraries"); 18377 pw.println(" f[eatures]: list device features"); 18378 pw.println(" k[eysets]: print known keysets"); 18379 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18380 pw.println(" perm[issions]: dump permissions"); 18381 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18382 pw.println(" pref[erred]: print preferred package settings"); 18383 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18384 pw.println(" prov[iders]: dump content providers"); 18385 pw.println(" p[ackages]: dump installed packages"); 18386 pw.println(" s[hared-users]: dump shared user IDs"); 18387 pw.println(" m[essages]: print collected runtime messages"); 18388 pw.println(" v[erifiers]: print package verifier info"); 18389 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18390 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18391 pw.println(" version: print database version info"); 18392 pw.println(" write: write current settings now"); 18393 pw.println(" installs: details about install sessions"); 18394 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18395 pw.println(" dexopt: dump dexopt state"); 18396 pw.println(" compiler-stats: dump compiler statistics"); 18397 pw.println(" <package.name>: info about given package"); 18398 return; 18399 } else if ("--checkin".equals(opt)) { 18400 checkin = true; 18401 } else if ("-f".equals(opt)) { 18402 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18403 } else { 18404 pw.println("Unknown argument: " + opt + "; use -h for help"); 18405 } 18406 } 18407 18408 // Is the caller requesting to dump a particular piece of data? 18409 if (opti < args.length) { 18410 String cmd = args[opti]; 18411 opti++; 18412 // Is this a package name? 18413 if ("android".equals(cmd) || cmd.contains(".")) { 18414 packageName = cmd; 18415 // When dumping a single package, we always dump all of its 18416 // filter information since the amount of data will be reasonable. 18417 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18418 } else if ("check-permission".equals(cmd)) { 18419 if (opti >= args.length) { 18420 pw.println("Error: check-permission missing permission argument"); 18421 return; 18422 } 18423 String perm = args[opti]; 18424 opti++; 18425 if (opti >= args.length) { 18426 pw.println("Error: check-permission missing package argument"); 18427 return; 18428 } 18429 String pkg = args[opti]; 18430 opti++; 18431 int user = UserHandle.getUserId(Binder.getCallingUid()); 18432 if (opti < args.length) { 18433 try { 18434 user = Integer.parseInt(args[opti]); 18435 } catch (NumberFormatException e) { 18436 pw.println("Error: check-permission user argument is not a number: " 18437 + args[opti]); 18438 return; 18439 } 18440 } 18441 pw.println(checkPermission(perm, pkg, user)); 18442 return; 18443 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18444 dumpState.setDump(DumpState.DUMP_LIBS); 18445 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18446 dumpState.setDump(DumpState.DUMP_FEATURES); 18447 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18448 if (opti >= args.length) { 18449 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18450 | DumpState.DUMP_SERVICE_RESOLVERS 18451 | DumpState.DUMP_RECEIVER_RESOLVERS 18452 | DumpState.DUMP_CONTENT_RESOLVERS); 18453 } else { 18454 while (opti < args.length) { 18455 String name = args[opti]; 18456 if ("a".equals(name) || "activity".equals(name)) { 18457 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18458 } else if ("s".equals(name) || "service".equals(name)) { 18459 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18460 } else if ("r".equals(name) || "receiver".equals(name)) { 18461 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18462 } else if ("c".equals(name) || "content".equals(name)) { 18463 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18464 } else { 18465 pw.println("Error: unknown resolver table type: " + name); 18466 return; 18467 } 18468 opti++; 18469 } 18470 } 18471 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18472 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18473 } else if ("permission".equals(cmd)) { 18474 if (opti >= args.length) { 18475 pw.println("Error: permission requires permission name"); 18476 return; 18477 } 18478 permissionNames = new ArraySet<>(); 18479 while (opti < args.length) { 18480 permissionNames.add(args[opti]); 18481 opti++; 18482 } 18483 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18484 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18485 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18486 dumpState.setDump(DumpState.DUMP_PREFERRED); 18487 } else if ("preferred-xml".equals(cmd)) { 18488 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18489 if (opti < args.length && "--full".equals(args[opti])) { 18490 fullPreferred = true; 18491 opti++; 18492 } 18493 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18494 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18495 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18496 dumpState.setDump(DumpState.DUMP_PACKAGES); 18497 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18498 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18499 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18500 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18501 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18502 dumpState.setDump(DumpState.DUMP_MESSAGES); 18503 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18504 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18505 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18506 || "intent-filter-verifiers".equals(cmd)) { 18507 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18508 } else if ("version".equals(cmd)) { 18509 dumpState.setDump(DumpState.DUMP_VERSION); 18510 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18511 dumpState.setDump(DumpState.DUMP_KEYSETS); 18512 } else if ("installs".equals(cmd)) { 18513 dumpState.setDump(DumpState.DUMP_INSTALLS); 18514 } else if ("frozen".equals(cmd)) { 18515 dumpState.setDump(DumpState.DUMP_FROZEN); 18516 } else if ("dexopt".equals(cmd)) { 18517 dumpState.setDump(DumpState.DUMP_DEXOPT); 18518 } else if ("compiler-stats".equals(cmd)) { 18519 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18520 } else if ("write".equals(cmd)) { 18521 synchronized (mPackages) { 18522 mSettings.writeLPr(); 18523 pw.println("Settings written."); 18524 return; 18525 } 18526 } 18527 } 18528 18529 if (checkin) { 18530 pw.println("vers,1"); 18531 } 18532 18533 // reader 18534 synchronized (mPackages) { 18535 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18536 if (!checkin) { 18537 if (dumpState.onTitlePrinted()) 18538 pw.println(); 18539 pw.println("Database versions:"); 18540 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18541 } 18542 } 18543 18544 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18545 if (!checkin) { 18546 if (dumpState.onTitlePrinted()) 18547 pw.println(); 18548 pw.println("Verifiers:"); 18549 pw.print(" Required: "); 18550 pw.print(mRequiredVerifierPackage); 18551 pw.print(" (uid="); 18552 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18553 UserHandle.USER_SYSTEM)); 18554 pw.println(")"); 18555 } else if (mRequiredVerifierPackage != null) { 18556 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18557 pw.print(","); 18558 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18559 UserHandle.USER_SYSTEM)); 18560 } 18561 } 18562 18563 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18564 packageName == null) { 18565 if (mIntentFilterVerifierComponent != null) { 18566 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18567 if (!checkin) { 18568 if (dumpState.onTitlePrinted()) 18569 pw.println(); 18570 pw.println("Intent Filter Verifier:"); 18571 pw.print(" Using: "); 18572 pw.print(verifierPackageName); 18573 pw.print(" (uid="); 18574 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18575 UserHandle.USER_SYSTEM)); 18576 pw.println(")"); 18577 } else if (verifierPackageName != null) { 18578 pw.print("ifv,"); pw.print(verifierPackageName); 18579 pw.print(","); 18580 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18581 UserHandle.USER_SYSTEM)); 18582 } 18583 } else { 18584 pw.println(); 18585 pw.println("No Intent Filter Verifier available!"); 18586 } 18587 } 18588 18589 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18590 boolean printedHeader = false; 18591 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18592 while (it.hasNext()) { 18593 String name = it.next(); 18594 SharedLibraryEntry ent = mSharedLibraries.get(name); 18595 if (!checkin) { 18596 if (!printedHeader) { 18597 if (dumpState.onTitlePrinted()) 18598 pw.println(); 18599 pw.println("Libraries:"); 18600 printedHeader = true; 18601 } 18602 pw.print(" "); 18603 } else { 18604 pw.print("lib,"); 18605 } 18606 pw.print(name); 18607 if (!checkin) { 18608 pw.print(" -> "); 18609 } 18610 if (ent.path != null) { 18611 if (!checkin) { 18612 pw.print("(jar) "); 18613 pw.print(ent.path); 18614 } else { 18615 pw.print(",jar,"); 18616 pw.print(ent.path); 18617 } 18618 } else { 18619 if (!checkin) { 18620 pw.print("(apk) "); 18621 pw.print(ent.apk); 18622 } else { 18623 pw.print(",apk,"); 18624 pw.print(ent.apk); 18625 } 18626 } 18627 pw.println(); 18628 } 18629 } 18630 18631 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18632 if (dumpState.onTitlePrinted()) 18633 pw.println(); 18634 if (!checkin) { 18635 pw.println("Features:"); 18636 } 18637 18638 for (FeatureInfo feat : mAvailableFeatures.values()) { 18639 if (checkin) { 18640 pw.print("feat,"); 18641 pw.print(feat.name); 18642 pw.print(","); 18643 pw.println(feat.version); 18644 } else { 18645 pw.print(" "); 18646 pw.print(feat.name); 18647 if (feat.version > 0) { 18648 pw.print(" version="); 18649 pw.print(feat.version); 18650 } 18651 pw.println(); 18652 } 18653 } 18654 } 18655 18656 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18657 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18658 : "Activity Resolver Table:", " ", packageName, 18659 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18660 dumpState.setTitlePrinted(true); 18661 } 18662 } 18663 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18664 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18665 : "Receiver Resolver Table:", " ", packageName, 18666 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18667 dumpState.setTitlePrinted(true); 18668 } 18669 } 18670 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18671 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18672 : "Service Resolver Table:", " ", packageName, 18673 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18674 dumpState.setTitlePrinted(true); 18675 } 18676 } 18677 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18678 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18679 : "Provider Resolver Table:", " ", packageName, 18680 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18681 dumpState.setTitlePrinted(true); 18682 } 18683 } 18684 18685 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18686 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18687 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18688 int user = mSettings.mPreferredActivities.keyAt(i); 18689 if (pir.dump(pw, 18690 dumpState.getTitlePrinted() 18691 ? "\nPreferred Activities User " + user + ":" 18692 : "Preferred Activities User " + user + ":", " ", 18693 packageName, true, false)) { 18694 dumpState.setTitlePrinted(true); 18695 } 18696 } 18697 } 18698 18699 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18700 pw.flush(); 18701 FileOutputStream fout = new FileOutputStream(fd); 18702 BufferedOutputStream str = new BufferedOutputStream(fout); 18703 XmlSerializer serializer = new FastXmlSerializer(); 18704 try { 18705 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18706 serializer.startDocument(null, true); 18707 serializer.setFeature( 18708 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18709 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18710 serializer.endDocument(); 18711 serializer.flush(); 18712 } catch (IllegalArgumentException e) { 18713 pw.println("Failed writing: " + e); 18714 } catch (IllegalStateException e) { 18715 pw.println("Failed writing: " + e); 18716 } catch (IOException e) { 18717 pw.println("Failed writing: " + e); 18718 } 18719 } 18720 18721 if (!checkin 18722 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18723 && packageName == null) { 18724 pw.println(); 18725 int count = mSettings.mPackages.size(); 18726 if (count == 0) { 18727 pw.println("No applications!"); 18728 pw.println(); 18729 } else { 18730 final String prefix = " "; 18731 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18732 if (allPackageSettings.size() == 0) { 18733 pw.println("No domain preferred apps!"); 18734 pw.println(); 18735 } else { 18736 pw.println("App verification status:"); 18737 pw.println(); 18738 count = 0; 18739 for (PackageSetting ps : allPackageSettings) { 18740 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18741 if (ivi == null || ivi.getPackageName() == null) continue; 18742 pw.println(prefix + "Package: " + ivi.getPackageName()); 18743 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18744 pw.println(prefix + "Status: " + ivi.getStatusString()); 18745 pw.println(); 18746 count++; 18747 } 18748 if (count == 0) { 18749 pw.println(prefix + "No app verification established."); 18750 pw.println(); 18751 } 18752 for (int userId : sUserManager.getUserIds()) { 18753 pw.println("App linkages for user " + userId + ":"); 18754 pw.println(); 18755 count = 0; 18756 for (PackageSetting ps : allPackageSettings) { 18757 final long status = ps.getDomainVerificationStatusForUser(userId); 18758 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18759 continue; 18760 } 18761 pw.println(prefix + "Package: " + ps.name); 18762 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18763 String statusStr = IntentFilterVerificationInfo. 18764 getStatusStringFromValue(status); 18765 pw.println(prefix + "Status: " + statusStr); 18766 pw.println(); 18767 count++; 18768 } 18769 if (count == 0) { 18770 pw.println(prefix + "No configured app linkages."); 18771 pw.println(); 18772 } 18773 } 18774 } 18775 } 18776 } 18777 18778 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18779 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18780 if (packageName == null && permissionNames == null) { 18781 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18782 if (iperm == 0) { 18783 if (dumpState.onTitlePrinted()) 18784 pw.println(); 18785 pw.println("AppOp Permissions:"); 18786 } 18787 pw.print(" AppOp Permission "); 18788 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18789 pw.println(":"); 18790 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18791 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18792 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18793 } 18794 } 18795 } 18796 } 18797 18798 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18799 boolean printedSomething = false; 18800 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18801 if (packageName != null && !packageName.equals(p.info.packageName)) { 18802 continue; 18803 } 18804 if (!printedSomething) { 18805 if (dumpState.onTitlePrinted()) 18806 pw.println(); 18807 pw.println("Registered ContentProviders:"); 18808 printedSomething = true; 18809 } 18810 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18811 pw.print(" "); pw.println(p.toString()); 18812 } 18813 printedSomething = false; 18814 for (Map.Entry<String, PackageParser.Provider> entry : 18815 mProvidersByAuthority.entrySet()) { 18816 PackageParser.Provider p = entry.getValue(); 18817 if (packageName != null && !packageName.equals(p.info.packageName)) { 18818 continue; 18819 } 18820 if (!printedSomething) { 18821 if (dumpState.onTitlePrinted()) 18822 pw.println(); 18823 pw.println("ContentProvider Authorities:"); 18824 printedSomething = true; 18825 } 18826 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18827 pw.print(" "); pw.println(p.toString()); 18828 if (p.info != null && p.info.applicationInfo != null) { 18829 final String appInfo = p.info.applicationInfo.toString(); 18830 pw.print(" applicationInfo="); pw.println(appInfo); 18831 } 18832 } 18833 } 18834 18835 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18836 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18837 } 18838 18839 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18840 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18841 } 18842 18843 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18844 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18845 } 18846 18847 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18848 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18849 } 18850 18851 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18852 // XXX should handle packageName != null by dumping only install data that 18853 // the given package is involved with. 18854 if (dumpState.onTitlePrinted()) pw.println(); 18855 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18856 } 18857 18858 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18859 // XXX should handle packageName != null by dumping only install data that 18860 // the given package is involved with. 18861 if (dumpState.onTitlePrinted()) pw.println(); 18862 18863 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18864 ipw.println(); 18865 ipw.println("Frozen packages:"); 18866 ipw.increaseIndent(); 18867 if (mFrozenPackages.size() == 0) { 18868 ipw.println("(none)"); 18869 } else { 18870 for (int i = 0; i < mFrozenPackages.size(); i++) { 18871 ipw.println(mFrozenPackages.valueAt(i)); 18872 } 18873 } 18874 ipw.decreaseIndent(); 18875 } 18876 18877 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18878 if (dumpState.onTitlePrinted()) pw.println(); 18879 dumpDexoptStateLPr(pw, packageName); 18880 } 18881 18882 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18883 if (dumpState.onTitlePrinted()) pw.println(); 18884 dumpCompilerStatsLPr(pw, packageName); 18885 } 18886 18887 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18888 if (dumpState.onTitlePrinted()) pw.println(); 18889 mSettings.dumpReadMessagesLPr(pw, dumpState); 18890 18891 pw.println(); 18892 pw.println("Package warning messages:"); 18893 BufferedReader in = null; 18894 String line = null; 18895 try { 18896 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18897 while ((line = in.readLine()) != null) { 18898 if (line.contains("ignored: updated version")) continue; 18899 pw.println(line); 18900 } 18901 } catch (IOException ignored) { 18902 } finally { 18903 IoUtils.closeQuietly(in); 18904 } 18905 } 18906 18907 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18908 BufferedReader in = null; 18909 String line = null; 18910 try { 18911 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18912 while ((line = in.readLine()) != null) { 18913 if (line.contains("ignored: updated version")) continue; 18914 pw.print("msg,"); 18915 pw.println(line); 18916 } 18917 } catch (IOException ignored) { 18918 } finally { 18919 IoUtils.closeQuietly(in); 18920 } 18921 } 18922 } 18923 } 18924 18925 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18926 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18927 ipw.println(); 18928 ipw.println("Dexopt state:"); 18929 ipw.increaseIndent(); 18930 Collection<PackageParser.Package> packages = null; 18931 if (packageName != null) { 18932 PackageParser.Package targetPackage = mPackages.get(packageName); 18933 if (targetPackage != null) { 18934 packages = Collections.singletonList(targetPackage); 18935 } else { 18936 ipw.println("Unable to find package: " + packageName); 18937 return; 18938 } 18939 } else { 18940 packages = mPackages.values(); 18941 } 18942 18943 for (PackageParser.Package pkg : packages) { 18944 ipw.println("[" + pkg.packageName + "]"); 18945 ipw.increaseIndent(); 18946 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18947 ipw.decreaseIndent(); 18948 } 18949 } 18950 18951 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18952 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18953 ipw.println(); 18954 ipw.println("Compiler stats:"); 18955 ipw.increaseIndent(); 18956 Collection<PackageParser.Package> packages = null; 18957 if (packageName != null) { 18958 PackageParser.Package targetPackage = mPackages.get(packageName); 18959 if (targetPackage != null) { 18960 packages = Collections.singletonList(targetPackage); 18961 } else { 18962 ipw.println("Unable to find package: " + packageName); 18963 return; 18964 } 18965 } else { 18966 packages = mPackages.values(); 18967 } 18968 18969 for (PackageParser.Package pkg : packages) { 18970 ipw.println("[" + pkg.packageName + "]"); 18971 ipw.increaseIndent(); 18972 18973 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18974 if (stats == null) { 18975 ipw.println("(No recorded stats)"); 18976 } else { 18977 stats.dump(ipw); 18978 } 18979 ipw.decreaseIndent(); 18980 } 18981 } 18982 18983 private String dumpDomainString(String packageName) { 18984 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18985 .getList(); 18986 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18987 18988 ArraySet<String> result = new ArraySet<>(); 18989 if (iviList.size() > 0) { 18990 for (IntentFilterVerificationInfo ivi : iviList) { 18991 for (String host : ivi.getDomains()) { 18992 result.add(host); 18993 } 18994 } 18995 } 18996 if (filters != null && filters.size() > 0) { 18997 for (IntentFilter filter : filters) { 18998 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18999 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19000 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19001 result.addAll(filter.getHostsList()); 19002 } 19003 } 19004 } 19005 19006 StringBuilder sb = new StringBuilder(result.size() * 16); 19007 for (String domain : result) { 19008 if (sb.length() > 0) sb.append(" "); 19009 sb.append(domain); 19010 } 19011 return sb.toString(); 19012 } 19013 19014 // ------- apps on sdcard specific code ------- 19015 static final boolean DEBUG_SD_INSTALL = false; 19016 19017 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19018 19019 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19020 19021 private boolean mMediaMounted = false; 19022 19023 static String getEncryptKey() { 19024 try { 19025 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19026 SD_ENCRYPTION_KEYSTORE_NAME); 19027 if (sdEncKey == null) { 19028 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19029 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19030 if (sdEncKey == null) { 19031 Slog.e(TAG, "Failed to create encryption keys"); 19032 return null; 19033 } 19034 } 19035 return sdEncKey; 19036 } catch (NoSuchAlgorithmException nsae) { 19037 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19038 return null; 19039 } catch (IOException ioe) { 19040 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19041 return null; 19042 } 19043 } 19044 19045 /* 19046 * Update media status on PackageManager. 19047 */ 19048 @Override 19049 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19050 int callingUid = Binder.getCallingUid(); 19051 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19052 throw new SecurityException("Media status can only be updated by the system"); 19053 } 19054 // reader; this apparently protects mMediaMounted, but should probably 19055 // be a different lock in that case. 19056 synchronized (mPackages) { 19057 Log.i(TAG, "Updating external media status from " 19058 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19059 + (mediaStatus ? "mounted" : "unmounted")); 19060 if (DEBUG_SD_INSTALL) 19061 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19062 + ", mMediaMounted=" + mMediaMounted); 19063 if (mediaStatus == mMediaMounted) { 19064 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19065 : 0, -1); 19066 mHandler.sendMessage(msg); 19067 return; 19068 } 19069 mMediaMounted = mediaStatus; 19070 } 19071 // Queue up an async operation since the package installation may take a 19072 // little while. 19073 mHandler.post(new Runnable() { 19074 public void run() { 19075 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19076 } 19077 }); 19078 } 19079 19080 /** 19081 * Called by MountService when the initial ASECs to scan are available. 19082 * Should block until all the ASEC containers are finished being scanned. 19083 */ 19084 public void scanAvailableAsecs() { 19085 updateExternalMediaStatusInner(true, false, false); 19086 } 19087 19088 /* 19089 * Collect information of applications on external media, map them against 19090 * existing containers and update information based on current mount status. 19091 * Please note that we always have to report status if reportStatus has been 19092 * set to true especially when unloading packages. 19093 */ 19094 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19095 boolean externalStorage) { 19096 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19097 int[] uidArr = EmptyArray.INT; 19098 19099 final String[] list = PackageHelper.getSecureContainerList(); 19100 if (ArrayUtils.isEmpty(list)) { 19101 Log.i(TAG, "No secure containers found"); 19102 } else { 19103 // Process list of secure containers and categorize them 19104 // as active or stale based on their package internal state. 19105 19106 // reader 19107 synchronized (mPackages) { 19108 for (String cid : list) { 19109 // Leave stages untouched for now; installer service owns them 19110 if (PackageInstallerService.isStageName(cid)) continue; 19111 19112 if (DEBUG_SD_INSTALL) 19113 Log.i(TAG, "Processing container " + cid); 19114 String pkgName = getAsecPackageName(cid); 19115 if (pkgName == null) { 19116 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19117 continue; 19118 } 19119 if (DEBUG_SD_INSTALL) 19120 Log.i(TAG, "Looking for pkg : " + pkgName); 19121 19122 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19123 if (ps == null) { 19124 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19125 continue; 19126 } 19127 19128 /* 19129 * Skip packages that are not external if we're unmounting 19130 * external storage. 19131 */ 19132 if (externalStorage && !isMounted && !isExternal(ps)) { 19133 continue; 19134 } 19135 19136 final AsecInstallArgs args = new AsecInstallArgs(cid, 19137 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19138 // The package status is changed only if the code path 19139 // matches between settings and the container id. 19140 if (ps.codePathString != null 19141 && ps.codePathString.startsWith(args.getCodePath())) { 19142 if (DEBUG_SD_INSTALL) { 19143 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19144 + " at code path: " + ps.codePathString); 19145 } 19146 19147 // We do have a valid package installed on sdcard 19148 processCids.put(args, ps.codePathString); 19149 final int uid = ps.appId; 19150 if (uid != -1) { 19151 uidArr = ArrayUtils.appendInt(uidArr, uid); 19152 } 19153 } else { 19154 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19155 + ps.codePathString); 19156 } 19157 } 19158 } 19159 19160 Arrays.sort(uidArr); 19161 } 19162 19163 // Process packages with valid entries. 19164 if (isMounted) { 19165 if (DEBUG_SD_INSTALL) 19166 Log.i(TAG, "Loading packages"); 19167 loadMediaPackages(processCids, uidArr, externalStorage); 19168 startCleaningPackages(); 19169 mInstallerService.onSecureContainersAvailable(); 19170 } else { 19171 if (DEBUG_SD_INSTALL) 19172 Log.i(TAG, "Unloading packages"); 19173 unloadMediaPackages(processCids, uidArr, reportStatus); 19174 } 19175 } 19176 19177 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19178 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19179 final int size = infos.size(); 19180 final String[] packageNames = new String[size]; 19181 final int[] packageUids = new int[size]; 19182 for (int i = 0; i < size; i++) { 19183 final ApplicationInfo info = infos.get(i); 19184 packageNames[i] = info.packageName; 19185 packageUids[i] = info.uid; 19186 } 19187 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19188 finishedReceiver); 19189 } 19190 19191 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19192 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19193 sendResourcesChangedBroadcast(mediaStatus, replacing, 19194 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19195 } 19196 19197 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19198 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19199 int size = pkgList.length; 19200 if (size > 0) { 19201 // Send broadcasts here 19202 Bundle extras = new Bundle(); 19203 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19204 if (uidArr != null) { 19205 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19206 } 19207 if (replacing) { 19208 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19209 } 19210 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19211 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19212 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19213 } 19214 } 19215 19216 /* 19217 * Look at potentially valid container ids from processCids If package 19218 * information doesn't match the one on record or package scanning fails, 19219 * the cid is added to list of removeCids. We currently don't delete stale 19220 * containers. 19221 */ 19222 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19223 boolean externalStorage) { 19224 ArrayList<String> pkgList = new ArrayList<String>(); 19225 Set<AsecInstallArgs> keys = processCids.keySet(); 19226 19227 for (AsecInstallArgs args : keys) { 19228 String codePath = processCids.get(args); 19229 if (DEBUG_SD_INSTALL) 19230 Log.i(TAG, "Loading container : " + args.cid); 19231 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19232 try { 19233 // Make sure there are no container errors first. 19234 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19235 Slog.e(TAG, "Failed to mount cid : " + args.cid 19236 + " when installing from sdcard"); 19237 continue; 19238 } 19239 // Check code path here. 19240 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19241 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19242 + " does not match one in settings " + codePath); 19243 continue; 19244 } 19245 // Parse package 19246 int parseFlags = mDefParseFlags; 19247 if (args.isExternalAsec()) { 19248 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19249 } 19250 if (args.isFwdLocked()) { 19251 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19252 } 19253 19254 synchronized (mInstallLock) { 19255 PackageParser.Package pkg = null; 19256 try { 19257 // Sadly we don't know the package name yet to freeze it 19258 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19259 SCAN_IGNORE_FROZEN, 0, null); 19260 } catch (PackageManagerException e) { 19261 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19262 } 19263 // Scan the package 19264 if (pkg != null) { 19265 /* 19266 * TODO why is the lock being held? doPostInstall is 19267 * called in other places without the lock. This needs 19268 * to be straightened out. 19269 */ 19270 // writer 19271 synchronized (mPackages) { 19272 retCode = PackageManager.INSTALL_SUCCEEDED; 19273 pkgList.add(pkg.packageName); 19274 // Post process args 19275 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19276 pkg.applicationInfo.uid); 19277 } 19278 } else { 19279 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19280 } 19281 } 19282 19283 } finally { 19284 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19285 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19286 } 19287 } 19288 } 19289 // writer 19290 synchronized (mPackages) { 19291 // If the platform SDK has changed since the last time we booted, 19292 // we need to re-grant app permission to catch any new ones that 19293 // appear. This is really a hack, and means that apps can in some 19294 // cases get permissions that the user didn't initially explicitly 19295 // allow... it would be nice to have some better way to handle 19296 // this situation. 19297 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19298 : mSettings.getInternalVersion(); 19299 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19300 : StorageManager.UUID_PRIVATE_INTERNAL; 19301 19302 int updateFlags = UPDATE_PERMISSIONS_ALL; 19303 if (ver.sdkVersion != mSdkVersion) { 19304 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19305 + mSdkVersion + "; regranting permissions for external"); 19306 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19307 } 19308 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19309 19310 // Yay, everything is now upgraded 19311 ver.forceCurrent(); 19312 19313 // can downgrade to reader 19314 // Persist settings 19315 mSettings.writeLPr(); 19316 } 19317 // Send a broadcast to let everyone know we are done processing 19318 if (pkgList.size() > 0) { 19319 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19320 } 19321 } 19322 19323 /* 19324 * Utility method to unload a list of specified containers 19325 */ 19326 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19327 // Just unmount all valid containers. 19328 for (AsecInstallArgs arg : cidArgs) { 19329 synchronized (mInstallLock) { 19330 arg.doPostDeleteLI(false); 19331 } 19332 } 19333 } 19334 19335 /* 19336 * Unload packages mounted on external media. This involves deleting package 19337 * data from internal structures, sending broadcasts about disabled packages, 19338 * gc'ing to free up references, unmounting all secure containers 19339 * corresponding to packages on external media, and posting a 19340 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19341 * that we always have to post this message if status has been requested no 19342 * matter what. 19343 */ 19344 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19345 final boolean reportStatus) { 19346 if (DEBUG_SD_INSTALL) 19347 Log.i(TAG, "unloading media packages"); 19348 ArrayList<String> pkgList = new ArrayList<String>(); 19349 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19350 final Set<AsecInstallArgs> keys = processCids.keySet(); 19351 for (AsecInstallArgs args : keys) { 19352 String pkgName = args.getPackageName(); 19353 if (DEBUG_SD_INSTALL) 19354 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19355 // Delete package internally 19356 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19357 synchronized (mInstallLock) { 19358 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19359 final boolean res; 19360 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19361 "unloadMediaPackages")) { 19362 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19363 null); 19364 } 19365 if (res) { 19366 pkgList.add(pkgName); 19367 } else { 19368 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19369 failedList.add(args); 19370 } 19371 } 19372 } 19373 19374 // reader 19375 synchronized (mPackages) { 19376 // We didn't update the settings after removing each package; 19377 // write them now for all packages. 19378 mSettings.writeLPr(); 19379 } 19380 19381 // We have to absolutely send UPDATED_MEDIA_STATUS only 19382 // after confirming that all the receivers processed the ordered 19383 // broadcast when packages get disabled, force a gc to clean things up. 19384 // and unload all the containers. 19385 if (pkgList.size() > 0) { 19386 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19387 new IIntentReceiver.Stub() { 19388 public void performReceive(Intent intent, int resultCode, String data, 19389 Bundle extras, boolean ordered, boolean sticky, 19390 int sendingUser) throws RemoteException { 19391 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19392 reportStatus ? 1 : 0, 1, keys); 19393 mHandler.sendMessage(msg); 19394 } 19395 }); 19396 } else { 19397 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19398 keys); 19399 mHandler.sendMessage(msg); 19400 } 19401 } 19402 19403 private void loadPrivatePackages(final VolumeInfo vol) { 19404 mHandler.post(new Runnable() { 19405 @Override 19406 public void run() { 19407 loadPrivatePackagesInner(vol); 19408 } 19409 }); 19410 } 19411 19412 private void loadPrivatePackagesInner(VolumeInfo vol) { 19413 final String volumeUuid = vol.fsUuid; 19414 if (TextUtils.isEmpty(volumeUuid)) { 19415 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19416 return; 19417 } 19418 19419 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19420 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19421 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19422 19423 final VersionInfo ver; 19424 final List<PackageSetting> packages; 19425 synchronized (mPackages) { 19426 ver = mSettings.findOrCreateVersion(volumeUuid); 19427 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19428 } 19429 19430 for (PackageSetting ps : packages) { 19431 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19432 synchronized (mInstallLock) { 19433 final PackageParser.Package pkg; 19434 try { 19435 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19436 loaded.add(pkg.applicationInfo); 19437 19438 } catch (PackageManagerException e) { 19439 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19440 } 19441 19442 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19443 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19444 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19445 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19446 } 19447 } 19448 } 19449 19450 // Reconcile app data for all started/unlocked users 19451 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19452 final UserManager um = mContext.getSystemService(UserManager.class); 19453 UserManagerInternal umInternal = getUserManagerInternal(); 19454 for (UserInfo user : um.getUsers()) { 19455 final int flags; 19456 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19457 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19458 } else if (umInternal.isUserRunning(user.id)) { 19459 flags = StorageManager.FLAG_STORAGE_DE; 19460 } else { 19461 continue; 19462 } 19463 19464 try { 19465 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19466 synchronized (mInstallLock) { 19467 reconcileAppsDataLI(volumeUuid, user.id, flags); 19468 } 19469 } catch (IllegalStateException e) { 19470 // Device was probably ejected, and we'll process that event momentarily 19471 Slog.w(TAG, "Failed to prepare storage: " + e); 19472 } 19473 } 19474 19475 synchronized (mPackages) { 19476 int updateFlags = UPDATE_PERMISSIONS_ALL; 19477 if (ver.sdkVersion != mSdkVersion) { 19478 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19479 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19480 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19481 } 19482 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19483 19484 // Yay, everything is now upgraded 19485 ver.forceCurrent(); 19486 19487 mSettings.writeLPr(); 19488 } 19489 19490 for (PackageFreezer freezer : freezers) { 19491 freezer.close(); 19492 } 19493 19494 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19495 sendResourcesChangedBroadcast(true, false, loaded, null); 19496 } 19497 19498 private void unloadPrivatePackages(final VolumeInfo vol) { 19499 mHandler.post(new Runnable() { 19500 @Override 19501 public void run() { 19502 unloadPrivatePackagesInner(vol); 19503 } 19504 }); 19505 } 19506 19507 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19508 final String volumeUuid = vol.fsUuid; 19509 if (TextUtils.isEmpty(volumeUuid)) { 19510 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19511 return; 19512 } 19513 19514 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19515 synchronized (mInstallLock) { 19516 synchronized (mPackages) { 19517 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19518 for (PackageSetting ps : packages) { 19519 if (ps.pkg == null) continue; 19520 19521 final ApplicationInfo info = ps.pkg.applicationInfo; 19522 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19523 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19524 19525 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19526 "unloadPrivatePackagesInner")) { 19527 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19528 false, null)) { 19529 unloaded.add(info); 19530 } else { 19531 Slog.w(TAG, "Failed to unload " + ps.codePath); 19532 } 19533 } 19534 19535 // Try very hard to release any references to this package 19536 // so we don't risk the system server being killed due to 19537 // open FDs 19538 AttributeCache.instance().removePackage(ps.name); 19539 } 19540 19541 mSettings.writeLPr(); 19542 } 19543 } 19544 19545 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19546 sendResourcesChangedBroadcast(false, false, unloaded, null); 19547 19548 // Try very hard to release any references to this path so we don't risk 19549 // the system server being killed due to open FDs 19550 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19551 19552 for (int i = 0; i < 3; i++) { 19553 System.gc(); 19554 System.runFinalization(); 19555 } 19556 } 19557 19558 /** 19559 * Prepare storage areas for given user on all mounted devices. 19560 */ 19561 void prepareUserData(int userId, int userSerial, int flags) { 19562 synchronized (mInstallLock) { 19563 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19564 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19565 final String volumeUuid = vol.getFsUuid(); 19566 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19567 } 19568 } 19569 } 19570 19571 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19572 boolean allowRecover) { 19573 // Prepare storage and verify that serial numbers are consistent; if 19574 // there's a mismatch we need to destroy to avoid leaking data 19575 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19576 try { 19577 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19578 19579 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19580 UserManagerService.enforceSerialNumber( 19581 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19582 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19583 UserManagerService.enforceSerialNumber( 19584 Environment.getDataSystemDeDirectory(userId), userSerial); 19585 } 19586 } 19587 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19588 UserManagerService.enforceSerialNumber( 19589 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19590 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19591 UserManagerService.enforceSerialNumber( 19592 Environment.getDataSystemCeDirectory(userId), userSerial); 19593 } 19594 } 19595 19596 synchronized (mInstallLock) { 19597 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19598 } 19599 } catch (Exception e) { 19600 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19601 + " because we failed to prepare: " + e); 19602 destroyUserDataLI(volumeUuid, userId, 19603 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19604 19605 if (allowRecover) { 19606 // Try one last time; if we fail again we're really in trouble 19607 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19608 } 19609 } 19610 } 19611 19612 /** 19613 * Destroy storage areas for given user on all mounted devices. 19614 */ 19615 void destroyUserData(int userId, int flags) { 19616 synchronized (mInstallLock) { 19617 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19618 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19619 final String volumeUuid = vol.getFsUuid(); 19620 destroyUserDataLI(volumeUuid, userId, flags); 19621 } 19622 } 19623 } 19624 19625 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19626 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19627 try { 19628 // Clean up app data, profile data, and media data 19629 mInstaller.destroyUserData(volumeUuid, userId, flags); 19630 19631 // Clean up system data 19632 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19633 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19634 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19635 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19636 } 19637 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19638 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19639 } 19640 } 19641 19642 // Data with special labels is now gone, so finish the job 19643 storage.destroyUserStorage(volumeUuid, userId, flags); 19644 19645 } catch (Exception e) { 19646 logCriticalInfo(Log.WARN, 19647 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19648 } 19649 } 19650 19651 /** 19652 * Examine all users present on given mounted volume, and destroy data 19653 * belonging to users that are no longer valid, or whose user ID has been 19654 * recycled. 19655 */ 19656 private void reconcileUsers(String volumeUuid) { 19657 final List<File> files = new ArrayList<>(); 19658 Collections.addAll(files, FileUtils 19659 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19660 Collections.addAll(files, FileUtils 19661 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19662 Collections.addAll(files, FileUtils 19663 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19664 Collections.addAll(files, FileUtils 19665 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19666 for (File file : files) { 19667 if (!file.isDirectory()) continue; 19668 19669 final int userId; 19670 final UserInfo info; 19671 try { 19672 userId = Integer.parseInt(file.getName()); 19673 info = sUserManager.getUserInfo(userId); 19674 } catch (NumberFormatException e) { 19675 Slog.w(TAG, "Invalid user directory " + file); 19676 continue; 19677 } 19678 19679 boolean destroyUser = false; 19680 if (info == null) { 19681 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19682 + " because no matching user was found"); 19683 destroyUser = true; 19684 } else if (!mOnlyCore) { 19685 try { 19686 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19687 } catch (IOException e) { 19688 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19689 + " because we failed to enforce serial number: " + e); 19690 destroyUser = true; 19691 } 19692 } 19693 19694 if (destroyUser) { 19695 synchronized (mInstallLock) { 19696 destroyUserDataLI(volumeUuid, userId, 19697 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19698 } 19699 } 19700 } 19701 } 19702 19703 private void assertPackageKnown(String volumeUuid, String packageName) 19704 throws PackageManagerException { 19705 synchronized (mPackages) { 19706 final PackageSetting ps = mSettings.mPackages.get(packageName); 19707 if (ps == null) { 19708 throw new PackageManagerException("Package " + packageName + " is unknown"); 19709 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19710 throw new PackageManagerException( 19711 "Package " + packageName + " found on unknown volume " + volumeUuid 19712 + "; expected volume " + ps.volumeUuid); 19713 } 19714 } 19715 } 19716 19717 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19718 throws PackageManagerException { 19719 synchronized (mPackages) { 19720 final PackageSetting ps = mSettings.mPackages.get(packageName); 19721 if (ps == null) { 19722 throw new PackageManagerException("Package " + packageName + " is unknown"); 19723 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19724 throw new PackageManagerException( 19725 "Package " + packageName + " found on unknown volume " + volumeUuid 19726 + "; expected volume " + ps.volumeUuid); 19727 } else if (!ps.getInstalled(userId)) { 19728 throw new PackageManagerException( 19729 "Package " + packageName + " not installed for user " + userId); 19730 } 19731 } 19732 } 19733 19734 /** 19735 * Examine all apps present on given mounted volume, and destroy apps that 19736 * aren't expected, either due to uninstallation or reinstallation on 19737 * another volume. 19738 */ 19739 private void reconcileApps(String volumeUuid) { 19740 final File[] files = FileUtils 19741 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19742 for (File file : files) { 19743 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19744 && !PackageInstallerService.isStageName(file.getName()); 19745 if (!isPackage) { 19746 // Ignore entries which are not packages 19747 continue; 19748 } 19749 19750 try { 19751 final PackageLite pkg = PackageParser.parsePackageLite(file, 19752 PackageParser.PARSE_MUST_BE_APK); 19753 assertPackageKnown(volumeUuid, pkg.packageName); 19754 19755 } catch (PackageParserException | PackageManagerException e) { 19756 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19757 synchronized (mInstallLock) { 19758 removeCodePathLI(file); 19759 } 19760 } 19761 } 19762 } 19763 19764 /** 19765 * Reconcile all app data for the given user. 19766 * <p> 19767 * Verifies that directories exist and that ownership and labeling is 19768 * correct for all installed apps on all mounted volumes. 19769 */ 19770 void reconcileAppsData(int userId, int flags) { 19771 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19772 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19773 final String volumeUuid = vol.getFsUuid(); 19774 synchronized (mInstallLock) { 19775 reconcileAppsDataLI(volumeUuid, userId, flags); 19776 } 19777 } 19778 } 19779 19780 /** 19781 * Reconcile all app data on given mounted volume. 19782 * <p> 19783 * Destroys app data that isn't expected, either due to uninstallation or 19784 * reinstallation on another volume. 19785 * <p> 19786 * Verifies that directories exist and that ownership and labeling is 19787 * correct for all installed apps. 19788 */ 19789 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19790 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19791 + Integer.toHexString(flags)); 19792 19793 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19794 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19795 19796 // First look for stale data that doesn't belong, and check if things 19797 // have changed since we did our last restorecon 19798 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19799 if (StorageManager.isFileEncryptedNativeOrEmulated() 19800 && !StorageManager.isUserKeyUnlocked(userId)) { 19801 throw new RuntimeException( 19802 "Yikes, someone asked us to reconcile CE storage while " + userId 19803 + " was still locked; this would have caused massive data loss!"); 19804 } 19805 19806 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19807 for (File file : files) { 19808 final String packageName = file.getName(); 19809 try { 19810 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19811 } catch (PackageManagerException e) { 19812 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19813 try { 19814 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19815 StorageManager.FLAG_STORAGE_CE, 0); 19816 } catch (InstallerException e2) { 19817 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19818 } 19819 } 19820 } 19821 } 19822 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19823 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19824 for (File file : files) { 19825 final String packageName = file.getName(); 19826 try { 19827 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19828 } catch (PackageManagerException e) { 19829 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19830 try { 19831 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19832 StorageManager.FLAG_STORAGE_DE, 0); 19833 } catch (InstallerException e2) { 19834 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19835 } 19836 } 19837 } 19838 } 19839 19840 // Ensure that data directories are ready to roll for all packages 19841 // installed for this volume and user 19842 final List<PackageSetting> packages; 19843 synchronized (mPackages) { 19844 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19845 } 19846 int preparedCount = 0; 19847 for (PackageSetting ps : packages) { 19848 final String packageName = ps.name; 19849 if (ps.pkg == null) { 19850 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19851 // TODO: might be due to legacy ASEC apps; we should circle back 19852 // and reconcile again once they're scanned 19853 continue; 19854 } 19855 19856 if (ps.getInstalled(userId)) { 19857 prepareAppDataLIF(ps.pkg, userId, flags); 19858 19859 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19860 // We may have just shuffled around app data directories, so 19861 // prepare them one more time 19862 prepareAppDataLIF(ps.pkg, userId, flags); 19863 } 19864 19865 preparedCount++; 19866 } 19867 } 19868 19869 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19870 } 19871 19872 /** 19873 * Prepare app data for the given app just after it was installed or 19874 * upgraded. This method carefully only touches users that it's installed 19875 * for, and it forces a restorecon to handle any seinfo changes. 19876 * <p> 19877 * Verifies that directories exist and that ownership and labeling is 19878 * correct for all installed apps. If there is an ownership mismatch, it 19879 * will try recovering system apps by wiping data; third-party app data is 19880 * left intact. 19881 * <p> 19882 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19883 */ 19884 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19885 final PackageSetting ps; 19886 synchronized (mPackages) { 19887 ps = mSettings.mPackages.get(pkg.packageName); 19888 mSettings.writeKernelMappingLPr(ps); 19889 } 19890 19891 final UserManager um = mContext.getSystemService(UserManager.class); 19892 UserManagerInternal umInternal = getUserManagerInternal(); 19893 for (UserInfo user : um.getUsers()) { 19894 final int flags; 19895 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19896 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19897 } else if (umInternal.isUserRunning(user.id)) { 19898 flags = StorageManager.FLAG_STORAGE_DE; 19899 } else { 19900 continue; 19901 } 19902 19903 if (ps.getInstalled(user.id)) { 19904 // TODO: when user data is locked, mark that we're still dirty 19905 prepareAppDataLIF(pkg, user.id, flags); 19906 } 19907 } 19908 } 19909 19910 /** 19911 * Prepare app data for the given app. 19912 * <p> 19913 * Verifies that directories exist and that ownership and labeling is 19914 * correct for all installed apps. If there is an ownership mismatch, this 19915 * will try recovering system apps by wiping data; third-party app data is 19916 * left intact. 19917 */ 19918 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 19919 if (pkg == null) { 19920 Slog.wtf(TAG, "Package was null!", new Throwable()); 19921 return; 19922 } 19923 prepareAppDataLeafLIF(pkg, userId, flags); 19924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19925 for (int i = 0; i < childCount; i++) { 19926 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 19927 } 19928 } 19929 19930 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19931 if (DEBUG_APP_DATA) { 19932 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19933 + Integer.toHexString(flags)); 19934 } 19935 19936 final String volumeUuid = pkg.volumeUuid; 19937 final String packageName = pkg.packageName; 19938 final ApplicationInfo app = pkg.applicationInfo; 19939 final int appId = UserHandle.getAppId(app.uid); 19940 19941 Preconditions.checkNotNull(app.seinfo); 19942 19943 try { 19944 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19945 appId, app.seinfo, app.targetSdkVersion); 19946 } catch (InstallerException e) { 19947 if (app.isSystemApp()) { 19948 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19949 + ", but trying to recover: " + e); 19950 destroyAppDataLeafLIF(pkg, userId, flags); 19951 try { 19952 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19953 appId, app.seinfo, app.targetSdkVersion); 19954 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19955 } catch (InstallerException e2) { 19956 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19957 } 19958 } else { 19959 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19960 } 19961 } 19962 19963 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19964 try { 19965 // CE storage is unlocked right now, so read out the inode and 19966 // remember for use later when it's locked 19967 // TODO: mark this structure as dirty so we persist it! 19968 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19969 StorageManager.FLAG_STORAGE_CE); 19970 synchronized (mPackages) { 19971 final PackageSetting ps = mSettings.mPackages.get(packageName); 19972 if (ps != null) { 19973 ps.setCeDataInode(ceDataInode, userId); 19974 } 19975 } 19976 } catch (InstallerException e) { 19977 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19978 } 19979 } 19980 19981 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19982 } 19983 19984 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19985 if (pkg == null) { 19986 Slog.wtf(TAG, "Package was null!", new Throwable()); 19987 return; 19988 } 19989 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19990 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19991 for (int i = 0; i < childCount; i++) { 19992 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19993 } 19994 } 19995 19996 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19997 final String volumeUuid = pkg.volumeUuid; 19998 final String packageName = pkg.packageName; 19999 final ApplicationInfo app = pkg.applicationInfo; 20000 20001 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20002 // Create a native library symlink only if we have native libraries 20003 // and if the native libraries are 32 bit libraries. We do not provide 20004 // this symlink for 64 bit libraries. 20005 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20006 final String nativeLibPath = app.nativeLibraryDir; 20007 try { 20008 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20009 nativeLibPath, userId); 20010 } catch (InstallerException e) { 20011 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20012 } 20013 } 20014 } 20015 } 20016 20017 /** 20018 * For system apps on non-FBE devices, this method migrates any existing 20019 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20020 * requested by the app. 20021 */ 20022 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20023 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20024 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20025 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20026 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20027 try { 20028 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20029 storageTarget); 20030 } catch (InstallerException e) { 20031 logCriticalInfo(Log.WARN, 20032 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20033 } 20034 return true; 20035 } else { 20036 return false; 20037 } 20038 } 20039 20040 public PackageFreezer freezePackage(String packageName, String killReason) { 20041 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20042 } 20043 20044 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20045 return new PackageFreezer(packageName, userId, killReason); 20046 } 20047 20048 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20049 String killReason) { 20050 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20051 } 20052 20053 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20054 String killReason) { 20055 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20056 return new PackageFreezer(); 20057 } else { 20058 return freezePackage(packageName, userId, killReason); 20059 } 20060 } 20061 20062 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20063 String killReason) { 20064 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20065 } 20066 20067 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20068 String killReason) { 20069 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20070 return new PackageFreezer(); 20071 } else { 20072 return freezePackage(packageName, userId, killReason); 20073 } 20074 } 20075 20076 /** 20077 * Class that freezes and kills the given package upon creation, and 20078 * unfreezes it upon closing. This is typically used when doing surgery on 20079 * app code/data to prevent the app from running while you're working. 20080 */ 20081 private class PackageFreezer implements AutoCloseable { 20082 private final String mPackageName; 20083 private final PackageFreezer[] mChildren; 20084 20085 private final boolean mWeFroze; 20086 20087 private final AtomicBoolean mClosed = new AtomicBoolean(); 20088 private final CloseGuard mCloseGuard = CloseGuard.get(); 20089 20090 /** 20091 * Create and return a stub freezer that doesn't actually do anything, 20092 * typically used when someone requested 20093 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20094 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20095 */ 20096 public PackageFreezer() { 20097 mPackageName = null; 20098 mChildren = null; 20099 mWeFroze = false; 20100 mCloseGuard.open("close"); 20101 } 20102 20103 public PackageFreezer(String packageName, int userId, String killReason) { 20104 synchronized (mPackages) { 20105 mPackageName = packageName; 20106 mWeFroze = mFrozenPackages.add(mPackageName); 20107 20108 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20109 if (ps != null) { 20110 killApplication(ps.name, ps.appId, userId, killReason); 20111 } 20112 20113 final PackageParser.Package p = mPackages.get(packageName); 20114 if (p != null && p.childPackages != null) { 20115 final int N = p.childPackages.size(); 20116 mChildren = new PackageFreezer[N]; 20117 for (int i = 0; i < N; i++) { 20118 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20119 userId, killReason); 20120 } 20121 } else { 20122 mChildren = null; 20123 } 20124 } 20125 mCloseGuard.open("close"); 20126 } 20127 20128 @Override 20129 protected void finalize() throws Throwable { 20130 try { 20131 mCloseGuard.warnIfOpen(); 20132 close(); 20133 } finally { 20134 super.finalize(); 20135 } 20136 } 20137 20138 @Override 20139 public void close() { 20140 mCloseGuard.close(); 20141 if (mClosed.compareAndSet(false, true)) { 20142 synchronized (mPackages) { 20143 if (mWeFroze) { 20144 mFrozenPackages.remove(mPackageName); 20145 } 20146 20147 if (mChildren != null) { 20148 for (PackageFreezer freezer : mChildren) { 20149 freezer.close(); 20150 } 20151 } 20152 } 20153 } 20154 } 20155 } 20156 20157 /** 20158 * Verify that given package is currently frozen. 20159 */ 20160 private void checkPackageFrozen(String packageName) { 20161 synchronized (mPackages) { 20162 if (!mFrozenPackages.contains(packageName)) { 20163 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20164 } 20165 } 20166 } 20167 20168 @Override 20169 public int movePackage(final String packageName, final String volumeUuid) { 20170 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20171 20172 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20173 final int moveId = mNextMoveId.getAndIncrement(); 20174 mHandler.post(new Runnable() { 20175 @Override 20176 public void run() { 20177 try { 20178 movePackageInternal(packageName, volumeUuid, moveId, user); 20179 } catch (PackageManagerException e) { 20180 Slog.w(TAG, "Failed to move " + packageName, e); 20181 mMoveCallbacks.notifyStatusChanged(moveId, 20182 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20183 } 20184 } 20185 }); 20186 return moveId; 20187 } 20188 20189 private void movePackageInternal(final String packageName, final String volumeUuid, 20190 final int moveId, UserHandle user) throws PackageManagerException { 20191 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20192 final PackageManager pm = mContext.getPackageManager(); 20193 20194 final boolean currentAsec; 20195 final String currentVolumeUuid; 20196 final File codeFile; 20197 final String installerPackageName; 20198 final String packageAbiOverride; 20199 final int appId; 20200 final String seinfo; 20201 final String label; 20202 final int targetSdkVersion; 20203 final PackageFreezer freezer; 20204 final int[] installedUserIds; 20205 20206 // reader 20207 synchronized (mPackages) { 20208 final PackageParser.Package pkg = mPackages.get(packageName); 20209 final PackageSetting ps = mSettings.mPackages.get(packageName); 20210 if (pkg == null || ps == null) { 20211 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20212 } 20213 20214 if (pkg.applicationInfo.isSystemApp()) { 20215 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20216 "Cannot move system application"); 20217 } 20218 20219 if (pkg.applicationInfo.isExternalAsec()) { 20220 currentAsec = true; 20221 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20222 } else if (pkg.applicationInfo.isForwardLocked()) { 20223 currentAsec = true; 20224 currentVolumeUuid = "forward_locked"; 20225 } else { 20226 currentAsec = false; 20227 currentVolumeUuid = ps.volumeUuid; 20228 20229 final File probe = new File(pkg.codePath); 20230 final File probeOat = new File(probe, "oat"); 20231 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20232 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20233 "Move only supported for modern cluster style installs"); 20234 } 20235 } 20236 20237 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20238 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20239 "Package already moved to " + volumeUuid); 20240 } 20241 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20242 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20243 "Device admin cannot be moved"); 20244 } 20245 20246 if (mFrozenPackages.contains(packageName)) { 20247 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20248 "Failed to move already frozen package"); 20249 } 20250 20251 codeFile = new File(pkg.codePath); 20252 installerPackageName = ps.installerPackageName; 20253 packageAbiOverride = ps.cpuAbiOverrideString; 20254 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20255 seinfo = pkg.applicationInfo.seinfo; 20256 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20257 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20258 freezer = freezePackage(packageName, "movePackageInternal"); 20259 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20260 } 20261 20262 final Bundle extras = new Bundle(); 20263 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20264 extras.putString(Intent.EXTRA_TITLE, label); 20265 mMoveCallbacks.notifyCreated(moveId, extras); 20266 20267 int installFlags; 20268 final boolean moveCompleteApp; 20269 final File measurePath; 20270 20271 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20272 installFlags = INSTALL_INTERNAL; 20273 moveCompleteApp = !currentAsec; 20274 measurePath = Environment.getDataAppDirectory(volumeUuid); 20275 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20276 installFlags = INSTALL_EXTERNAL; 20277 moveCompleteApp = false; 20278 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20279 } else { 20280 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20281 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20282 || !volume.isMountedWritable()) { 20283 freezer.close(); 20284 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20285 "Move location not mounted private volume"); 20286 } 20287 20288 Preconditions.checkState(!currentAsec); 20289 20290 installFlags = INSTALL_INTERNAL; 20291 moveCompleteApp = true; 20292 measurePath = Environment.getDataAppDirectory(volumeUuid); 20293 } 20294 20295 final PackageStats stats = new PackageStats(null, -1); 20296 synchronized (mInstaller) { 20297 for (int userId : installedUserIds) { 20298 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20299 freezer.close(); 20300 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20301 "Failed to measure package size"); 20302 } 20303 } 20304 } 20305 20306 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20307 + stats.dataSize); 20308 20309 final long startFreeBytes = measurePath.getFreeSpace(); 20310 final long sizeBytes; 20311 if (moveCompleteApp) { 20312 sizeBytes = stats.codeSize + stats.dataSize; 20313 } else { 20314 sizeBytes = stats.codeSize; 20315 } 20316 20317 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20318 freezer.close(); 20319 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20320 "Not enough free space to move"); 20321 } 20322 20323 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20324 20325 final CountDownLatch installedLatch = new CountDownLatch(1); 20326 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20327 @Override 20328 public void onUserActionRequired(Intent intent) throws RemoteException { 20329 throw new IllegalStateException(); 20330 } 20331 20332 @Override 20333 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20334 Bundle extras) throws RemoteException { 20335 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20336 + PackageManager.installStatusToString(returnCode, msg)); 20337 20338 installedLatch.countDown(); 20339 freezer.close(); 20340 20341 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20342 switch (status) { 20343 case PackageInstaller.STATUS_SUCCESS: 20344 mMoveCallbacks.notifyStatusChanged(moveId, 20345 PackageManager.MOVE_SUCCEEDED); 20346 break; 20347 case PackageInstaller.STATUS_FAILURE_STORAGE: 20348 mMoveCallbacks.notifyStatusChanged(moveId, 20349 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20350 break; 20351 default: 20352 mMoveCallbacks.notifyStatusChanged(moveId, 20353 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20354 break; 20355 } 20356 } 20357 }; 20358 20359 final MoveInfo move; 20360 if (moveCompleteApp) { 20361 // Kick off a thread to report progress estimates 20362 new Thread() { 20363 @Override 20364 public void run() { 20365 while (true) { 20366 try { 20367 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20368 break; 20369 } 20370 } catch (InterruptedException ignored) { 20371 } 20372 20373 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20374 final int progress = 10 + (int) MathUtils.constrain( 20375 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20376 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20377 } 20378 } 20379 }.start(); 20380 20381 final String dataAppName = codeFile.getName(); 20382 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20383 dataAppName, appId, seinfo, targetSdkVersion); 20384 } else { 20385 move = null; 20386 } 20387 20388 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20389 20390 final Message msg = mHandler.obtainMessage(INIT_COPY); 20391 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20392 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20393 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20394 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20395 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20396 msg.obj = params; 20397 20398 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20399 System.identityHashCode(msg.obj)); 20400 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20401 System.identityHashCode(msg.obj)); 20402 20403 mHandler.sendMessage(msg); 20404 } 20405 20406 @Override 20407 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20408 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20409 20410 final int realMoveId = mNextMoveId.getAndIncrement(); 20411 final Bundle extras = new Bundle(); 20412 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20413 mMoveCallbacks.notifyCreated(realMoveId, extras); 20414 20415 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20416 @Override 20417 public void onCreated(int moveId, Bundle extras) { 20418 // Ignored 20419 } 20420 20421 @Override 20422 public void onStatusChanged(int moveId, int status, long estMillis) { 20423 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20424 } 20425 }; 20426 20427 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20428 storage.setPrimaryStorageUuid(volumeUuid, callback); 20429 return realMoveId; 20430 } 20431 20432 @Override 20433 public int getMoveStatus(int moveId) { 20434 mContext.enforceCallingOrSelfPermission( 20435 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20436 return mMoveCallbacks.mLastStatus.get(moveId); 20437 } 20438 20439 @Override 20440 public void registerMoveCallback(IPackageMoveObserver callback) { 20441 mContext.enforceCallingOrSelfPermission( 20442 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20443 mMoveCallbacks.register(callback); 20444 } 20445 20446 @Override 20447 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20448 mContext.enforceCallingOrSelfPermission( 20449 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20450 mMoveCallbacks.unregister(callback); 20451 } 20452 20453 @Override 20454 public boolean setInstallLocation(int loc) { 20455 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20456 null); 20457 if (getInstallLocation() == loc) { 20458 return true; 20459 } 20460 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20461 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20462 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20463 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20464 return true; 20465 } 20466 return false; 20467 } 20468 20469 @Override 20470 public int getInstallLocation() { 20471 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20472 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20473 PackageHelper.APP_INSTALL_AUTO); 20474 } 20475 20476 /** Called by UserManagerService */ 20477 void cleanUpUser(UserManagerService userManager, int userHandle) { 20478 synchronized (mPackages) { 20479 mDirtyUsers.remove(userHandle); 20480 mUserNeedsBadging.delete(userHandle); 20481 mSettings.removeUserLPw(userHandle); 20482 mPendingBroadcasts.remove(userHandle); 20483 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20484 removeUnusedPackagesLPw(userManager, userHandle); 20485 } 20486 } 20487 20488 /** 20489 * We're removing userHandle and would like to remove any downloaded packages 20490 * that are no longer in use by any other user. 20491 * @param userHandle the user being removed 20492 */ 20493 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20494 final boolean DEBUG_CLEAN_APKS = false; 20495 int [] users = userManager.getUserIds(); 20496 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20497 while (psit.hasNext()) { 20498 PackageSetting ps = psit.next(); 20499 if (ps.pkg == null) { 20500 continue; 20501 } 20502 final String packageName = ps.pkg.packageName; 20503 // Skip over if system app 20504 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20505 continue; 20506 } 20507 if (DEBUG_CLEAN_APKS) { 20508 Slog.i(TAG, "Checking package " + packageName); 20509 } 20510 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20511 if (keep) { 20512 if (DEBUG_CLEAN_APKS) { 20513 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20514 } 20515 } else { 20516 for (int i = 0; i < users.length; i++) { 20517 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20518 keep = true; 20519 if (DEBUG_CLEAN_APKS) { 20520 Slog.i(TAG, " Keeping package " + packageName + " for user " 20521 + users[i]); 20522 } 20523 break; 20524 } 20525 } 20526 } 20527 if (!keep) { 20528 if (DEBUG_CLEAN_APKS) { 20529 Slog.i(TAG, " Removing package " + packageName); 20530 } 20531 mHandler.post(new Runnable() { 20532 public void run() { 20533 deletePackageX(packageName, userHandle, 0); 20534 } //end run 20535 }); 20536 } 20537 } 20538 } 20539 20540 /** Called by UserManagerService */ 20541 void createNewUser(int userId) { 20542 synchronized (mInstallLock) { 20543 mSettings.createNewUserLI(this, mInstaller, userId); 20544 } 20545 synchronized (mPackages) { 20546 scheduleWritePackageRestrictionsLocked(userId); 20547 scheduleWritePackageListLocked(userId); 20548 applyFactoryDefaultBrowserLPw(userId); 20549 primeDomainVerificationsLPw(userId); 20550 } 20551 } 20552 20553 void onNewUserCreated(final int userId) { 20554 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20555 // If permission review for legacy apps is required, we represent 20556 // dagerous permissions for such apps as always granted runtime 20557 // permissions to keep per user flag state whether review is needed. 20558 // Hence, if a new user is added we have to propagate dangerous 20559 // permission grants for these legacy apps. 20560 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20561 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20562 | UPDATE_PERMISSIONS_REPLACE_ALL); 20563 } 20564 } 20565 20566 @Override 20567 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20568 mContext.enforceCallingOrSelfPermission( 20569 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20570 "Only package verification agents can read the verifier device identity"); 20571 20572 synchronized (mPackages) { 20573 return mSettings.getVerifierDeviceIdentityLPw(); 20574 } 20575 } 20576 20577 @Override 20578 public void setPermissionEnforced(String permission, boolean enforced) { 20579 // TODO: Now that we no longer change GID for storage, this should to away. 20580 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20581 "setPermissionEnforced"); 20582 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20583 synchronized (mPackages) { 20584 if (mSettings.mReadExternalStorageEnforced == null 20585 || mSettings.mReadExternalStorageEnforced != enforced) { 20586 mSettings.mReadExternalStorageEnforced = enforced; 20587 mSettings.writeLPr(); 20588 } 20589 } 20590 // kill any non-foreground processes so we restart them and 20591 // grant/revoke the GID. 20592 final IActivityManager am = ActivityManagerNative.getDefault(); 20593 if (am != null) { 20594 final long token = Binder.clearCallingIdentity(); 20595 try { 20596 am.killProcessesBelowForeground("setPermissionEnforcement"); 20597 } catch (RemoteException e) { 20598 } finally { 20599 Binder.restoreCallingIdentity(token); 20600 } 20601 } 20602 } else { 20603 throw new IllegalArgumentException("No selective enforcement for " + permission); 20604 } 20605 } 20606 20607 @Override 20608 @Deprecated 20609 public boolean isPermissionEnforced(String permission) { 20610 return true; 20611 } 20612 20613 @Override 20614 public boolean isStorageLow() { 20615 final long token = Binder.clearCallingIdentity(); 20616 try { 20617 final DeviceStorageMonitorInternal 20618 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20619 if (dsm != null) { 20620 return dsm.isMemoryLow(); 20621 } else { 20622 return false; 20623 } 20624 } finally { 20625 Binder.restoreCallingIdentity(token); 20626 } 20627 } 20628 20629 @Override 20630 public IPackageInstaller getPackageInstaller() { 20631 return mInstallerService; 20632 } 20633 20634 private boolean userNeedsBadging(int userId) { 20635 int index = mUserNeedsBadging.indexOfKey(userId); 20636 if (index < 0) { 20637 final UserInfo userInfo; 20638 final long token = Binder.clearCallingIdentity(); 20639 try { 20640 userInfo = sUserManager.getUserInfo(userId); 20641 } finally { 20642 Binder.restoreCallingIdentity(token); 20643 } 20644 final boolean b; 20645 if (userInfo != null && userInfo.isManagedProfile()) { 20646 b = true; 20647 } else { 20648 b = false; 20649 } 20650 mUserNeedsBadging.put(userId, b); 20651 return b; 20652 } 20653 return mUserNeedsBadging.valueAt(index); 20654 } 20655 20656 @Override 20657 public KeySet getKeySetByAlias(String packageName, String alias) { 20658 if (packageName == null || alias == null) { 20659 return null; 20660 } 20661 synchronized(mPackages) { 20662 final PackageParser.Package pkg = mPackages.get(packageName); 20663 if (pkg == null) { 20664 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20665 throw new IllegalArgumentException("Unknown package: " + packageName); 20666 } 20667 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20668 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20669 } 20670 } 20671 20672 @Override 20673 public KeySet getSigningKeySet(String packageName) { 20674 if (packageName == null) { 20675 return null; 20676 } 20677 synchronized(mPackages) { 20678 final PackageParser.Package pkg = mPackages.get(packageName); 20679 if (pkg == null) { 20680 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20681 throw new IllegalArgumentException("Unknown package: " + packageName); 20682 } 20683 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20684 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20685 throw new SecurityException("May not access signing KeySet of other apps."); 20686 } 20687 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20688 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20689 } 20690 } 20691 20692 @Override 20693 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20694 if (packageName == null || ks == null) { 20695 return false; 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 IBinder ksh = ks.getToken(); 20704 if (ksh instanceof KeySetHandle) { 20705 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20706 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20707 } 20708 return false; 20709 } 20710 } 20711 20712 @Override 20713 public boolean isPackageSignedByKeySetExactly(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.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20727 } 20728 return false; 20729 } 20730 } 20731 20732 private void deletePackageIfUnusedLPr(final String packageName) { 20733 PackageSetting ps = mSettings.mPackages.get(packageName); 20734 if (ps == null) { 20735 return; 20736 } 20737 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20738 // TODO Implement atomic delete if package is unused 20739 // It is currently possible that the package will be deleted even if it is installed 20740 // after this method returns. 20741 mHandler.post(new Runnable() { 20742 public void run() { 20743 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20744 } 20745 }); 20746 } 20747 } 20748 20749 /** 20750 * Check and throw if the given before/after packages would be considered a 20751 * downgrade. 20752 */ 20753 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20754 throws PackageManagerException { 20755 if (after.versionCode < before.mVersionCode) { 20756 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20757 "Update version code " + after.versionCode + " is older than current " 20758 + before.mVersionCode); 20759 } else if (after.versionCode == before.mVersionCode) { 20760 if (after.baseRevisionCode < before.baseRevisionCode) { 20761 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20762 "Update base revision code " + after.baseRevisionCode 20763 + " is older than current " + before.baseRevisionCode); 20764 } 20765 20766 if (!ArrayUtils.isEmpty(after.splitNames)) { 20767 for (int i = 0; i < after.splitNames.length; i++) { 20768 final String splitName = after.splitNames[i]; 20769 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20770 if (j != -1) { 20771 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20772 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20773 "Update split " + splitName + " revision code " 20774 + after.splitRevisionCodes[i] + " is older than current " 20775 + before.splitRevisionCodes[j]); 20776 } 20777 } 20778 } 20779 } 20780 } 20781 } 20782 20783 private static class MoveCallbacks extends Handler { 20784 private static final int MSG_CREATED = 1; 20785 private static final int MSG_STATUS_CHANGED = 2; 20786 20787 private final RemoteCallbackList<IPackageMoveObserver> 20788 mCallbacks = new RemoteCallbackList<>(); 20789 20790 private final SparseIntArray mLastStatus = new SparseIntArray(); 20791 20792 public MoveCallbacks(Looper looper) { 20793 super(looper); 20794 } 20795 20796 public void register(IPackageMoveObserver callback) { 20797 mCallbacks.register(callback); 20798 } 20799 20800 public void unregister(IPackageMoveObserver callback) { 20801 mCallbacks.unregister(callback); 20802 } 20803 20804 @Override 20805 public void handleMessage(Message msg) { 20806 final SomeArgs args = (SomeArgs) msg.obj; 20807 final int n = mCallbacks.beginBroadcast(); 20808 for (int i = 0; i < n; i++) { 20809 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20810 try { 20811 invokeCallback(callback, msg.what, args); 20812 } catch (RemoteException ignored) { 20813 } 20814 } 20815 mCallbacks.finishBroadcast(); 20816 args.recycle(); 20817 } 20818 20819 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20820 throws RemoteException { 20821 switch (what) { 20822 case MSG_CREATED: { 20823 callback.onCreated(args.argi1, (Bundle) args.arg2); 20824 break; 20825 } 20826 case MSG_STATUS_CHANGED: { 20827 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20828 break; 20829 } 20830 } 20831 } 20832 20833 private void notifyCreated(int moveId, Bundle extras) { 20834 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20835 20836 final SomeArgs args = SomeArgs.obtain(); 20837 args.argi1 = moveId; 20838 args.arg2 = extras; 20839 obtainMessage(MSG_CREATED, args).sendToTarget(); 20840 } 20841 20842 private void notifyStatusChanged(int moveId, int status) { 20843 notifyStatusChanged(moveId, status, -1); 20844 } 20845 20846 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20847 Slog.v(TAG, "Move " + moveId + " status " + status); 20848 20849 final SomeArgs args = SomeArgs.obtain(); 20850 args.argi1 = moveId; 20851 args.argi2 = status; 20852 args.arg3 = estMillis; 20853 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20854 20855 synchronized (mLastStatus) { 20856 mLastStatus.put(moveId, status); 20857 } 20858 } 20859 } 20860 20861 private final static class OnPermissionChangeListeners extends Handler { 20862 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20863 20864 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20865 new RemoteCallbackList<>(); 20866 20867 public OnPermissionChangeListeners(Looper looper) { 20868 super(looper); 20869 } 20870 20871 @Override 20872 public void handleMessage(Message msg) { 20873 switch (msg.what) { 20874 case MSG_ON_PERMISSIONS_CHANGED: { 20875 final int uid = msg.arg1; 20876 handleOnPermissionsChanged(uid); 20877 } break; 20878 } 20879 } 20880 20881 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20882 mPermissionListeners.register(listener); 20883 20884 } 20885 20886 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20887 mPermissionListeners.unregister(listener); 20888 } 20889 20890 public void onPermissionsChanged(int uid) { 20891 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20892 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20893 } 20894 } 20895 20896 private void handleOnPermissionsChanged(int uid) { 20897 final int count = mPermissionListeners.beginBroadcast(); 20898 try { 20899 for (int i = 0; i < count; i++) { 20900 IOnPermissionsChangeListener callback = mPermissionListeners 20901 .getBroadcastItem(i); 20902 try { 20903 callback.onPermissionsChanged(uid); 20904 } catch (RemoteException e) { 20905 Log.e(TAG, "Permission listener is dead", e); 20906 } 20907 } 20908 } finally { 20909 mPermissionListeners.finishBroadcast(); 20910 } 20911 } 20912 } 20913 20914 private class PackageManagerInternalImpl extends PackageManagerInternal { 20915 @Override 20916 public void setLocationPackagesProvider(PackagesProvider provider) { 20917 synchronized (mPackages) { 20918 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20919 } 20920 } 20921 20922 @Override 20923 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20924 synchronized (mPackages) { 20925 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20926 } 20927 } 20928 20929 @Override 20930 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20931 synchronized (mPackages) { 20932 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20933 } 20934 } 20935 20936 @Override 20937 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20938 synchronized (mPackages) { 20939 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20940 } 20941 } 20942 20943 @Override 20944 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20945 synchronized (mPackages) { 20946 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20947 } 20948 } 20949 20950 @Override 20951 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20952 synchronized (mPackages) { 20953 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20954 } 20955 } 20956 20957 @Override 20958 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20959 synchronized (mPackages) { 20960 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20961 packageName, userId); 20962 } 20963 } 20964 20965 @Override 20966 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20967 synchronized (mPackages) { 20968 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20969 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20970 packageName, userId); 20971 } 20972 } 20973 20974 @Override 20975 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20976 synchronized (mPackages) { 20977 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20978 packageName, userId); 20979 } 20980 } 20981 20982 @Override 20983 public void setKeepUninstalledPackages(final List<String> packageList) { 20984 Preconditions.checkNotNull(packageList); 20985 List<String> removedFromList = null; 20986 synchronized (mPackages) { 20987 if (mKeepUninstalledPackages != null) { 20988 final int packagesCount = mKeepUninstalledPackages.size(); 20989 for (int i = 0; i < packagesCount; i++) { 20990 String oldPackage = mKeepUninstalledPackages.get(i); 20991 if (packageList != null && packageList.contains(oldPackage)) { 20992 continue; 20993 } 20994 if (removedFromList == null) { 20995 removedFromList = new ArrayList<>(); 20996 } 20997 removedFromList.add(oldPackage); 20998 } 20999 } 21000 mKeepUninstalledPackages = new ArrayList<>(packageList); 21001 if (removedFromList != null) { 21002 final int removedCount = removedFromList.size(); 21003 for (int i = 0; i < removedCount; i++) { 21004 deletePackageIfUnusedLPr(removedFromList.get(i)); 21005 } 21006 } 21007 } 21008 } 21009 21010 @Override 21011 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21012 synchronized (mPackages) { 21013 // If we do not support permission review, done. 21014 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 21015 return false; 21016 } 21017 21018 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21019 if (packageSetting == null) { 21020 return false; 21021 } 21022 21023 // Permission review applies only to apps not supporting the new permission model. 21024 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21025 return false; 21026 } 21027 21028 // Legacy apps have the permission and get user consent on launch. 21029 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21030 return permissionsState.isPermissionReviewRequired(userId); 21031 } 21032 } 21033 21034 @Override 21035 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21036 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21037 } 21038 21039 @Override 21040 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21041 int userId) { 21042 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21043 } 21044 21045 @Override 21046 public void setDeviceAndProfileOwnerPackages( 21047 int deviceOwnerUserId, String deviceOwnerPackage, 21048 SparseArray<String> profileOwnerPackages) { 21049 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21050 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21051 } 21052 21053 @Override 21054 public boolean isPackageDataProtected(int userId, String packageName) { 21055 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21056 } 21057 21058 @Override 21059 public boolean wasPackageEverLaunched(String packageName, int userId) { 21060 synchronized (mPackages) { 21061 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21062 } 21063 } 21064 } 21065 21066 @Override 21067 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21068 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21069 synchronized (mPackages) { 21070 final long identity = Binder.clearCallingIdentity(); 21071 try { 21072 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21073 packageNames, userId); 21074 } finally { 21075 Binder.restoreCallingIdentity(identity); 21076 } 21077 } 21078 } 21079 21080 private static void enforceSystemOrPhoneCaller(String tag) { 21081 int callingUid = Binder.getCallingUid(); 21082 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21083 throw new SecurityException( 21084 "Cannot call " + tag + " from UID " + callingUid); 21085 } 21086 } 21087 21088 boolean isHistoricalPackageUsageAvailable() { 21089 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21090 } 21091 21092 /** 21093 * Return a <b>copy</b> of the collection of packages known to the package manager. 21094 * @return A copy of the values of mPackages. 21095 */ 21096 Collection<PackageParser.Package> getPackages() { 21097 synchronized (mPackages) { 21098 return new ArrayList<>(mPackages.values()); 21099 } 21100 } 21101 21102 /** 21103 * Logs process start information (including base APK hash) to the security log. 21104 * @hide 21105 */ 21106 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21107 String apkFile, int pid) { 21108 if (!SecurityLog.isLoggingEnabled()) { 21109 return; 21110 } 21111 Bundle data = new Bundle(); 21112 data.putLong("startTimestamp", System.currentTimeMillis()); 21113 data.putString("processName", processName); 21114 data.putInt("uid", uid); 21115 data.putString("seinfo", seinfo); 21116 data.putString("apkFile", apkFile); 21117 data.putInt("pid", pid); 21118 Message msg = mProcessLoggingHandler.obtainMessage( 21119 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21120 msg.setData(data); 21121 mProcessLoggingHandler.sendMessage(msg); 21122 } 21123 21124 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21125 return mCompilerStats.getPackageStats(pkgName); 21126 } 21127 21128 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21129 return getOrCreateCompilerPackageStats(pkg.packageName); 21130 } 21131 21132 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21133 return mCompilerStats.getOrCreatePackageStats(pkgName); 21134 } 21135 21136 public void deleteCompilerPackageStats(String pkgName) { 21137 mCompilerStats.deletePackageStats(pkgName); 21138 } 21139} 21140