PackageManagerService.java revision 4a6e2466713e50d642b375b621265013d73e5d8e
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 also in 468 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> in addition to 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. (Do this before scanning any apps.) 2275 // For security and version matching reason, only consider 2276 // overlay packages if they reside in the right directory. 2277 String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY); 2278 if (!overlaySkuDir.isEmpty()) { 2279 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlaySkuDir), mDefParseFlags 2280 | PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR 2282 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2283 } 2284 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2285 | PackageParser.PARSE_IS_SYSTEM 2286 | PackageParser.PARSE_IS_SYSTEM_DIR 2287 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2288 2289 // Find base frameworks (resource packages without code). 2290 scanDirTracedLI(frameworkDir, mDefParseFlags 2291 | PackageParser.PARSE_IS_SYSTEM 2292 | PackageParser.PARSE_IS_SYSTEM_DIR 2293 | PackageParser.PARSE_IS_PRIVILEGED, 2294 scanFlags | SCAN_NO_DEX, 0); 2295 2296 // Collected privileged system packages. 2297 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2298 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2299 | PackageParser.PARSE_IS_SYSTEM 2300 | PackageParser.PARSE_IS_SYSTEM_DIR 2301 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2302 2303 // Collect ordinary system packages. 2304 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2305 scanDirTracedLI(systemAppDir, mDefParseFlags 2306 | PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2308 2309 // Collect all vendor packages. 2310 File vendorAppDir = new File("/vendor/app"); 2311 try { 2312 vendorAppDir = vendorAppDir.getCanonicalFile(); 2313 } catch (IOException e) { 2314 // failed to look up canonical path, continue with original one 2315 } 2316 scanDirTracedLI(vendorAppDir, mDefParseFlags 2317 | PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2319 2320 // Collect all OEM packages. 2321 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2322 scanDirTracedLI(oemAppDir, mDefParseFlags 2323 | PackageParser.PARSE_IS_SYSTEM 2324 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2325 2326 // Prune any system packages that no longer exist. 2327 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2328 if (!mOnlyCore) { 2329 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2330 while (psit.hasNext()) { 2331 PackageSetting ps = psit.next(); 2332 2333 /* 2334 * If this is not a system app, it can't be a 2335 * disable system app. 2336 */ 2337 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2338 continue; 2339 } 2340 2341 /* 2342 * If the package is scanned, it's not erased. 2343 */ 2344 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2345 if (scannedPkg != null) { 2346 /* 2347 * If the system app is both scanned and in the 2348 * disabled packages list, then it must have been 2349 * added via OTA. Remove it from the currently 2350 * scanned package so the previously user-installed 2351 * application can be scanned. 2352 */ 2353 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2354 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2355 + ps.name + "; removing system app. Last known codePath=" 2356 + ps.codePathString + ", installStatus=" + ps.installStatus 2357 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2358 + scannedPkg.mVersionCode); 2359 removePackageLI(scannedPkg, true); 2360 mExpectingBetter.put(ps.name, ps.codePath); 2361 } 2362 2363 continue; 2364 } 2365 2366 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2367 psit.remove(); 2368 logCriticalInfo(Log.WARN, "System package " + ps.name 2369 + " no longer exists; it's data will be wiped"); 2370 // Actual deletion of code and data will be handled by later 2371 // reconciliation step 2372 } else { 2373 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2374 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2375 possiblyDeletedUpdatedSystemApps.add(ps.name); 2376 } 2377 } 2378 } 2379 } 2380 2381 //look for any incomplete package installations 2382 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2383 for (int i = 0; i < deletePkgsList.size(); i++) { 2384 // Actual deletion of code and data will be handled by later 2385 // reconciliation step 2386 final String packageName = deletePkgsList.get(i).name; 2387 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2388 synchronized (mPackages) { 2389 mSettings.removePackageLPw(packageName); 2390 } 2391 } 2392 2393 //delete tmp files 2394 deleteTempPackageFiles(); 2395 2396 // Remove any shared userIDs that have no associated packages 2397 mSettings.pruneSharedUsersLPw(); 2398 2399 if (!mOnlyCore) { 2400 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2401 SystemClock.uptimeMillis()); 2402 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2403 2404 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2405 | PackageParser.PARSE_FORWARD_LOCK, 2406 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2407 2408 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2409 | PackageParser.PARSE_IS_EPHEMERAL, 2410 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2411 2412 /** 2413 * Remove disable package settings for any updated system 2414 * apps that were removed via an OTA. If they're not a 2415 * previously-updated app, remove them completely. 2416 * Otherwise, just revoke their system-level permissions. 2417 */ 2418 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2419 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2420 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2421 2422 String msg; 2423 if (deletedPkg == null) { 2424 msg = "Updated system package " + deletedAppName 2425 + " no longer exists; it's data will be wiped"; 2426 // Actual deletion of code and data will be handled by later 2427 // reconciliation step 2428 } else { 2429 msg = "Updated system app + " + deletedAppName 2430 + " no longer present; removing system privileges for " 2431 + deletedAppName; 2432 2433 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2434 2435 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2436 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2437 } 2438 logCriticalInfo(Log.WARN, msg); 2439 } 2440 2441 /** 2442 * Make sure all system apps that we expected to appear on 2443 * the userdata partition actually showed up. If they never 2444 * appeared, crawl back and revive the system version. 2445 */ 2446 for (int i = 0; i < mExpectingBetter.size(); i++) { 2447 final String packageName = mExpectingBetter.keyAt(i); 2448 if (!mPackages.containsKey(packageName)) { 2449 final File scanFile = mExpectingBetter.valueAt(i); 2450 2451 logCriticalInfo(Log.WARN, "Expected better " + packageName 2452 + " but never showed up; reverting to system"); 2453 2454 int reparseFlags = mDefParseFlags; 2455 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2456 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2457 | PackageParser.PARSE_IS_SYSTEM_DIR 2458 | PackageParser.PARSE_IS_PRIVILEGED; 2459 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2460 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2461 | PackageParser.PARSE_IS_SYSTEM_DIR; 2462 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2463 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2464 | PackageParser.PARSE_IS_SYSTEM_DIR; 2465 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2466 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2467 | PackageParser.PARSE_IS_SYSTEM_DIR; 2468 } else { 2469 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2470 continue; 2471 } 2472 2473 mSettings.enableSystemPackageLPw(packageName); 2474 2475 try { 2476 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2477 } catch (PackageManagerException e) { 2478 Slog.e(TAG, "Failed to parse original system package: " 2479 + e.getMessage()); 2480 } 2481 } 2482 } 2483 } 2484 mExpectingBetter.clear(); 2485 2486 // Resolve the storage manager. 2487 mStorageManagerPackage = getStorageManagerPackageName(); 2488 2489 // Resolve protected action filters. Only the setup wizard is allowed to 2490 // have a high priority filter for these actions. 2491 mSetupWizardPackage = getSetupWizardPackageName(); 2492 if (mProtectedFilters.size() > 0) { 2493 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2494 Slog.i(TAG, "No setup wizard;" 2495 + " All protected intents capped to priority 0"); 2496 } 2497 for (ActivityIntentInfo filter : mProtectedFilters) { 2498 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2499 if (DEBUG_FILTERS) { 2500 Slog.i(TAG, "Found setup wizard;" 2501 + " allow priority " + filter.getPriority() + ";" 2502 + " package: " + filter.activity.info.packageName 2503 + " activity: " + filter.activity.className 2504 + " priority: " + filter.getPriority()); 2505 } 2506 // skip setup wizard; allow it to keep the high priority filter 2507 continue; 2508 } 2509 Slog.w(TAG, "Protected action; cap priority to 0;" 2510 + " package: " + filter.activity.info.packageName 2511 + " activity: " + filter.activity.className 2512 + " origPrio: " + filter.getPriority()); 2513 filter.setPriority(0); 2514 } 2515 } 2516 mDeferProtectedFilters = false; 2517 mProtectedFilters.clear(); 2518 2519 // Now that we know all of the shared libraries, update all clients to have 2520 // the correct library paths. 2521 updateAllSharedLibrariesLPw(); 2522 2523 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2524 // NOTE: We ignore potential failures here during a system scan (like 2525 // the rest of the commands above) because there's precious little we 2526 // can do about it. A settings error is reported, though. 2527 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2528 false /* boot complete */); 2529 } 2530 2531 // Now that we know all the packages we are keeping, 2532 // read and update their last usage times. 2533 mPackageUsage.read(mPackages); 2534 mCompilerStats.read(); 2535 2536 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2537 SystemClock.uptimeMillis()); 2538 Slog.i(TAG, "Time to scan packages: " 2539 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2540 + " seconds"); 2541 2542 // If the platform SDK has changed since the last time we booted, 2543 // we need to re-grant app permission to catch any new ones that 2544 // appear. This is really a hack, and means that apps can in some 2545 // cases get permissions that the user didn't initially explicitly 2546 // allow... it would be nice to have some better way to handle 2547 // this situation. 2548 int updateFlags = UPDATE_PERMISSIONS_ALL; 2549 if (ver.sdkVersion != mSdkVersion) { 2550 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2551 + mSdkVersion + "; regranting permissions for internal storage"); 2552 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2553 } 2554 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2555 ver.sdkVersion = mSdkVersion; 2556 2557 // If this is the first boot or an update from pre-M, and it is a normal 2558 // boot, then we need to initialize the default preferred apps across 2559 // all defined users. 2560 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2561 for (UserInfo user : sUserManager.getUsers(true)) { 2562 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2563 applyFactoryDefaultBrowserLPw(user.id); 2564 primeDomainVerificationsLPw(user.id); 2565 } 2566 } 2567 2568 // Prepare storage for system user really early during boot, 2569 // since core system apps like SettingsProvider and SystemUI 2570 // can't wait for user to start 2571 final int storageFlags; 2572 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2573 storageFlags = StorageManager.FLAG_STORAGE_DE; 2574 } else { 2575 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2576 } 2577 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2578 storageFlags); 2579 2580 // If this is first boot after an OTA, and a normal boot, then 2581 // we need to clear code cache directories. 2582 // Note that we do *not* clear the application profiles. These remain valid 2583 // across OTAs and are used to drive profile verification (post OTA) and 2584 // profile compilation (without waiting to collect a fresh set of profiles). 2585 if (mIsUpgrade && !onlyCore) { 2586 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2587 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2588 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2589 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2590 // No apps are running this early, so no need to freeze 2591 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2592 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2593 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2594 } 2595 } 2596 ver.fingerprint = Build.FINGERPRINT; 2597 } 2598 2599 checkDefaultBrowser(); 2600 2601 // clear only after permissions and other defaults have been updated 2602 mExistingSystemPackages.clear(); 2603 mPromoteSystemApps = false; 2604 2605 // All the changes are done during package scanning. 2606 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2607 2608 // can downgrade to reader 2609 mSettings.writeLPr(); 2610 2611 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2612 // early on (before the package manager declares itself as early) because other 2613 // components in the system server might ask for package contexts for these apps. 2614 // 2615 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2616 // (i.e, that the data partition is unavailable). 2617 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2618 long start = System.nanoTime(); 2619 List<PackageParser.Package> coreApps = new ArrayList<>(); 2620 for (PackageParser.Package pkg : mPackages.values()) { 2621 if (pkg.coreApp) { 2622 coreApps.add(pkg); 2623 } 2624 } 2625 2626 int[] stats = performDexOptUpgrade(coreApps, false, 2627 getCompilerFilterForReason(REASON_CORE_APP)); 2628 2629 final int elapsedTimeSeconds = 2630 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2631 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2632 2633 if (DEBUG_DEXOPT) { 2634 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2635 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2636 } 2637 2638 2639 // TODO: Should we log these stats to tron too ? 2640 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2641 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2642 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2643 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2644 } 2645 2646 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2647 SystemClock.uptimeMillis()); 2648 2649 if (!mOnlyCore) { 2650 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2651 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2652 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2653 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2654 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2655 mIntentFilterVerifierComponent); 2656 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2657 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2658 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2659 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2660 } else { 2661 mRequiredVerifierPackage = null; 2662 mRequiredInstallerPackage = null; 2663 mRequiredUninstallerPackage = null; 2664 mIntentFilterVerifierComponent = null; 2665 mIntentFilterVerifier = null; 2666 mServicesSystemSharedLibraryPackageName = null; 2667 mSharedSystemSharedLibraryPackageName = null; 2668 } 2669 2670 mInstallerService = new PackageInstallerService(context, this); 2671 2672 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2673 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2674 // both the installer and resolver must be present to enable ephemeral 2675 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2676 if (DEBUG_EPHEMERAL) { 2677 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2678 + " installer:" + ephemeralInstallerComponent); 2679 } 2680 mEphemeralResolverComponent = ephemeralResolverComponent; 2681 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2682 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2683 mEphemeralResolverConnection = 2684 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2685 } else { 2686 if (DEBUG_EPHEMERAL) { 2687 final String missingComponent = 2688 (ephemeralResolverComponent == null) 2689 ? (ephemeralInstallerComponent == null) 2690 ? "resolver and installer" 2691 : "resolver" 2692 : "installer"; 2693 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2694 } 2695 mEphemeralResolverComponent = null; 2696 mEphemeralInstallerComponent = null; 2697 mEphemeralResolverConnection = null; 2698 } 2699 2700 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2701 } // synchronized (mPackages) 2702 } // synchronized (mInstallLock) 2703 2704 // Now after opening every single application zip, make sure they 2705 // are all flushed. Not really needed, but keeps things nice and 2706 // tidy. 2707 Runtime.getRuntime().gc(); 2708 2709 // The initial scanning above does many calls into installd while 2710 // holding the mPackages lock, but we're mostly interested in yelling 2711 // once we have a booted system. 2712 mInstaller.setWarnIfHeld(mPackages); 2713 2714 // Expose private service for system components to use. 2715 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2716 } 2717 2718 @Override 2719 public boolean isFirstBoot() { 2720 return mFirstBoot; 2721 } 2722 2723 @Override 2724 public boolean isOnlyCoreApps() { 2725 return mOnlyCore; 2726 } 2727 2728 @Override 2729 public boolean isUpgrade() { 2730 return mIsUpgrade; 2731 } 2732 2733 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2734 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2735 2736 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2737 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2738 UserHandle.USER_SYSTEM); 2739 if (matches.size() == 1) { 2740 return matches.get(0).getComponentInfo().packageName; 2741 } else if (matches.size() == 0) { 2742 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2743 return null; 2744 } 2745 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2746 } 2747 2748 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2749 synchronized (mPackages) { 2750 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2751 if (libraryEntry == null) { 2752 throw new IllegalStateException("Missing required shared library:" + libraryName); 2753 } 2754 return libraryEntry.apk; 2755 } 2756 } 2757 2758 private @NonNull String getRequiredInstallerLPr() { 2759 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2760 intent.addCategory(Intent.CATEGORY_DEFAULT); 2761 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2762 2763 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2764 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2765 UserHandle.USER_SYSTEM); 2766 if (matches.size() == 1) { 2767 ResolveInfo resolveInfo = matches.get(0); 2768 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2769 throw new RuntimeException("The installer must be a privileged app"); 2770 } 2771 return matches.get(0).getComponentInfo().packageName; 2772 } else { 2773 throw new RuntimeException("There must be exactly one installer; found " + matches); 2774 } 2775 } 2776 2777 private @NonNull String getRequiredUninstallerLPr() { 2778 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2779 intent.addCategory(Intent.CATEGORY_DEFAULT); 2780 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2781 2782 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2783 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2784 UserHandle.USER_SYSTEM); 2785 if (resolveInfo == null || 2786 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2787 throw new RuntimeException("There must be exactly one uninstaller; found " 2788 + resolveInfo); 2789 } 2790 return resolveInfo.getComponentInfo().packageName; 2791 } 2792 2793 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2794 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2795 2796 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2797 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2798 UserHandle.USER_SYSTEM); 2799 ResolveInfo best = null; 2800 final int N = matches.size(); 2801 for (int i = 0; i < N; i++) { 2802 final ResolveInfo cur = matches.get(i); 2803 final String packageName = cur.getComponentInfo().packageName; 2804 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2805 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2806 continue; 2807 } 2808 2809 if (best == null || cur.priority > best.priority) { 2810 best = cur; 2811 } 2812 } 2813 2814 if (best != null) { 2815 return best.getComponentInfo().getComponentName(); 2816 } else { 2817 throw new RuntimeException("There must be at least one intent filter verifier"); 2818 } 2819 } 2820 2821 private @Nullable ComponentName getEphemeralResolverLPr() { 2822 final String[] packageArray = 2823 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2824 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2825 if (DEBUG_EPHEMERAL) { 2826 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2827 } 2828 return null; 2829 } 2830 2831 final int resolveFlags = 2832 MATCH_DIRECT_BOOT_AWARE 2833 | MATCH_DIRECT_BOOT_UNAWARE 2834 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2835 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2836 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2837 resolveFlags, UserHandle.USER_SYSTEM); 2838 2839 final int N = resolvers.size(); 2840 if (N == 0) { 2841 if (DEBUG_EPHEMERAL) { 2842 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2843 } 2844 return null; 2845 } 2846 2847 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2848 for (int i = 0; i < N; i++) { 2849 final ResolveInfo info = resolvers.get(i); 2850 2851 if (info.serviceInfo == null) { 2852 continue; 2853 } 2854 2855 final String packageName = info.serviceInfo.packageName; 2856 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2857 if (DEBUG_EPHEMERAL) { 2858 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2859 + " pkg: " + packageName + ", info:" + info); 2860 } 2861 continue; 2862 } 2863 2864 if (DEBUG_EPHEMERAL) { 2865 Slog.v(TAG, "Ephemeral resolver found;" 2866 + " pkg: " + packageName + ", info:" + info); 2867 } 2868 return new ComponentName(packageName, info.serviceInfo.name); 2869 } 2870 if (DEBUG_EPHEMERAL) { 2871 Slog.v(TAG, "Ephemeral resolver NOT found"); 2872 } 2873 return null; 2874 } 2875 2876 private @Nullable ComponentName getEphemeralInstallerLPr() { 2877 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2878 intent.addCategory(Intent.CATEGORY_DEFAULT); 2879 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2880 2881 final int resolveFlags = 2882 MATCH_DIRECT_BOOT_AWARE 2883 | MATCH_DIRECT_BOOT_UNAWARE 2884 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2885 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2886 resolveFlags, UserHandle.USER_SYSTEM); 2887 if (matches.size() == 0) { 2888 return null; 2889 } else if (matches.size() == 1) { 2890 return matches.get(0).getComponentInfo().getComponentName(); 2891 } else { 2892 throw new RuntimeException( 2893 "There must be at most one ephemeral installer; found " + matches); 2894 } 2895 } 2896 2897 private void primeDomainVerificationsLPw(int userId) { 2898 if (DEBUG_DOMAIN_VERIFICATION) { 2899 Slog.d(TAG, "Priming domain verifications in user " + userId); 2900 } 2901 2902 SystemConfig systemConfig = SystemConfig.getInstance(); 2903 ArraySet<String> packages = systemConfig.getLinkedApps(); 2904 ArraySet<String> domains = new ArraySet<String>(); 2905 2906 for (String packageName : packages) { 2907 PackageParser.Package pkg = mPackages.get(packageName); 2908 if (pkg != null) { 2909 if (!pkg.isSystemApp()) { 2910 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2911 continue; 2912 } 2913 2914 domains.clear(); 2915 for (PackageParser.Activity a : pkg.activities) { 2916 for (ActivityIntentInfo filter : a.intents) { 2917 if (hasValidDomains(filter)) { 2918 domains.addAll(filter.getHostsList()); 2919 } 2920 } 2921 } 2922 2923 if (domains.size() > 0) { 2924 if (DEBUG_DOMAIN_VERIFICATION) { 2925 Slog.v(TAG, " + " + packageName); 2926 } 2927 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2928 // state w.r.t. the formal app-linkage "no verification attempted" state; 2929 // and then 'always' in the per-user state actually used for intent resolution. 2930 final IntentFilterVerificationInfo ivi; 2931 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2932 new ArrayList<String>(domains)); 2933 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2934 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2935 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2936 } else { 2937 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2938 + "' does not handle web links"); 2939 } 2940 } else { 2941 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2942 } 2943 } 2944 2945 scheduleWritePackageRestrictionsLocked(userId); 2946 scheduleWriteSettingsLocked(); 2947 } 2948 2949 private void applyFactoryDefaultBrowserLPw(int userId) { 2950 // The default browser app's package name is stored in a string resource, 2951 // with a product-specific overlay used for vendor customization. 2952 String browserPkg = mContext.getResources().getString( 2953 com.android.internal.R.string.default_browser); 2954 if (!TextUtils.isEmpty(browserPkg)) { 2955 // non-empty string => required to be a known package 2956 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2957 if (ps == null) { 2958 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2959 browserPkg = null; 2960 } else { 2961 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2962 } 2963 } 2964 2965 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2966 // default. If there's more than one, just leave everything alone. 2967 if (browserPkg == null) { 2968 calculateDefaultBrowserLPw(userId); 2969 } 2970 } 2971 2972 private void calculateDefaultBrowserLPw(int userId) { 2973 List<String> allBrowsers = resolveAllBrowserApps(userId); 2974 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2975 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2976 } 2977 2978 private List<String> resolveAllBrowserApps(int userId) { 2979 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2980 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2981 PackageManager.MATCH_ALL, userId); 2982 2983 final int count = list.size(); 2984 List<String> result = new ArrayList<String>(count); 2985 for (int i=0; i<count; i++) { 2986 ResolveInfo info = list.get(i); 2987 if (info.activityInfo == null 2988 || !info.handleAllWebDataURI 2989 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2990 || result.contains(info.activityInfo.packageName)) { 2991 continue; 2992 } 2993 result.add(info.activityInfo.packageName); 2994 } 2995 2996 return result; 2997 } 2998 2999 private boolean packageIsBrowser(String packageName, int userId) { 3000 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3001 PackageManager.MATCH_ALL, userId); 3002 final int N = list.size(); 3003 for (int i = 0; i < N; i++) { 3004 ResolveInfo info = list.get(i); 3005 if (packageName.equals(info.activityInfo.packageName)) { 3006 return true; 3007 } 3008 } 3009 return false; 3010 } 3011 3012 private void checkDefaultBrowser() { 3013 final int myUserId = UserHandle.myUserId(); 3014 final String packageName = getDefaultBrowserPackageName(myUserId); 3015 if (packageName != null) { 3016 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3017 if (info == null) { 3018 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3019 synchronized (mPackages) { 3020 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3021 } 3022 } 3023 } 3024 } 3025 3026 @Override 3027 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3028 throws RemoteException { 3029 try { 3030 return super.onTransact(code, data, reply, flags); 3031 } catch (RuntimeException e) { 3032 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3033 Slog.wtf(TAG, "Package Manager Crash", e); 3034 } 3035 throw e; 3036 } 3037 } 3038 3039 static int[] appendInts(int[] cur, int[] add) { 3040 if (add == null) return cur; 3041 if (cur == null) return add; 3042 final int N = add.length; 3043 for (int i=0; i<N; i++) { 3044 cur = appendInt(cur, add[i]); 3045 } 3046 return cur; 3047 } 3048 3049 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3050 if (!sUserManager.exists(userId)) return null; 3051 if (ps == null) { 3052 return null; 3053 } 3054 final PackageParser.Package p = ps.pkg; 3055 if (p == null) { 3056 return null; 3057 } 3058 3059 final PermissionsState permissionsState = ps.getPermissionsState(); 3060 3061 // Compute GIDs only if requested 3062 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3063 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3064 // Compute granted permissions only if package has requested permissions 3065 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3066 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3067 final PackageUserState state = ps.readUserState(userId); 3068 3069 return PackageParser.generatePackageInfo(p, gids, flags, 3070 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3071 } 3072 3073 @Override 3074 public void checkPackageStartable(String packageName, int userId) { 3075 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3076 3077 synchronized (mPackages) { 3078 final PackageSetting ps = mSettings.mPackages.get(packageName); 3079 if (ps == null) { 3080 throw new SecurityException("Package " + packageName + " was not found!"); 3081 } 3082 3083 if (!ps.getInstalled(userId)) { 3084 throw new SecurityException( 3085 "Package " + packageName + " was not installed for user " + userId + "!"); 3086 } 3087 3088 if (mSafeMode && !ps.isSystem()) { 3089 throw new SecurityException("Package " + packageName + " not a system app!"); 3090 } 3091 3092 if (mFrozenPackages.contains(packageName)) { 3093 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3094 } 3095 3096 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3097 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3098 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3099 } 3100 } 3101 } 3102 3103 @Override 3104 public boolean isPackageAvailable(String packageName, int userId) { 3105 if (!sUserManager.exists(userId)) return false; 3106 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3107 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3108 synchronized (mPackages) { 3109 PackageParser.Package p = mPackages.get(packageName); 3110 if (p != null) { 3111 final PackageSetting ps = (PackageSetting) p.mExtras; 3112 if (ps != null) { 3113 final PackageUserState state = ps.readUserState(userId); 3114 if (state != null) { 3115 return PackageParser.isAvailable(state); 3116 } 3117 } 3118 } 3119 } 3120 return false; 3121 } 3122 3123 @Override 3124 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3125 if (!sUserManager.exists(userId)) return null; 3126 flags = updateFlagsForPackage(flags, userId, packageName); 3127 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3128 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3129 // reader 3130 synchronized (mPackages) { 3131 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3132 PackageParser.Package p = null; 3133 if (matchFactoryOnly) { 3134 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3135 if (ps != null) { 3136 return generatePackageInfo(ps, flags, userId); 3137 } 3138 } 3139 if (p == null) { 3140 p = mPackages.get(packageName); 3141 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3142 return null; 3143 } 3144 } 3145 if (DEBUG_PACKAGE_INFO) 3146 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3147 if (p != null) { 3148 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3149 } 3150 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3151 final PackageSetting ps = mSettings.mPackages.get(packageName); 3152 return generatePackageInfo(ps, flags, userId); 3153 } 3154 } 3155 return null; 3156 } 3157 3158 @Override 3159 public String[] currentToCanonicalPackageNames(String[] names) { 3160 String[] out = new String[names.length]; 3161 // reader 3162 synchronized (mPackages) { 3163 for (int i=names.length-1; i>=0; i--) { 3164 PackageSetting ps = mSettings.mPackages.get(names[i]); 3165 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3166 } 3167 } 3168 return out; 3169 } 3170 3171 @Override 3172 public String[] canonicalToCurrentPackageNames(String[] names) { 3173 String[] out = new String[names.length]; 3174 // reader 3175 synchronized (mPackages) { 3176 for (int i=names.length-1; i>=0; i--) { 3177 String cur = mSettings.mRenamedPackages.get(names[i]); 3178 out[i] = cur != null ? cur : names[i]; 3179 } 3180 } 3181 return out; 3182 } 3183 3184 @Override 3185 public int getPackageUid(String packageName, int flags, int userId) { 3186 if (!sUserManager.exists(userId)) return -1; 3187 flags = updateFlagsForPackage(flags, userId, packageName); 3188 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3189 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3190 3191 // reader 3192 synchronized (mPackages) { 3193 final PackageParser.Package p = mPackages.get(packageName); 3194 if (p != null && p.isMatch(flags)) { 3195 return UserHandle.getUid(userId, p.applicationInfo.uid); 3196 } 3197 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3198 final PackageSetting ps = mSettings.mPackages.get(packageName); 3199 if (ps != null && ps.isMatch(flags)) { 3200 return UserHandle.getUid(userId, ps.appId); 3201 } 3202 } 3203 } 3204 3205 return -1; 3206 } 3207 3208 @Override 3209 public int[] getPackageGids(String packageName, int flags, int userId) { 3210 if (!sUserManager.exists(userId)) return null; 3211 flags = updateFlagsForPackage(flags, userId, packageName); 3212 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3213 false /* requireFullPermission */, false /* checkShell */, 3214 "getPackageGids"); 3215 3216 // reader 3217 synchronized (mPackages) { 3218 final PackageParser.Package p = mPackages.get(packageName); 3219 if (p != null && p.isMatch(flags)) { 3220 PackageSetting ps = (PackageSetting) p.mExtras; 3221 return ps.getPermissionsState().computeGids(userId); 3222 } 3223 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3224 final PackageSetting ps = mSettings.mPackages.get(packageName); 3225 if (ps != null && ps.isMatch(flags)) { 3226 return ps.getPermissionsState().computeGids(userId); 3227 } 3228 } 3229 } 3230 3231 return null; 3232 } 3233 3234 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3235 if (bp.perm != null) { 3236 return PackageParser.generatePermissionInfo(bp.perm, flags); 3237 } 3238 PermissionInfo pi = new PermissionInfo(); 3239 pi.name = bp.name; 3240 pi.packageName = bp.sourcePackage; 3241 pi.nonLocalizedLabel = bp.name; 3242 pi.protectionLevel = bp.protectionLevel; 3243 return pi; 3244 } 3245 3246 @Override 3247 public PermissionInfo getPermissionInfo(String name, int flags) { 3248 // reader 3249 synchronized (mPackages) { 3250 final BasePermission p = mSettings.mPermissions.get(name); 3251 if (p != null) { 3252 return generatePermissionInfo(p, flags); 3253 } 3254 return null; 3255 } 3256 } 3257 3258 @Override 3259 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3260 int flags) { 3261 // reader 3262 synchronized (mPackages) { 3263 if (group != null && !mPermissionGroups.containsKey(group)) { 3264 // This is thrown as NameNotFoundException 3265 return null; 3266 } 3267 3268 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3269 for (BasePermission p : mSettings.mPermissions.values()) { 3270 if (group == null) { 3271 if (p.perm == null || p.perm.info.group == null) { 3272 out.add(generatePermissionInfo(p, flags)); 3273 } 3274 } else { 3275 if (p.perm != null && group.equals(p.perm.info.group)) { 3276 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3277 } 3278 } 3279 } 3280 return new ParceledListSlice<>(out); 3281 } 3282 } 3283 3284 @Override 3285 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3286 // reader 3287 synchronized (mPackages) { 3288 return PackageParser.generatePermissionGroupInfo( 3289 mPermissionGroups.get(name), flags); 3290 } 3291 } 3292 3293 @Override 3294 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3295 // reader 3296 synchronized (mPackages) { 3297 final int N = mPermissionGroups.size(); 3298 ArrayList<PermissionGroupInfo> out 3299 = new ArrayList<PermissionGroupInfo>(N); 3300 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3301 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3302 } 3303 return new ParceledListSlice<>(out); 3304 } 3305 } 3306 3307 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3308 int userId) { 3309 if (!sUserManager.exists(userId)) return null; 3310 PackageSetting ps = mSettings.mPackages.get(packageName); 3311 if (ps != null) { 3312 if (ps.pkg == null) { 3313 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3314 if (pInfo != null) { 3315 return pInfo.applicationInfo; 3316 } 3317 return null; 3318 } 3319 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3320 ps.readUserState(userId), userId); 3321 } 3322 return null; 3323 } 3324 3325 @Override 3326 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3327 if (!sUserManager.exists(userId)) return null; 3328 flags = updateFlagsForApplication(flags, userId, packageName); 3329 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3330 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3331 // writer 3332 synchronized (mPackages) { 3333 PackageParser.Package p = mPackages.get(packageName); 3334 if (DEBUG_PACKAGE_INFO) Log.v( 3335 TAG, "getApplicationInfo " + packageName 3336 + ": " + p); 3337 if (p != null) { 3338 PackageSetting ps = mSettings.mPackages.get(packageName); 3339 if (ps == null) return null; 3340 // Note: isEnabledLP() does not apply here - always return info 3341 return PackageParser.generateApplicationInfo( 3342 p, flags, ps.readUserState(userId), userId); 3343 } 3344 if ("android".equals(packageName)||"system".equals(packageName)) { 3345 return mAndroidApplication; 3346 } 3347 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3348 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3349 } 3350 } 3351 return null; 3352 } 3353 3354 @Override 3355 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3356 final IPackageDataObserver observer) { 3357 mContext.enforceCallingOrSelfPermission( 3358 android.Manifest.permission.CLEAR_APP_CACHE, null); 3359 // Queue up an async operation since clearing cache may take a little while. 3360 mHandler.post(new Runnable() { 3361 public void run() { 3362 mHandler.removeCallbacks(this); 3363 boolean success = true; 3364 synchronized (mInstallLock) { 3365 try { 3366 mInstaller.freeCache(volumeUuid, freeStorageSize); 3367 } catch (InstallerException e) { 3368 Slog.w(TAG, "Couldn't clear application caches: " + e); 3369 success = false; 3370 } 3371 } 3372 if (observer != null) { 3373 try { 3374 observer.onRemoveCompleted(null, success); 3375 } catch (RemoteException e) { 3376 Slog.w(TAG, "RemoveException when invoking call back"); 3377 } 3378 } 3379 } 3380 }); 3381 } 3382 3383 @Override 3384 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3385 final IntentSender pi) { 3386 mContext.enforceCallingOrSelfPermission( 3387 android.Manifest.permission.CLEAR_APP_CACHE, null); 3388 // Queue up an async operation since clearing cache may take a little while. 3389 mHandler.post(new Runnable() { 3390 public void run() { 3391 mHandler.removeCallbacks(this); 3392 boolean success = true; 3393 synchronized (mInstallLock) { 3394 try { 3395 mInstaller.freeCache(volumeUuid, freeStorageSize); 3396 } catch (InstallerException e) { 3397 Slog.w(TAG, "Couldn't clear application caches: " + e); 3398 success = false; 3399 } 3400 } 3401 if(pi != null) { 3402 try { 3403 // Callback via pending intent 3404 int code = success ? 1 : 0; 3405 pi.sendIntent(null, code, null, 3406 null, null); 3407 } catch (SendIntentException e1) { 3408 Slog.i(TAG, "Failed to send pending intent"); 3409 } 3410 } 3411 } 3412 }); 3413 } 3414 3415 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3416 synchronized (mInstallLock) { 3417 try { 3418 mInstaller.freeCache(volumeUuid, freeStorageSize); 3419 } catch (InstallerException e) { 3420 throw new IOException("Failed to free enough space", e); 3421 } 3422 } 3423 } 3424 3425 /** 3426 * Update given flags based on encryption status of current user. 3427 */ 3428 private int updateFlags(int flags, int userId) { 3429 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3430 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3431 // Caller expressed an explicit opinion about what encryption 3432 // aware/unaware components they want to see, so fall through and 3433 // give them what they want 3434 } else { 3435 // Caller expressed no opinion, so match based on user state 3436 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3437 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3438 } else { 3439 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3440 } 3441 } 3442 return flags; 3443 } 3444 3445 private UserManagerInternal getUserManagerInternal() { 3446 if (mUserManagerInternal == null) { 3447 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3448 } 3449 return mUserManagerInternal; 3450 } 3451 3452 /** 3453 * Update given flags when being used to request {@link PackageInfo}. 3454 */ 3455 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3456 boolean triaged = true; 3457 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3458 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3459 // Caller is asking for component details, so they'd better be 3460 // asking for specific encryption matching behavior, or be triaged 3461 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3462 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3463 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3464 triaged = false; 3465 } 3466 } 3467 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3468 | PackageManager.MATCH_SYSTEM_ONLY 3469 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3470 triaged = false; 3471 } 3472 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3473 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3474 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3475 } 3476 return updateFlags(flags, userId); 3477 } 3478 3479 /** 3480 * Update given flags when being used to request {@link ApplicationInfo}. 3481 */ 3482 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3483 return updateFlagsForPackage(flags, userId, cookie); 3484 } 3485 3486 /** 3487 * Update given flags when being used to request {@link ComponentInfo}. 3488 */ 3489 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3490 if (cookie instanceof Intent) { 3491 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3492 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3493 } 3494 } 3495 3496 boolean triaged = true; 3497 // Caller is asking for component details, so they'd better be 3498 // asking for specific encryption matching behavior, or be triaged 3499 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3500 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3501 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3502 triaged = false; 3503 } 3504 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3505 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3506 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3507 } 3508 3509 return updateFlags(flags, userId); 3510 } 3511 3512 /** 3513 * Update given flags when being used to request {@link ResolveInfo}. 3514 */ 3515 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3516 // Safe mode means we shouldn't match any third-party components 3517 if (mSafeMode) { 3518 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3519 } 3520 3521 return updateFlagsForComponent(flags, userId, cookie); 3522 } 3523 3524 @Override 3525 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3526 if (!sUserManager.exists(userId)) return null; 3527 flags = updateFlagsForComponent(flags, userId, component); 3528 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3529 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3530 synchronized (mPackages) { 3531 PackageParser.Activity a = mActivities.mActivities.get(component); 3532 3533 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3534 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3535 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3536 if (ps == null) return null; 3537 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3538 userId); 3539 } 3540 if (mResolveComponentName.equals(component)) { 3541 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3542 new PackageUserState(), userId); 3543 } 3544 } 3545 return null; 3546 } 3547 3548 @Override 3549 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3550 String resolvedType) { 3551 synchronized (mPackages) { 3552 if (component.equals(mResolveComponentName)) { 3553 // The resolver supports EVERYTHING! 3554 return true; 3555 } 3556 PackageParser.Activity a = mActivities.mActivities.get(component); 3557 if (a == null) { 3558 return false; 3559 } 3560 for (int i=0; i<a.intents.size(); i++) { 3561 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3562 intent.getData(), intent.getCategories(), TAG) >= 0) { 3563 return true; 3564 } 3565 } 3566 return false; 3567 } 3568 } 3569 3570 @Override 3571 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3572 if (!sUserManager.exists(userId)) return null; 3573 flags = updateFlagsForComponent(flags, userId, component); 3574 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3575 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3576 synchronized (mPackages) { 3577 PackageParser.Activity a = mReceivers.mActivities.get(component); 3578 if (DEBUG_PACKAGE_INFO) Log.v( 3579 TAG, "getReceiverInfo " + component + ": " + a); 3580 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3581 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3582 if (ps == null) return null; 3583 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3584 userId); 3585 } 3586 } 3587 return null; 3588 } 3589 3590 @Override 3591 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3592 if (!sUserManager.exists(userId)) return null; 3593 flags = updateFlagsForComponent(flags, userId, component); 3594 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3595 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3596 synchronized (mPackages) { 3597 PackageParser.Service s = mServices.mServices.get(component); 3598 if (DEBUG_PACKAGE_INFO) Log.v( 3599 TAG, "getServiceInfo " + component + ": " + s); 3600 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3601 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3602 if (ps == null) return null; 3603 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3604 userId); 3605 } 3606 } 3607 return null; 3608 } 3609 3610 @Override 3611 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3612 if (!sUserManager.exists(userId)) return null; 3613 flags = updateFlagsForComponent(flags, userId, component); 3614 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3615 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3616 synchronized (mPackages) { 3617 PackageParser.Provider p = mProviders.mProviders.get(component); 3618 if (DEBUG_PACKAGE_INFO) Log.v( 3619 TAG, "getProviderInfo " + component + ": " + p); 3620 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3621 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3622 if (ps == null) return null; 3623 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3624 userId); 3625 } 3626 } 3627 return null; 3628 } 3629 3630 @Override 3631 public String[] getSystemSharedLibraryNames() { 3632 Set<String> libSet; 3633 synchronized (mPackages) { 3634 libSet = mSharedLibraries.keySet(); 3635 int size = libSet.size(); 3636 if (size > 0) { 3637 String[] libs = new String[size]; 3638 libSet.toArray(libs); 3639 return libs; 3640 } 3641 } 3642 return null; 3643 } 3644 3645 @Override 3646 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3647 synchronized (mPackages) { 3648 return mServicesSystemSharedLibraryPackageName; 3649 } 3650 } 3651 3652 @Override 3653 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3654 synchronized (mPackages) { 3655 return mSharedSystemSharedLibraryPackageName; 3656 } 3657 } 3658 3659 @Override 3660 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3661 synchronized (mPackages) { 3662 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3663 3664 final FeatureInfo fi = new FeatureInfo(); 3665 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3666 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3667 res.add(fi); 3668 3669 return new ParceledListSlice<>(res); 3670 } 3671 } 3672 3673 @Override 3674 public boolean hasSystemFeature(String name, int version) { 3675 synchronized (mPackages) { 3676 final FeatureInfo feat = mAvailableFeatures.get(name); 3677 if (feat == null) { 3678 return false; 3679 } else { 3680 return feat.version >= version; 3681 } 3682 } 3683 } 3684 3685 @Override 3686 public int checkPermission(String permName, String pkgName, int userId) { 3687 if (!sUserManager.exists(userId)) { 3688 return PackageManager.PERMISSION_DENIED; 3689 } 3690 3691 synchronized (mPackages) { 3692 final PackageParser.Package p = mPackages.get(pkgName); 3693 if (p != null && p.mExtras != null) { 3694 final PackageSetting ps = (PackageSetting) p.mExtras; 3695 final PermissionsState permissionsState = ps.getPermissionsState(); 3696 if (permissionsState.hasPermission(permName, userId)) { 3697 return PackageManager.PERMISSION_GRANTED; 3698 } 3699 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3700 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3701 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3702 return PackageManager.PERMISSION_GRANTED; 3703 } 3704 } 3705 } 3706 3707 return PackageManager.PERMISSION_DENIED; 3708 } 3709 3710 @Override 3711 public int checkUidPermission(String permName, int uid) { 3712 final int userId = UserHandle.getUserId(uid); 3713 3714 if (!sUserManager.exists(userId)) { 3715 return PackageManager.PERMISSION_DENIED; 3716 } 3717 3718 synchronized (mPackages) { 3719 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3720 if (obj != null) { 3721 final SettingBase ps = (SettingBase) obj; 3722 final PermissionsState permissionsState = ps.getPermissionsState(); 3723 if (permissionsState.hasPermission(permName, userId)) { 3724 return PackageManager.PERMISSION_GRANTED; 3725 } 3726 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3727 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3728 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3729 return PackageManager.PERMISSION_GRANTED; 3730 } 3731 } else { 3732 ArraySet<String> perms = mSystemPermissions.get(uid); 3733 if (perms != null) { 3734 if (perms.contains(permName)) { 3735 return PackageManager.PERMISSION_GRANTED; 3736 } 3737 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3738 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3739 return PackageManager.PERMISSION_GRANTED; 3740 } 3741 } 3742 } 3743 } 3744 3745 return PackageManager.PERMISSION_DENIED; 3746 } 3747 3748 @Override 3749 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3750 if (UserHandle.getCallingUserId() != userId) { 3751 mContext.enforceCallingPermission( 3752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3753 "isPermissionRevokedByPolicy for user " + userId); 3754 } 3755 3756 if (checkPermission(permission, packageName, userId) 3757 == PackageManager.PERMISSION_GRANTED) { 3758 return false; 3759 } 3760 3761 final long identity = Binder.clearCallingIdentity(); 3762 try { 3763 final int flags = getPermissionFlags(permission, packageName, userId); 3764 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3765 } finally { 3766 Binder.restoreCallingIdentity(identity); 3767 } 3768 } 3769 3770 @Override 3771 public String getPermissionControllerPackageName() { 3772 synchronized (mPackages) { 3773 return mRequiredInstallerPackage; 3774 } 3775 } 3776 3777 /** 3778 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3779 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3780 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3781 * @param message the message to log on security exception 3782 */ 3783 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3784 boolean checkShell, String message) { 3785 if (userId < 0) { 3786 throw new IllegalArgumentException("Invalid userId " + userId); 3787 } 3788 if (checkShell) { 3789 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3790 } 3791 if (userId == UserHandle.getUserId(callingUid)) return; 3792 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3793 if (requireFullPermission) { 3794 mContext.enforceCallingOrSelfPermission( 3795 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3796 } else { 3797 try { 3798 mContext.enforceCallingOrSelfPermission( 3799 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3800 } catch (SecurityException se) { 3801 mContext.enforceCallingOrSelfPermission( 3802 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3803 } 3804 } 3805 } 3806 } 3807 3808 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3809 if (callingUid == Process.SHELL_UID) { 3810 if (userHandle >= 0 3811 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3812 throw new SecurityException("Shell does not have permission to access user " 3813 + userHandle); 3814 } else if (userHandle < 0) { 3815 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3816 + Debug.getCallers(3)); 3817 } 3818 } 3819 } 3820 3821 private BasePermission findPermissionTreeLP(String permName) { 3822 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3823 if (permName.startsWith(bp.name) && 3824 permName.length() > bp.name.length() && 3825 permName.charAt(bp.name.length()) == '.') { 3826 return bp; 3827 } 3828 } 3829 return null; 3830 } 3831 3832 private BasePermission checkPermissionTreeLP(String permName) { 3833 if (permName != null) { 3834 BasePermission bp = findPermissionTreeLP(permName); 3835 if (bp != null) { 3836 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3837 return bp; 3838 } 3839 throw new SecurityException("Calling uid " 3840 + Binder.getCallingUid() 3841 + " is not allowed to add to permission tree " 3842 + bp.name + " owned by uid " + bp.uid); 3843 } 3844 } 3845 throw new SecurityException("No permission tree found for " + permName); 3846 } 3847 3848 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3849 if (s1 == null) { 3850 return s2 == null; 3851 } 3852 if (s2 == null) { 3853 return false; 3854 } 3855 if (s1.getClass() != s2.getClass()) { 3856 return false; 3857 } 3858 return s1.equals(s2); 3859 } 3860 3861 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3862 if (pi1.icon != pi2.icon) return false; 3863 if (pi1.logo != pi2.logo) return false; 3864 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3865 if (!compareStrings(pi1.name, pi2.name)) return false; 3866 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3867 // We'll take care of setting this one. 3868 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3869 // These are not currently stored in settings. 3870 //if (!compareStrings(pi1.group, pi2.group)) return false; 3871 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3872 //if (pi1.labelRes != pi2.labelRes) return false; 3873 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3874 return true; 3875 } 3876 3877 int permissionInfoFootprint(PermissionInfo info) { 3878 int size = info.name.length(); 3879 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3880 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3881 return size; 3882 } 3883 3884 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3885 int size = 0; 3886 for (BasePermission perm : mSettings.mPermissions.values()) { 3887 if (perm.uid == tree.uid) { 3888 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3889 } 3890 } 3891 return size; 3892 } 3893 3894 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3895 // We calculate the max size of permissions defined by this uid and throw 3896 // if that plus the size of 'info' would exceed our stated maximum. 3897 if (tree.uid != Process.SYSTEM_UID) { 3898 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3899 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3900 throw new SecurityException("Permission tree size cap exceeded"); 3901 } 3902 } 3903 } 3904 3905 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3906 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3907 throw new SecurityException("Label must be specified in permission"); 3908 } 3909 BasePermission tree = checkPermissionTreeLP(info.name); 3910 BasePermission bp = mSettings.mPermissions.get(info.name); 3911 boolean added = bp == null; 3912 boolean changed = true; 3913 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3914 if (added) { 3915 enforcePermissionCapLocked(info, tree); 3916 bp = new BasePermission(info.name, tree.sourcePackage, 3917 BasePermission.TYPE_DYNAMIC); 3918 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3919 throw new SecurityException( 3920 "Not allowed to modify non-dynamic permission " 3921 + info.name); 3922 } else { 3923 if (bp.protectionLevel == fixedLevel 3924 && bp.perm.owner.equals(tree.perm.owner) 3925 && bp.uid == tree.uid 3926 && comparePermissionInfos(bp.perm.info, info)) { 3927 changed = false; 3928 } 3929 } 3930 bp.protectionLevel = fixedLevel; 3931 info = new PermissionInfo(info); 3932 info.protectionLevel = fixedLevel; 3933 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3934 bp.perm.info.packageName = tree.perm.info.packageName; 3935 bp.uid = tree.uid; 3936 if (added) { 3937 mSettings.mPermissions.put(info.name, bp); 3938 } 3939 if (changed) { 3940 if (!async) { 3941 mSettings.writeLPr(); 3942 } else { 3943 scheduleWriteSettingsLocked(); 3944 } 3945 } 3946 return added; 3947 } 3948 3949 @Override 3950 public boolean addPermission(PermissionInfo info) { 3951 synchronized (mPackages) { 3952 return addPermissionLocked(info, false); 3953 } 3954 } 3955 3956 @Override 3957 public boolean addPermissionAsync(PermissionInfo info) { 3958 synchronized (mPackages) { 3959 return addPermissionLocked(info, true); 3960 } 3961 } 3962 3963 @Override 3964 public void removePermission(String name) { 3965 synchronized (mPackages) { 3966 checkPermissionTreeLP(name); 3967 BasePermission bp = mSettings.mPermissions.get(name); 3968 if (bp != null) { 3969 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3970 throw new SecurityException( 3971 "Not allowed to modify non-dynamic permission " 3972 + name); 3973 } 3974 mSettings.mPermissions.remove(name); 3975 mSettings.writeLPr(); 3976 } 3977 } 3978 } 3979 3980 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3981 BasePermission bp) { 3982 int index = pkg.requestedPermissions.indexOf(bp.name); 3983 if (index == -1) { 3984 throw new SecurityException("Package " + pkg.packageName 3985 + " has not requested permission " + bp.name); 3986 } 3987 if (!bp.isRuntime() && !bp.isDevelopment()) { 3988 throw new SecurityException("Permission " + bp.name 3989 + " is not a changeable permission type"); 3990 } 3991 } 3992 3993 @Override 3994 public void grantRuntimePermission(String packageName, String name, final int userId) { 3995 if (!sUserManager.exists(userId)) { 3996 Log.e(TAG, "No such user:" + userId); 3997 return; 3998 } 3999 4000 mContext.enforceCallingOrSelfPermission( 4001 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4002 "grantRuntimePermission"); 4003 4004 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4005 true /* requireFullPermission */, true /* checkShell */, 4006 "grantRuntimePermission"); 4007 4008 final int uid; 4009 final SettingBase sb; 4010 4011 synchronized (mPackages) { 4012 final PackageParser.Package pkg = mPackages.get(packageName); 4013 if (pkg == null) { 4014 throw new IllegalArgumentException("Unknown package: " + packageName); 4015 } 4016 4017 final BasePermission bp = mSettings.mPermissions.get(name); 4018 if (bp == null) { 4019 throw new IllegalArgumentException("Unknown permission: " + name); 4020 } 4021 4022 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4023 4024 // If a permission review is required for legacy apps we represent 4025 // their permissions as always granted runtime ones since we need 4026 // to keep the review required permission flag per user while an 4027 // install permission's state is shared across all users. 4028 if (Build.PERMISSIONS_REVIEW_REQUIRED 4029 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4030 && bp.isRuntime()) { 4031 return; 4032 } 4033 4034 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4035 sb = (SettingBase) pkg.mExtras; 4036 if (sb == null) { 4037 throw new IllegalArgumentException("Unknown package: " + packageName); 4038 } 4039 4040 final PermissionsState permissionsState = sb.getPermissionsState(); 4041 4042 final int flags = permissionsState.getPermissionFlags(name, userId); 4043 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4044 throw new SecurityException("Cannot grant system fixed permission " 4045 + name + " for package " + packageName); 4046 } 4047 4048 if (bp.isDevelopment()) { 4049 // Development permissions must be handled specially, since they are not 4050 // normal runtime permissions. For now they apply to all users. 4051 if (permissionsState.grantInstallPermission(bp) != 4052 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4053 scheduleWriteSettingsLocked(); 4054 } 4055 return; 4056 } 4057 4058 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4059 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4060 return; 4061 } 4062 4063 final int result = permissionsState.grantRuntimePermission(bp, userId); 4064 switch (result) { 4065 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4066 return; 4067 } 4068 4069 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4070 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4071 mHandler.post(new Runnable() { 4072 @Override 4073 public void run() { 4074 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4075 } 4076 }); 4077 } 4078 break; 4079 } 4080 4081 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4082 4083 // Not critical if that is lost - app has to request again. 4084 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4085 } 4086 4087 // Only need to do this if user is initialized. Otherwise it's a new user 4088 // and there are no processes running as the user yet and there's no need 4089 // to make an expensive call to remount processes for the changed permissions. 4090 if (READ_EXTERNAL_STORAGE.equals(name) 4091 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4092 final long token = Binder.clearCallingIdentity(); 4093 try { 4094 if (sUserManager.isInitialized(userId)) { 4095 MountServiceInternal mountServiceInternal = LocalServices.getService( 4096 MountServiceInternal.class); 4097 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4098 } 4099 } finally { 4100 Binder.restoreCallingIdentity(token); 4101 } 4102 } 4103 } 4104 4105 @Override 4106 public void revokeRuntimePermission(String packageName, String name, int userId) { 4107 if (!sUserManager.exists(userId)) { 4108 Log.e(TAG, "No such user:" + userId); 4109 return; 4110 } 4111 4112 mContext.enforceCallingOrSelfPermission( 4113 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4114 "revokeRuntimePermission"); 4115 4116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4117 true /* requireFullPermission */, true /* checkShell */, 4118 "revokeRuntimePermission"); 4119 4120 final int appId; 4121 4122 synchronized (mPackages) { 4123 final PackageParser.Package pkg = mPackages.get(packageName); 4124 if (pkg == null) { 4125 throw new IllegalArgumentException("Unknown package: " + packageName); 4126 } 4127 4128 final BasePermission bp = mSettings.mPermissions.get(name); 4129 if (bp == null) { 4130 throw new IllegalArgumentException("Unknown permission: " + name); 4131 } 4132 4133 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4134 4135 // If a permission review is required for legacy apps we represent 4136 // their permissions as always granted runtime ones since we need 4137 // to keep the review required permission flag per user while an 4138 // install permission's state is shared across all users. 4139 if (Build.PERMISSIONS_REVIEW_REQUIRED 4140 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4141 && bp.isRuntime()) { 4142 return; 4143 } 4144 4145 SettingBase sb = (SettingBase) pkg.mExtras; 4146 if (sb == null) { 4147 throw new IllegalArgumentException("Unknown package: " + packageName); 4148 } 4149 4150 final PermissionsState permissionsState = sb.getPermissionsState(); 4151 4152 final int flags = permissionsState.getPermissionFlags(name, userId); 4153 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4154 throw new SecurityException("Cannot revoke system fixed permission " 4155 + name + " for package " + packageName); 4156 } 4157 4158 if (bp.isDevelopment()) { 4159 // Development permissions must be handled specially, since they are not 4160 // normal runtime permissions. For now they apply to all users. 4161 if (permissionsState.revokeInstallPermission(bp) != 4162 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4163 scheduleWriteSettingsLocked(); 4164 } 4165 return; 4166 } 4167 4168 if (permissionsState.revokeRuntimePermission(bp, userId) == 4169 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4170 return; 4171 } 4172 4173 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4174 4175 // Critical, after this call app should never have the permission. 4176 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4177 4178 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4179 } 4180 4181 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4182 } 4183 4184 @Override 4185 public void resetRuntimePermissions() { 4186 mContext.enforceCallingOrSelfPermission( 4187 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4188 "revokeRuntimePermission"); 4189 4190 int callingUid = Binder.getCallingUid(); 4191 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4192 mContext.enforceCallingOrSelfPermission( 4193 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4194 "resetRuntimePermissions"); 4195 } 4196 4197 synchronized (mPackages) { 4198 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4199 for (int userId : UserManagerService.getInstance().getUserIds()) { 4200 final int packageCount = mPackages.size(); 4201 for (int i = 0; i < packageCount; i++) { 4202 PackageParser.Package pkg = mPackages.valueAt(i); 4203 if (!(pkg.mExtras instanceof PackageSetting)) { 4204 continue; 4205 } 4206 PackageSetting ps = (PackageSetting) pkg.mExtras; 4207 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4208 } 4209 } 4210 } 4211 } 4212 4213 @Override 4214 public int getPermissionFlags(String name, String packageName, int userId) { 4215 if (!sUserManager.exists(userId)) { 4216 return 0; 4217 } 4218 4219 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4220 4221 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4222 true /* requireFullPermission */, false /* checkShell */, 4223 "getPermissionFlags"); 4224 4225 synchronized (mPackages) { 4226 final PackageParser.Package pkg = mPackages.get(packageName); 4227 if (pkg == null) { 4228 return 0; 4229 } 4230 4231 final BasePermission bp = mSettings.mPermissions.get(name); 4232 if (bp == null) { 4233 return 0; 4234 } 4235 4236 SettingBase sb = (SettingBase) pkg.mExtras; 4237 if (sb == null) { 4238 return 0; 4239 } 4240 4241 PermissionsState permissionsState = sb.getPermissionsState(); 4242 return permissionsState.getPermissionFlags(name, userId); 4243 } 4244 } 4245 4246 @Override 4247 public void updatePermissionFlags(String name, String packageName, int flagMask, 4248 int flagValues, int userId) { 4249 if (!sUserManager.exists(userId)) { 4250 return; 4251 } 4252 4253 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4254 4255 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4256 true /* requireFullPermission */, true /* checkShell */, 4257 "updatePermissionFlags"); 4258 4259 // Only the system can change these flags and nothing else. 4260 if (getCallingUid() != Process.SYSTEM_UID) { 4261 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4262 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4263 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4264 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4265 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4266 } 4267 4268 synchronized (mPackages) { 4269 final PackageParser.Package pkg = mPackages.get(packageName); 4270 if (pkg == null) { 4271 throw new IllegalArgumentException("Unknown package: " + packageName); 4272 } 4273 4274 final BasePermission bp = mSettings.mPermissions.get(name); 4275 if (bp == null) { 4276 throw new IllegalArgumentException("Unknown permission: " + name); 4277 } 4278 4279 SettingBase sb = (SettingBase) pkg.mExtras; 4280 if (sb == null) { 4281 throw new IllegalArgumentException("Unknown package: " + packageName); 4282 } 4283 4284 PermissionsState permissionsState = sb.getPermissionsState(); 4285 4286 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4287 4288 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4289 // Install and runtime permissions are stored in different places, 4290 // so figure out what permission changed and persist the change. 4291 if (permissionsState.getInstallPermissionState(name) != null) { 4292 scheduleWriteSettingsLocked(); 4293 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4294 || hadState) { 4295 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4296 } 4297 } 4298 } 4299 } 4300 4301 /** 4302 * Update the permission flags for all packages and runtime permissions of a user in order 4303 * to allow device or profile owner to remove POLICY_FIXED. 4304 */ 4305 @Override 4306 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4307 if (!sUserManager.exists(userId)) { 4308 return; 4309 } 4310 4311 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4312 4313 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4314 true /* requireFullPermission */, true /* checkShell */, 4315 "updatePermissionFlagsForAllApps"); 4316 4317 // Only the system can change system fixed flags. 4318 if (getCallingUid() != Process.SYSTEM_UID) { 4319 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4320 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4321 } 4322 4323 synchronized (mPackages) { 4324 boolean changed = false; 4325 final int packageCount = mPackages.size(); 4326 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4327 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4328 SettingBase sb = (SettingBase) pkg.mExtras; 4329 if (sb == null) { 4330 continue; 4331 } 4332 PermissionsState permissionsState = sb.getPermissionsState(); 4333 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4334 userId, flagMask, flagValues); 4335 } 4336 if (changed) { 4337 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4338 } 4339 } 4340 } 4341 4342 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4343 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4344 != PackageManager.PERMISSION_GRANTED 4345 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4346 != PackageManager.PERMISSION_GRANTED) { 4347 throw new SecurityException(message + " requires " 4348 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4349 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4350 } 4351 } 4352 4353 @Override 4354 public boolean shouldShowRequestPermissionRationale(String permissionName, 4355 String packageName, int userId) { 4356 if (UserHandle.getCallingUserId() != userId) { 4357 mContext.enforceCallingPermission( 4358 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4359 "canShowRequestPermissionRationale for user " + userId); 4360 } 4361 4362 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4363 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4364 return false; 4365 } 4366 4367 if (checkPermission(permissionName, packageName, userId) 4368 == PackageManager.PERMISSION_GRANTED) { 4369 return false; 4370 } 4371 4372 final int flags; 4373 4374 final long identity = Binder.clearCallingIdentity(); 4375 try { 4376 flags = getPermissionFlags(permissionName, 4377 packageName, userId); 4378 } finally { 4379 Binder.restoreCallingIdentity(identity); 4380 } 4381 4382 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4383 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4384 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4385 4386 if ((flags & fixedFlags) != 0) { 4387 return false; 4388 } 4389 4390 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4391 } 4392 4393 @Override 4394 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4395 mContext.enforceCallingOrSelfPermission( 4396 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4397 "addOnPermissionsChangeListener"); 4398 4399 synchronized (mPackages) { 4400 mOnPermissionChangeListeners.addListenerLocked(listener); 4401 } 4402 } 4403 4404 @Override 4405 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4406 synchronized (mPackages) { 4407 mOnPermissionChangeListeners.removeListenerLocked(listener); 4408 } 4409 } 4410 4411 @Override 4412 public boolean isProtectedBroadcast(String actionName) { 4413 synchronized (mPackages) { 4414 if (mProtectedBroadcasts.contains(actionName)) { 4415 return true; 4416 } else if (actionName != null) { 4417 // TODO: remove these terrible hacks 4418 if (actionName.startsWith("android.net.netmon.lingerExpired") 4419 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4420 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4421 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4422 return true; 4423 } 4424 } 4425 } 4426 return false; 4427 } 4428 4429 @Override 4430 public int checkSignatures(String pkg1, String pkg2) { 4431 synchronized (mPackages) { 4432 final PackageParser.Package p1 = mPackages.get(pkg1); 4433 final PackageParser.Package p2 = mPackages.get(pkg2); 4434 if (p1 == null || p1.mExtras == null 4435 || p2 == null || p2.mExtras == null) { 4436 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4437 } 4438 return compareSignatures(p1.mSignatures, p2.mSignatures); 4439 } 4440 } 4441 4442 @Override 4443 public int checkUidSignatures(int uid1, int uid2) { 4444 // Map to base uids. 4445 uid1 = UserHandle.getAppId(uid1); 4446 uid2 = UserHandle.getAppId(uid2); 4447 // reader 4448 synchronized (mPackages) { 4449 Signature[] s1; 4450 Signature[] s2; 4451 Object obj = mSettings.getUserIdLPr(uid1); 4452 if (obj != null) { 4453 if (obj instanceof SharedUserSetting) { 4454 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4455 } else if (obj instanceof PackageSetting) { 4456 s1 = ((PackageSetting)obj).signatures.mSignatures; 4457 } else { 4458 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4459 } 4460 } else { 4461 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4462 } 4463 obj = mSettings.getUserIdLPr(uid2); 4464 if (obj != null) { 4465 if (obj instanceof SharedUserSetting) { 4466 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4467 } else if (obj instanceof PackageSetting) { 4468 s2 = ((PackageSetting)obj).signatures.mSignatures; 4469 } else { 4470 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4471 } 4472 } else { 4473 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4474 } 4475 return compareSignatures(s1, s2); 4476 } 4477 } 4478 4479 /** 4480 * This method should typically only be used when granting or revoking 4481 * permissions, since the app may immediately restart after this call. 4482 * <p> 4483 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4484 * guard your work against the app being relaunched. 4485 */ 4486 private void killUid(int appId, int userId, String reason) { 4487 final long identity = Binder.clearCallingIdentity(); 4488 try { 4489 IActivityManager am = ActivityManagerNative.getDefault(); 4490 if (am != null) { 4491 try { 4492 am.killUid(appId, userId, reason); 4493 } catch (RemoteException e) { 4494 /* ignore - same process */ 4495 } 4496 } 4497 } finally { 4498 Binder.restoreCallingIdentity(identity); 4499 } 4500 } 4501 4502 /** 4503 * Compares two sets of signatures. Returns: 4504 * <br /> 4505 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4506 * <br /> 4507 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4508 * <br /> 4509 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4510 * <br /> 4511 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4512 * <br /> 4513 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4514 */ 4515 static int compareSignatures(Signature[] s1, Signature[] s2) { 4516 if (s1 == null) { 4517 return s2 == null 4518 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4519 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4520 } 4521 4522 if (s2 == null) { 4523 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4524 } 4525 4526 if (s1.length != s2.length) { 4527 return PackageManager.SIGNATURE_NO_MATCH; 4528 } 4529 4530 // Since both signature sets are of size 1, we can compare without HashSets. 4531 if (s1.length == 1) { 4532 return s1[0].equals(s2[0]) ? 4533 PackageManager.SIGNATURE_MATCH : 4534 PackageManager.SIGNATURE_NO_MATCH; 4535 } 4536 4537 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4538 for (Signature sig : s1) { 4539 set1.add(sig); 4540 } 4541 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4542 for (Signature sig : s2) { 4543 set2.add(sig); 4544 } 4545 // Make sure s2 contains all signatures in s1. 4546 if (set1.equals(set2)) { 4547 return PackageManager.SIGNATURE_MATCH; 4548 } 4549 return PackageManager.SIGNATURE_NO_MATCH; 4550 } 4551 4552 /** 4553 * If the database version for this type of package (internal storage or 4554 * external storage) is less than the version where package signatures 4555 * were updated, return true. 4556 */ 4557 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4558 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4559 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4560 } 4561 4562 /** 4563 * Used for backward compatibility to make sure any packages with 4564 * certificate chains get upgraded to the new style. {@code existingSigs} 4565 * will be in the old format (since they were stored on disk from before the 4566 * system upgrade) and {@code scannedSigs} will be in the newer format. 4567 */ 4568 private int compareSignaturesCompat(PackageSignatures existingSigs, 4569 PackageParser.Package scannedPkg) { 4570 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4571 return PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4575 for (Signature sig : existingSigs.mSignatures) { 4576 existingSet.add(sig); 4577 } 4578 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4579 for (Signature sig : scannedPkg.mSignatures) { 4580 try { 4581 Signature[] chainSignatures = sig.getChainSignatures(); 4582 for (Signature chainSig : chainSignatures) { 4583 scannedCompatSet.add(chainSig); 4584 } 4585 } catch (CertificateEncodingException e) { 4586 scannedCompatSet.add(sig); 4587 } 4588 } 4589 /* 4590 * Make sure the expanded scanned set contains all signatures in the 4591 * existing one. 4592 */ 4593 if (scannedCompatSet.equals(existingSet)) { 4594 // Migrate the old signatures to the new scheme. 4595 existingSigs.assignSignatures(scannedPkg.mSignatures); 4596 // The new KeySets will be re-added later in the scanning process. 4597 synchronized (mPackages) { 4598 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4599 } 4600 return PackageManager.SIGNATURE_MATCH; 4601 } 4602 return PackageManager.SIGNATURE_NO_MATCH; 4603 } 4604 4605 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4606 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4607 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4608 } 4609 4610 private int compareSignaturesRecover(PackageSignatures existingSigs, 4611 PackageParser.Package scannedPkg) { 4612 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4613 return PackageManager.SIGNATURE_NO_MATCH; 4614 } 4615 4616 String msg = null; 4617 try { 4618 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4619 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4620 + scannedPkg.packageName); 4621 return PackageManager.SIGNATURE_MATCH; 4622 } 4623 } catch (CertificateException e) { 4624 msg = e.getMessage(); 4625 } 4626 4627 logCriticalInfo(Log.INFO, 4628 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4629 return PackageManager.SIGNATURE_NO_MATCH; 4630 } 4631 4632 @Override 4633 public List<String> getAllPackages() { 4634 synchronized (mPackages) { 4635 return new ArrayList<String>(mPackages.keySet()); 4636 } 4637 } 4638 4639 @Override 4640 public String[] getPackagesForUid(int uid) { 4641 uid = UserHandle.getAppId(uid); 4642 // reader 4643 synchronized (mPackages) { 4644 Object obj = mSettings.getUserIdLPr(uid); 4645 if (obj instanceof SharedUserSetting) { 4646 final SharedUserSetting sus = (SharedUserSetting) obj; 4647 final int N = sus.packages.size(); 4648 final String[] res = new String[N]; 4649 for (int i = 0; i < N; i++) { 4650 res[i] = sus.packages.valueAt(i).name; 4651 } 4652 return res; 4653 } else if (obj instanceof PackageSetting) { 4654 final PackageSetting ps = (PackageSetting) obj; 4655 return new String[] { ps.name }; 4656 } 4657 } 4658 return null; 4659 } 4660 4661 @Override 4662 public String getNameForUid(int uid) { 4663 // reader 4664 synchronized (mPackages) { 4665 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4666 if (obj instanceof SharedUserSetting) { 4667 final SharedUserSetting sus = (SharedUserSetting) obj; 4668 return sus.name + ":" + sus.userId; 4669 } else if (obj instanceof PackageSetting) { 4670 final PackageSetting ps = (PackageSetting) obj; 4671 return ps.name; 4672 } 4673 } 4674 return null; 4675 } 4676 4677 @Override 4678 public int getUidForSharedUser(String sharedUserName) { 4679 if(sharedUserName == null) { 4680 return -1; 4681 } 4682 // reader 4683 synchronized (mPackages) { 4684 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4685 if (suid == null) { 4686 return -1; 4687 } 4688 return suid.userId; 4689 } 4690 } 4691 4692 @Override 4693 public int getFlagsForUid(int uid) { 4694 synchronized (mPackages) { 4695 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4696 if (obj instanceof SharedUserSetting) { 4697 final SharedUserSetting sus = (SharedUserSetting) obj; 4698 return sus.pkgFlags; 4699 } else if (obj instanceof PackageSetting) { 4700 final PackageSetting ps = (PackageSetting) obj; 4701 return ps.pkgFlags; 4702 } 4703 } 4704 return 0; 4705 } 4706 4707 @Override 4708 public int getPrivateFlagsForUid(int uid) { 4709 synchronized (mPackages) { 4710 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4711 if (obj instanceof SharedUserSetting) { 4712 final SharedUserSetting sus = (SharedUserSetting) obj; 4713 return sus.pkgPrivateFlags; 4714 } else if (obj instanceof PackageSetting) { 4715 final PackageSetting ps = (PackageSetting) obj; 4716 return ps.pkgPrivateFlags; 4717 } 4718 } 4719 return 0; 4720 } 4721 4722 @Override 4723 public boolean isUidPrivileged(int uid) { 4724 uid = UserHandle.getAppId(uid); 4725 // reader 4726 synchronized (mPackages) { 4727 Object obj = mSettings.getUserIdLPr(uid); 4728 if (obj instanceof SharedUserSetting) { 4729 final SharedUserSetting sus = (SharedUserSetting) obj; 4730 final Iterator<PackageSetting> it = sus.packages.iterator(); 4731 while (it.hasNext()) { 4732 if (it.next().isPrivileged()) { 4733 return true; 4734 } 4735 } 4736 } else if (obj instanceof PackageSetting) { 4737 final PackageSetting ps = (PackageSetting) obj; 4738 return ps.isPrivileged(); 4739 } 4740 } 4741 return false; 4742 } 4743 4744 @Override 4745 public String[] getAppOpPermissionPackages(String permissionName) { 4746 synchronized (mPackages) { 4747 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4748 if (pkgs == null) { 4749 return null; 4750 } 4751 return pkgs.toArray(new String[pkgs.size()]); 4752 } 4753 } 4754 4755 @Override 4756 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4757 int flags, int userId) { 4758 try { 4759 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4760 4761 if (!sUserManager.exists(userId)) return null; 4762 flags = updateFlagsForResolve(flags, userId, intent); 4763 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4764 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4765 4766 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4767 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4768 flags, userId); 4769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4770 4771 final ResolveInfo bestChoice = 4772 chooseBestActivity(intent, resolvedType, flags, query, userId); 4773 return bestChoice; 4774 } finally { 4775 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4776 } 4777 } 4778 4779 @Override 4780 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4781 IntentFilter filter, int match, ComponentName activity) { 4782 final int userId = UserHandle.getCallingUserId(); 4783 if (DEBUG_PREFERRED) { 4784 Log.v(TAG, "setLastChosenActivity intent=" + intent 4785 + " resolvedType=" + resolvedType 4786 + " flags=" + flags 4787 + " filter=" + filter 4788 + " match=" + match 4789 + " activity=" + activity); 4790 filter.dump(new PrintStreamPrinter(System.out), " "); 4791 } 4792 intent.setComponent(null); 4793 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4794 userId); 4795 // Find any earlier preferred or last chosen entries and nuke them 4796 findPreferredActivity(intent, resolvedType, 4797 flags, query, 0, false, true, false, userId); 4798 // Add the new activity as the last chosen for this filter 4799 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4800 "Setting last chosen"); 4801 } 4802 4803 @Override 4804 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4805 final int userId = UserHandle.getCallingUserId(); 4806 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4807 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4808 userId); 4809 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4810 false, false, false, userId); 4811 } 4812 4813 private boolean isEphemeralDisabled() { 4814 // ephemeral apps have been disabled across the board 4815 if (DISABLE_EPHEMERAL_APPS) { 4816 return true; 4817 } 4818 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4819 if (!mSystemReady) { 4820 return true; 4821 } 4822 // we can't get a content resolver until the system is ready; these checks must happen last 4823 final ContentResolver resolver = mContext.getContentResolver(); 4824 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4825 return true; 4826 } 4827 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4828 } 4829 4830 private boolean isEphemeralAllowed( 4831 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4832 boolean skipPackageCheck) { 4833 // Short circuit and return early if possible. 4834 if (isEphemeralDisabled()) { 4835 return false; 4836 } 4837 final int callingUser = UserHandle.getCallingUserId(); 4838 if (callingUser != UserHandle.USER_SYSTEM) { 4839 return false; 4840 } 4841 if (mEphemeralResolverConnection == null) { 4842 return false; 4843 } 4844 if (intent.getComponent() != null) { 4845 return false; 4846 } 4847 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4848 return false; 4849 } 4850 if (!skipPackageCheck && intent.getPackage() != null) { 4851 return false; 4852 } 4853 final boolean isWebUri = hasWebURI(intent); 4854 if (!isWebUri || intent.getData().getHost() == null) { 4855 return false; 4856 } 4857 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4858 synchronized (mPackages) { 4859 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4860 for (int n = 0; n < count; n++) { 4861 ResolveInfo info = resolvedActivities.get(n); 4862 String packageName = info.activityInfo.packageName; 4863 PackageSetting ps = mSettings.mPackages.get(packageName); 4864 if (ps != null) { 4865 // Try to get the status from User settings first 4866 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4867 int status = (int) (packedStatus >> 32); 4868 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4869 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4870 if (DEBUG_EPHEMERAL) { 4871 Slog.v(TAG, "DENY ephemeral apps;" 4872 + " pkg: " + packageName + ", status: " + status); 4873 } 4874 return false; 4875 } 4876 } 4877 } 4878 } 4879 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4880 return true; 4881 } 4882 4883 private static EphemeralResolveInfo getEphemeralResolveInfo( 4884 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4885 String resolvedType, int userId, String packageName) { 4886 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4887 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4888 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4889 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4890 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4891 ephemeralPrefixCount); 4892 final int[] shaPrefix = digest.getDigestPrefix(); 4893 final byte[][] digestBytes = digest.getDigestBytes(); 4894 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4895 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4896 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4897 // No hash prefix match; there are no ephemeral apps for this domain. 4898 return null; 4899 } 4900 4901 // Go in reverse order so we match the narrowest scope first. 4902 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4903 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4904 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4905 continue; 4906 } 4907 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4908 // No filters; this should never happen. 4909 if (filters.isEmpty()) { 4910 continue; 4911 } 4912 if (packageName != null 4913 && !packageName.equals(ephemeralApplication.getPackageName())) { 4914 continue; 4915 } 4916 // We have a domain match; resolve the filters to see if anything matches. 4917 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4918 for (int j = filters.size() - 1; j >= 0; --j) { 4919 final EphemeralResolveIntentInfo intentInfo = 4920 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4921 ephemeralResolver.addFilter(intentInfo); 4922 } 4923 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4924 intent, resolvedType, false /*defaultOnly*/, userId); 4925 if (!matchedResolveInfoList.isEmpty()) { 4926 return matchedResolveInfoList.get(0); 4927 } 4928 } 4929 } 4930 // Hash or filter mis-match; no ephemeral apps for this domain. 4931 return null; 4932 } 4933 4934 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4935 int flags, List<ResolveInfo> query, int userId) { 4936 if (query != null) { 4937 final int N = query.size(); 4938 if (N == 1) { 4939 return query.get(0); 4940 } else if (N > 1) { 4941 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4942 // If there is more than one activity with the same priority, 4943 // then let the user decide between them. 4944 ResolveInfo r0 = query.get(0); 4945 ResolveInfo r1 = query.get(1); 4946 if (DEBUG_INTENT_MATCHING || debug) { 4947 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4948 + r1.activityInfo.name + "=" + r1.priority); 4949 } 4950 // If the first activity has a higher priority, or a different 4951 // default, then it is always desirable to pick it. 4952 if (r0.priority != r1.priority 4953 || r0.preferredOrder != r1.preferredOrder 4954 || r0.isDefault != r1.isDefault) { 4955 return query.get(0); 4956 } 4957 // If we have saved a preference for a preferred activity for 4958 // this Intent, use that. 4959 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4960 flags, query, r0.priority, true, false, debug, userId); 4961 if (ri != null) { 4962 return ri; 4963 } 4964 ri = new ResolveInfo(mResolveInfo); 4965 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4966 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4967 // If all of the options come from the same package, show the application's 4968 // label and icon instead of the generic resolver's. 4969 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4970 // and then throw away the ResolveInfo itself, meaning that the caller loses 4971 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4972 // a fallback for this case; we only set the target package's resources on 4973 // the ResolveInfo, not the ActivityInfo. 4974 final String intentPackage = intent.getPackage(); 4975 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4976 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4977 ri.resolvePackageName = intentPackage; 4978 if (userNeedsBadging(userId)) { 4979 ri.noResourceId = true; 4980 } else { 4981 ri.icon = appi.icon; 4982 } 4983 ri.iconResourceId = appi.icon; 4984 ri.labelRes = appi.labelRes; 4985 } 4986 ri.activityInfo.applicationInfo = new ApplicationInfo( 4987 ri.activityInfo.applicationInfo); 4988 if (userId != 0) { 4989 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4990 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4991 } 4992 // Make sure that the resolver is displayable in car mode 4993 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4994 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4995 return ri; 4996 } 4997 } 4998 return null; 4999 } 5000 5001 /** 5002 * Return true if the given list is not empty and all of its contents have 5003 * an activityInfo with the given package name. 5004 */ 5005 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5006 if (ArrayUtils.isEmpty(list)) { 5007 return false; 5008 } 5009 for (int i = 0, N = list.size(); i < N; i++) { 5010 final ResolveInfo ri = list.get(i); 5011 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5012 if (ai == null || !packageName.equals(ai.packageName)) { 5013 return false; 5014 } 5015 } 5016 return true; 5017 } 5018 5019 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5020 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5021 final int N = query.size(); 5022 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5023 .get(userId); 5024 // Get the list of persistent preferred activities that handle the intent 5025 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5026 List<PersistentPreferredActivity> pprefs = ppir != null 5027 ? ppir.queryIntent(intent, resolvedType, 5028 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5029 : null; 5030 if (pprefs != null && pprefs.size() > 0) { 5031 final int M = pprefs.size(); 5032 for (int i=0; i<M; i++) { 5033 final PersistentPreferredActivity ppa = pprefs.get(i); 5034 if (DEBUG_PREFERRED || debug) { 5035 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5036 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5037 + "\n component=" + ppa.mComponent); 5038 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5039 } 5040 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5041 flags | MATCH_DISABLED_COMPONENTS, userId); 5042 if (DEBUG_PREFERRED || debug) { 5043 Slog.v(TAG, "Found persistent preferred activity:"); 5044 if (ai != null) { 5045 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5046 } else { 5047 Slog.v(TAG, " null"); 5048 } 5049 } 5050 if (ai == null) { 5051 // This previously registered persistent preferred activity 5052 // component is no longer known. Ignore it and do NOT remove it. 5053 continue; 5054 } 5055 for (int j=0; j<N; j++) { 5056 final ResolveInfo ri = query.get(j); 5057 if (!ri.activityInfo.applicationInfo.packageName 5058 .equals(ai.applicationInfo.packageName)) { 5059 continue; 5060 } 5061 if (!ri.activityInfo.name.equals(ai.name)) { 5062 continue; 5063 } 5064 // Found a persistent preference that can handle the intent. 5065 if (DEBUG_PREFERRED || debug) { 5066 Slog.v(TAG, "Returning persistent preferred activity: " + 5067 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5068 } 5069 return ri; 5070 } 5071 } 5072 } 5073 return null; 5074 } 5075 5076 // TODO: handle preferred activities missing while user has amnesia 5077 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5078 List<ResolveInfo> query, int priority, boolean always, 5079 boolean removeMatches, boolean debug, int userId) { 5080 if (!sUserManager.exists(userId)) return null; 5081 flags = updateFlagsForResolve(flags, userId, intent); 5082 // writer 5083 synchronized (mPackages) { 5084 if (intent.getSelector() != null) { 5085 intent = intent.getSelector(); 5086 } 5087 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5088 5089 // Try to find a matching persistent preferred activity. 5090 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5091 debug, userId); 5092 5093 // If a persistent preferred activity matched, use it. 5094 if (pri != null) { 5095 return pri; 5096 } 5097 5098 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5099 // Get the list of preferred activities that handle the intent 5100 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5101 List<PreferredActivity> prefs = pir != null 5102 ? pir.queryIntent(intent, resolvedType, 5103 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5104 : null; 5105 if (prefs != null && prefs.size() > 0) { 5106 boolean changed = false; 5107 try { 5108 // First figure out how good the original match set is. 5109 // We will only allow preferred activities that came 5110 // from the same match quality. 5111 int match = 0; 5112 5113 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5114 5115 final int N = query.size(); 5116 for (int j=0; j<N; j++) { 5117 final ResolveInfo ri = query.get(j); 5118 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5119 + ": 0x" + Integer.toHexString(match)); 5120 if (ri.match > match) { 5121 match = ri.match; 5122 } 5123 } 5124 5125 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5126 + Integer.toHexString(match)); 5127 5128 match &= IntentFilter.MATCH_CATEGORY_MASK; 5129 final int M = prefs.size(); 5130 for (int i=0; i<M; i++) { 5131 final PreferredActivity pa = prefs.get(i); 5132 if (DEBUG_PREFERRED || debug) { 5133 Slog.v(TAG, "Checking PreferredActivity ds=" 5134 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5135 + "\n component=" + pa.mPref.mComponent); 5136 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5137 } 5138 if (pa.mPref.mMatch != match) { 5139 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5140 + Integer.toHexString(pa.mPref.mMatch)); 5141 continue; 5142 } 5143 // If it's not an "always" type preferred activity and that's what we're 5144 // looking for, skip it. 5145 if (always && !pa.mPref.mAlways) { 5146 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5147 continue; 5148 } 5149 final ActivityInfo ai = getActivityInfo( 5150 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5151 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5152 userId); 5153 if (DEBUG_PREFERRED || debug) { 5154 Slog.v(TAG, "Found preferred activity:"); 5155 if (ai != null) { 5156 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5157 } else { 5158 Slog.v(TAG, " null"); 5159 } 5160 } 5161 if (ai == null) { 5162 // This previously registered preferred activity 5163 // component is no longer known. Most likely an update 5164 // to the app was installed and in the new version this 5165 // component no longer exists. Clean it up by removing 5166 // it from the preferred activities list, and skip it. 5167 Slog.w(TAG, "Removing dangling preferred activity: " 5168 + pa.mPref.mComponent); 5169 pir.removeFilter(pa); 5170 changed = true; 5171 continue; 5172 } 5173 for (int j=0; j<N; j++) { 5174 final ResolveInfo ri = query.get(j); 5175 if (!ri.activityInfo.applicationInfo.packageName 5176 .equals(ai.applicationInfo.packageName)) { 5177 continue; 5178 } 5179 if (!ri.activityInfo.name.equals(ai.name)) { 5180 continue; 5181 } 5182 5183 if (removeMatches) { 5184 pir.removeFilter(pa); 5185 changed = true; 5186 if (DEBUG_PREFERRED) { 5187 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5188 } 5189 break; 5190 } 5191 5192 // Okay we found a previously set preferred or last chosen app. 5193 // If the result set is different from when this 5194 // was created, we need to clear it and re-ask the 5195 // user their preference, if we're looking for an "always" type entry. 5196 if (always && !pa.mPref.sameSet(query)) { 5197 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5198 + intent + " type " + resolvedType); 5199 if (DEBUG_PREFERRED) { 5200 Slog.v(TAG, "Removing preferred activity since set changed " 5201 + pa.mPref.mComponent); 5202 } 5203 pir.removeFilter(pa); 5204 // Re-add the filter as a "last chosen" entry (!always) 5205 PreferredActivity lastChosen = new PreferredActivity( 5206 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5207 pir.addFilter(lastChosen); 5208 changed = true; 5209 return null; 5210 } 5211 5212 // Yay! Either the set matched or we're looking for the last chosen 5213 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5214 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5215 return ri; 5216 } 5217 } 5218 } finally { 5219 if (changed) { 5220 if (DEBUG_PREFERRED) { 5221 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5222 } 5223 scheduleWritePackageRestrictionsLocked(userId); 5224 } 5225 } 5226 } 5227 } 5228 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5229 return null; 5230 } 5231 5232 /* 5233 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5234 */ 5235 @Override 5236 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5237 int targetUserId) { 5238 mContext.enforceCallingOrSelfPermission( 5239 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5240 List<CrossProfileIntentFilter> matches = 5241 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5242 if (matches != null) { 5243 int size = matches.size(); 5244 for (int i = 0; i < size; i++) { 5245 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5246 } 5247 } 5248 if (hasWebURI(intent)) { 5249 // cross-profile app linking works only towards the parent. 5250 final UserInfo parent = getProfileParent(sourceUserId); 5251 synchronized(mPackages) { 5252 int flags = updateFlagsForResolve(0, parent.id, intent); 5253 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5254 intent, resolvedType, flags, sourceUserId, parent.id); 5255 return xpDomainInfo != null; 5256 } 5257 } 5258 return false; 5259 } 5260 5261 private UserInfo getProfileParent(int userId) { 5262 final long identity = Binder.clearCallingIdentity(); 5263 try { 5264 return sUserManager.getProfileParent(userId); 5265 } finally { 5266 Binder.restoreCallingIdentity(identity); 5267 } 5268 } 5269 5270 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5271 String resolvedType, int userId) { 5272 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5273 if (resolver != null) { 5274 return resolver.queryIntent(intent, resolvedType, false, userId); 5275 } 5276 return null; 5277 } 5278 5279 @Override 5280 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5281 String resolvedType, int flags, int userId) { 5282 try { 5283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5284 5285 return new ParceledListSlice<>( 5286 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5287 } finally { 5288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5289 } 5290 } 5291 5292 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5293 String resolvedType, int flags, int userId) { 5294 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5295 flags = updateFlagsForResolve(flags, userId, intent); 5296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5297 false /* requireFullPermission */, false /* checkShell */, 5298 "query intent activities"); 5299 ComponentName comp = intent.getComponent(); 5300 if (comp == null) { 5301 if (intent.getSelector() != null) { 5302 intent = intent.getSelector(); 5303 comp = intent.getComponent(); 5304 } 5305 } 5306 5307 if (comp != null) { 5308 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5309 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5310 if (ai != null) { 5311 final ResolveInfo ri = new ResolveInfo(); 5312 ri.activityInfo = ai; 5313 list.add(ri); 5314 } 5315 return list; 5316 } 5317 5318 // reader 5319 boolean sortResult = false; 5320 boolean addEphemeral = false; 5321 boolean matchEphemeralPackage = false; 5322 List<ResolveInfo> result; 5323 final String pkgName = intent.getPackage(); 5324 synchronized (mPackages) { 5325 if (pkgName == null) { 5326 List<CrossProfileIntentFilter> matchingFilters = 5327 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5328 // Check for results that need to skip the current profile. 5329 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5330 resolvedType, flags, userId); 5331 if (xpResolveInfo != null) { 5332 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5333 xpResult.add(xpResolveInfo); 5334 return filterIfNotSystemUser(xpResult, userId); 5335 } 5336 5337 // Check for results in the current profile. 5338 result = filterIfNotSystemUser(mActivities.queryIntent( 5339 intent, resolvedType, flags, userId), userId); 5340 addEphemeral = 5341 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5342 5343 // Check for cross profile results. 5344 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5345 xpResolveInfo = queryCrossProfileIntents( 5346 matchingFilters, intent, resolvedType, flags, userId, 5347 hasNonNegativePriorityResult); 5348 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5349 boolean isVisibleToUser = filterIfNotSystemUser( 5350 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5351 if (isVisibleToUser) { 5352 result.add(xpResolveInfo); 5353 sortResult = true; 5354 } 5355 } 5356 if (hasWebURI(intent)) { 5357 CrossProfileDomainInfo xpDomainInfo = null; 5358 final UserInfo parent = getProfileParent(userId); 5359 if (parent != null) { 5360 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5361 flags, userId, parent.id); 5362 } 5363 if (xpDomainInfo != null) { 5364 if (xpResolveInfo != null) { 5365 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5366 // in the result. 5367 result.remove(xpResolveInfo); 5368 } 5369 if (result.size() == 0 && !addEphemeral) { 5370 result.add(xpDomainInfo.resolveInfo); 5371 return result; 5372 } 5373 } 5374 if (result.size() > 1 || addEphemeral) { 5375 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5376 intent, flags, result, xpDomainInfo, userId); 5377 sortResult = true; 5378 } 5379 } 5380 } else { 5381 final PackageParser.Package pkg = mPackages.get(pkgName); 5382 if (pkg != null) { 5383 result = filterIfNotSystemUser( 5384 mActivities.queryIntentForPackage( 5385 intent, resolvedType, flags, pkg.activities, userId), 5386 userId); 5387 } else { 5388 // the caller wants to resolve for a particular package; however, there 5389 // were no installed results, so, try to find an ephemeral result 5390 addEphemeral = isEphemeralAllowed( 5391 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5392 matchEphemeralPackage = true; 5393 result = new ArrayList<ResolveInfo>(); 5394 } 5395 } 5396 } 5397 if (addEphemeral) { 5398 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5399 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5400 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5401 matchEphemeralPackage ? pkgName : null); 5402 if (ai != null) { 5403 if (DEBUG_EPHEMERAL) { 5404 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5405 } 5406 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5407 ephemeralInstaller.ephemeralResolveInfo = ai; 5408 // make sure this resolver is the default 5409 ephemeralInstaller.isDefault = true; 5410 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5411 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5412 // add a non-generic filter 5413 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5414 ephemeralInstaller.filter.addDataPath( 5415 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5416 result.add(ephemeralInstaller); 5417 } 5418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5419 } 5420 if (sortResult) { 5421 Collections.sort(result, mResolvePrioritySorter); 5422 } 5423 return result; 5424 } 5425 5426 private static class CrossProfileDomainInfo { 5427 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5428 ResolveInfo resolveInfo; 5429 /* Best domain verification status of the activities found in the other profile */ 5430 int bestDomainVerificationStatus; 5431 } 5432 5433 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5434 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5435 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5436 sourceUserId)) { 5437 return null; 5438 } 5439 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5440 resolvedType, flags, parentUserId); 5441 5442 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5443 return null; 5444 } 5445 CrossProfileDomainInfo result = null; 5446 int size = resultTargetUser.size(); 5447 for (int i = 0; i < size; i++) { 5448 ResolveInfo riTargetUser = resultTargetUser.get(i); 5449 // Intent filter verification is only for filters that specify a host. So don't return 5450 // those that handle all web uris. 5451 if (riTargetUser.handleAllWebDataURI) { 5452 continue; 5453 } 5454 String packageName = riTargetUser.activityInfo.packageName; 5455 PackageSetting ps = mSettings.mPackages.get(packageName); 5456 if (ps == null) { 5457 continue; 5458 } 5459 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5460 int status = (int)(verificationState >> 32); 5461 if (result == null) { 5462 result = new CrossProfileDomainInfo(); 5463 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5464 sourceUserId, parentUserId); 5465 result.bestDomainVerificationStatus = status; 5466 } else { 5467 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5468 result.bestDomainVerificationStatus); 5469 } 5470 } 5471 // Don't consider matches with status NEVER across profiles. 5472 if (result != null && result.bestDomainVerificationStatus 5473 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5474 return null; 5475 } 5476 return result; 5477 } 5478 5479 /** 5480 * Verification statuses are ordered from the worse to the best, except for 5481 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5482 */ 5483 private int bestDomainVerificationStatus(int status1, int status2) { 5484 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5485 return status2; 5486 } 5487 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5488 return status1; 5489 } 5490 return (int) MathUtils.max(status1, status2); 5491 } 5492 5493 private boolean isUserEnabled(int userId) { 5494 long callingId = Binder.clearCallingIdentity(); 5495 try { 5496 UserInfo userInfo = sUserManager.getUserInfo(userId); 5497 return userInfo != null && userInfo.isEnabled(); 5498 } finally { 5499 Binder.restoreCallingIdentity(callingId); 5500 } 5501 } 5502 5503 /** 5504 * Filter out activities with systemUserOnly flag set, when current user is not System. 5505 * 5506 * @return filtered list 5507 */ 5508 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5509 if (userId == UserHandle.USER_SYSTEM) { 5510 return resolveInfos; 5511 } 5512 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5513 ResolveInfo info = resolveInfos.get(i); 5514 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5515 resolveInfos.remove(i); 5516 } 5517 } 5518 return resolveInfos; 5519 } 5520 5521 /** 5522 * @param resolveInfos list of resolve infos in descending priority order 5523 * @return if the list contains a resolve info with non-negative priority 5524 */ 5525 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5526 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5527 } 5528 5529 private static boolean hasWebURI(Intent intent) { 5530 if (intent.getData() == null) { 5531 return false; 5532 } 5533 final String scheme = intent.getScheme(); 5534 if (TextUtils.isEmpty(scheme)) { 5535 return false; 5536 } 5537 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5538 } 5539 5540 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5541 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5542 int userId) { 5543 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5544 5545 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5546 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5547 candidates.size()); 5548 } 5549 5550 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5551 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5552 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5553 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5554 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5555 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5556 5557 synchronized (mPackages) { 5558 final int count = candidates.size(); 5559 // First, try to use linked apps. Partition the candidates into four lists: 5560 // one for the final results, one for the "do not use ever", one for "undefined status" 5561 // and finally one for "browser app type". 5562 for (int n=0; n<count; n++) { 5563 ResolveInfo info = candidates.get(n); 5564 String packageName = info.activityInfo.packageName; 5565 PackageSetting ps = mSettings.mPackages.get(packageName); 5566 if (ps != null) { 5567 // Add to the special match all list (Browser use case) 5568 if (info.handleAllWebDataURI) { 5569 matchAllList.add(info); 5570 continue; 5571 } 5572 // Try to get the status from User settings first 5573 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5574 int status = (int)(packedStatus >> 32); 5575 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5576 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5577 if (DEBUG_DOMAIN_VERIFICATION) { 5578 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5579 + " : linkgen=" + linkGeneration); 5580 } 5581 // Use link-enabled generation as preferredOrder, i.e. 5582 // prefer newly-enabled over earlier-enabled. 5583 info.preferredOrder = linkGeneration; 5584 alwaysList.add(info); 5585 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5586 if (DEBUG_DOMAIN_VERIFICATION) { 5587 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5588 } 5589 neverList.add(info); 5590 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5591 if (DEBUG_DOMAIN_VERIFICATION) { 5592 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5593 } 5594 alwaysAskList.add(info); 5595 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5596 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5597 if (DEBUG_DOMAIN_VERIFICATION) { 5598 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5599 } 5600 undefinedList.add(info); 5601 } 5602 } 5603 } 5604 5605 // We'll want to include browser possibilities in a few cases 5606 boolean includeBrowser = false; 5607 5608 // First try to add the "always" resolution(s) for the current user, if any 5609 if (alwaysList.size() > 0) { 5610 result.addAll(alwaysList); 5611 } else { 5612 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5613 result.addAll(undefinedList); 5614 // Maybe add one for the other profile. 5615 if (xpDomainInfo != null && ( 5616 xpDomainInfo.bestDomainVerificationStatus 5617 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5618 result.add(xpDomainInfo.resolveInfo); 5619 } 5620 includeBrowser = true; 5621 } 5622 5623 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5624 // If there were 'always' entries their preferred order has been set, so we also 5625 // back that off to make the alternatives equivalent 5626 if (alwaysAskList.size() > 0) { 5627 for (ResolveInfo i : result) { 5628 i.preferredOrder = 0; 5629 } 5630 result.addAll(alwaysAskList); 5631 includeBrowser = true; 5632 } 5633 5634 if (includeBrowser) { 5635 // Also add browsers (all of them or only the default one) 5636 if (DEBUG_DOMAIN_VERIFICATION) { 5637 Slog.v(TAG, " ...including browsers in candidate set"); 5638 } 5639 if ((matchFlags & MATCH_ALL) != 0) { 5640 result.addAll(matchAllList); 5641 } else { 5642 // Browser/generic handling case. If there's a default browser, go straight 5643 // to that (but only if there is no other higher-priority match). 5644 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5645 int maxMatchPrio = 0; 5646 ResolveInfo defaultBrowserMatch = null; 5647 final int numCandidates = matchAllList.size(); 5648 for (int n = 0; n < numCandidates; n++) { 5649 ResolveInfo info = matchAllList.get(n); 5650 // track the highest overall match priority... 5651 if (info.priority > maxMatchPrio) { 5652 maxMatchPrio = info.priority; 5653 } 5654 // ...and the highest-priority default browser match 5655 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5656 if (defaultBrowserMatch == null 5657 || (defaultBrowserMatch.priority < info.priority)) { 5658 if (debug) { 5659 Slog.v(TAG, "Considering default browser match " + info); 5660 } 5661 defaultBrowserMatch = info; 5662 } 5663 } 5664 } 5665 if (defaultBrowserMatch != null 5666 && defaultBrowserMatch.priority >= maxMatchPrio 5667 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5668 { 5669 if (debug) { 5670 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5671 } 5672 result.add(defaultBrowserMatch); 5673 } else { 5674 result.addAll(matchAllList); 5675 } 5676 } 5677 5678 // If there is nothing selected, add all candidates and remove the ones that the user 5679 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5680 if (result.size() == 0) { 5681 result.addAll(candidates); 5682 result.removeAll(neverList); 5683 } 5684 } 5685 } 5686 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5687 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5688 result.size()); 5689 for (ResolveInfo info : result) { 5690 Slog.v(TAG, " + " + info.activityInfo); 5691 } 5692 } 5693 return result; 5694 } 5695 5696 // Returns a packed value as a long: 5697 // 5698 // high 'int'-sized word: link status: undefined/ask/never/always. 5699 // low 'int'-sized word: relative priority among 'always' results. 5700 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5701 long result = ps.getDomainVerificationStatusForUser(userId); 5702 // if none available, get the master status 5703 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5704 if (ps.getIntentFilterVerificationInfo() != null) { 5705 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5706 } 5707 } 5708 return result; 5709 } 5710 5711 private ResolveInfo querySkipCurrentProfileIntents( 5712 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5713 int flags, int sourceUserId) { 5714 if (matchingFilters != null) { 5715 int size = matchingFilters.size(); 5716 for (int i = 0; i < size; i ++) { 5717 CrossProfileIntentFilter filter = matchingFilters.get(i); 5718 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5719 // Checking if there are activities in the target user that can handle the 5720 // intent. 5721 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5722 resolvedType, flags, sourceUserId); 5723 if (resolveInfo != null) { 5724 return resolveInfo; 5725 } 5726 } 5727 } 5728 } 5729 return null; 5730 } 5731 5732 // Return matching ResolveInfo in target user if any. 5733 private ResolveInfo queryCrossProfileIntents( 5734 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5735 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5736 if (matchingFilters != null) { 5737 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5738 // match the same intent. For performance reasons, it is better not to 5739 // run queryIntent twice for the same userId 5740 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5741 int size = matchingFilters.size(); 5742 for (int i = 0; i < size; i++) { 5743 CrossProfileIntentFilter filter = matchingFilters.get(i); 5744 int targetUserId = filter.getTargetUserId(); 5745 boolean skipCurrentProfile = 5746 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5747 boolean skipCurrentProfileIfNoMatchFound = 5748 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5749 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5750 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5751 // Checking if there are activities in the target user that can handle the 5752 // intent. 5753 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5754 resolvedType, flags, sourceUserId); 5755 if (resolveInfo != null) return resolveInfo; 5756 alreadyTriedUserIds.put(targetUserId, true); 5757 } 5758 } 5759 } 5760 return null; 5761 } 5762 5763 /** 5764 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5765 * will forward the intent to the filter's target user. 5766 * Otherwise, returns null. 5767 */ 5768 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5769 String resolvedType, int flags, int sourceUserId) { 5770 int targetUserId = filter.getTargetUserId(); 5771 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5772 resolvedType, flags, targetUserId); 5773 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5774 // If all the matches in the target profile are suspended, return null. 5775 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5776 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5777 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5778 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5779 targetUserId); 5780 } 5781 } 5782 } 5783 return null; 5784 } 5785 5786 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5787 int sourceUserId, int targetUserId) { 5788 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5789 long ident = Binder.clearCallingIdentity(); 5790 boolean targetIsProfile; 5791 try { 5792 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5793 } finally { 5794 Binder.restoreCallingIdentity(ident); 5795 } 5796 String className; 5797 if (targetIsProfile) { 5798 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5799 } else { 5800 className = FORWARD_INTENT_TO_PARENT; 5801 } 5802 ComponentName forwardingActivityComponentName = new ComponentName( 5803 mAndroidApplication.packageName, className); 5804 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5805 sourceUserId); 5806 if (!targetIsProfile) { 5807 forwardingActivityInfo.showUserIcon = targetUserId; 5808 forwardingResolveInfo.noResourceId = true; 5809 } 5810 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5811 forwardingResolveInfo.priority = 0; 5812 forwardingResolveInfo.preferredOrder = 0; 5813 forwardingResolveInfo.match = 0; 5814 forwardingResolveInfo.isDefault = true; 5815 forwardingResolveInfo.filter = filter; 5816 forwardingResolveInfo.targetUserId = targetUserId; 5817 return forwardingResolveInfo; 5818 } 5819 5820 @Override 5821 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5822 Intent[] specifics, String[] specificTypes, Intent intent, 5823 String resolvedType, int flags, int userId) { 5824 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5825 specificTypes, intent, resolvedType, flags, userId)); 5826 } 5827 5828 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5829 Intent[] specifics, String[] specificTypes, Intent intent, 5830 String resolvedType, int flags, int userId) { 5831 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5832 flags = updateFlagsForResolve(flags, userId, intent); 5833 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5834 false /* requireFullPermission */, false /* checkShell */, 5835 "query intent activity options"); 5836 final String resultsAction = intent.getAction(); 5837 5838 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5839 | PackageManager.GET_RESOLVED_FILTER, userId); 5840 5841 if (DEBUG_INTENT_MATCHING) { 5842 Log.v(TAG, "Query " + intent + ": " + results); 5843 } 5844 5845 int specificsPos = 0; 5846 int N; 5847 5848 // todo: note that the algorithm used here is O(N^2). This 5849 // isn't a problem in our current environment, but if we start running 5850 // into situations where we have more than 5 or 10 matches then this 5851 // should probably be changed to something smarter... 5852 5853 // First we go through and resolve each of the specific items 5854 // that were supplied, taking care of removing any corresponding 5855 // duplicate items in the generic resolve list. 5856 if (specifics != null) { 5857 for (int i=0; i<specifics.length; i++) { 5858 final Intent sintent = specifics[i]; 5859 if (sintent == null) { 5860 continue; 5861 } 5862 5863 if (DEBUG_INTENT_MATCHING) { 5864 Log.v(TAG, "Specific #" + i + ": " + sintent); 5865 } 5866 5867 String action = sintent.getAction(); 5868 if (resultsAction != null && resultsAction.equals(action)) { 5869 // If this action was explicitly requested, then don't 5870 // remove things that have it. 5871 action = null; 5872 } 5873 5874 ResolveInfo ri = null; 5875 ActivityInfo ai = null; 5876 5877 ComponentName comp = sintent.getComponent(); 5878 if (comp == null) { 5879 ri = resolveIntent( 5880 sintent, 5881 specificTypes != null ? specificTypes[i] : null, 5882 flags, userId); 5883 if (ri == null) { 5884 continue; 5885 } 5886 if (ri == mResolveInfo) { 5887 // ACK! Must do something better with this. 5888 } 5889 ai = ri.activityInfo; 5890 comp = new ComponentName(ai.applicationInfo.packageName, 5891 ai.name); 5892 } else { 5893 ai = getActivityInfo(comp, flags, userId); 5894 if (ai == null) { 5895 continue; 5896 } 5897 } 5898 5899 // Look for any generic query activities that are duplicates 5900 // of this specific one, and remove them from the results. 5901 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5902 N = results.size(); 5903 int j; 5904 for (j=specificsPos; j<N; j++) { 5905 ResolveInfo sri = results.get(j); 5906 if ((sri.activityInfo.name.equals(comp.getClassName()) 5907 && sri.activityInfo.applicationInfo.packageName.equals( 5908 comp.getPackageName())) 5909 || (action != null && sri.filter.matchAction(action))) { 5910 results.remove(j); 5911 if (DEBUG_INTENT_MATCHING) Log.v( 5912 TAG, "Removing duplicate item from " + j 5913 + " due to specific " + specificsPos); 5914 if (ri == null) { 5915 ri = sri; 5916 } 5917 j--; 5918 N--; 5919 } 5920 } 5921 5922 // Add this specific item to its proper place. 5923 if (ri == null) { 5924 ri = new ResolveInfo(); 5925 ri.activityInfo = ai; 5926 } 5927 results.add(specificsPos, ri); 5928 ri.specificIndex = i; 5929 specificsPos++; 5930 } 5931 } 5932 5933 // Now we go through the remaining generic results and remove any 5934 // duplicate actions that are found here. 5935 N = results.size(); 5936 for (int i=specificsPos; i<N-1; i++) { 5937 final ResolveInfo rii = results.get(i); 5938 if (rii.filter == null) { 5939 continue; 5940 } 5941 5942 // Iterate over all of the actions of this result's intent 5943 // filter... typically this should be just one. 5944 final Iterator<String> it = rii.filter.actionsIterator(); 5945 if (it == null) { 5946 continue; 5947 } 5948 while (it.hasNext()) { 5949 final String action = it.next(); 5950 if (resultsAction != null && resultsAction.equals(action)) { 5951 // If this action was explicitly requested, then don't 5952 // remove things that have it. 5953 continue; 5954 } 5955 for (int j=i+1; j<N; j++) { 5956 final ResolveInfo rij = results.get(j); 5957 if (rij.filter != null && rij.filter.hasAction(action)) { 5958 results.remove(j); 5959 if (DEBUG_INTENT_MATCHING) Log.v( 5960 TAG, "Removing duplicate item from " + j 5961 + " due to action " + action + " at " + i); 5962 j--; 5963 N--; 5964 } 5965 } 5966 } 5967 5968 // If the caller didn't request filter information, drop it now 5969 // so we don't have to marshall/unmarshall it. 5970 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5971 rii.filter = null; 5972 } 5973 } 5974 5975 // Filter out the caller activity if so requested. 5976 if (caller != null) { 5977 N = results.size(); 5978 for (int i=0; i<N; i++) { 5979 ActivityInfo ainfo = results.get(i).activityInfo; 5980 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5981 && caller.getClassName().equals(ainfo.name)) { 5982 results.remove(i); 5983 break; 5984 } 5985 } 5986 } 5987 5988 // If the caller didn't request filter information, 5989 // drop them now so we don't have to 5990 // marshall/unmarshall it. 5991 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5992 N = results.size(); 5993 for (int i=0; i<N; i++) { 5994 results.get(i).filter = null; 5995 } 5996 } 5997 5998 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5999 return results; 6000 } 6001 6002 @Override 6003 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6004 String resolvedType, int flags, int userId) { 6005 return new ParceledListSlice<>( 6006 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6007 } 6008 6009 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6010 String resolvedType, int flags, int userId) { 6011 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6012 flags = updateFlagsForResolve(flags, userId, intent); 6013 ComponentName comp = intent.getComponent(); 6014 if (comp == null) { 6015 if (intent.getSelector() != null) { 6016 intent = intent.getSelector(); 6017 comp = intent.getComponent(); 6018 } 6019 } 6020 if (comp != null) { 6021 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6022 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6023 if (ai != null) { 6024 ResolveInfo ri = new ResolveInfo(); 6025 ri.activityInfo = ai; 6026 list.add(ri); 6027 } 6028 return list; 6029 } 6030 6031 // reader 6032 synchronized (mPackages) { 6033 String pkgName = intent.getPackage(); 6034 if (pkgName == null) { 6035 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6036 } 6037 final PackageParser.Package pkg = mPackages.get(pkgName); 6038 if (pkg != null) { 6039 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6040 userId); 6041 } 6042 return Collections.emptyList(); 6043 } 6044 } 6045 6046 @Override 6047 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6048 if (!sUserManager.exists(userId)) return null; 6049 flags = updateFlagsForResolve(flags, userId, intent); 6050 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6051 if (query != null) { 6052 if (query.size() >= 1) { 6053 // If there is more than one service with the same priority, 6054 // just arbitrarily pick the first one. 6055 return query.get(0); 6056 } 6057 } 6058 return null; 6059 } 6060 6061 @Override 6062 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6063 String resolvedType, int flags, int userId) { 6064 return new ParceledListSlice<>( 6065 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6066 } 6067 6068 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6069 String resolvedType, int flags, int userId) { 6070 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6071 flags = updateFlagsForResolve(flags, userId, intent); 6072 ComponentName comp = intent.getComponent(); 6073 if (comp == null) { 6074 if (intent.getSelector() != null) { 6075 intent = intent.getSelector(); 6076 comp = intent.getComponent(); 6077 } 6078 } 6079 if (comp != null) { 6080 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6081 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6082 if (si != null) { 6083 final ResolveInfo ri = new ResolveInfo(); 6084 ri.serviceInfo = si; 6085 list.add(ri); 6086 } 6087 return list; 6088 } 6089 6090 // reader 6091 synchronized (mPackages) { 6092 String pkgName = intent.getPackage(); 6093 if (pkgName == null) { 6094 return mServices.queryIntent(intent, resolvedType, flags, userId); 6095 } 6096 final PackageParser.Package pkg = mPackages.get(pkgName); 6097 if (pkg != null) { 6098 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6099 userId); 6100 } 6101 return Collections.emptyList(); 6102 } 6103 } 6104 6105 @Override 6106 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6107 String resolvedType, int flags, int userId) { 6108 return new ParceledListSlice<>( 6109 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6110 } 6111 6112 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6113 Intent intent, String resolvedType, int flags, int userId) { 6114 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6115 flags = updateFlagsForResolve(flags, userId, intent); 6116 ComponentName comp = intent.getComponent(); 6117 if (comp == null) { 6118 if (intent.getSelector() != null) { 6119 intent = intent.getSelector(); 6120 comp = intent.getComponent(); 6121 } 6122 } 6123 if (comp != null) { 6124 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6125 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6126 if (pi != null) { 6127 final ResolveInfo ri = new ResolveInfo(); 6128 ri.providerInfo = pi; 6129 list.add(ri); 6130 } 6131 return list; 6132 } 6133 6134 // reader 6135 synchronized (mPackages) { 6136 String pkgName = intent.getPackage(); 6137 if (pkgName == null) { 6138 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6139 } 6140 final PackageParser.Package pkg = mPackages.get(pkgName); 6141 if (pkg != null) { 6142 return mProviders.queryIntentForPackage( 6143 intent, resolvedType, flags, pkg.providers, userId); 6144 } 6145 return Collections.emptyList(); 6146 } 6147 } 6148 6149 @Override 6150 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6151 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6152 flags = updateFlagsForPackage(flags, userId, null); 6153 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6155 true /* requireFullPermission */, false /* checkShell */, 6156 "get installed packages"); 6157 6158 // writer 6159 synchronized (mPackages) { 6160 ArrayList<PackageInfo> list; 6161 if (listUninstalled) { 6162 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6163 for (PackageSetting ps : mSettings.mPackages.values()) { 6164 final PackageInfo pi; 6165 if (ps.pkg != null) { 6166 pi = generatePackageInfo(ps, flags, userId); 6167 } else { 6168 pi = generatePackageInfo(ps, flags, userId); 6169 } 6170 if (pi != null) { 6171 list.add(pi); 6172 } 6173 } 6174 } else { 6175 list = new ArrayList<PackageInfo>(mPackages.size()); 6176 for (PackageParser.Package p : mPackages.values()) { 6177 final PackageInfo pi = 6178 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6179 if (pi != null) { 6180 list.add(pi); 6181 } 6182 } 6183 } 6184 6185 return new ParceledListSlice<PackageInfo>(list); 6186 } 6187 } 6188 6189 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6190 String[] permissions, boolean[] tmp, int flags, int userId) { 6191 int numMatch = 0; 6192 final PermissionsState permissionsState = ps.getPermissionsState(); 6193 for (int i=0; i<permissions.length; i++) { 6194 final String permission = permissions[i]; 6195 if (permissionsState.hasPermission(permission, userId)) { 6196 tmp[i] = true; 6197 numMatch++; 6198 } else { 6199 tmp[i] = false; 6200 } 6201 } 6202 if (numMatch == 0) { 6203 return; 6204 } 6205 final PackageInfo pi; 6206 if (ps.pkg != null) { 6207 pi = generatePackageInfo(ps, flags, userId); 6208 } else { 6209 pi = generatePackageInfo(ps, flags, userId); 6210 } 6211 // The above might return null in cases of uninstalled apps or install-state 6212 // skew across users/profiles. 6213 if (pi != null) { 6214 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6215 if (numMatch == permissions.length) { 6216 pi.requestedPermissions = permissions; 6217 } else { 6218 pi.requestedPermissions = new String[numMatch]; 6219 numMatch = 0; 6220 for (int i=0; i<permissions.length; i++) { 6221 if (tmp[i]) { 6222 pi.requestedPermissions[numMatch] = permissions[i]; 6223 numMatch++; 6224 } 6225 } 6226 } 6227 } 6228 list.add(pi); 6229 } 6230 } 6231 6232 @Override 6233 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6234 String[] permissions, int flags, int userId) { 6235 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6236 flags = updateFlagsForPackage(flags, userId, permissions); 6237 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6238 6239 // writer 6240 synchronized (mPackages) { 6241 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6242 boolean[] tmpBools = new boolean[permissions.length]; 6243 if (listUninstalled) { 6244 for (PackageSetting ps : mSettings.mPackages.values()) { 6245 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6246 } 6247 } else { 6248 for (PackageParser.Package pkg : mPackages.values()) { 6249 PackageSetting ps = (PackageSetting)pkg.mExtras; 6250 if (ps != null) { 6251 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6252 userId); 6253 } 6254 } 6255 } 6256 6257 return new ParceledListSlice<PackageInfo>(list); 6258 } 6259 } 6260 6261 @Override 6262 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6263 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6264 flags = updateFlagsForApplication(flags, userId, null); 6265 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6266 6267 // writer 6268 synchronized (mPackages) { 6269 ArrayList<ApplicationInfo> list; 6270 if (listUninstalled) { 6271 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6272 for (PackageSetting ps : mSettings.mPackages.values()) { 6273 ApplicationInfo ai; 6274 if (ps.pkg != null) { 6275 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6276 ps.readUserState(userId), userId); 6277 } else { 6278 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6279 } 6280 if (ai != null) { 6281 list.add(ai); 6282 } 6283 } 6284 } else { 6285 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6286 for (PackageParser.Package p : mPackages.values()) { 6287 if (p.mExtras != null) { 6288 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6289 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6290 if (ai != null) { 6291 list.add(ai); 6292 } 6293 } 6294 } 6295 } 6296 6297 return new ParceledListSlice<ApplicationInfo>(list); 6298 } 6299 } 6300 6301 @Override 6302 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6303 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6304 return null; 6305 } 6306 6307 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6308 "getEphemeralApplications"); 6309 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6310 true /* requireFullPermission */, false /* checkShell */, 6311 "getEphemeralApplications"); 6312 synchronized (mPackages) { 6313 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6314 .getEphemeralApplicationsLPw(userId); 6315 if (ephemeralApps != null) { 6316 return new ParceledListSlice<>(ephemeralApps); 6317 } 6318 } 6319 return null; 6320 } 6321 6322 @Override 6323 public boolean isEphemeralApplication(String packageName, int userId) { 6324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6325 true /* requireFullPermission */, false /* checkShell */, 6326 "isEphemeral"); 6327 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6328 return false; 6329 } 6330 6331 if (!isCallerSameApp(packageName)) { 6332 return false; 6333 } 6334 synchronized (mPackages) { 6335 PackageParser.Package pkg = mPackages.get(packageName); 6336 if (pkg != null) { 6337 return pkg.applicationInfo.isEphemeralApp(); 6338 } 6339 } 6340 return false; 6341 } 6342 6343 @Override 6344 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6345 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6346 return null; 6347 } 6348 6349 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6350 true /* requireFullPermission */, false /* checkShell */, 6351 "getCookie"); 6352 if (!isCallerSameApp(packageName)) { 6353 return null; 6354 } 6355 synchronized (mPackages) { 6356 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6357 packageName, userId); 6358 } 6359 } 6360 6361 @Override 6362 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6363 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6364 return true; 6365 } 6366 6367 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6368 true /* requireFullPermission */, true /* checkShell */, 6369 "setCookie"); 6370 if (!isCallerSameApp(packageName)) { 6371 return false; 6372 } 6373 synchronized (mPackages) { 6374 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6375 packageName, cookie, userId); 6376 } 6377 } 6378 6379 @Override 6380 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6381 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6382 return null; 6383 } 6384 6385 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6386 "getEphemeralApplicationIcon"); 6387 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6388 true /* requireFullPermission */, false /* checkShell */, 6389 "getEphemeralApplicationIcon"); 6390 synchronized (mPackages) { 6391 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6392 packageName, userId); 6393 } 6394 } 6395 6396 private boolean isCallerSameApp(String packageName) { 6397 PackageParser.Package pkg = mPackages.get(packageName); 6398 return pkg != null 6399 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6400 } 6401 6402 @Override 6403 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6404 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6405 } 6406 6407 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6408 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6409 6410 // reader 6411 synchronized (mPackages) { 6412 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6413 final int userId = UserHandle.getCallingUserId(); 6414 while (i.hasNext()) { 6415 final PackageParser.Package p = i.next(); 6416 if (p.applicationInfo == null) continue; 6417 6418 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6419 && !p.applicationInfo.isDirectBootAware(); 6420 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6421 && p.applicationInfo.isDirectBootAware(); 6422 6423 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6424 && (!mSafeMode || isSystemApp(p)) 6425 && (matchesUnaware || matchesAware)) { 6426 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6427 if (ps != null) { 6428 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6429 ps.readUserState(userId), userId); 6430 if (ai != null) { 6431 finalList.add(ai); 6432 } 6433 } 6434 } 6435 } 6436 } 6437 6438 return finalList; 6439 } 6440 6441 @Override 6442 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6443 if (!sUserManager.exists(userId)) return null; 6444 flags = updateFlagsForComponent(flags, userId, name); 6445 // reader 6446 synchronized (mPackages) { 6447 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6448 PackageSetting ps = provider != null 6449 ? mSettings.mPackages.get(provider.owner.packageName) 6450 : null; 6451 return ps != null 6452 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6453 ? PackageParser.generateProviderInfo(provider, flags, 6454 ps.readUserState(userId), userId) 6455 : null; 6456 } 6457 } 6458 6459 /** 6460 * @deprecated 6461 */ 6462 @Deprecated 6463 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6464 // reader 6465 synchronized (mPackages) { 6466 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6467 .entrySet().iterator(); 6468 final int userId = UserHandle.getCallingUserId(); 6469 while (i.hasNext()) { 6470 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6471 PackageParser.Provider p = entry.getValue(); 6472 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6473 6474 if (ps != null && p.syncable 6475 && (!mSafeMode || (p.info.applicationInfo.flags 6476 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6477 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6478 ps.readUserState(userId), userId); 6479 if (info != null) { 6480 outNames.add(entry.getKey()); 6481 outInfo.add(info); 6482 } 6483 } 6484 } 6485 } 6486 } 6487 6488 @Override 6489 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6490 int uid, int flags) { 6491 final int userId = processName != null ? UserHandle.getUserId(uid) 6492 : UserHandle.getCallingUserId(); 6493 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6494 flags = updateFlagsForComponent(flags, userId, processName); 6495 6496 ArrayList<ProviderInfo> finalList = null; 6497 // reader 6498 synchronized (mPackages) { 6499 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6500 while (i.hasNext()) { 6501 final PackageParser.Provider p = i.next(); 6502 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6503 if (ps != null && p.info.authority != null 6504 && (processName == null 6505 || (p.info.processName.equals(processName) 6506 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6507 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6508 if (finalList == null) { 6509 finalList = new ArrayList<ProviderInfo>(3); 6510 } 6511 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6512 ps.readUserState(userId), userId); 6513 if (info != null) { 6514 finalList.add(info); 6515 } 6516 } 6517 } 6518 } 6519 6520 if (finalList != null) { 6521 Collections.sort(finalList, mProviderInitOrderSorter); 6522 return new ParceledListSlice<ProviderInfo>(finalList); 6523 } 6524 6525 return ParceledListSlice.emptyList(); 6526 } 6527 6528 @Override 6529 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6530 // reader 6531 synchronized (mPackages) { 6532 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6533 return PackageParser.generateInstrumentationInfo(i, flags); 6534 } 6535 } 6536 6537 @Override 6538 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6539 String targetPackage, int flags) { 6540 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6541 } 6542 6543 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6544 int flags) { 6545 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6546 6547 // reader 6548 synchronized (mPackages) { 6549 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6550 while (i.hasNext()) { 6551 final PackageParser.Instrumentation p = i.next(); 6552 if (targetPackage == null 6553 || targetPackage.equals(p.info.targetPackage)) { 6554 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6555 flags); 6556 if (ii != null) { 6557 finalList.add(ii); 6558 } 6559 } 6560 } 6561 } 6562 6563 return finalList; 6564 } 6565 6566 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6567 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6568 if (overlays == null) { 6569 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6570 return; 6571 } 6572 for (PackageParser.Package opkg : overlays.values()) { 6573 // Not much to do if idmap fails: we already logged the error 6574 // and we certainly don't want to abort installation of pkg simply 6575 // because an overlay didn't fit properly. For these reasons, 6576 // ignore the return value of createIdmapForPackagePairLI. 6577 createIdmapForPackagePairLI(pkg, opkg); 6578 } 6579 } 6580 6581 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6582 PackageParser.Package opkg) { 6583 if (!opkg.mTrustedOverlay) { 6584 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6585 opkg.baseCodePath + ": overlay not trusted"); 6586 return false; 6587 } 6588 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6589 if (overlaySet == null) { 6590 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6591 opkg.baseCodePath + " but target package has no known overlays"); 6592 return false; 6593 } 6594 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6595 // TODO: generate idmap for split APKs 6596 try { 6597 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6598 } catch (InstallerException e) { 6599 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6600 + opkg.baseCodePath); 6601 return false; 6602 } 6603 PackageParser.Package[] overlayArray = 6604 overlaySet.values().toArray(new PackageParser.Package[0]); 6605 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6606 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6607 return p1.mOverlayPriority - p2.mOverlayPriority; 6608 } 6609 }; 6610 Arrays.sort(overlayArray, cmp); 6611 6612 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6613 int i = 0; 6614 for (PackageParser.Package p : overlayArray) { 6615 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6616 } 6617 return true; 6618 } 6619 6620 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6622 try { 6623 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6624 } finally { 6625 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6626 } 6627 } 6628 6629 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6630 final File[] files = dir.listFiles(); 6631 if (ArrayUtils.isEmpty(files)) { 6632 Log.d(TAG, "No files in app dir " + dir); 6633 return; 6634 } 6635 6636 if (DEBUG_PACKAGE_SCANNING) { 6637 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6638 + " flags=0x" + Integer.toHexString(parseFlags)); 6639 } 6640 6641 for (File file : files) { 6642 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6643 && !PackageInstallerService.isStageName(file.getName()); 6644 if (!isPackage) { 6645 // Ignore entries which are not packages 6646 continue; 6647 } 6648 try { 6649 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6650 scanFlags, currentTime, null); 6651 } catch (PackageManagerException e) { 6652 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6653 6654 // Delete invalid userdata apps 6655 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6656 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6657 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6658 removeCodePathLI(file); 6659 } 6660 } 6661 } 6662 } 6663 6664 private static File getSettingsProblemFile() { 6665 File dataDir = Environment.getDataDirectory(); 6666 File systemDir = new File(dataDir, "system"); 6667 File fname = new File(systemDir, "uiderrors.txt"); 6668 return fname; 6669 } 6670 6671 static void reportSettingsProblem(int priority, String msg) { 6672 logCriticalInfo(priority, msg); 6673 } 6674 6675 static void logCriticalInfo(int priority, String msg) { 6676 Slog.println(priority, TAG, msg); 6677 EventLogTags.writePmCriticalInfo(msg); 6678 try { 6679 File fname = getSettingsProblemFile(); 6680 FileOutputStream out = new FileOutputStream(fname, true); 6681 PrintWriter pw = new FastPrintWriter(out); 6682 SimpleDateFormat formatter = new SimpleDateFormat(); 6683 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6684 pw.println(dateString + ": " + msg); 6685 pw.close(); 6686 FileUtils.setPermissions( 6687 fname.toString(), 6688 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6689 -1, -1); 6690 } catch (java.io.IOException e) { 6691 } 6692 } 6693 6694 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6695 if (srcFile.isDirectory()) { 6696 final File baseFile = new File(pkg.baseCodePath); 6697 long maxModifiedTime = baseFile.lastModified(); 6698 if (pkg.splitCodePaths != null) { 6699 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6700 final File splitFile = new File(pkg.splitCodePaths[i]); 6701 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6702 } 6703 } 6704 return maxModifiedTime; 6705 } 6706 return srcFile.lastModified(); 6707 } 6708 6709 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6710 final int policyFlags) throws PackageManagerException { 6711 // When upgrading from pre-N MR1, verify the package time stamp using the package 6712 // directory and not the APK file. 6713 final long lastModifiedTime = mIsPreNMR1Upgrade 6714 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6715 if (ps != null 6716 && ps.codePath.equals(srcFile) 6717 && ps.timeStamp == lastModifiedTime 6718 && !isCompatSignatureUpdateNeeded(pkg) 6719 && !isRecoverSignatureUpdateNeeded(pkg)) { 6720 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6721 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6722 ArraySet<PublicKey> signingKs; 6723 synchronized (mPackages) { 6724 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6725 } 6726 if (ps.signatures.mSignatures != null 6727 && ps.signatures.mSignatures.length != 0 6728 && signingKs != null) { 6729 // Optimization: reuse the existing cached certificates 6730 // if the package appears to be unchanged. 6731 pkg.mSignatures = ps.signatures.mSignatures; 6732 pkg.mSigningKeys = signingKs; 6733 return; 6734 } 6735 6736 Slog.w(TAG, "PackageSetting for " + ps.name 6737 + " is missing signatures. Collecting certs again to recover them."); 6738 } else { 6739 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6740 } 6741 6742 try { 6743 PackageParser.collectCertificates(pkg, policyFlags); 6744 } catch (PackageParserException e) { 6745 throw PackageManagerException.from(e); 6746 } 6747 } 6748 6749 /** 6750 * Traces a package scan. 6751 * @see #scanPackageLI(File, int, int, long, UserHandle) 6752 */ 6753 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6754 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6755 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6756 try { 6757 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6758 } finally { 6759 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6760 } 6761 } 6762 6763 /** 6764 * Scans a package and returns the newly parsed package. 6765 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6766 */ 6767 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6768 long currentTime, UserHandle user) throws PackageManagerException { 6769 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6770 PackageParser pp = new PackageParser(); 6771 pp.setSeparateProcesses(mSeparateProcesses); 6772 pp.setOnlyCoreApps(mOnlyCore); 6773 pp.setDisplayMetrics(mMetrics); 6774 6775 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6776 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6777 } 6778 6779 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6780 final PackageParser.Package pkg; 6781 try { 6782 pkg = pp.parsePackage(scanFile, parseFlags); 6783 } catch (PackageParserException e) { 6784 throw PackageManagerException.from(e); 6785 } finally { 6786 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6787 } 6788 6789 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6790 } 6791 6792 /** 6793 * Scans a package and returns the newly parsed package. 6794 * @throws PackageManagerException on a parse error. 6795 */ 6796 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6797 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6798 throws PackageManagerException { 6799 // If the package has children and this is the first dive in the function 6800 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6801 // packages (parent and children) would be successfully scanned before the 6802 // actual scan since scanning mutates internal state and we want to atomically 6803 // install the package and its children. 6804 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6805 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6806 scanFlags |= SCAN_CHECK_ONLY; 6807 } 6808 } else { 6809 scanFlags &= ~SCAN_CHECK_ONLY; 6810 } 6811 6812 // Scan the parent 6813 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6814 scanFlags, currentTime, user); 6815 6816 // Scan the children 6817 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6818 for (int i = 0; i < childCount; i++) { 6819 PackageParser.Package childPackage = pkg.childPackages.get(i); 6820 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6821 currentTime, user); 6822 } 6823 6824 6825 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6826 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6827 } 6828 6829 return scannedPkg; 6830 } 6831 6832 /** 6833 * Scans a package and returns the newly parsed package. 6834 * @throws PackageManagerException on a parse error. 6835 */ 6836 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6837 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6838 throws PackageManagerException { 6839 PackageSetting ps = null; 6840 PackageSetting updatedPkg; 6841 // reader 6842 synchronized (mPackages) { 6843 // Look to see if we already know about this package. 6844 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6845 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6846 // This package has been renamed to its original name. Let's 6847 // use that. 6848 ps = mSettings.peekPackageLPr(oldName); 6849 } 6850 // If there was no original package, see one for the real package name. 6851 if (ps == null) { 6852 ps = mSettings.peekPackageLPr(pkg.packageName); 6853 } 6854 // Check to see if this package could be hiding/updating a system 6855 // package. Must look for it either under the original or real 6856 // package name depending on our state. 6857 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6858 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6859 6860 // If this is a package we don't know about on the system partition, we 6861 // may need to remove disabled child packages on the system partition 6862 // or may need to not add child packages if the parent apk is updated 6863 // on the data partition and no longer defines this child package. 6864 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6865 // If this is a parent package for an updated system app and this system 6866 // app got an OTA update which no longer defines some of the child packages 6867 // we have to prune them from the disabled system packages. 6868 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6869 if (disabledPs != null) { 6870 final int scannedChildCount = (pkg.childPackages != null) 6871 ? pkg.childPackages.size() : 0; 6872 final int disabledChildCount = disabledPs.childPackageNames != null 6873 ? disabledPs.childPackageNames.size() : 0; 6874 for (int i = 0; i < disabledChildCount; i++) { 6875 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6876 boolean disabledPackageAvailable = false; 6877 for (int j = 0; j < scannedChildCount; j++) { 6878 PackageParser.Package childPkg = pkg.childPackages.get(j); 6879 if (childPkg.packageName.equals(disabledChildPackageName)) { 6880 disabledPackageAvailable = true; 6881 break; 6882 } 6883 } 6884 if (!disabledPackageAvailable) { 6885 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6886 } 6887 } 6888 } 6889 } 6890 } 6891 6892 boolean updatedPkgBetter = false; 6893 // First check if this is a system package that may involve an update 6894 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6895 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6896 // it needs to drop FLAG_PRIVILEGED. 6897 if (locationIsPrivileged(scanFile)) { 6898 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6899 } else { 6900 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6901 } 6902 6903 if (ps != null && !ps.codePath.equals(scanFile)) { 6904 // The path has changed from what was last scanned... check the 6905 // version of the new path against what we have stored to determine 6906 // what to do. 6907 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6908 if (pkg.mVersionCode <= ps.versionCode) { 6909 // The system package has been updated and the code path does not match 6910 // Ignore entry. Skip it. 6911 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6912 + " ignored: updated version " + ps.versionCode 6913 + " better than this " + pkg.mVersionCode); 6914 if (!updatedPkg.codePath.equals(scanFile)) { 6915 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6916 + ps.name + " changing from " + updatedPkg.codePathString 6917 + " to " + scanFile); 6918 updatedPkg.codePath = scanFile; 6919 updatedPkg.codePathString = scanFile.toString(); 6920 updatedPkg.resourcePath = scanFile; 6921 updatedPkg.resourcePathString = scanFile.toString(); 6922 } 6923 updatedPkg.pkg = pkg; 6924 updatedPkg.versionCode = pkg.mVersionCode; 6925 6926 // Update the disabled system child packages to point to the package too. 6927 final int childCount = updatedPkg.childPackageNames != null 6928 ? updatedPkg.childPackageNames.size() : 0; 6929 for (int i = 0; i < childCount; i++) { 6930 String childPackageName = updatedPkg.childPackageNames.get(i); 6931 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6932 childPackageName); 6933 if (updatedChildPkg != null) { 6934 updatedChildPkg.pkg = pkg; 6935 updatedChildPkg.versionCode = pkg.mVersionCode; 6936 } 6937 } 6938 6939 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6940 + scanFile + " ignored: updated version " + ps.versionCode 6941 + " better than this " + pkg.mVersionCode); 6942 } else { 6943 // The current app on the system partition is better than 6944 // what we have updated to on the data partition; switch 6945 // back to the system partition version. 6946 // At this point, its safely assumed that package installation for 6947 // apps in system partition will go through. If not there won't be a working 6948 // version of the app 6949 // writer 6950 synchronized (mPackages) { 6951 // Just remove the loaded entries from package lists. 6952 mPackages.remove(ps.name); 6953 } 6954 6955 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6956 + " reverting from " + ps.codePathString 6957 + ": new version " + pkg.mVersionCode 6958 + " better than installed " + ps.versionCode); 6959 6960 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6961 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6962 synchronized (mInstallLock) { 6963 args.cleanUpResourcesLI(); 6964 } 6965 synchronized (mPackages) { 6966 mSettings.enableSystemPackageLPw(ps.name); 6967 } 6968 updatedPkgBetter = true; 6969 } 6970 } 6971 } 6972 6973 if (updatedPkg != null) { 6974 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6975 // initially 6976 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6977 6978 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6979 // flag set initially 6980 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6981 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6982 } 6983 } 6984 6985 // Verify certificates against what was last scanned 6986 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6987 6988 /* 6989 * A new system app appeared, but we already had a non-system one of the 6990 * same name installed earlier. 6991 */ 6992 boolean shouldHideSystemApp = false; 6993 if (updatedPkg == null && ps != null 6994 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6995 /* 6996 * Check to make sure the signatures match first. If they don't, 6997 * wipe the installed application and its data. 6998 */ 6999 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7000 != PackageManager.SIGNATURE_MATCH) { 7001 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7002 + " signatures don't match existing userdata copy; removing"); 7003 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7004 "scanPackageInternalLI")) { 7005 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7006 } 7007 ps = null; 7008 } else { 7009 /* 7010 * If the newly-added system app is an older version than the 7011 * already installed version, hide it. It will be scanned later 7012 * and re-added like an update. 7013 */ 7014 if (pkg.mVersionCode <= ps.versionCode) { 7015 shouldHideSystemApp = true; 7016 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7017 + " but new version " + pkg.mVersionCode + " better than installed " 7018 + ps.versionCode + "; hiding system"); 7019 } else { 7020 /* 7021 * The newly found system app is a newer version that the 7022 * one previously installed. Simply remove the 7023 * already-installed application and replace it with our own 7024 * while keeping the application data. 7025 */ 7026 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7027 + " reverting from " + ps.codePathString + ": new version " 7028 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7029 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7030 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7031 synchronized (mInstallLock) { 7032 args.cleanUpResourcesLI(); 7033 } 7034 } 7035 } 7036 } 7037 7038 // The apk is forward locked (not public) if its code and resources 7039 // are kept in different files. (except for app in either system or 7040 // vendor path). 7041 // TODO grab this value from PackageSettings 7042 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7043 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7044 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7045 } 7046 } 7047 7048 // TODO: extend to support forward-locked splits 7049 String resourcePath = null; 7050 String baseResourcePath = null; 7051 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7052 if (ps != null && ps.resourcePathString != null) { 7053 resourcePath = ps.resourcePathString; 7054 baseResourcePath = ps.resourcePathString; 7055 } else { 7056 // Should not happen at all. Just log an error. 7057 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7058 } 7059 } else { 7060 resourcePath = pkg.codePath; 7061 baseResourcePath = pkg.baseCodePath; 7062 } 7063 7064 // Set application objects path explicitly. 7065 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7066 pkg.setApplicationInfoCodePath(pkg.codePath); 7067 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7068 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7069 pkg.setApplicationInfoResourcePath(resourcePath); 7070 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7071 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7072 7073 // Note that we invoke the following method only if we are about to unpack an application 7074 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7075 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7076 7077 /* 7078 * If the system app should be overridden by a previously installed 7079 * data, hide the system app now and let the /data/app scan pick it up 7080 * again. 7081 */ 7082 if (shouldHideSystemApp) { 7083 synchronized (mPackages) { 7084 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7085 } 7086 } 7087 7088 return scannedPkg; 7089 } 7090 7091 private static String fixProcessName(String defProcessName, 7092 String processName, int uid) { 7093 if (processName == null) { 7094 return defProcessName; 7095 } 7096 return processName; 7097 } 7098 7099 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7100 throws PackageManagerException { 7101 if (pkgSetting.signatures.mSignatures != null) { 7102 // Already existing package. Make sure signatures match 7103 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7104 == PackageManager.SIGNATURE_MATCH; 7105 if (!match) { 7106 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7107 == PackageManager.SIGNATURE_MATCH; 7108 } 7109 if (!match) { 7110 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7111 == PackageManager.SIGNATURE_MATCH; 7112 } 7113 if (!match) { 7114 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7115 + pkg.packageName + " signatures do not match the " 7116 + "previously installed version; ignoring!"); 7117 } 7118 } 7119 7120 // Check for shared user signatures 7121 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7122 // Already existing package. Make sure signatures match 7123 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7124 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7125 if (!match) { 7126 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7127 == PackageManager.SIGNATURE_MATCH; 7128 } 7129 if (!match) { 7130 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7131 == PackageManager.SIGNATURE_MATCH; 7132 } 7133 if (!match) { 7134 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7135 "Package " + pkg.packageName 7136 + " has no signatures that match those in shared user " 7137 + pkgSetting.sharedUser.name + "; ignoring!"); 7138 } 7139 } 7140 } 7141 7142 /** 7143 * Enforces that only the system UID or root's UID can call a method exposed 7144 * via Binder. 7145 * 7146 * @param message used as message if SecurityException is thrown 7147 * @throws SecurityException if the caller is not system or root 7148 */ 7149 private static final void enforceSystemOrRoot(String message) { 7150 final int uid = Binder.getCallingUid(); 7151 if (uid != Process.SYSTEM_UID && uid != 0) { 7152 throw new SecurityException(message); 7153 } 7154 } 7155 7156 @Override 7157 public void performFstrimIfNeeded() { 7158 enforceSystemOrRoot("Only the system can request fstrim"); 7159 7160 // Before everything else, see whether we need to fstrim. 7161 try { 7162 IMountService ms = PackageHelper.getMountService(); 7163 if (ms != null) { 7164 boolean doTrim = false; 7165 final long interval = android.provider.Settings.Global.getLong( 7166 mContext.getContentResolver(), 7167 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7168 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7169 if (interval > 0) { 7170 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7171 if (timeSinceLast > interval) { 7172 doTrim = true; 7173 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7174 + "; running immediately"); 7175 } 7176 } 7177 if (doTrim) { 7178 final boolean dexOptDialogShown; 7179 synchronized (mPackages) { 7180 dexOptDialogShown = mDexOptDialogShown; 7181 } 7182 if (!isFirstBoot() && dexOptDialogShown) { 7183 try { 7184 ActivityManagerNative.getDefault().showBootMessage( 7185 mContext.getResources().getString( 7186 R.string.android_upgrading_fstrim), true); 7187 } catch (RemoteException e) { 7188 } 7189 } 7190 ms.runMaintenance(); 7191 } 7192 } else { 7193 Slog.e(TAG, "Mount service unavailable!"); 7194 } 7195 } catch (RemoteException e) { 7196 // Can't happen; MountService is local 7197 } 7198 } 7199 7200 @Override 7201 public void updatePackagesIfNeeded() { 7202 enforceSystemOrRoot("Only the system can request package update"); 7203 7204 // We need to re-extract after an OTA. 7205 boolean causeUpgrade = isUpgrade(); 7206 7207 // First boot or factory reset. 7208 // Note: we also handle devices that are upgrading to N right now as if it is their 7209 // first boot, as they do not have profile data. 7210 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7211 7212 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7213 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7214 7215 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7216 return; 7217 } 7218 7219 List<PackageParser.Package> pkgs; 7220 synchronized (mPackages) { 7221 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7222 } 7223 7224 final long startTime = System.nanoTime(); 7225 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7226 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7227 7228 final int elapsedTimeSeconds = 7229 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7230 7231 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7232 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7233 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7234 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7235 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7236 } 7237 7238 /** 7239 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7240 * containing statistics about the invocation. The array consists of three elements, 7241 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7242 * and {@code numberOfPackagesFailed}. 7243 */ 7244 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7245 String compilerFilter) { 7246 7247 int numberOfPackagesVisited = 0; 7248 int numberOfPackagesOptimized = 0; 7249 int numberOfPackagesSkipped = 0; 7250 int numberOfPackagesFailed = 0; 7251 final int numberOfPackagesToDexopt = pkgs.size(); 7252 7253 for (PackageParser.Package pkg : pkgs) { 7254 numberOfPackagesVisited++; 7255 7256 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7257 if (DEBUG_DEXOPT) { 7258 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7259 } 7260 numberOfPackagesSkipped++; 7261 continue; 7262 } 7263 7264 if (DEBUG_DEXOPT) { 7265 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7266 numberOfPackagesToDexopt + ": " + pkg.packageName); 7267 } 7268 7269 if (showDialog) { 7270 try { 7271 ActivityManagerNative.getDefault().showBootMessage( 7272 mContext.getResources().getString(R.string.android_upgrading_apk, 7273 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7274 } catch (RemoteException e) { 7275 } 7276 synchronized (mPackages) { 7277 mDexOptDialogShown = true; 7278 } 7279 } 7280 7281 // If the OTA updates a system app which was previously preopted to a non-preopted state 7282 // the app might end up being verified at runtime. That's because by default the apps 7283 // are verify-profile but for preopted apps there's no profile. 7284 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7285 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7286 // filter (by default interpret-only). 7287 // Note that at this stage unused apps are already filtered. 7288 if (isSystemApp(pkg) && 7289 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7290 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7291 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7292 } 7293 7294 // checkProfiles is false to avoid merging profiles during boot which 7295 // might interfere with background compilation (b/28612421). 7296 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7297 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7298 // trade-off worth doing to save boot time work. 7299 int dexOptStatus = performDexOptTraced(pkg.packageName, 7300 false /* checkProfiles */, 7301 compilerFilter, 7302 false /* force */); 7303 switch (dexOptStatus) { 7304 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7305 numberOfPackagesOptimized++; 7306 break; 7307 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7308 numberOfPackagesSkipped++; 7309 break; 7310 case PackageDexOptimizer.DEX_OPT_FAILED: 7311 numberOfPackagesFailed++; 7312 break; 7313 default: 7314 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7315 break; 7316 } 7317 } 7318 7319 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7320 numberOfPackagesFailed }; 7321 } 7322 7323 @Override 7324 public void notifyPackageUse(String packageName, int reason) { 7325 synchronized (mPackages) { 7326 PackageParser.Package p = mPackages.get(packageName); 7327 if (p == null) { 7328 return; 7329 } 7330 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7331 } 7332 } 7333 7334 // TODO: this is not used nor needed. Delete it. 7335 @Override 7336 public boolean performDexOptIfNeeded(String packageName) { 7337 int dexOptStatus = performDexOptTraced(packageName, 7338 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7339 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7340 } 7341 7342 @Override 7343 public boolean performDexOpt(String packageName, 7344 boolean checkProfiles, int compileReason, boolean force) { 7345 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7346 getCompilerFilterForReason(compileReason), force); 7347 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7348 } 7349 7350 @Override 7351 public boolean performDexOptMode(String packageName, 7352 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7353 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7354 targetCompilerFilter, force); 7355 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7356 } 7357 7358 private int performDexOptTraced(String packageName, 7359 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7361 try { 7362 return performDexOptInternal(packageName, checkProfiles, 7363 targetCompilerFilter, force); 7364 } finally { 7365 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7366 } 7367 } 7368 7369 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7370 // if the package can now be considered up to date for the given filter. 7371 private int performDexOptInternal(String packageName, 7372 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7373 PackageParser.Package p; 7374 synchronized (mPackages) { 7375 p = mPackages.get(packageName); 7376 if (p == null) { 7377 // Package could not be found. Report failure. 7378 return PackageDexOptimizer.DEX_OPT_FAILED; 7379 } 7380 mPackageUsage.maybeWriteAsync(mPackages); 7381 mCompilerStats.maybeWriteAsync(); 7382 } 7383 long callingId = Binder.clearCallingIdentity(); 7384 try { 7385 synchronized (mInstallLock) { 7386 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7387 targetCompilerFilter, force); 7388 } 7389 } finally { 7390 Binder.restoreCallingIdentity(callingId); 7391 } 7392 } 7393 7394 public ArraySet<String> getOptimizablePackages() { 7395 ArraySet<String> pkgs = new ArraySet<String>(); 7396 synchronized (mPackages) { 7397 for (PackageParser.Package p : mPackages.values()) { 7398 if (PackageDexOptimizer.canOptimizePackage(p)) { 7399 pkgs.add(p.packageName); 7400 } 7401 } 7402 } 7403 return pkgs; 7404 } 7405 7406 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7407 boolean checkProfiles, String targetCompilerFilter, 7408 boolean force) { 7409 // Select the dex optimizer based on the force parameter. 7410 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7411 // allocate an object here. 7412 PackageDexOptimizer pdo = force 7413 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7414 : mPackageDexOptimizer; 7415 7416 // Optimize all dependencies first. Note: we ignore the return value and march on 7417 // on errors. 7418 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7419 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7420 if (!deps.isEmpty()) { 7421 for (PackageParser.Package depPackage : deps) { 7422 // TODO: Analyze and investigate if we (should) profile libraries. 7423 // Currently this will do a full compilation of the library by default. 7424 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7425 false /* checkProfiles */, 7426 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7427 getOrCreateCompilerPackageStats(depPackage)); 7428 } 7429 } 7430 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7431 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7432 } 7433 7434 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7435 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7436 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7437 Set<String> collectedNames = new HashSet<>(); 7438 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7439 7440 retValue.remove(p); 7441 7442 return retValue; 7443 } else { 7444 return Collections.emptyList(); 7445 } 7446 } 7447 7448 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7449 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7450 if (!collectedNames.contains(p.packageName)) { 7451 collectedNames.add(p.packageName); 7452 collected.add(p); 7453 7454 if (p.usesLibraries != null) { 7455 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7456 } 7457 if (p.usesOptionalLibraries != null) { 7458 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7459 collectedNames); 7460 } 7461 } 7462 } 7463 7464 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7465 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7466 for (String libName : libs) { 7467 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7468 if (libPkg != null) { 7469 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7470 } 7471 } 7472 } 7473 7474 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7475 synchronized (mPackages) { 7476 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7477 if (lib != null && lib.apk != null) { 7478 return mPackages.get(lib.apk); 7479 } 7480 } 7481 return null; 7482 } 7483 7484 public void shutdown() { 7485 mPackageUsage.writeNow(mPackages); 7486 mCompilerStats.writeNow(); 7487 } 7488 7489 @Override 7490 public void dumpProfiles(String packageName) { 7491 PackageParser.Package pkg; 7492 synchronized (mPackages) { 7493 pkg = mPackages.get(packageName); 7494 if (pkg == null) { 7495 throw new IllegalArgumentException("Unknown package: " + packageName); 7496 } 7497 } 7498 /* Only the shell, root, or the app user should be able to dump profiles. */ 7499 int callingUid = Binder.getCallingUid(); 7500 if (callingUid != Process.SHELL_UID && 7501 callingUid != Process.ROOT_UID && 7502 callingUid != pkg.applicationInfo.uid) { 7503 throw new SecurityException("dumpProfiles"); 7504 } 7505 7506 synchronized (mInstallLock) { 7507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7508 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7509 try { 7510 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7511 String gid = Integer.toString(sharedGid); 7512 String codePaths = TextUtils.join(";", allCodePaths); 7513 mInstaller.dumpProfiles(gid, packageName, codePaths); 7514 } catch (InstallerException e) { 7515 Slog.w(TAG, "Failed to dump profiles", e); 7516 } 7517 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7518 } 7519 } 7520 7521 @Override 7522 public void forceDexOpt(String packageName) { 7523 enforceSystemOrRoot("forceDexOpt"); 7524 7525 PackageParser.Package pkg; 7526 synchronized (mPackages) { 7527 pkg = mPackages.get(packageName); 7528 if (pkg == null) { 7529 throw new IllegalArgumentException("Unknown package: " + packageName); 7530 } 7531 } 7532 7533 synchronized (mInstallLock) { 7534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7535 7536 // Whoever is calling forceDexOpt wants a fully compiled package. 7537 // Don't use profiles since that may cause compilation to be skipped. 7538 final int res = performDexOptInternalWithDependenciesLI(pkg, 7539 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7540 true /* force */); 7541 7542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7543 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7544 throw new IllegalStateException("Failed to dexopt: " + res); 7545 } 7546 } 7547 } 7548 7549 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7550 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7551 Slog.w(TAG, "Unable to update from " + oldPkg.name 7552 + " to " + newPkg.packageName 7553 + ": old package not in system partition"); 7554 return false; 7555 } else if (mPackages.get(oldPkg.name) != null) { 7556 Slog.w(TAG, "Unable to update from " + oldPkg.name 7557 + " to " + newPkg.packageName 7558 + ": old package still exists"); 7559 return false; 7560 } 7561 return true; 7562 } 7563 7564 void removeCodePathLI(File codePath) { 7565 if (codePath.isDirectory()) { 7566 try { 7567 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7568 } catch (InstallerException e) { 7569 Slog.w(TAG, "Failed to remove code path", e); 7570 } 7571 } else { 7572 codePath.delete(); 7573 } 7574 } 7575 7576 private int[] resolveUserIds(int userId) { 7577 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7578 } 7579 7580 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7581 if (pkg == null) { 7582 Slog.wtf(TAG, "Package was null!", new Throwable()); 7583 return; 7584 } 7585 clearAppDataLeafLIF(pkg, userId, flags); 7586 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7587 for (int i = 0; i < childCount; i++) { 7588 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7589 } 7590 } 7591 7592 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7593 final PackageSetting ps; 7594 synchronized (mPackages) { 7595 ps = mSettings.mPackages.get(pkg.packageName); 7596 } 7597 for (int realUserId : resolveUserIds(userId)) { 7598 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7599 try { 7600 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7601 ceDataInode); 7602 } catch (InstallerException e) { 7603 Slog.w(TAG, String.valueOf(e)); 7604 } 7605 } 7606 } 7607 7608 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7609 if (pkg == null) { 7610 Slog.wtf(TAG, "Package was null!", new Throwable()); 7611 return; 7612 } 7613 destroyAppDataLeafLIF(pkg, userId, flags); 7614 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7615 for (int i = 0; i < childCount; i++) { 7616 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7617 } 7618 } 7619 7620 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7621 final PackageSetting ps; 7622 synchronized (mPackages) { 7623 ps = mSettings.mPackages.get(pkg.packageName); 7624 } 7625 for (int realUserId : resolveUserIds(userId)) { 7626 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7627 try { 7628 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7629 ceDataInode); 7630 } catch (InstallerException e) { 7631 Slog.w(TAG, String.valueOf(e)); 7632 } 7633 } 7634 } 7635 7636 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7637 if (pkg == null) { 7638 Slog.wtf(TAG, "Package was null!", new Throwable()); 7639 return; 7640 } 7641 destroyAppProfilesLeafLIF(pkg); 7642 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7643 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7644 for (int i = 0; i < childCount; i++) { 7645 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7646 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7647 true /* removeBaseMarker */); 7648 } 7649 } 7650 7651 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7652 boolean removeBaseMarker) { 7653 if (pkg.isForwardLocked()) { 7654 return; 7655 } 7656 7657 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7658 try { 7659 path = PackageManagerServiceUtils.realpath(new File(path)); 7660 } catch (IOException e) { 7661 // TODO: Should we return early here ? 7662 Slog.w(TAG, "Failed to get canonical path", e); 7663 continue; 7664 } 7665 7666 final String useMarker = path.replace('/', '@'); 7667 for (int realUserId : resolveUserIds(userId)) { 7668 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7669 if (removeBaseMarker) { 7670 File foreignUseMark = new File(profileDir, useMarker); 7671 if (foreignUseMark.exists()) { 7672 if (!foreignUseMark.delete()) { 7673 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7674 + pkg.packageName); 7675 } 7676 } 7677 } 7678 7679 File[] markers = profileDir.listFiles(); 7680 if (markers != null) { 7681 final String searchString = "@" + pkg.packageName + "@"; 7682 // We also delete all markers that contain the package name we're 7683 // uninstalling. These are associated with secondary dex-files belonging 7684 // to the package. Reconstructing the path of these dex files is messy 7685 // in general. 7686 for (File marker : markers) { 7687 if (marker.getName().indexOf(searchString) > 0) { 7688 if (!marker.delete()) { 7689 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7690 + pkg.packageName); 7691 } 7692 } 7693 } 7694 } 7695 } 7696 } 7697 } 7698 7699 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7700 try { 7701 mInstaller.destroyAppProfiles(pkg.packageName); 7702 } catch (InstallerException e) { 7703 Slog.w(TAG, String.valueOf(e)); 7704 } 7705 } 7706 7707 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7708 if (pkg == null) { 7709 Slog.wtf(TAG, "Package was null!", new Throwable()); 7710 return; 7711 } 7712 clearAppProfilesLeafLIF(pkg); 7713 // We don't remove the base foreign use marker when clearing profiles because 7714 // we will rename it when the app is updated. Unlike the actual profile contents, 7715 // the foreign use marker is good across installs. 7716 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7718 for (int i = 0; i < childCount; i++) { 7719 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7720 } 7721 } 7722 7723 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7724 try { 7725 mInstaller.clearAppProfiles(pkg.packageName); 7726 } catch (InstallerException e) { 7727 Slog.w(TAG, String.valueOf(e)); 7728 } 7729 } 7730 7731 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7732 long lastUpdateTime) { 7733 // Set parent install/update time 7734 PackageSetting ps = (PackageSetting) pkg.mExtras; 7735 if (ps != null) { 7736 ps.firstInstallTime = firstInstallTime; 7737 ps.lastUpdateTime = lastUpdateTime; 7738 } 7739 // Set children install/update time 7740 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7741 for (int i = 0; i < childCount; i++) { 7742 PackageParser.Package childPkg = pkg.childPackages.get(i); 7743 ps = (PackageSetting) childPkg.mExtras; 7744 if (ps != null) { 7745 ps.firstInstallTime = firstInstallTime; 7746 ps.lastUpdateTime = lastUpdateTime; 7747 } 7748 } 7749 } 7750 7751 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7752 PackageParser.Package changingLib) { 7753 if (file.path != null) { 7754 usesLibraryFiles.add(file.path); 7755 return; 7756 } 7757 PackageParser.Package p = mPackages.get(file.apk); 7758 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7759 // If we are doing this while in the middle of updating a library apk, 7760 // then we need to make sure to use that new apk for determining the 7761 // dependencies here. (We haven't yet finished committing the new apk 7762 // to the package manager state.) 7763 if (p == null || p.packageName.equals(changingLib.packageName)) { 7764 p = changingLib; 7765 } 7766 } 7767 if (p != null) { 7768 usesLibraryFiles.addAll(p.getAllCodePaths()); 7769 } 7770 } 7771 7772 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7773 PackageParser.Package changingLib) throws PackageManagerException { 7774 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7775 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7776 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7777 for (int i=0; i<N; i++) { 7778 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7779 if (file == null) { 7780 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7781 "Package " + pkg.packageName + " requires unavailable shared library " 7782 + pkg.usesLibraries.get(i) + "; failing!"); 7783 } 7784 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7785 } 7786 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7787 for (int i=0; i<N; i++) { 7788 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7789 if (file == null) { 7790 Slog.w(TAG, "Package " + pkg.packageName 7791 + " desires unavailable shared library " 7792 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7793 } else { 7794 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7795 } 7796 } 7797 N = usesLibraryFiles.size(); 7798 if (N > 0) { 7799 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7800 } else { 7801 pkg.usesLibraryFiles = null; 7802 } 7803 } 7804 } 7805 7806 private static boolean hasString(List<String> list, List<String> which) { 7807 if (list == null) { 7808 return false; 7809 } 7810 for (int i=list.size()-1; i>=0; i--) { 7811 for (int j=which.size()-1; j>=0; j--) { 7812 if (which.get(j).equals(list.get(i))) { 7813 return true; 7814 } 7815 } 7816 } 7817 return false; 7818 } 7819 7820 private void updateAllSharedLibrariesLPw() { 7821 for (PackageParser.Package pkg : mPackages.values()) { 7822 try { 7823 updateSharedLibrariesLPw(pkg, null); 7824 } catch (PackageManagerException e) { 7825 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7826 } 7827 } 7828 } 7829 7830 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7831 PackageParser.Package changingPkg) { 7832 ArrayList<PackageParser.Package> res = null; 7833 for (PackageParser.Package pkg : mPackages.values()) { 7834 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7835 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7836 if (res == null) { 7837 res = new ArrayList<PackageParser.Package>(); 7838 } 7839 res.add(pkg); 7840 try { 7841 updateSharedLibrariesLPw(pkg, changingPkg); 7842 } catch (PackageManagerException e) { 7843 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7844 } 7845 } 7846 } 7847 return res; 7848 } 7849 7850 /** 7851 * Derive the value of the {@code cpuAbiOverride} based on the provided 7852 * value and an optional stored value from the package settings. 7853 */ 7854 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7855 String cpuAbiOverride = null; 7856 7857 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7858 cpuAbiOverride = null; 7859 } else if (abiOverride != null) { 7860 cpuAbiOverride = abiOverride; 7861 } else if (settings != null) { 7862 cpuAbiOverride = settings.cpuAbiOverrideString; 7863 } 7864 7865 return cpuAbiOverride; 7866 } 7867 7868 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7869 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7870 throws PackageManagerException { 7871 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7872 // If the package has children and this is the first dive in the function 7873 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7874 // whether all packages (parent and children) would be successfully scanned 7875 // before the actual scan since scanning mutates internal state and we want 7876 // to atomically install the package and its children. 7877 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7878 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7879 scanFlags |= SCAN_CHECK_ONLY; 7880 } 7881 } else { 7882 scanFlags &= ~SCAN_CHECK_ONLY; 7883 } 7884 7885 final PackageParser.Package scannedPkg; 7886 try { 7887 // Scan the parent 7888 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7889 // Scan the children 7890 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7891 for (int i = 0; i < childCount; i++) { 7892 PackageParser.Package childPkg = pkg.childPackages.get(i); 7893 scanPackageLI(childPkg, policyFlags, 7894 scanFlags, currentTime, user); 7895 } 7896 } finally { 7897 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7898 } 7899 7900 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7901 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7902 } 7903 7904 return scannedPkg; 7905 } 7906 7907 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7908 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7909 boolean success = false; 7910 try { 7911 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7912 currentTime, user); 7913 success = true; 7914 return res; 7915 } finally { 7916 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7917 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7918 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7919 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7920 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7921 } 7922 } 7923 } 7924 7925 /** 7926 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7927 */ 7928 private static boolean apkHasCode(String fileName) { 7929 StrictJarFile jarFile = null; 7930 try { 7931 jarFile = new StrictJarFile(fileName, 7932 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7933 return jarFile.findEntry("classes.dex") != null; 7934 } catch (IOException ignore) { 7935 } finally { 7936 try { 7937 if (jarFile != null) { 7938 jarFile.close(); 7939 } 7940 } catch (IOException ignore) {} 7941 } 7942 return false; 7943 } 7944 7945 /** 7946 * Enforces code policy for the package. This ensures that if an APK has 7947 * declared hasCode="true" in its manifest that the APK actually contains 7948 * code. 7949 * 7950 * @throws PackageManagerException If bytecode could not be found when it should exist 7951 */ 7952 private static void enforceCodePolicy(PackageParser.Package pkg) 7953 throws PackageManagerException { 7954 final boolean shouldHaveCode = 7955 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7956 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7957 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7958 "Package " + pkg.baseCodePath + " code is missing"); 7959 } 7960 7961 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7962 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7963 final boolean splitShouldHaveCode = 7964 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7965 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7966 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7967 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7968 } 7969 } 7970 } 7971 } 7972 7973 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7974 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7975 throws PackageManagerException { 7976 final File scanFile = new File(pkg.codePath); 7977 if (pkg.applicationInfo.getCodePath() == null || 7978 pkg.applicationInfo.getResourcePath() == null) { 7979 // Bail out. The resource and code paths haven't been set. 7980 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7981 "Code and resource paths haven't been set correctly"); 7982 } 7983 7984 // Apply policy 7985 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7986 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7987 if (pkg.applicationInfo.isDirectBootAware()) { 7988 // we're direct boot aware; set for all components 7989 for (PackageParser.Service s : pkg.services) { 7990 s.info.encryptionAware = s.info.directBootAware = true; 7991 } 7992 for (PackageParser.Provider p : pkg.providers) { 7993 p.info.encryptionAware = p.info.directBootAware = true; 7994 } 7995 for (PackageParser.Activity a : pkg.activities) { 7996 a.info.encryptionAware = a.info.directBootAware = true; 7997 } 7998 for (PackageParser.Activity r : pkg.receivers) { 7999 r.info.encryptionAware = r.info.directBootAware = true; 8000 } 8001 } 8002 } else { 8003 // Only allow system apps to be flagged as core apps. 8004 pkg.coreApp = false; 8005 // clear flags not applicable to regular apps 8006 pkg.applicationInfo.privateFlags &= 8007 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8008 pkg.applicationInfo.privateFlags &= 8009 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8010 } 8011 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8012 8013 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8014 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8015 } 8016 8017 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8018 enforceCodePolicy(pkg); 8019 } 8020 8021 if (mCustomResolverComponentName != null && 8022 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8023 setUpCustomResolverActivity(pkg); 8024 } 8025 8026 if (pkg.packageName.equals("android")) { 8027 synchronized (mPackages) { 8028 if (mAndroidApplication != null) { 8029 Slog.w(TAG, "*************************************************"); 8030 Slog.w(TAG, "Core android package being redefined. Skipping."); 8031 Slog.w(TAG, " file=" + scanFile); 8032 Slog.w(TAG, "*************************************************"); 8033 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8034 "Core android package being redefined. Skipping."); 8035 } 8036 8037 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8038 // Set up information for our fall-back user intent resolution activity. 8039 mPlatformPackage = pkg; 8040 pkg.mVersionCode = mSdkVersion; 8041 mAndroidApplication = pkg.applicationInfo; 8042 8043 if (!mResolverReplaced) { 8044 mResolveActivity.applicationInfo = mAndroidApplication; 8045 mResolveActivity.name = ResolverActivity.class.getName(); 8046 mResolveActivity.packageName = mAndroidApplication.packageName; 8047 mResolveActivity.processName = "system:ui"; 8048 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8049 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8050 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8051 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8052 mResolveActivity.exported = true; 8053 mResolveActivity.enabled = true; 8054 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8055 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8056 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8057 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8058 | ActivityInfo.CONFIG_ORIENTATION 8059 | ActivityInfo.CONFIG_KEYBOARD 8060 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8061 mResolveInfo.activityInfo = mResolveActivity; 8062 mResolveInfo.priority = 0; 8063 mResolveInfo.preferredOrder = 0; 8064 mResolveInfo.match = 0; 8065 mResolveComponentName = new ComponentName( 8066 mAndroidApplication.packageName, mResolveActivity.name); 8067 } 8068 } 8069 } 8070 } 8071 8072 if (DEBUG_PACKAGE_SCANNING) { 8073 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8074 Log.d(TAG, "Scanning package " + pkg.packageName); 8075 } 8076 8077 synchronized (mPackages) { 8078 if (mPackages.containsKey(pkg.packageName) 8079 || mSharedLibraries.containsKey(pkg.packageName)) { 8080 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8081 "Application package " + pkg.packageName 8082 + " already installed. Skipping duplicate."); 8083 } 8084 8085 // If we're only installing presumed-existing packages, require that the 8086 // scanned APK is both already known and at the path previously established 8087 // for it. Previously unknown packages we pick up normally, but if we have an 8088 // a priori expectation about this package's install presence, enforce it. 8089 // With a singular exception for new system packages. When an OTA contains 8090 // a new system package, we allow the codepath to change from a system location 8091 // to the user-installed location. If we don't allow this change, any newer, 8092 // user-installed version of the application will be ignored. 8093 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8094 if (mExpectingBetter.containsKey(pkg.packageName)) { 8095 logCriticalInfo(Log.WARN, 8096 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8097 } else { 8098 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8099 if (known != null) { 8100 if (DEBUG_PACKAGE_SCANNING) { 8101 Log.d(TAG, "Examining " + pkg.codePath 8102 + " and requiring known paths " + known.codePathString 8103 + " & " + known.resourcePathString); 8104 } 8105 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8106 || !pkg.applicationInfo.getResourcePath().equals( 8107 known.resourcePathString)) { 8108 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8109 "Application package " + pkg.packageName 8110 + " found at " + pkg.applicationInfo.getCodePath() 8111 + " but expected at " + known.codePathString 8112 + "; ignoring."); 8113 } 8114 } 8115 } 8116 } 8117 } 8118 8119 // Initialize package source and resource directories 8120 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8121 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8122 8123 SharedUserSetting suid = null; 8124 PackageSetting pkgSetting = null; 8125 8126 if (!isSystemApp(pkg)) { 8127 // Only system apps can use these features. 8128 pkg.mOriginalPackages = null; 8129 pkg.mRealPackage = null; 8130 pkg.mAdoptPermissions = null; 8131 } 8132 8133 // Getting the package setting may have a side-effect, so if we 8134 // are only checking if scan would succeed, stash a copy of the 8135 // old setting to restore at the end. 8136 PackageSetting nonMutatedPs = null; 8137 8138 // writer 8139 synchronized (mPackages) { 8140 if (pkg.mSharedUserId != null) { 8141 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8142 if (suid == null) { 8143 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8144 "Creating application package " + pkg.packageName 8145 + " for shared user failed"); 8146 } 8147 if (DEBUG_PACKAGE_SCANNING) { 8148 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8149 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8150 + "): packages=" + suid.packages); 8151 } 8152 } 8153 8154 // Check if we are renaming from an original package name. 8155 PackageSetting origPackage = null; 8156 String realName = null; 8157 if (pkg.mOriginalPackages != null) { 8158 // This package may need to be renamed to a previously 8159 // installed name. Let's check on that... 8160 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8161 if (pkg.mOriginalPackages.contains(renamed)) { 8162 // This package had originally been installed as the 8163 // original name, and we have already taken care of 8164 // transitioning to the new one. Just update the new 8165 // one to continue using the old name. 8166 realName = pkg.mRealPackage; 8167 if (!pkg.packageName.equals(renamed)) { 8168 // Callers into this function may have already taken 8169 // care of renaming the package; only do it here if 8170 // it is not already done. 8171 pkg.setPackageName(renamed); 8172 } 8173 8174 } else { 8175 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8176 if ((origPackage = mSettings.peekPackageLPr( 8177 pkg.mOriginalPackages.get(i))) != null) { 8178 // We do have the package already installed under its 8179 // original name... should we use it? 8180 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8181 // New package is not compatible with original. 8182 origPackage = null; 8183 continue; 8184 } else if (origPackage.sharedUser != null) { 8185 // Make sure uid is compatible between packages. 8186 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8187 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8188 + " to " + pkg.packageName + ": old uid " 8189 + origPackage.sharedUser.name 8190 + " differs from " + pkg.mSharedUserId); 8191 origPackage = null; 8192 continue; 8193 } 8194 // TODO: Add case when shared user id is added [b/28144775] 8195 } else { 8196 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8197 + pkg.packageName + " to old name " + origPackage.name); 8198 } 8199 break; 8200 } 8201 } 8202 } 8203 } 8204 8205 if (mTransferedPackages.contains(pkg.packageName)) { 8206 Slog.w(TAG, "Package " + pkg.packageName 8207 + " was transferred to another, but its .apk remains"); 8208 } 8209 8210 // See comments in nonMutatedPs declaration 8211 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8212 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8213 if (foundPs != null) { 8214 nonMutatedPs = new PackageSetting(foundPs); 8215 } 8216 } 8217 8218 // Just create the setting, don't add it yet. For already existing packages 8219 // the PkgSetting exists already and doesn't have to be created. 8220 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8221 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8222 pkg.applicationInfo.primaryCpuAbi, 8223 pkg.applicationInfo.secondaryCpuAbi, 8224 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8225 user, false); 8226 if (pkgSetting == null) { 8227 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8228 "Creating application package " + pkg.packageName + " failed"); 8229 } 8230 8231 if (pkgSetting.origPackage != null) { 8232 // If we are first transitioning from an original package, 8233 // fix up the new package's name now. We need to do this after 8234 // looking up the package under its new name, so getPackageLP 8235 // can take care of fiddling things correctly. 8236 pkg.setPackageName(origPackage.name); 8237 8238 // File a report about this. 8239 String msg = "New package " + pkgSetting.realName 8240 + " renamed to replace old package " + pkgSetting.name; 8241 reportSettingsProblem(Log.WARN, msg); 8242 8243 // Make a note of it. 8244 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8245 mTransferedPackages.add(origPackage.name); 8246 } 8247 8248 // No longer need to retain this. 8249 pkgSetting.origPackage = null; 8250 } 8251 8252 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8253 // Make a note of it. 8254 mTransferedPackages.add(pkg.packageName); 8255 } 8256 8257 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8258 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8259 } 8260 8261 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8262 // Check all shared libraries and map to their actual file path. 8263 // We only do this here for apps not on a system dir, because those 8264 // are the only ones that can fail an install due to this. We 8265 // will take care of the system apps by updating all of their 8266 // library paths after the scan is done. 8267 updateSharedLibrariesLPw(pkg, null); 8268 } 8269 8270 if (mFoundPolicyFile) { 8271 SELinuxMMAC.assignSeinfoValue(pkg); 8272 } 8273 8274 pkg.applicationInfo.uid = pkgSetting.appId; 8275 pkg.mExtras = pkgSetting; 8276 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8277 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8278 // We just determined the app is signed correctly, so bring 8279 // over the latest parsed certs. 8280 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8281 } else { 8282 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8283 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8284 "Package " + pkg.packageName + " upgrade keys do not match the " 8285 + "previously installed version"); 8286 } else { 8287 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8288 String msg = "System package " + pkg.packageName 8289 + " signature changed; retaining data."; 8290 reportSettingsProblem(Log.WARN, msg); 8291 } 8292 } 8293 } else { 8294 try { 8295 verifySignaturesLP(pkgSetting, pkg); 8296 // We just determined the app is signed correctly, so bring 8297 // over the latest parsed certs. 8298 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8299 } catch (PackageManagerException e) { 8300 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8301 throw e; 8302 } 8303 // The signature has changed, but this package is in the system 8304 // image... let's recover! 8305 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8306 // However... if this package is part of a shared user, but it 8307 // doesn't match the signature of the shared user, let's fail. 8308 // What this means is that you can't change the signatures 8309 // associated with an overall shared user, which doesn't seem all 8310 // that unreasonable. 8311 if (pkgSetting.sharedUser != null) { 8312 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8313 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8314 throw new PackageManagerException( 8315 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8316 "Signature mismatch for shared user: " 8317 + pkgSetting.sharedUser); 8318 } 8319 } 8320 // File a report about this. 8321 String msg = "System package " + pkg.packageName 8322 + " signature changed; retaining data."; 8323 reportSettingsProblem(Log.WARN, msg); 8324 } 8325 } 8326 // Verify that this new package doesn't have any content providers 8327 // that conflict with existing packages. Only do this if the 8328 // package isn't already installed, since we don't want to break 8329 // things that are installed. 8330 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8331 final int N = pkg.providers.size(); 8332 int i; 8333 for (i=0; i<N; i++) { 8334 PackageParser.Provider p = pkg.providers.get(i); 8335 if (p.info.authority != null) { 8336 String names[] = p.info.authority.split(";"); 8337 for (int j = 0; j < names.length; j++) { 8338 if (mProvidersByAuthority.containsKey(names[j])) { 8339 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8340 final String otherPackageName = 8341 ((other != null && other.getComponentName() != null) ? 8342 other.getComponentName().getPackageName() : "?"); 8343 throw new PackageManagerException( 8344 INSTALL_FAILED_CONFLICTING_PROVIDER, 8345 "Can't install because provider name " + names[j] 8346 + " (in package " + pkg.applicationInfo.packageName 8347 + ") is already used by " + otherPackageName); 8348 } 8349 } 8350 } 8351 } 8352 } 8353 8354 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8355 // This package wants to adopt ownership of permissions from 8356 // another package. 8357 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8358 final String origName = pkg.mAdoptPermissions.get(i); 8359 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8360 if (orig != null) { 8361 if (verifyPackageUpdateLPr(orig, pkg)) { 8362 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8363 + pkg.packageName); 8364 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8365 } 8366 } 8367 } 8368 } 8369 } 8370 8371 final String pkgName = pkg.packageName; 8372 8373 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8374 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8375 pkg.applicationInfo.processName = fixProcessName( 8376 pkg.applicationInfo.packageName, 8377 pkg.applicationInfo.processName, 8378 pkg.applicationInfo.uid); 8379 8380 if (pkg != mPlatformPackage) { 8381 // Get all of our default paths setup 8382 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8383 } 8384 8385 final String path = scanFile.getPath(); 8386 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8387 8388 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8389 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8390 8391 // Some system apps still use directory structure for native libraries 8392 // in which case we might end up not detecting abi solely based on apk 8393 // structure. Try to detect abi based on directory structure. 8394 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8395 pkg.applicationInfo.primaryCpuAbi == null) { 8396 setBundledAppAbisAndRoots(pkg, pkgSetting); 8397 setNativeLibraryPaths(pkg); 8398 } 8399 8400 } else { 8401 if ((scanFlags & SCAN_MOVE) != 0) { 8402 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8403 // but we already have this packages package info in the PackageSetting. We just 8404 // use that and derive the native library path based on the new codepath. 8405 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8406 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8407 } 8408 8409 // Set native library paths again. For moves, the path will be updated based on the 8410 // ABIs we've determined above. For non-moves, the path will be updated based on the 8411 // ABIs we determined during compilation, but the path will depend on the final 8412 // package path (after the rename away from the stage path). 8413 setNativeLibraryPaths(pkg); 8414 } 8415 8416 // This is a special case for the "system" package, where the ABI is 8417 // dictated by the zygote configuration (and init.rc). We should keep track 8418 // of this ABI so that we can deal with "normal" applications that run under 8419 // the same UID correctly. 8420 if (mPlatformPackage == pkg) { 8421 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8422 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8423 } 8424 8425 // If there's a mismatch between the abi-override in the package setting 8426 // and the abiOverride specified for the install. Warn about this because we 8427 // would've already compiled the app without taking the package setting into 8428 // account. 8429 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8430 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8431 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8432 " for package " + pkg.packageName); 8433 } 8434 } 8435 8436 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8437 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8438 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8439 8440 // Copy the derived override back to the parsed package, so that we can 8441 // update the package settings accordingly. 8442 pkg.cpuAbiOverride = cpuAbiOverride; 8443 8444 if (DEBUG_ABI_SELECTION) { 8445 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8446 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8447 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8448 } 8449 8450 // Push the derived path down into PackageSettings so we know what to 8451 // clean up at uninstall time. 8452 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8453 8454 if (DEBUG_ABI_SELECTION) { 8455 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8456 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8457 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8458 } 8459 8460 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8461 // We don't do this here during boot because we can do it all 8462 // at once after scanning all existing packages. 8463 // 8464 // We also do this *before* we perform dexopt on this package, so that 8465 // we can avoid redundant dexopts, and also to make sure we've got the 8466 // code and package path correct. 8467 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8468 pkg, true /* boot complete */); 8469 } 8470 8471 if (mFactoryTest && pkg.requestedPermissions.contains( 8472 android.Manifest.permission.FACTORY_TEST)) { 8473 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8474 } 8475 8476 if (isSystemApp(pkg)) { 8477 pkgSetting.isOrphaned = true; 8478 } 8479 8480 ArrayList<PackageParser.Package> clientLibPkgs = null; 8481 8482 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8483 if (nonMutatedPs != null) { 8484 synchronized (mPackages) { 8485 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8486 } 8487 } 8488 return pkg; 8489 } 8490 8491 // Only privileged apps and updated privileged apps can add child packages. 8492 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8493 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8494 throw new PackageManagerException("Only privileged apps and updated " 8495 + "privileged apps can add child packages. Ignoring package " 8496 + pkg.packageName); 8497 } 8498 final int childCount = pkg.childPackages.size(); 8499 for (int i = 0; i < childCount; i++) { 8500 PackageParser.Package childPkg = pkg.childPackages.get(i); 8501 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8502 childPkg.packageName)) { 8503 throw new PackageManagerException("Cannot override a child package of " 8504 + "another disabled system app. Ignoring package " + pkg.packageName); 8505 } 8506 } 8507 } 8508 8509 // writer 8510 synchronized (mPackages) { 8511 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8512 // Only system apps can add new shared libraries. 8513 if (pkg.libraryNames != null) { 8514 for (int i=0; i<pkg.libraryNames.size(); i++) { 8515 String name = pkg.libraryNames.get(i); 8516 boolean allowed = false; 8517 if (pkg.isUpdatedSystemApp()) { 8518 // New library entries can only be added through the 8519 // system image. This is important to get rid of a lot 8520 // of nasty edge cases: for example if we allowed a non- 8521 // system update of the app to add a library, then uninstalling 8522 // the update would make the library go away, and assumptions 8523 // we made such as through app install filtering would now 8524 // have allowed apps on the device which aren't compatible 8525 // with it. Better to just have the restriction here, be 8526 // conservative, and create many fewer cases that can negatively 8527 // impact the user experience. 8528 final PackageSetting sysPs = mSettings 8529 .getDisabledSystemPkgLPr(pkg.packageName); 8530 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8531 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8532 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8533 allowed = true; 8534 break; 8535 } 8536 } 8537 } 8538 } else { 8539 allowed = true; 8540 } 8541 if (allowed) { 8542 if (!mSharedLibraries.containsKey(name)) { 8543 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8544 } else if (!name.equals(pkg.packageName)) { 8545 Slog.w(TAG, "Package " + pkg.packageName + " library " 8546 + name + " already exists; skipping"); 8547 } 8548 } else { 8549 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8550 + name + " that is not declared on system image; skipping"); 8551 } 8552 } 8553 if ((scanFlags & SCAN_BOOTING) == 0) { 8554 // If we are not booting, we need to update any applications 8555 // that are clients of our shared library. If we are booting, 8556 // this will all be done once the scan is complete. 8557 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8558 } 8559 } 8560 } 8561 } 8562 8563 if ((scanFlags & SCAN_BOOTING) != 0) { 8564 // No apps can run during boot scan, so they don't need to be frozen 8565 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8566 // Caller asked to not kill app, so it's probably not frozen 8567 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8568 // Caller asked us to ignore frozen check for some reason; they 8569 // probably didn't know the package name 8570 } else { 8571 // We're doing major surgery on this package, so it better be frozen 8572 // right now to keep it from launching 8573 checkPackageFrozen(pkgName); 8574 } 8575 8576 // Also need to kill any apps that are dependent on the library. 8577 if (clientLibPkgs != null) { 8578 for (int i=0; i<clientLibPkgs.size(); i++) { 8579 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8580 killApplication(clientPkg.applicationInfo.packageName, 8581 clientPkg.applicationInfo.uid, "update lib"); 8582 } 8583 } 8584 8585 // Make sure we're not adding any bogus keyset info 8586 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8587 ksms.assertScannedPackageValid(pkg); 8588 8589 // writer 8590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8591 8592 boolean createIdmapFailed = false; 8593 synchronized (mPackages) { 8594 // We don't expect installation to fail beyond this point 8595 8596 if (pkgSetting.pkg != null) { 8597 // Note that |user| might be null during the initial boot scan. If a codePath 8598 // for an app has changed during a boot scan, it's due to an app update that's 8599 // part of the system partition and marker changes must be applied to all users. 8600 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8601 (user != null) ? user : UserHandle.ALL); 8602 } 8603 8604 // Add the new setting to mSettings 8605 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8606 // Add the new setting to mPackages 8607 mPackages.put(pkg.applicationInfo.packageName, pkg); 8608 // Make sure we don't accidentally delete its data. 8609 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8610 while (iter.hasNext()) { 8611 PackageCleanItem item = iter.next(); 8612 if (pkgName.equals(item.packageName)) { 8613 iter.remove(); 8614 } 8615 } 8616 8617 // Take care of first install / last update times. 8618 if (currentTime != 0) { 8619 if (pkgSetting.firstInstallTime == 0) { 8620 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8621 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8622 pkgSetting.lastUpdateTime = currentTime; 8623 } 8624 } else if (pkgSetting.firstInstallTime == 0) { 8625 // We need *something*. Take time time stamp of the file. 8626 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8627 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8628 if (scanFileTime != pkgSetting.timeStamp) { 8629 // A package on the system image has changed; consider this 8630 // to be an update. 8631 pkgSetting.lastUpdateTime = scanFileTime; 8632 } 8633 } 8634 8635 // Add the package's KeySets to the global KeySetManagerService 8636 ksms.addScannedPackageLPw(pkg); 8637 8638 int N = pkg.providers.size(); 8639 StringBuilder r = null; 8640 int i; 8641 for (i=0; i<N; i++) { 8642 PackageParser.Provider p = pkg.providers.get(i); 8643 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8644 p.info.processName, pkg.applicationInfo.uid); 8645 mProviders.addProvider(p); 8646 p.syncable = p.info.isSyncable; 8647 if (p.info.authority != null) { 8648 String names[] = p.info.authority.split(";"); 8649 p.info.authority = null; 8650 for (int j = 0; j < names.length; j++) { 8651 if (j == 1 && p.syncable) { 8652 // We only want the first authority for a provider to possibly be 8653 // syncable, so if we already added this provider using a different 8654 // authority clear the syncable flag. We copy the provider before 8655 // changing it because the mProviders object contains a reference 8656 // to a provider that we don't want to change. 8657 // Only do this for the second authority since the resulting provider 8658 // object can be the same for all future authorities for this provider. 8659 p = new PackageParser.Provider(p); 8660 p.syncable = false; 8661 } 8662 if (!mProvidersByAuthority.containsKey(names[j])) { 8663 mProvidersByAuthority.put(names[j], p); 8664 if (p.info.authority == null) { 8665 p.info.authority = names[j]; 8666 } else { 8667 p.info.authority = p.info.authority + ";" + names[j]; 8668 } 8669 if (DEBUG_PACKAGE_SCANNING) { 8670 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8671 Log.d(TAG, "Registered content provider: " + names[j] 8672 + ", className = " + p.info.name + ", isSyncable = " 8673 + p.info.isSyncable); 8674 } 8675 } else { 8676 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8677 Slog.w(TAG, "Skipping provider name " + names[j] + 8678 " (in package " + pkg.applicationInfo.packageName + 8679 "): name already used by " 8680 + ((other != null && other.getComponentName() != null) 8681 ? other.getComponentName().getPackageName() : "?")); 8682 } 8683 } 8684 } 8685 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8686 if (r == null) { 8687 r = new StringBuilder(256); 8688 } else { 8689 r.append(' '); 8690 } 8691 r.append(p.info.name); 8692 } 8693 } 8694 if (r != null) { 8695 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8696 } 8697 8698 N = pkg.services.size(); 8699 r = null; 8700 for (i=0; i<N; i++) { 8701 PackageParser.Service s = pkg.services.get(i); 8702 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8703 s.info.processName, pkg.applicationInfo.uid); 8704 mServices.addService(s); 8705 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8706 if (r == null) { 8707 r = new StringBuilder(256); 8708 } else { 8709 r.append(' '); 8710 } 8711 r.append(s.info.name); 8712 } 8713 } 8714 if (r != null) { 8715 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8716 } 8717 8718 N = pkg.receivers.size(); 8719 r = null; 8720 for (i=0; i<N; i++) { 8721 PackageParser.Activity a = pkg.receivers.get(i); 8722 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8723 a.info.processName, pkg.applicationInfo.uid); 8724 mReceivers.addActivity(a, "receiver"); 8725 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8726 if (r == null) { 8727 r = new StringBuilder(256); 8728 } else { 8729 r.append(' '); 8730 } 8731 r.append(a.info.name); 8732 } 8733 } 8734 if (r != null) { 8735 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8736 } 8737 8738 N = pkg.activities.size(); 8739 r = null; 8740 for (i=0; i<N; i++) { 8741 PackageParser.Activity a = pkg.activities.get(i); 8742 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8743 a.info.processName, pkg.applicationInfo.uid); 8744 mActivities.addActivity(a, "activity"); 8745 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8746 if (r == null) { 8747 r = new StringBuilder(256); 8748 } else { 8749 r.append(' '); 8750 } 8751 r.append(a.info.name); 8752 } 8753 } 8754 if (r != null) { 8755 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8756 } 8757 8758 N = pkg.permissionGroups.size(); 8759 r = null; 8760 for (i=0; i<N; i++) { 8761 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8762 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8763 final String curPackageName = cur == null ? null : cur.info.packageName; 8764 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8765 if (cur == null || isPackageUpdate) { 8766 mPermissionGroups.put(pg.info.name, pg); 8767 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8768 if (r == null) { 8769 r = new StringBuilder(256); 8770 } else { 8771 r.append(' '); 8772 } 8773 if (isPackageUpdate) { 8774 r.append("UPD:"); 8775 } 8776 r.append(pg.info.name); 8777 } 8778 } else { 8779 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8780 + pg.info.packageName + " ignored: original from " 8781 + cur.info.packageName); 8782 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8783 if (r == null) { 8784 r = new StringBuilder(256); 8785 } else { 8786 r.append(' '); 8787 } 8788 r.append("DUP:"); 8789 r.append(pg.info.name); 8790 } 8791 } 8792 } 8793 if (r != null) { 8794 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8795 } 8796 8797 N = pkg.permissions.size(); 8798 r = null; 8799 for (i=0; i<N; i++) { 8800 PackageParser.Permission p = pkg.permissions.get(i); 8801 8802 // Assume by default that we did not install this permission into the system. 8803 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8804 8805 // Now that permission groups have a special meaning, we ignore permission 8806 // groups for legacy apps to prevent unexpected behavior. In particular, 8807 // permissions for one app being granted to someone just becase they happen 8808 // to be in a group defined by another app (before this had no implications). 8809 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8810 p.group = mPermissionGroups.get(p.info.group); 8811 // Warn for a permission in an unknown group. 8812 if (p.info.group != null && p.group == null) { 8813 Slog.w(TAG, "Permission " + p.info.name + " from package " 8814 + p.info.packageName + " in an unknown group " + p.info.group); 8815 } 8816 } 8817 8818 ArrayMap<String, BasePermission> permissionMap = 8819 p.tree ? mSettings.mPermissionTrees 8820 : mSettings.mPermissions; 8821 BasePermission bp = permissionMap.get(p.info.name); 8822 8823 // Allow system apps to redefine non-system permissions 8824 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8825 final boolean currentOwnerIsSystem = (bp.perm != null 8826 && isSystemApp(bp.perm.owner)); 8827 if (isSystemApp(p.owner)) { 8828 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8829 // It's a built-in permission and no owner, take ownership now 8830 bp.packageSetting = pkgSetting; 8831 bp.perm = p; 8832 bp.uid = pkg.applicationInfo.uid; 8833 bp.sourcePackage = p.info.packageName; 8834 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8835 } else if (!currentOwnerIsSystem) { 8836 String msg = "New decl " + p.owner + " of permission " 8837 + p.info.name + " is system; overriding " + bp.sourcePackage; 8838 reportSettingsProblem(Log.WARN, msg); 8839 bp = null; 8840 } 8841 } 8842 } 8843 8844 if (bp == null) { 8845 bp = new BasePermission(p.info.name, p.info.packageName, 8846 BasePermission.TYPE_NORMAL); 8847 permissionMap.put(p.info.name, bp); 8848 } 8849 8850 if (bp.perm == null) { 8851 if (bp.sourcePackage == null 8852 || bp.sourcePackage.equals(p.info.packageName)) { 8853 BasePermission tree = findPermissionTreeLP(p.info.name); 8854 if (tree == null 8855 || tree.sourcePackage.equals(p.info.packageName)) { 8856 bp.packageSetting = pkgSetting; 8857 bp.perm = p; 8858 bp.uid = pkg.applicationInfo.uid; 8859 bp.sourcePackage = p.info.packageName; 8860 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8861 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8862 if (r == null) { 8863 r = new StringBuilder(256); 8864 } else { 8865 r.append(' '); 8866 } 8867 r.append(p.info.name); 8868 } 8869 } else { 8870 Slog.w(TAG, "Permission " + p.info.name + " from package " 8871 + p.info.packageName + " ignored: base tree " 8872 + tree.name + " is from package " 8873 + tree.sourcePackage); 8874 } 8875 } else { 8876 Slog.w(TAG, "Permission " + p.info.name + " from package " 8877 + p.info.packageName + " ignored: original from " 8878 + bp.sourcePackage); 8879 } 8880 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8881 if (r == null) { 8882 r = new StringBuilder(256); 8883 } else { 8884 r.append(' '); 8885 } 8886 r.append("DUP:"); 8887 r.append(p.info.name); 8888 } 8889 if (bp.perm == p) { 8890 bp.protectionLevel = p.info.protectionLevel; 8891 } 8892 } 8893 8894 if (r != null) { 8895 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8896 } 8897 8898 N = pkg.instrumentation.size(); 8899 r = null; 8900 for (i=0; i<N; i++) { 8901 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8902 a.info.packageName = pkg.applicationInfo.packageName; 8903 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8904 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8905 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8906 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8907 a.info.dataDir = pkg.applicationInfo.dataDir; 8908 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8909 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8910 8911 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8912 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8913 mInstrumentation.put(a.getComponentName(), a); 8914 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8915 if (r == null) { 8916 r = new StringBuilder(256); 8917 } else { 8918 r.append(' '); 8919 } 8920 r.append(a.info.name); 8921 } 8922 } 8923 if (r != null) { 8924 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8925 } 8926 8927 if (pkg.protectedBroadcasts != null) { 8928 N = pkg.protectedBroadcasts.size(); 8929 for (i=0; i<N; i++) { 8930 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8931 } 8932 } 8933 8934 pkgSetting.setTimeStamp(scanFileTime); 8935 8936 // Create idmap files for pairs of (packages, overlay packages). 8937 // Note: "android", ie framework-res.apk, is handled by native layers. 8938 if (pkg.mOverlayTarget != null) { 8939 // This is an overlay package. 8940 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8941 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8942 mOverlays.put(pkg.mOverlayTarget, 8943 new ArrayMap<String, PackageParser.Package>()); 8944 } 8945 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8946 map.put(pkg.packageName, pkg); 8947 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8948 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8949 createIdmapFailed = true; 8950 } 8951 } 8952 } else if (mOverlays.containsKey(pkg.packageName) && 8953 !pkg.packageName.equals("android")) { 8954 // This is a regular package, with one or more known overlay packages. 8955 createIdmapsForPackageLI(pkg); 8956 } 8957 } 8958 8959 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8960 8961 if (createIdmapFailed) { 8962 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8963 "scanPackageLI failed to createIdmap"); 8964 } 8965 return pkg; 8966 } 8967 8968 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8969 PackageParser.Package update, UserHandle user) { 8970 if (existing.applicationInfo == null || update.applicationInfo == null) { 8971 // This isn't due to an app installation. 8972 return; 8973 } 8974 8975 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8976 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8977 8978 // The codePath hasn't changed, so there's nothing for us to do. 8979 if (Objects.equals(oldCodePath, newCodePath)) { 8980 return; 8981 } 8982 8983 File canonicalNewCodePath; 8984 try { 8985 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8986 } catch (IOException e) { 8987 Slog.w(TAG, "Failed to get canonical path.", e); 8988 return; 8989 } 8990 8991 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8992 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8993 // that the last component of the path (i.e, the name) doesn't need canonicalization 8994 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8995 // but may change in the future. Hopefully this function won't exist at that point. 8996 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8997 oldCodePath.getName()); 8998 8999 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9000 // with "@". 9001 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9002 if (!oldMarkerPrefix.endsWith("@")) { 9003 oldMarkerPrefix += "@"; 9004 } 9005 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9006 if (!newMarkerPrefix.endsWith("@")) { 9007 newMarkerPrefix += "@"; 9008 } 9009 9010 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9011 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9012 for (String updatedPath : updatedPaths) { 9013 String updatedPathName = new File(updatedPath).getName(); 9014 markerSuffixes.add(updatedPathName.replace('/', '@')); 9015 } 9016 9017 for (int userId : resolveUserIds(user.getIdentifier())) { 9018 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9019 9020 for (String markerSuffix : markerSuffixes) { 9021 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9022 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9023 if (oldForeignUseMark.exists()) { 9024 try { 9025 Os.rename(oldForeignUseMark.getAbsolutePath(), 9026 newForeignUseMark.getAbsolutePath()); 9027 } catch (ErrnoException e) { 9028 Slog.w(TAG, "Failed to rename foreign use marker", e); 9029 oldForeignUseMark.delete(); 9030 } 9031 } 9032 } 9033 } 9034 } 9035 9036 /** 9037 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9038 * is derived purely on the basis of the contents of {@code scanFile} and 9039 * {@code cpuAbiOverride}. 9040 * 9041 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9042 */ 9043 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9044 String cpuAbiOverride, boolean extractLibs) 9045 throws PackageManagerException { 9046 // TODO: We can probably be smarter about this stuff. For installed apps, 9047 // we can calculate this information at install time once and for all. For 9048 // system apps, we can probably assume that this information doesn't change 9049 // after the first boot scan. As things stand, we do lots of unnecessary work. 9050 9051 // Give ourselves some initial paths; we'll come back for another 9052 // pass once we've determined ABI below. 9053 setNativeLibraryPaths(pkg); 9054 9055 // We would never need to extract libs for forward-locked and external packages, 9056 // since the container service will do it for us. We shouldn't attempt to 9057 // extract libs from system app when it was not updated. 9058 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9059 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9060 extractLibs = false; 9061 } 9062 9063 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9064 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9065 9066 NativeLibraryHelper.Handle handle = null; 9067 try { 9068 handle = NativeLibraryHelper.Handle.create(pkg); 9069 // TODO(multiArch): This can be null for apps that didn't go through the 9070 // usual installation process. We can calculate it again, like we 9071 // do during install time. 9072 // 9073 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9074 // unnecessary. 9075 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9076 9077 // Null out the abis so that they can be recalculated. 9078 pkg.applicationInfo.primaryCpuAbi = null; 9079 pkg.applicationInfo.secondaryCpuAbi = null; 9080 if (isMultiArch(pkg.applicationInfo)) { 9081 // Warn if we've set an abiOverride for multi-lib packages.. 9082 // By definition, we need to copy both 32 and 64 bit libraries for 9083 // such packages. 9084 if (pkg.cpuAbiOverride != null 9085 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9086 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9087 } 9088 9089 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9090 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9091 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9092 if (extractLibs) { 9093 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9094 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9095 useIsaSpecificSubdirs); 9096 } else { 9097 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9098 } 9099 } 9100 9101 maybeThrowExceptionForMultiArchCopy( 9102 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9103 9104 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9105 if (extractLibs) { 9106 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9107 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9108 useIsaSpecificSubdirs); 9109 } else { 9110 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9111 } 9112 } 9113 9114 maybeThrowExceptionForMultiArchCopy( 9115 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9116 9117 if (abi64 >= 0) { 9118 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9119 } 9120 9121 if (abi32 >= 0) { 9122 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9123 if (abi64 >= 0) { 9124 if (pkg.use32bitAbi) { 9125 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9126 pkg.applicationInfo.primaryCpuAbi = abi; 9127 } else { 9128 pkg.applicationInfo.secondaryCpuAbi = abi; 9129 } 9130 } else { 9131 pkg.applicationInfo.primaryCpuAbi = abi; 9132 } 9133 } 9134 9135 } else { 9136 String[] abiList = (cpuAbiOverride != null) ? 9137 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9138 9139 // Enable gross and lame hacks for apps that are built with old 9140 // SDK tools. We must scan their APKs for renderscript bitcode and 9141 // not launch them if it's present. Don't bother checking on devices 9142 // that don't have 64 bit support. 9143 boolean needsRenderScriptOverride = false; 9144 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9145 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9146 abiList = Build.SUPPORTED_32_BIT_ABIS; 9147 needsRenderScriptOverride = true; 9148 } 9149 9150 final int copyRet; 9151 if (extractLibs) { 9152 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9153 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9154 } else { 9155 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9156 } 9157 9158 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9159 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9160 "Error unpackaging native libs for app, errorCode=" + copyRet); 9161 } 9162 9163 if (copyRet >= 0) { 9164 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9165 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9166 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9167 } else if (needsRenderScriptOverride) { 9168 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9169 } 9170 } 9171 } catch (IOException ioe) { 9172 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9173 } finally { 9174 IoUtils.closeQuietly(handle); 9175 } 9176 9177 // Now that we've calculated the ABIs and determined if it's an internal app, 9178 // we will go ahead and populate the nativeLibraryPath. 9179 setNativeLibraryPaths(pkg); 9180 } 9181 9182 /** 9183 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9184 * i.e, so that all packages can be run inside a single process if required. 9185 * 9186 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9187 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9188 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9189 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9190 * updating a package that belongs to a shared user. 9191 * 9192 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9193 * adds unnecessary complexity. 9194 */ 9195 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9196 PackageParser.Package scannedPackage, boolean bootComplete) { 9197 String requiredInstructionSet = null; 9198 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9199 requiredInstructionSet = VMRuntime.getInstructionSet( 9200 scannedPackage.applicationInfo.primaryCpuAbi); 9201 } 9202 9203 PackageSetting requirer = null; 9204 for (PackageSetting ps : packagesForUser) { 9205 // If packagesForUser contains scannedPackage, we skip it. This will happen 9206 // when scannedPackage is an update of an existing package. Without this check, 9207 // we will never be able to change the ABI of any package belonging to a shared 9208 // user, even if it's compatible with other packages. 9209 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9210 if (ps.primaryCpuAbiString == null) { 9211 continue; 9212 } 9213 9214 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9215 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9216 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9217 // this but there's not much we can do. 9218 String errorMessage = "Instruction set mismatch, " 9219 + ((requirer == null) ? "[caller]" : requirer) 9220 + " requires " + requiredInstructionSet + " whereas " + ps 9221 + " requires " + instructionSet; 9222 Slog.w(TAG, errorMessage); 9223 } 9224 9225 if (requiredInstructionSet == null) { 9226 requiredInstructionSet = instructionSet; 9227 requirer = ps; 9228 } 9229 } 9230 } 9231 9232 if (requiredInstructionSet != null) { 9233 String adjustedAbi; 9234 if (requirer != null) { 9235 // requirer != null implies that either scannedPackage was null or that scannedPackage 9236 // did not require an ABI, in which case we have to adjust scannedPackage to match 9237 // the ABI of the set (which is the same as requirer's ABI) 9238 adjustedAbi = requirer.primaryCpuAbiString; 9239 if (scannedPackage != null) { 9240 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9241 } 9242 } else { 9243 // requirer == null implies that we're updating all ABIs in the set to 9244 // match scannedPackage. 9245 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9246 } 9247 9248 for (PackageSetting ps : packagesForUser) { 9249 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9250 if (ps.primaryCpuAbiString != null) { 9251 continue; 9252 } 9253 9254 ps.primaryCpuAbiString = adjustedAbi; 9255 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9256 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9257 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9258 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9259 + " (requirer=" 9260 + (requirer == null ? "null" : requirer.pkg.packageName) 9261 + ", scannedPackage=" 9262 + (scannedPackage != null ? scannedPackage.packageName : "null") 9263 + ")"); 9264 try { 9265 mInstaller.rmdex(ps.codePathString, 9266 getDexCodeInstructionSet(getPreferredInstructionSet())); 9267 } catch (InstallerException ignored) { 9268 } 9269 } 9270 } 9271 } 9272 } 9273 } 9274 9275 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9276 synchronized (mPackages) { 9277 mResolverReplaced = true; 9278 // Set up information for custom user intent resolution activity. 9279 mResolveActivity.applicationInfo = pkg.applicationInfo; 9280 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9281 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9282 mResolveActivity.processName = pkg.applicationInfo.packageName; 9283 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9284 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9285 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9286 mResolveActivity.theme = 0; 9287 mResolveActivity.exported = true; 9288 mResolveActivity.enabled = true; 9289 mResolveInfo.activityInfo = mResolveActivity; 9290 mResolveInfo.priority = 0; 9291 mResolveInfo.preferredOrder = 0; 9292 mResolveInfo.match = 0; 9293 mResolveComponentName = mCustomResolverComponentName; 9294 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9295 mResolveComponentName); 9296 } 9297 } 9298 9299 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9300 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9301 9302 // Set up information for ephemeral installer activity 9303 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9304 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9305 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9306 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9307 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9308 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9309 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9310 mEphemeralInstallerActivity.theme = 0; 9311 mEphemeralInstallerActivity.exported = true; 9312 mEphemeralInstallerActivity.enabled = true; 9313 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9314 mEphemeralInstallerInfo.priority = 0; 9315 mEphemeralInstallerInfo.preferredOrder = 1; 9316 mEphemeralInstallerInfo.isDefault = true; 9317 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9318 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9319 9320 if (DEBUG_EPHEMERAL) { 9321 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9322 } 9323 } 9324 9325 private static String calculateBundledApkRoot(final String codePathString) { 9326 final File codePath = new File(codePathString); 9327 final File codeRoot; 9328 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9329 codeRoot = Environment.getRootDirectory(); 9330 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9331 codeRoot = Environment.getOemDirectory(); 9332 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9333 codeRoot = Environment.getVendorDirectory(); 9334 } else { 9335 // Unrecognized code path; take its top real segment as the apk root: 9336 // e.g. /something/app/blah.apk => /something 9337 try { 9338 File f = codePath.getCanonicalFile(); 9339 File parent = f.getParentFile(); // non-null because codePath is a file 9340 File tmp; 9341 while ((tmp = parent.getParentFile()) != null) { 9342 f = parent; 9343 parent = tmp; 9344 } 9345 codeRoot = f; 9346 Slog.w(TAG, "Unrecognized code path " 9347 + codePath + " - using " + codeRoot); 9348 } catch (IOException e) { 9349 // Can't canonicalize the code path -- shenanigans? 9350 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9351 return Environment.getRootDirectory().getPath(); 9352 } 9353 } 9354 return codeRoot.getPath(); 9355 } 9356 9357 /** 9358 * Derive and set the location of native libraries for the given package, 9359 * which varies depending on where and how the package was installed. 9360 */ 9361 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9362 final ApplicationInfo info = pkg.applicationInfo; 9363 final String codePath = pkg.codePath; 9364 final File codeFile = new File(codePath); 9365 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9366 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9367 9368 info.nativeLibraryRootDir = null; 9369 info.nativeLibraryRootRequiresIsa = false; 9370 info.nativeLibraryDir = null; 9371 info.secondaryNativeLibraryDir = null; 9372 9373 if (isApkFile(codeFile)) { 9374 // Monolithic install 9375 if (bundledApp) { 9376 // If "/system/lib64/apkname" exists, assume that is the per-package 9377 // native library directory to use; otherwise use "/system/lib/apkname". 9378 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9379 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9380 getPrimaryInstructionSet(info)); 9381 9382 // This is a bundled system app so choose the path based on the ABI. 9383 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9384 // is just the default path. 9385 final String apkName = deriveCodePathName(codePath); 9386 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9387 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9388 apkName).getAbsolutePath(); 9389 9390 if (info.secondaryCpuAbi != null) { 9391 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9392 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9393 secondaryLibDir, apkName).getAbsolutePath(); 9394 } 9395 } else if (asecApp) { 9396 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9397 .getAbsolutePath(); 9398 } else { 9399 final String apkName = deriveCodePathName(codePath); 9400 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9401 .getAbsolutePath(); 9402 } 9403 9404 info.nativeLibraryRootRequiresIsa = false; 9405 info.nativeLibraryDir = info.nativeLibraryRootDir; 9406 } else { 9407 // Cluster install 9408 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9409 info.nativeLibraryRootRequiresIsa = true; 9410 9411 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9412 getPrimaryInstructionSet(info)).getAbsolutePath(); 9413 9414 if (info.secondaryCpuAbi != null) { 9415 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9416 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9417 } 9418 } 9419 } 9420 9421 /** 9422 * Calculate the abis and roots for a bundled app. These can uniquely 9423 * be determined from the contents of the system partition, i.e whether 9424 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9425 * of this information, and instead assume that the system was built 9426 * sensibly. 9427 */ 9428 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9429 PackageSetting pkgSetting) { 9430 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9431 9432 // If "/system/lib64/apkname" exists, assume that is the per-package 9433 // native library directory to use; otherwise use "/system/lib/apkname". 9434 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9435 setBundledAppAbi(pkg, apkRoot, apkName); 9436 // pkgSetting might be null during rescan following uninstall of updates 9437 // to a bundled app, so accommodate that possibility. The settings in 9438 // that case will be established later from the parsed package. 9439 // 9440 // If the settings aren't null, sync them up with what we've just derived. 9441 // note that apkRoot isn't stored in the package settings. 9442 if (pkgSetting != null) { 9443 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9444 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9445 } 9446 } 9447 9448 /** 9449 * Deduces the ABI of a bundled app and sets the relevant fields on the 9450 * parsed pkg object. 9451 * 9452 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9453 * under which system libraries are installed. 9454 * @param apkName the name of the installed package. 9455 */ 9456 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9457 final File codeFile = new File(pkg.codePath); 9458 9459 final boolean has64BitLibs; 9460 final boolean has32BitLibs; 9461 if (isApkFile(codeFile)) { 9462 // Monolithic install 9463 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9464 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9465 } else { 9466 // Cluster install 9467 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9468 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9469 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9470 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9471 has64BitLibs = (new File(rootDir, isa)).exists(); 9472 } else { 9473 has64BitLibs = false; 9474 } 9475 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9476 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9477 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9478 has32BitLibs = (new File(rootDir, isa)).exists(); 9479 } else { 9480 has32BitLibs = false; 9481 } 9482 } 9483 9484 if (has64BitLibs && !has32BitLibs) { 9485 // The package has 64 bit libs, but not 32 bit libs. Its primary 9486 // ABI should be 64 bit. We can safely assume here that the bundled 9487 // native libraries correspond to the most preferred ABI in the list. 9488 9489 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9490 pkg.applicationInfo.secondaryCpuAbi = null; 9491 } else if (has32BitLibs && !has64BitLibs) { 9492 // The package has 32 bit libs but not 64 bit libs. Its primary 9493 // ABI should be 32 bit. 9494 9495 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9496 pkg.applicationInfo.secondaryCpuAbi = null; 9497 } else if (has32BitLibs && has64BitLibs) { 9498 // The application has both 64 and 32 bit bundled libraries. We check 9499 // here that the app declares multiArch support, and warn if it doesn't. 9500 // 9501 // We will be lenient here and record both ABIs. The primary will be the 9502 // ABI that's higher on the list, i.e, a device that's configured to prefer 9503 // 64 bit apps will see a 64 bit primary ABI, 9504 9505 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9506 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9507 } 9508 9509 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9510 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9511 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9512 } else { 9513 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9514 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9515 } 9516 } else { 9517 pkg.applicationInfo.primaryCpuAbi = null; 9518 pkg.applicationInfo.secondaryCpuAbi = null; 9519 } 9520 } 9521 9522 private void killApplication(String pkgName, int appId, String reason) { 9523 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9524 } 9525 9526 private void killApplication(String pkgName, int appId, int userId, String reason) { 9527 // Request the ActivityManager to kill the process(only for existing packages) 9528 // so that we do not end up in a confused state while the user is still using the older 9529 // version of the application while the new one gets installed. 9530 final long token = Binder.clearCallingIdentity(); 9531 try { 9532 IActivityManager am = ActivityManagerNative.getDefault(); 9533 if (am != null) { 9534 try { 9535 am.killApplication(pkgName, appId, userId, reason); 9536 } catch (RemoteException e) { 9537 } 9538 } 9539 } finally { 9540 Binder.restoreCallingIdentity(token); 9541 } 9542 } 9543 9544 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9545 // Remove the parent package setting 9546 PackageSetting ps = (PackageSetting) pkg.mExtras; 9547 if (ps != null) { 9548 removePackageLI(ps, chatty); 9549 } 9550 // Remove the child package setting 9551 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9552 for (int i = 0; i < childCount; i++) { 9553 PackageParser.Package childPkg = pkg.childPackages.get(i); 9554 ps = (PackageSetting) childPkg.mExtras; 9555 if (ps != null) { 9556 removePackageLI(ps, chatty); 9557 } 9558 } 9559 } 9560 9561 void removePackageLI(PackageSetting ps, boolean chatty) { 9562 if (DEBUG_INSTALL) { 9563 if (chatty) 9564 Log.d(TAG, "Removing package " + ps.name); 9565 } 9566 9567 // writer 9568 synchronized (mPackages) { 9569 mPackages.remove(ps.name); 9570 final PackageParser.Package pkg = ps.pkg; 9571 if (pkg != null) { 9572 cleanPackageDataStructuresLILPw(pkg, chatty); 9573 } 9574 } 9575 } 9576 9577 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9578 if (DEBUG_INSTALL) { 9579 if (chatty) 9580 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9581 } 9582 9583 // writer 9584 synchronized (mPackages) { 9585 // Remove the parent package 9586 mPackages.remove(pkg.applicationInfo.packageName); 9587 cleanPackageDataStructuresLILPw(pkg, chatty); 9588 9589 // Remove the child packages 9590 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9591 for (int i = 0; i < childCount; i++) { 9592 PackageParser.Package childPkg = pkg.childPackages.get(i); 9593 mPackages.remove(childPkg.applicationInfo.packageName); 9594 cleanPackageDataStructuresLILPw(childPkg, chatty); 9595 } 9596 } 9597 } 9598 9599 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9600 int N = pkg.providers.size(); 9601 StringBuilder r = null; 9602 int i; 9603 for (i=0; i<N; i++) { 9604 PackageParser.Provider p = pkg.providers.get(i); 9605 mProviders.removeProvider(p); 9606 if (p.info.authority == null) { 9607 9608 /* There was another ContentProvider with this authority when 9609 * this app was installed so this authority is null, 9610 * Ignore it as we don't have to unregister the provider. 9611 */ 9612 continue; 9613 } 9614 String names[] = p.info.authority.split(";"); 9615 for (int j = 0; j < names.length; j++) { 9616 if (mProvidersByAuthority.get(names[j]) == p) { 9617 mProvidersByAuthority.remove(names[j]); 9618 if (DEBUG_REMOVE) { 9619 if (chatty) 9620 Log.d(TAG, "Unregistered content provider: " + names[j] 9621 + ", className = " + p.info.name + ", isSyncable = " 9622 + p.info.isSyncable); 9623 } 9624 } 9625 } 9626 if (DEBUG_REMOVE && chatty) { 9627 if (r == null) { 9628 r = new StringBuilder(256); 9629 } else { 9630 r.append(' '); 9631 } 9632 r.append(p.info.name); 9633 } 9634 } 9635 if (r != null) { 9636 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9637 } 9638 9639 N = pkg.services.size(); 9640 r = null; 9641 for (i=0; i<N; i++) { 9642 PackageParser.Service s = pkg.services.get(i); 9643 mServices.removeService(s); 9644 if (chatty) { 9645 if (r == null) { 9646 r = new StringBuilder(256); 9647 } else { 9648 r.append(' '); 9649 } 9650 r.append(s.info.name); 9651 } 9652 } 9653 if (r != null) { 9654 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9655 } 9656 9657 N = pkg.receivers.size(); 9658 r = null; 9659 for (i=0; i<N; i++) { 9660 PackageParser.Activity a = pkg.receivers.get(i); 9661 mReceivers.removeActivity(a, "receiver"); 9662 if (DEBUG_REMOVE && chatty) { 9663 if (r == null) { 9664 r = new StringBuilder(256); 9665 } else { 9666 r.append(' '); 9667 } 9668 r.append(a.info.name); 9669 } 9670 } 9671 if (r != null) { 9672 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9673 } 9674 9675 N = pkg.activities.size(); 9676 r = null; 9677 for (i=0; i<N; i++) { 9678 PackageParser.Activity a = pkg.activities.get(i); 9679 mActivities.removeActivity(a, "activity"); 9680 if (DEBUG_REMOVE && chatty) { 9681 if (r == null) { 9682 r = new StringBuilder(256); 9683 } else { 9684 r.append(' '); 9685 } 9686 r.append(a.info.name); 9687 } 9688 } 9689 if (r != null) { 9690 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9691 } 9692 9693 N = pkg.permissions.size(); 9694 r = null; 9695 for (i=0; i<N; i++) { 9696 PackageParser.Permission p = pkg.permissions.get(i); 9697 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9698 if (bp == null) { 9699 bp = mSettings.mPermissionTrees.get(p.info.name); 9700 } 9701 if (bp != null && bp.perm == p) { 9702 bp.perm = null; 9703 if (DEBUG_REMOVE && chatty) { 9704 if (r == null) { 9705 r = new StringBuilder(256); 9706 } else { 9707 r.append(' '); 9708 } 9709 r.append(p.info.name); 9710 } 9711 } 9712 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9713 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9714 if (appOpPkgs != null) { 9715 appOpPkgs.remove(pkg.packageName); 9716 } 9717 } 9718 } 9719 if (r != null) { 9720 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9721 } 9722 9723 N = pkg.requestedPermissions.size(); 9724 r = null; 9725 for (i=0; i<N; i++) { 9726 String perm = pkg.requestedPermissions.get(i); 9727 BasePermission bp = mSettings.mPermissions.get(perm); 9728 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9729 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9730 if (appOpPkgs != null) { 9731 appOpPkgs.remove(pkg.packageName); 9732 if (appOpPkgs.isEmpty()) { 9733 mAppOpPermissionPackages.remove(perm); 9734 } 9735 } 9736 } 9737 } 9738 if (r != null) { 9739 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9740 } 9741 9742 N = pkg.instrumentation.size(); 9743 r = null; 9744 for (i=0; i<N; i++) { 9745 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9746 mInstrumentation.remove(a.getComponentName()); 9747 if (DEBUG_REMOVE && chatty) { 9748 if (r == null) { 9749 r = new StringBuilder(256); 9750 } else { 9751 r.append(' '); 9752 } 9753 r.append(a.info.name); 9754 } 9755 } 9756 if (r != null) { 9757 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9758 } 9759 9760 r = null; 9761 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9762 // Only system apps can hold shared libraries. 9763 if (pkg.libraryNames != null) { 9764 for (i=0; i<pkg.libraryNames.size(); i++) { 9765 String name = pkg.libraryNames.get(i); 9766 SharedLibraryEntry cur = mSharedLibraries.get(name); 9767 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9768 mSharedLibraries.remove(name); 9769 if (DEBUG_REMOVE && chatty) { 9770 if (r == null) { 9771 r = new StringBuilder(256); 9772 } else { 9773 r.append(' '); 9774 } 9775 r.append(name); 9776 } 9777 } 9778 } 9779 } 9780 } 9781 if (r != null) { 9782 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9783 } 9784 } 9785 9786 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9787 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9788 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9789 return true; 9790 } 9791 } 9792 return false; 9793 } 9794 9795 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9796 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9797 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9798 9799 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9800 // Update the parent permissions 9801 updatePermissionsLPw(pkg.packageName, pkg, flags); 9802 // Update the child permissions 9803 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9804 for (int i = 0; i < childCount; i++) { 9805 PackageParser.Package childPkg = pkg.childPackages.get(i); 9806 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9807 } 9808 } 9809 9810 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9811 int flags) { 9812 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9813 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9814 } 9815 9816 private void updatePermissionsLPw(String changingPkg, 9817 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9818 // Make sure there are no dangling permission trees. 9819 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9820 while (it.hasNext()) { 9821 final BasePermission bp = it.next(); 9822 if (bp.packageSetting == null) { 9823 // We may not yet have parsed the package, so just see if 9824 // we still know about its settings. 9825 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9826 } 9827 if (bp.packageSetting == null) { 9828 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9829 + " from package " + bp.sourcePackage); 9830 it.remove(); 9831 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9832 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9833 Slog.i(TAG, "Removing old permission tree: " + bp.name 9834 + " from package " + bp.sourcePackage); 9835 flags |= UPDATE_PERMISSIONS_ALL; 9836 it.remove(); 9837 } 9838 } 9839 } 9840 9841 // Make sure all dynamic permissions have been assigned to a package, 9842 // and make sure there are no dangling permissions. 9843 it = mSettings.mPermissions.values().iterator(); 9844 while (it.hasNext()) { 9845 final BasePermission bp = it.next(); 9846 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9847 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9848 + bp.name + " pkg=" + bp.sourcePackage 9849 + " info=" + bp.pendingInfo); 9850 if (bp.packageSetting == null && bp.pendingInfo != null) { 9851 final BasePermission tree = findPermissionTreeLP(bp.name); 9852 if (tree != null && tree.perm != null) { 9853 bp.packageSetting = tree.packageSetting; 9854 bp.perm = new PackageParser.Permission(tree.perm.owner, 9855 new PermissionInfo(bp.pendingInfo)); 9856 bp.perm.info.packageName = tree.perm.info.packageName; 9857 bp.perm.info.name = bp.name; 9858 bp.uid = tree.uid; 9859 } 9860 } 9861 } 9862 if (bp.packageSetting == null) { 9863 // We may not yet have parsed the package, so just see if 9864 // we still know about its settings. 9865 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9866 } 9867 if (bp.packageSetting == null) { 9868 Slog.w(TAG, "Removing dangling permission: " + bp.name 9869 + " from package " + bp.sourcePackage); 9870 it.remove(); 9871 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9872 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9873 Slog.i(TAG, "Removing old permission: " + bp.name 9874 + " from package " + bp.sourcePackage); 9875 flags |= UPDATE_PERMISSIONS_ALL; 9876 it.remove(); 9877 } 9878 } 9879 } 9880 9881 // Now update the permissions for all packages, in particular 9882 // replace the granted permissions of the system packages. 9883 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9884 for (PackageParser.Package pkg : mPackages.values()) { 9885 if (pkg != pkgInfo) { 9886 // Only replace for packages on requested volume 9887 final String volumeUuid = getVolumeUuidForPackage(pkg); 9888 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9889 && Objects.equals(replaceVolumeUuid, volumeUuid); 9890 grantPermissionsLPw(pkg, replace, changingPkg); 9891 } 9892 } 9893 } 9894 9895 if (pkgInfo != null) { 9896 // Only replace for packages on requested volume 9897 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9898 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9899 && Objects.equals(replaceVolumeUuid, volumeUuid); 9900 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9901 } 9902 } 9903 9904 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9905 String packageOfInterest) { 9906 // IMPORTANT: There are two types of permissions: install and runtime. 9907 // Install time permissions are granted when the app is installed to 9908 // all device users and users added in the future. Runtime permissions 9909 // are granted at runtime explicitly to specific users. Normal and signature 9910 // protected permissions are install time permissions. Dangerous permissions 9911 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9912 // otherwise they are runtime permissions. This function does not manage 9913 // runtime permissions except for the case an app targeting Lollipop MR1 9914 // being upgraded to target a newer SDK, in which case dangerous permissions 9915 // are transformed from install time to runtime ones. 9916 9917 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9918 if (ps == null) { 9919 return; 9920 } 9921 9922 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9923 9924 PermissionsState permissionsState = ps.getPermissionsState(); 9925 PermissionsState origPermissions = permissionsState; 9926 9927 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9928 9929 boolean runtimePermissionsRevoked = false; 9930 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9931 9932 boolean changedInstallPermission = false; 9933 9934 if (replace) { 9935 ps.installPermissionsFixed = false; 9936 if (!ps.isSharedUser()) { 9937 origPermissions = new PermissionsState(permissionsState); 9938 permissionsState.reset(); 9939 } else { 9940 // We need to know only about runtime permission changes since the 9941 // calling code always writes the install permissions state but 9942 // the runtime ones are written only if changed. The only cases of 9943 // changed runtime permissions here are promotion of an install to 9944 // runtime and revocation of a runtime from a shared user. 9945 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9946 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9947 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9948 runtimePermissionsRevoked = true; 9949 } 9950 } 9951 } 9952 9953 permissionsState.setGlobalGids(mGlobalGids); 9954 9955 final int N = pkg.requestedPermissions.size(); 9956 for (int i=0; i<N; i++) { 9957 final String name = pkg.requestedPermissions.get(i); 9958 final BasePermission bp = mSettings.mPermissions.get(name); 9959 9960 if (DEBUG_INSTALL) { 9961 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9962 } 9963 9964 if (bp == null || bp.packageSetting == null) { 9965 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9966 Slog.w(TAG, "Unknown permission " + name 9967 + " in package " + pkg.packageName); 9968 } 9969 continue; 9970 } 9971 9972 final String perm = bp.name; 9973 boolean allowedSig = false; 9974 int grant = GRANT_DENIED; 9975 9976 // Keep track of app op permissions. 9977 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9978 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9979 if (pkgs == null) { 9980 pkgs = new ArraySet<>(); 9981 mAppOpPermissionPackages.put(bp.name, pkgs); 9982 } 9983 pkgs.add(pkg.packageName); 9984 } 9985 9986 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9987 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9988 >= Build.VERSION_CODES.M; 9989 switch (level) { 9990 case PermissionInfo.PROTECTION_NORMAL: { 9991 // For all apps normal permissions are install time ones. 9992 grant = GRANT_INSTALL; 9993 } break; 9994 9995 case PermissionInfo.PROTECTION_DANGEROUS: { 9996 // If a permission review is required for legacy apps we represent 9997 // their permissions as always granted runtime ones since we need 9998 // to keep the review required permission flag per user while an 9999 // install permission's state is shared across all users. 10000 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10001 // For legacy apps dangerous permissions are install time ones. 10002 grant = GRANT_INSTALL; 10003 } else if (origPermissions.hasInstallPermission(bp.name)) { 10004 // For legacy apps that became modern, install becomes runtime. 10005 grant = GRANT_UPGRADE; 10006 } else if (mPromoteSystemApps 10007 && isSystemApp(ps) 10008 && mExistingSystemPackages.contains(ps.name)) { 10009 // For legacy system apps, install becomes runtime. 10010 // We cannot check hasInstallPermission() for system apps since those 10011 // permissions were granted implicitly and not persisted pre-M. 10012 grant = GRANT_UPGRADE; 10013 } else { 10014 // For modern apps keep runtime permissions unchanged. 10015 grant = GRANT_RUNTIME; 10016 } 10017 } break; 10018 10019 case PermissionInfo.PROTECTION_SIGNATURE: { 10020 // For all apps signature permissions are install time ones. 10021 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10022 if (allowedSig) { 10023 grant = GRANT_INSTALL; 10024 } 10025 } break; 10026 } 10027 10028 if (DEBUG_INSTALL) { 10029 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10030 } 10031 10032 if (grant != GRANT_DENIED) { 10033 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10034 // If this is an existing, non-system package, then 10035 // we can't add any new permissions to it. 10036 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10037 // Except... if this is a permission that was added 10038 // to the platform (note: need to only do this when 10039 // updating the platform). 10040 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10041 grant = GRANT_DENIED; 10042 } 10043 } 10044 } 10045 10046 switch (grant) { 10047 case GRANT_INSTALL: { 10048 // Revoke this as runtime permission to handle the case of 10049 // a runtime permission being downgraded to an install one. 10050 // Also in permission review mode we keep dangerous permissions 10051 // for legacy apps 10052 for (int userId : UserManagerService.getInstance().getUserIds()) { 10053 if (origPermissions.getRuntimePermissionState( 10054 bp.name, userId) != null) { 10055 // Revoke the runtime permission and clear the flags. 10056 origPermissions.revokeRuntimePermission(bp, userId); 10057 origPermissions.updatePermissionFlags(bp, userId, 10058 PackageManager.MASK_PERMISSION_FLAGS, 0); 10059 // If we revoked a permission permission, we have to write. 10060 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10061 changedRuntimePermissionUserIds, userId); 10062 } 10063 } 10064 // Grant an install permission. 10065 if (permissionsState.grantInstallPermission(bp) != 10066 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10067 changedInstallPermission = true; 10068 } 10069 } break; 10070 10071 case GRANT_RUNTIME: { 10072 // Grant previously granted runtime permissions. 10073 for (int userId : UserManagerService.getInstance().getUserIds()) { 10074 PermissionState permissionState = origPermissions 10075 .getRuntimePermissionState(bp.name, userId); 10076 int flags = permissionState != null 10077 ? permissionState.getFlags() : 0; 10078 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10079 if (permissionsState.grantRuntimePermission(bp, userId) == 10080 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10081 // If we cannot put the permission as it was, we have to write. 10082 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10083 changedRuntimePermissionUserIds, userId); 10084 } 10085 // If the app supports runtime permissions no need for a review. 10086 if (Build.PERMISSIONS_REVIEW_REQUIRED 10087 && appSupportsRuntimePermissions 10088 && (flags & PackageManager 10089 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10090 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10091 // Since we changed the flags, we have to write. 10092 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10093 changedRuntimePermissionUserIds, userId); 10094 } 10095 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10096 && !appSupportsRuntimePermissions) { 10097 // For legacy apps that need a permission review, every new 10098 // runtime permission is granted but it is pending a review. 10099 // We also need to review only platform defined runtime 10100 // permissions as these are the only ones the platform knows 10101 // how to disable the API to simulate revocation as legacy 10102 // apps don't expect to run with revoked permissions. 10103 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10104 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10105 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10106 // We changed the flags, hence have to write. 10107 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10108 changedRuntimePermissionUserIds, userId); 10109 } 10110 } 10111 if (permissionsState.grantRuntimePermission(bp, userId) 10112 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10113 // We changed the permission, hence have to write. 10114 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10115 changedRuntimePermissionUserIds, userId); 10116 } 10117 } 10118 // Propagate the permission flags. 10119 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10120 } 10121 } break; 10122 10123 case GRANT_UPGRADE: { 10124 // Grant runtime permissions for a previously held install permission. 10125 PermissionState permissionState = origPermissions 10126 .getInstallPermissionState(bp.name); 10127 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10128 10129 if (origPermissions.revokeInstallPermission(bp) 10130 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10131 // We will be transferring the permission flags, so clear them. 10132 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10133 PackageManager.MASK_PERMISSION_FLAGS, 0); 10134 changedInstallPermission = true; 10135 } 10136 10137 // If the permission is not to be promoted to runtime we ignore it and 10138 // also its other flags as they are not applicable to install permissions. 10139 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10140 for (int userId : currentUserIds) { 10141 if (permissionsState.grantRuntimePermission(bp, userId) != 10142 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10143 // Transfer the permission flags. 10144 permissionsState.updatePermissionFlags(bp, userId, 10145 flags, flags); 10146 // If we granted the permission, we have to write. 10147 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10148 changedRuntimePermissionUserIds, userId); 10149 } 10150 } 10151 } 10152 } break; 10153 10154 default: { 10155 if (packageOfInterest == null 10156 || packageOfInterest.equals(pkg.packageName)) { 10157 Slog.w(TAG, "Not granting permission " + perm 10158 + " to package " + pkg.packageName 10159 + " because it was previously installed without"); 10160 } 10161 } break; 10162 } 10163 } else { 10164 if (permissionsState.revokeInstallPermission(bp) != 10165 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10166 // Also drop the permission flags. 10167 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10168 PackageManager.MASK_PERMISSION_FLAGS, 0); 10169 changedInstallPermission = true; 10170 Slog.i(TAG, "Un-granting permission " + perm 10171 + " from package " + pkg.packageName 10172 + " (protectionLevel=" + bp.protectionLevel 10173 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10174 + ")"); 10175 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10176 // Don't print warning for app op permissions, since it is fine for them 10177 // not to be granted, there is a UI for the user to decide. 10178 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10179 Slog.w(TAG, "Not granting permission " + perm 10180 + " to package " + pkg.packageName 10181 + " (protectionLevel=" + bp.protectionLevel 10182 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10183 + ")"); 10184 } 10185 } 10186 } 10187 } 10188 10189 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10190 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10191 // This is the first that we have heard about this package, so the 10192 // permissions we have now selected are fixed until explicitly 10193 // changed. 10194 ps.installPermissionsFixed = true; 10195 } 10196 10197 // Persist the runtime permissions state for users with changes. If permissions 10198 // were revoked because no app in the shared user declares them we have to 10199 // write synchronously to avoid losing runtime permissions state. 10200 for (int userId : changedRuntimePermissionUserIds) { 10201 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10202 } 10203 10204 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10205 } 10206 10207 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10208 boolean allowed = false; 10209 final int NP = PackageParser.NEW_PERMISSIONS.length; 10210 for (int ip=0; ip<NP; ip++) { 10211 final PackageParser.NewPermissionInfo npi 10212 = PackageParser.NEW_PERMISSIONS[ip]; 10213 if (npi.name.equals(perm) 10214 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10215 allowed = true; 10216 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10217 + pkg.packageName); 10218 break; 10219 } 10220 } 10221 return allowed; 10222 } 10223 10224 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10225 BasePermission bp, PermissionsState origPermissions) { 10226 boolean allowed; 10227 allowed = (compareSignatures( 10228 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10229 == PackageManager.SIGNATURE_MATCH) 10230 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10231 == PackageManager.SIGNATURE_MATCH); 10232 if (!allowed && (bp.protectionLevel 10233 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10234 if (isSystemApp(pkg)) { 10235 // For updated system applications, a system permission 10236 // is granted only if it had been defined by the original application. 10237 if (pkg.isUpdatedSystemApp()) { 10238 final PackageSetting sysPs = mSettings 10239 .getDisabledSystemPkgLPr(pkg.packageName); 10240 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10241 // If the original was granted this permission, we take 10242 // that grant decision as read and propagate it to the 10243 // update. 10244 if (sysPs.isPrivileged()) { 10245 allowed = true; 10246 } 10247 } else { 10248 // The system apk may have been updated with an older 10249 // version of the one on the data partition, but which 10250 // granted a new system permission that it didn't have 10251 // before. In this case we do want to allow the app to 10252 // now get the new permission if the ancestral apk is 10253 // privileged to get it. 10254 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10255 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10256 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10257 allowed = true; 10258 break; 10259 } 10260 } 10261 } 10262 // Also if a privileged parent package on the system image or any of 10263 // its children requested a privileged permission, the updated child 10264 // packages can also get the permission. 10265 if (pkg.parentPackage != null) { 10266 final PackageSetting disabledSysParentPs = mSettings 10267 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10268 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10269 && disabledSysParentPs.isPrivileged()) { 10270 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10271 allowed = true; 10272 } else if (disabledSysParentPs.pkg.childPackages != null) { 10273 final int count = disabledSysParentPs.pkg.childPackages.size(); 10274 for (int i = 0; i < count; i++) { 10275 PackageParser.Package disabledSysChildPkg = 10276 disabledSysParentPs.pkg.childPackages.get(i); 10277 if (isPackageRequestingPermission(disabledSysChildPkg, 10278 perm)) { 10279 allowed = true; 10280 break; 10281 } 10282 } 10283 } 10284 } 10285 } 10286 } 10287 } else { 10288 allowed = isPrivilegedApp(pkg); 10289 } 10290 } 10291 } 10292 if (!allowed) { 10293 if (!allowed && (bp.protectionLevel 10294 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10295 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10296 // If this was a previously normal/dangerous permission that got moved 10297 // to a system permission as part of the runtime permission redesign, then 10298 // we still want to blindly grant it to old apps. 10299 allowed = true; 10300 } 10301 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10302 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10303 // If this permission is to be granted to the system installer and 10304 // this app is an installer, then it gets the permission. 10305 allowed = true; 10306 } 10307 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10308 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10309 // If this permission is to be granted to the system verifier and 10310 // this app is a verifier, then it gets the permission. 10311 allowed = true; 10312 } 10313 if (!allowed && (bp.protectionLevel 10314 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10315 && isSystemApp(pkg)) { 10316 // Any pre-installed system app is allowed to get this permission. 10317 allowed = true; 10318 } 10319 if (!allowed && (bp.protectionLevel 10320 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10321 // For development permissions, a development permission 10322 // is granted only if it was already granted. 10323 allowed = origPermissions.hasInstallPermission(perm); 10324 } 10325 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10326 && pkg.packageName.equals(mSetupWizardPackage)) { 10327 // If this permission is to be granted to the system setup wizard and 10328 // this app is a setup wizard, then it gets the permission. 10329 allowed = true; 10330 } 10331 } 10332 return allowed; 10333 } 10334 10335 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10336 final int permCount = pkg.requestedPermissions.size(); 10337 for (int j = 0; j < permCount; j++) { 10338 String requestedPermission = pkg.requestedPermissions.get(j); 10339 if (permission.equals(requestedPermission)) { 10340 return true; 10341 } 10342 } 10343 return false; 10344 } 10345 10346 final class ActivityIntentResolver 10347 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10348 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10349 boolean defaultOnly, int userId) { 10350 if (!sUserManager.exists(userId)) return null; 10351 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10352 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10353 } 10354 10355 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10356 int userId) { 10357 if (!sUserManager.exists(userId)) return null; 10358 mFlags = flags; 10359 return super.queryIntent(intent, resolvedType, 10360 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10361 } 10362 10363 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10364 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10365 if (!sUserManager.exists(userId)) return null; 10366 if (packageActivities == null) { 10367 return null; 10368 } 10369 mFlags = flags; 10370 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10371 final int N = packageActivities.size(); 10372 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10373 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10374 10375 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10376 for (int i = 0; i < N; ++i) { 10377 intentFilters = packageActivities.get(i).intents; 10378 if (intentFilters != null && intentFilters.size() > 0) { 10379 PackageParser.ActivityIntentInfo[] array = 10380 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10381 intentFilters.toArray(array); 10382 listCut.add(array); 10383 } 10384 } 10385 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10386 } 10387 10388 /** 10389 * Finds a privileged activity that matches the specified activity names. 10390 */ 10391 private PackageParser.Activity findMatchingActivity( 10392 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10393 for (PackageParser.Activity sysActivity : activityList) { 10394 if (sysActivity.info.name.equals(activityInfo.name)) { 10395 return sysActivity; 10396 } 10397 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10398 return sysActivity; 10399 } 10400 if (sysActivity.info.targetActivity != null) { 10401 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10402 return sysActivity; 10403 } 10404 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10405 return sysActivity; 10406 } 10407 } 10408 } 10409 return null; 10410 } 10411 10412 public class IterGenerator<E> { 10413 public Iterator<E> generate(ActivityIntentInfo info) { 10414 return null; 10415 } 10416 } 10417 10418 public class ActionIterGenerator extends IterGenerator<String> { 10419 @Override 10420 public Iterator<String> generate(ActivityIntentInfo info) { 10421 return info.actionsIterator(); 10422 } 10423 } 10424 10425 public class CategoriesIterGenerator extends IterGenerator<String> { 10426 @Override 10427 public Iterator<String> generate(ActivityIntentInfo info) { 10428 return info.categoriesIterator(); 10429 } 10430 } 10431 10432 public class SchemesIterGenerator extends IterGenerator<String> { 10433 @Override 10434 public Iterator<String> generate(ActivityIntentInfo info) { 10435 return info.schemesIterator(); 10436 } 10437 } 10438 10439 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10440 @Override 10441 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10442 return info.authoritiesIterator(); 10443 } 10444 } 10445 10446 /** 10447 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10448 * MODIFIED. Do not pass in a list that should not be changed. 10449 */ 10450 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10451 IterGenerator<T> generator, Iterator<T> searchIterator) { 10452 // loop through the set of actions; every one must be found in the intent filter 10453 while (searchIterator.hasNext()) { 10454 // we must have at least one filter in the list to consider a match 10455 if (intentList.size() == 0) { 10456 break; 10457 } 10458 10459 final T searchAction = searchIterator.next(); 10460 10461 // loop through the set of intent filters 10462 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10463 while (intentIter.hasNext()) { 10464 final ActivityIntentInfo intentInfo = intentIter.next(); 10465 boolean selectionFound = false; 10466 10467 // loop through the intent filter's selection criteria; at least one 10468 // of them must match the searched criteria 10469 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10470 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10471 final T intentSelection = intentSelectionIter.next(); 10472 if (intentSelection != null && intentSelection.equals(searchAction)) { 10473 selectionFound = true; 10474 break; 10475 } 10476 } 10477 10478 // the selection criteria wasn't found in this filter's set; this filter 10479 // is not a potential match 10480 if (!selectionFound) { 10481 intentIter.remove(); 10482 } 10483 } 10484 } 10485 } 10486 10487 private boolean isProtectedAction(ActivityIntentInfo filter) { 10488 final Iterator<String> actionsIter = filter.actionsIterator(); 10489 while (actionsIter != null && actionsIter.hasNext()) { 10490 final String filterAction = actionsIter.next(); 10491 if (PROTECTED_ACTIONS.contains(filterAction)) { 10492 return true; 10493 } 10494 } 10495 return false; 10496 } 10497 10498 /** 10499 * Adjusts the priority of the given intent filter according to policy. 10500 * <p> 10501 * <ul> 10502 * <li>The priority for non privileged applications is capped to '0'</li> 10503 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10504 * <li>The priority for unbundled updates to privileged applications is capped to the 10505 * priority defined on the system partition</li> 10506 * </ul> 10507 * <p> 10508 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10509 * allowed to obtain any priority on any action. 10510 */ 10511 private void adjustPriority( 10512 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10513 // nothing to do; priority is fine as-is 10514 if (intent.getPriority() <= 0) { 10515 return; 10516 } 10517 10518 final ActivityInfo activityInfo = intent.activity.info; 10519 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10520 10521 final boolean privilegedApp = 10522 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10523 if (!privilegedApp) { 10524 // non-privileged applications can never define a priority >0 10525 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10526 + " package: " + applicationInfo.packageName 10527 + " activity: " + intent.activity.className 10528 + " origPrio: " + intent.getPriority()); 10529 intent.setPriority(0); 10530 return; 10531 } 10532 10533 if (systemActivities == null) { 10534 // the system package is not disabled; we're parsing the system partition 10535 if (isProtectedAction(intent)) { 10536 if (mDeferProtectedFilters) { 10537 // We can't deal with these just yet. No component should ever obtain a 10538 // >0 priority for a protected actions, with ONE exception -- the setup 10539 // wizard. The setup wizard, however, cannot be known until we're able to 10540 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10541 // until all intent filters have been processed. Chicken, meet egg. 10542 // Let the filter temporarily have a high priority and rectify the 10543 // priorities after all system packages have been scanned. 10544 mProtectedFilters.add(intent); 10545 if (DEBUG_FILTERS) { 10546 Slog.i(TAG, "Protected action; save for later;" 10547 + " package: " + applicationInfo.packageName 10548 + " activity: " + intent.activity.className 10549 + " origPrio: " + intent.getPriority()); 10550 } 10551 return; 10552 } else { 10553 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10554 Slog.i(TAG, "No setup wizard;" 10555 + " All protected intents capped to priority 0"); 10556 } 10557 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10558 if (DEBUG_FILTERS) { 10559 Slog.i(TAG, "Found setup wizard;" 10560 + " allow priority " + intent.getPriority() + ";" 10561 + " package: " + intent.activity.info.packageName 10562 + " activity: " + intent.activity.className 10563 + " priority: " + intent.getPriority()); 10564 } 10565 // setup wizard gets whatever it wants 10566 return; 10567 } 10568 Slog.w(TAG, "Protected action; cap priority to 0;" 10569 + " package: " + intent.activity.info.packageName 10570 + " activity: " + intent.activity.className 10571 + " origPrio: " + intent.getPriority()); 10572 intent.setPriority(0); 10573 return; 10574 } 10575 } 10576 // privileged apps on the system image get whatever priority they request 10577 return; 10578 } 10579 10580 // privileged app unbundled update ... try to find the same activity 10581 final PackageParser.Activity foundActivity = 10582 findMatchingActivity(systemActivities, activityInfo); 10583 if (foundActivity == null) { 10584 // this is a new activity; it cannot obtain >0 priority 10585 if (DEBUG_FILTERS) { 10586 Slog.i(TAG, "New activity; cap priority to 0;" 10587 + " package: " + applicationInfo.packageName 10588 + " activity: " + intent.activity.className 10589 + " origPrio: " + intent.getPriority()); 10590 } 10591 intent.setPriority(0); 10592 return; 10593 } 10594 10595 // found activity, now check for filter equivalence 10596 10597 // a shallow copy is enough; we modify the list, not its contents 10598 final List<ActivityIntentInfo> intentListCopy = 10599 new ArrayList<>(foundActivity.intents); 10600 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10601 10602 // find matching action subsets 10603 final Iterator<String> actionsIterator = intent.actionsIterator(); 10604 if (actionsIterator != null) { 10605 getIntentListSubset( 10606 intentListCopy, new ActionIterGenerator(), actionsIterator); 10607 if (intentListCopy.size() == 0) { 10608 // no more intents to match; we're not equivalent 10609 if (DEBUG_FILTERS) { 10610 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10611 + " package: " + applicationInfo.packageName 10612 + " activity: " + intent.activity.className 10613 + " origPrio: " + intent.getPriority()); 10614 } 10615 intent.setPriority(0); 10616 return; 10617 } 10618 } 10619 10620 // find matching category subsets 10621 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10622 if (categoriesIterator != null) { 10623 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10624 categoriesIterator); 10625 if (intentListCopy.size() == 0) { 10626 // no more intents to match; we're not equivalent 10627 if (DEBUG_FILTERS) { 10628 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10629 + " package: " + applicationInfo.packageName 10630 + " activity: " + intent.activity.className 10631 + " origPrio: " + intent.getPriority()); 10632 } 10633 intent.setPriority(0); 10634 return; 10635 } 10636 } 10637 10638 // find matching schemes subsets 10639 final Iterator<String> schemesIterator = intent.schemesIterator(); 10640 if (schemesIterator != null) { 10641 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10642 schemesIterator); 10643 if (intentListCopy.size() == 0) { 10644 // no more intents to match; we're not equivalent 10645 if (DEBUG_FILTERS) { 10646 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10647 + " package: " + applicationInfo.packageName 10648 + " activity: " + intent.activity.className 10649 + " origPrio: " + intent.getPriority()); 10650 } 10651 intent.setPriority(0); 10652 return; 10653 } 10654 } 10655 10656 // find matching authorities subsets 10657 final Iterator<IntentFilter.AuthorityEntry> 10658 authoritiesIterator = intent.authoritiesIterator(); 10659 if (authoritiesIterator != null) { 10660 getIntentListSubset(intentListCopy, 10661 new AuthoritiesIterGenerator(), 10662 authoritiesIterator); 10663 if (intentListCopy.size() == 0) { 10664 // no more intents to match; we're not equivalent 10665 if (DEBUG_FILTERS) { 10666 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10667 + " package: " + applicationInfo.packageName 10668 + " activity: " + intent.activity.className 10669 + " origPrio: " + intent.getPriority()); 10670 } 10671 intent.setPriority(0); 10672 return; 10673 } 10674 } 10675 10676 // we found matching filter(s); app gets the max priority of all intents 10677 int cappedPriority = 0; 10678 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10679 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10680 } 10681 if (intent.getPriority() > cappedPriority) { 10682 if (DEBUG_FILTERS) { 10683 Slog.i(TAG, "Found matching filter(s);" 10684 + " cap priority to " + cappedPriority + ";" 10685 + " package: " + applicationInfo.packageName 10686 + " activity: " + intent.activity.className 10687 + " origPrio: " + intent.getPriority()); 10688 } 10689 intent.setPriority(cappedPriority); 10690 return; 10691 } 10692 // all this for nothing; the requested priority was <= what was on the system 10693 } 10694 10695 public final void addActivity(PackageParser.Activity a, String type) { 10696 mActivities.put(a.getComponentName(), a); 10697 if (DEBUG_SHOW_INFO) 10698 Log.v( 10699 TAG, " " + type + " " + 10700 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10701 if (DEBUG_SHOW_INFO) 10702 Log.v(TAG, " Class=" + a.info.name); 10703 final int NI = a.intents.size(); 10704 for (int j=0; j<NI; j++) { 10705 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10706 if ("activity".equals(type)) { 10707 final PackageSetting ps = 10708 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10709 final List<PackageParser.Activity> systemActivities = 10710 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10711 adjustPriority(systemActivities, intent); 10712 } 10713 if (DEBUG_SHOW_INFO) { 10714 Log.v(TAG, " IntentFilter:"); 10715 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10716 } 10717 if (!intent.debugCheck()) { 10718 Log.w(TAG, "==> For Activity " + a.info.name); 10719 } 10720 addFilter(intent); 10721 } 10722 } 10723 10724 public final void removeActivity(PackageParser.Activity a, String type) { 10725 mActivities.remove(a.getComponentName()); 10726 if (DEBUG_SHOW_INFO) { 10727 Log.v(TAG, " " + type + " " 10728 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10729 : a.info.name) + ":"); 10730 Log.v(TAG, " Class=" + a.info.name); 10731 } 10732 final int NI = a.intents.size(); 10733 for (int j=0; j<NI; j++) { 10734 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10735 if (DEBUG_SHOW_INFO) { 10736 Log.v(TAG, " IntentFilter:"); 10737 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10738 } 10739 removeFilter(intent); 10740 } 10741 } 10742 10743 @Override 10744 protected boolean allowFilterResult( 10745 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10746 ActivityInfo filterAi = filter.activity.info; 10747 for (int i=dest.size()-1; i>=0; i--) { 10748 ActivityInfo destAi = dest.get(i).activityInfo; 10749 if (destAi.name == filterAi.name 10750 && destAi.packageName == filterAi.packageName) { 10751 return false; 10752 } 10753 } 10754 return true; 10755 } 10756 10757 @Override 10758 protected ActivityIntentInfo[] newArray(int size) { 10759 return new ActivityIntentInfo[size]; 10760 } 10761 10762 @Override 10763 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10764 if (!sUserManager.exists(userId)) return true; 10765 PackageParser.Package p = filter.activity.owner; 10766 if (p != null) { 10767 PackageSetting ps = (PackageSetting)p.mExtras; 10768 if (ps != null) { 10769 // System apps are never considered stopped for purposes of 10770 // filtering, because there may be no way for the user to 10771 // actually re-launch them. 10772 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10773 && ps.getStopped(userId); 10774 } 10775 } 10776 return false; 10777 } 10778 10779 @Override 10780 protected boolean isPackageForFilter(String packageName, 10781 PackageParser.ActivityIntentInfo info) { 10782 return packageName.equals(info.activity.owner.packageName); 10783 } 10784 10785 @Override 10786 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10787 int match, int userId) { 10788 if (!sUserManager.exists(userId)) return null; 10789 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10790 return null; 10791 } 10792 final PackageParser.Activity activity = info.activity; 10793 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10794 if (ps == null) { 10795 return null; 10796 } 10797 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10798 ps.readUserState(userId), userId); 10799 if (ai == null) { 10800 return null; 10801 } 10802 final ResolveInfo res = new ResolveInfo(); 10803 res.activityInfo = ai; 10804 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10805 res.filter = info; 10806 } 10807 if (info != null) { 10808 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10809 } 10810 res.priority = info.getPriority(); 10811 res.preferredOrder = activity.owner.mPreferredOrder; 10812 //System.out.println("Result: " + res.activityInfo.className + 10813 // " = " + res.priority); 10814 res.match = match; 10815 res.isDefault = info.hasDefault; 10816 res.labelRes = info.labelRes; 10817 res.nonLocalizedLabel = info.nonLocalizedLabel; 10818 if (userNeedsBadging(userId)) { 10819 res.noResourceId = true; 10820 } else { 10821 res.icon = info.icon; 10822 } 10823 res.iconResourceId = info.icon; 10824 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10825 return res; 10826 } 10827 10828 @Override 10829 protected void sortResults(List<ResolveInfo> results) { 10830 Collections.sort(results, mResolvePrioritySorter); 10831 } 10832 10833 @Override 10834 protected void dumpFilter(PrintWriter out, String prefix, 10835 PackageParser.ActivityIntentInfo filter) { 10836 out.print(prefix); out.print( 10837 Integer.toHexString(System.identityHashCode(filter.activity))); 10838 out.print(' '); 10839 filter.activity.printComponentShortName(out); 10840 out.print(" filter "); 10841 out.println(Integer.toHexString(System.identityHashCode(filter))); 10842 } 10843 10844 @Override 10845 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10846 return filter.activity; 10847 } 10848 10849 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10850 PackageParser.Activity activity = (PackageParser.Activity)label; 10851 out.print(prefix); out.print( 10852 Integer.toHexString(System.identityHashCode(activity))); 10853 out.print(' '); 10854 activity.printComponentShortName(out); 10855 if (count > 1) { 10856 out.print(" ("); out.print(count); out.print(" filters)"); 10857 } 10858 out.println(); 10859 } 10860 10861 // Keys are String (activity class name), values are Activity. 10862 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10863 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10864 private int mFlags; 10865 } 10866 10867 private final class ServiceIntentResolver 10868 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10869 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10870 boolean defaultOnly, int userId) { 10871 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10872 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10873 } 10874 10875 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10876 int userId) { 10877 if (!sUserManager.exists(userId)) return null; 10878 mFlags = flags; 10879 return super.queryIntent(intent, resolvedType, 10880 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10881 } 10882 10883 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10884 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10885 if (!sUserManager.exists(userId)) return null; 10886 if (packageServices == null) { 10887 return null; 10888 } 10889 mFlags = flags; 10890 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10891 final int N = packageServices.size(); 10892 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10893 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10894 10895 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10896 for (int i = 0; i < N; ++i) { 10897 intentFilters = packageServices.get(i).intents; 10898 if (intentFilters != null && intentFilters.size() > 0) { 10899 PackageParser.ServiceIntentInfo[] array = 10900 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10901 intentFilters.toArray(array); 10902 listCut.add(array); 10903 } 10904 } 10905 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10906 } 10907 10908 public final void addService(PackageParser.Service s) { 10909 mServices.put(s.getComponentName(), s); 10910 if (DEBUG_SHOW_INFO) { 10911 Log.v(TAG, " " 10912 + (s.info.nonLocalizedLabel != null 10913 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10914 Log.v(TAG, " Class=" + s.info.name); 10915 } 10916 final int NI = s.intents.size(); 10917 int j; 10918 for (j=0; j<NI; j++) { 10919 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10920 if (DEBUG_SHOW_INFO) { 10921 Log.v(TAG, " IntentFilter:"); 10922 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10923 } 10924 if (!intent.debugCheck()) { 10925 Log.w(TAG, "==> For Service " + s.info.name); 10926 } 10927 addFilter(intent); 10928 } 10929 } 10930 10931 public final void removeService(PackageParser.Service s) { 10932 mServices.remove(s.getComponentName()); 10933 if (DEBUG_SHOW_INFO) { 10934 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10935 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10936 Log.v(TAG, " Class=" + s.info.name); 10937 } 10938 final int NI = s.intents.size(); 10939 int j; 10940 for (j=0; j<NI; j++) { 10941 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10942 if (DEBUG_SHOW_INFO) { 10943 Log.v(TAG, " IntentFilter:"); 10944 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10945 } 10946 removeFilter(intent); 10947 } 10948 } 10949 10950 @Override 10951 protected boolean allowFilterResult( 10952 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10953 ServiceInfo filterSi = filter.service.info; 10954 for (int i=dest.size()-1; i>=0; i--) { 10955 ServiceInfo destAi = dest.get(i).serviceInfo; 10956 if (destAi.name == filterSi.name 10957 && destAi.packageName == filterSi.packageName) { 10958 return false; 10959 } 10960 } 10961 return true; 10962 } 10963 10964 @Override 10965 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10966 return new PackageParser.ServiceIntentInfo[size]; 10967 } 10968 10969 @Override 10970 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10971 if (!sUserManager.exists(userId)) return true; 10972 PackageParser.Package p = filter.service.owner; 10973 if (p != null) { 10974 PackageSetting ps = (PackageSetting)p.mExtras; 10975 if (ps != null) { 10976 // System apps are never considered stopped for purposes of 10977 // filtering, because there may be no way for the user to 10978 // actually re-launch them. 10979 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10980 && ps.getStopped(userId); 10981 } 10982 } 10983 return false; 10984 } 10985 10986 @Override 10987 protected boolean isPackageForFilter(String packageName, 10988 PackageParser.ServiceIntentInfo info) { 10989 return packageName.equals(info.service.owner.packageName); 10990 } 10991 10992 @Override 10993 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10994 int match, int userId) { 10995 if (!sUserManager.exists(userId)) return null; 10996 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10997 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10998 return null; 10999 } 11000 final PackageParser.Service service = info.service; 11001 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11002 if (ps == null) { 11003 return null; 11004 } 11005 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11006 ps.readUserState(userId), userId); 11007 if (si == null) { 11008 return null; 11009 } 11010 final ResolveInfo res = new ResolveInfo(); 11011 res.serviceInfo = si; 11012 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11013 res.filter = filter; 11014 } 11015 res.priority = info.getPriority(); 11016 res.preferredOrder = service.owner.mPreferredOrder; 11017 res.match = match; 11018 res.isDefault = info.hasDefault; 11019 res.labelRes = info.labelRes; 11020 res.nonLocalizedLabel = info.nonLocalizedLabel; 11021 res.icon = info.icon; 11022 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11023 return res; 11024 } 11025 11026 @Override 11027 protected void sortResults(List<ResolveInfo> results) { 11028 Collections.sort(results, mResolvePrioritySorter); 11029 } 11030 11031 @Override 11032 protected void dumpFilter(PrintWriter out, String prefix, 11033 PackageParser.ServiceIntentInfo filter) { 11034 out.print(prefix); out.print( 11035 Integer.toHexString(System.identityHashCode(filter.service))); 11036 out.print(' '); 11037 filter.service.printComponentShortName(out); 11038 out.print(" filter "); 11039 out.println(Integer.toHexString(System.identityHashCode(filter))); 11040 } 11041 11042 @Override 11043 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11044 return filter.service; 11045 } 11046 11047 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11048 PackageParser.Service service = (PackageParser.Service)label; 11049 out.print(prefix); out.print( 11050 Integer.toHexString(System.identityHashCode(service))); 11051 out.print(' '); 11052 service.printComponentShortName(out); 11053 if (count > 1) { 11054 out.print(" ("); out.print(count); out.print(" filters)"); 11055 } 11056 out.println(); 11057 } 11058 11059// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11060// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11061// final List<ResolveInfo> retList = Lists.newArrayList(); 11062// while (i.hasNext()) { 11063// final ResolveInfo resolveInfo = (ResolveInfo) i; 11064// if (isEnabledLP(resolveInfo.serviceInfo)) { 11065// retList.add(resolveInfo); 11066// } 11067// } 11068// return retList; 11069// } 11070 11071 // Keys are String (activity class name), values are Activity. 11072 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11073 = new ArrayMap<ComponentName, PackageParser.Service>(); 11074 private int mFlags; 11075 }; 11076 11077 private final class ProviderIntentResolver 11078 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11079 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11080 boolean defaultOnly, int userId) { 11081 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11082 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11083 } 11084 11085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11086 int userId) { 11087 if (!sUserManager.exists(userId)) 11088 return null; 11089 mFlags = flags; 11090 return super.queryIntent(intent, resolvedType, 11091 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11092 } 11093 11094 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11095 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11096 if (!sUserManager.exists(userId)) 11097 return null; 11098 if (packageProviders == null) { 11099 return null; 11100 } 11101 mFlags = flags; 11102 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11103 final int N = packageProviders.size(); 11104 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11105 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11106 11107 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11108 for (int i = 0; i < N; ++i) { 11109 intentFilters = packageProviders.get(i).intents; 11110 if (intentFilters != null && intentFilters.size() > 0) { 11111 PackageParser.ProviderIntentInfo[] array = 11112 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11113 intentFilters.toArray(array); 11114 listCut.add(array); 11115 } 11116 } 11117 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11118 } 11119 11120 public final void addProvider(PackageParser.Provider p) { 11121 if (mProviders.containsKey(p.getComponentName())) { 11122 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11123 return; 11124 } 11125 11126 mProviders.put(p.getComponentName(), p); 11127 if (DEBUG_SHOW_INFO) { 11128 Log.v(TAG, " " 11129 + (p.info.nonLocalizedLabel != null 11130 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11131 Log.v(TAG, " Class=" + p.info.name); 11132 } 11133 final int NI = p.intents.size(); 11134 int j; 11135 for (j = 0; j < NI; j++) { 11136 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11137 if (DEBUG_SHOW_INFO) { 11138 Log.v(TAG, " IntentFilter:"); 11139 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11140 } 11141 if (!intent.debugCheck()) { 11142 Log.w(TAG, "==> For Provider " + p.info.name); 11143 } 11144 addFilter(intent); 11145 } 11146 } 11147 11148 public final void removeProvider(PackageParser.Provider p) { 11149 mProviders.remove(p.getComponentName()); 11150 if (DEBUG_SHOW_INFO) { 11151 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11152 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11153 Log.v(TAG, " Class=" + p.info.name); 11154 } 11155 final int NI = p.intents.size(); 11156 int j; 11157 for (j = 0; j < NI; j++) { 11158 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11159 if (DEBUG_SHOW_INFO) { 11160 Log.v(TAG, " IntentFilter:"); 11161 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11162 } 11163 removeFilter(intent); 11164 } 11165 } 11166 11167 @Override 11168 protected boolean allowFilterResult( 11169 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11170 ProviderInfo filterPi = filter.provider.info; 11171 for (int i = dest.size() - 1; i >= 0; i--) { 11172 ProviderInfo destPi = dest.get(i).providerInfo; 11173 if (destPi.name == filterPi.name 11174 && destPi.packageName == filterPi.packageName) { 11175 return false; 11176 } 11177 } 11178 return true; 11179 } 11180 11181 @Override 11182 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11183 return new PackageParser.ProviderIntentInfo[size]; 11184 } 11185 11186 @Override 11187 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11188 if (!sUserManager.exists(userId)) 11189 return true; 11190 PackageParser.Package p = filter.provider.owner; 11191 if (p != null) { 11192 PackageSetting ps = (PackageSetting) p.mExtras; 11193 if (ps != null) { 11194 // System apps are never considered stopped for purposes of 11195 // filtering, because there may be no way for the user to 11196 // actually re-launch them. 11197 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11198 && ps.getStopped(userId); 11199 } 11200 } 11201 return false; 11202 } 11203 11204 @Override 11205 protected boolean isPackageForFilter(String packageName, 11206 PackageParser.ProviderIntentInfo info) { 11207 return packageName.equals(info.provider.owner.packageName); 11208 } 11209 11210 @Override 11211 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11212 int match, int userId) { 11213 if (!sUserManager.exists(userId)) 11214 return null; 11215 final PackageParser.ProviderIntentInfo info = filter; 11216 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11217 return null; 11218 } 11219 final PackageParser.Provider provider = info.provider; 11220 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11221 if (ps == null) { 11222 return null; 11223 } 11224 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11225 ps.readUserState(userId), userId); 11226 if (pi == null) { 11227 return null; 11228 } 11229 final ResolveInfo res = new ResolveInfo(); 11230 res.providerInfo = pi; 11231 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11232 res.filter = filter; 11233 } 11234 res.priority = info.getPriority(); 11235 res.preferredOrder = provider.owner.mPreferredOrder; 11236 res.match = match; 11237 res.isDefault = info.hasDefault; 11238 res.labelRes = info.labelRes; 11239 res.nonLocalizedLabel = info.nonLocalizedLabel; 11240 res.icon = info.icon; 11241 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11242 return res; 11243 } 11244 11245 @Override 11246 protected void sortResults(List<ResolveInfo> results) { 11247 Collections.sort(results, mResolvePrioritySorter); 11248 } 11249 11250 @Override 11251 protected void dumpFilter(PrintWriter out, String prefix, 11252 PackageParser.ProviderIntentInfo filter) { 11253 out.print(prefix); 11254 out.print( 11255 Integer.toHexString(System.identityHashCode(filter.provider))); 11256 out.print(' '); 11257 filter.provider.printComponentShortName(out); 11258 out.print(" filter "); 11259 out.println(Integer.toHexString(System.identityHashCode(filter))); 11260 } 11261 11262 @Override 11263 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11264 return filter.provider; 11265 } 11266 11267 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11268 PackageParser.Provider provider = (PackageParser.Provider)label; 11269 out.print(prefix); out.print( 11270 Integer.toHexString(System.identityHashCode(provider))); 11271 out.print(' '); 11272 provider.printComponentShortName(out); 11273 if (count > 1) { 11274 out.print(" ("); out.print(count); out.print(" filters)"); 11275 } 11276 out.println(); 11277 } 11278 11279 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11280 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11281 private int mFlags; 11282 } 11283 11284 private static final class EphemeralIntentResolver 11285 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11286 /** 11287 * The result that has the highest defined order. Ordering applies on a 11288 * per-package basis. Mapping is from package name to Pair of order and 11289 * EphemeralResolveInfo. 11290 * <p> 11291 * NOTE: This is implemented as a field variable for convenience and efficiency. 11292 * By having a field variable, we're able to track filter ordering as soon as 11293 * a non-zero order is defined. Otherwise, multiple loops across the result set 11294 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11295 * this needs to be contained entirely within {@link #filterResults()}. 11296 */ 11297 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11298 11299 @Override 11300 protected EphemeralResolveIntentInfo[] newArray(int size) { 11301 return new EphemeralResolveIntentInfo[size]; 11302 } 11303 11304 @Override 11305 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11306 return true; 11307 } 11308 11309 @Override 11310 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11311 int userId) { 11312 if (!sUserManager.exists(userId)) { 11313 return null; 11314 } 11315 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11316 final Integer order = info.getOrder(); 11317 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11318 mOrderResult.get(packageName); 11319 // ordering is enabled and this item's order isn't high enough 11320 if (lastOrderResult != null && lastOrderResult.first >= order) { 11321 return null; 11322 } 11323 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11324 if (order > 0) { 11325 // non-zero order, enable ordering 11326 mOrderResult.put(packageName, new Pair<>(order, res)); 11327 } 11328 return res; 11329 } 11330 11331 @Override 11332 protected void filterResults(List<EphemeralResolveInfo> results) { 11333 // only do work if ordering is enabled [most of the time it won't be] 11334 if (mOrderResult.size() == 0) { 11335 return; 11336 } 11337 int resultSize = results.size(); 11338 for (int i = 0; i < resultSize; i++) { 11339 final EphemeralResolveInfo info = results.get(i); 11340 final String packageName = info.getPackageName(); 11341 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11342 if (savedInfo == null) { 11343 // package doesn't having ordering 11344 continue; 11345 } 11346 if (savedInfo.second == info) { 11347 // circled back to the highest ordered item; remove from order list 11348 mOrderResult.remove(savedInfo); 11349 if (mOrderResult.size() == 0) { 11350 // no more ordered items 11351 break; 11352 } 11353 continue; 11354 } 11355 // item has a worse order, remove it from the result list 11356 results.remove(i); 11357 resultSize--; 11358 i--; 11359 } 11360 } 11361 } 11362 11363 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11364 new Comparator<ResolveInfo>() { 11365 public int compare(ResolveInfo r1, ResolveInfo r2) { 11366 int v1 = r1.priority; 11367 int v2 = r2.priority; 11368 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11369 if (v1 != v2) { 11370 return (v1 > v2) ? -1 : 1; 11371 } 11372 v1 = r1.preferredOrder; 11373 v2 = r2.preferredOrder; 11374 if (v1 != v2) { 11375 return (v1 > v2) ? -1 : 1; 11376 } 11377 if (r1.isDefault != r2.isDefault) { 11378 return r1.isDefault ? -1 : 1; 11379 } 11380 v1 = r1.match; 11381 v2 = r2.match; 11382 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11383 if (v1 != v2) { 11384 return (v1 > v2) ? -1 : 1; 11385 } 11386 if (r1.system != r2.system) { 11387 return r1.system ? -1 : 1; 11388 } 11389 if (r1.activityInfo != null) { 11390 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11391 } 11392 if (r1.serviceInfo != null) { 11393 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11394 } 11395 if (r1.providerInfo != null) { 11396 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11397 } 11398 return 0; 11399 } 11400 }; 11401 11402 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11403 new Comparator<ProviderInfo>() { 11404 public int compare(ProviderInfo p1, ProviderInfo p2) { 11405 final int v1 = p1.initOrder; 11406 final int v2 = p2.initOrder; 11407 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11408 } 11409 }; 11410 11411 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11412 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11413 final int[] userIds) { 11414 mHandler.post(new Runnable() { 11415 @Override 11416 public void run() { 11417 try { 11418 final IActivityManager am = ActivityManagerNative.getDefault(); 11419 if (am == null) return; 11420 final int[] resolvedUserIds; 11421 if (userIds == null) { 11422 resolvedUserIds = am.getRunningUserIds(); 11423 } else { 11424 resolvedUserIds = userIds; 11425 } 11426 for (int id : resolvedUserIds) { 11427 final Intent intent = new Intent(action, 11428 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11429 if (extras != null) { 11430 intent.putExtras(extras); 11431 } 11432 if (targetPkg != null) { 11433 intent.setPackage(targetPkg); 11434 } 11435 // Modify the UID when posting to other users 11436 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11437 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11438 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11439 intent.putExtra(Intent.EXTRA_UID, uid); 11440 } 11441 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11442 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11443 if (DEBUG_BROADCASTS) { 11444 RuntimeException here = new RuntimeException("here"); 11445 here.fillInStackTrace(); 11446 Slog.d(TAG, "Sending to user " + id + ": " 11447 + intent.toShortString(false, true, false, false) 11448 + " " + intent.getExtras(), here); 11449 } 11450 am.broadcastIntent(null, intent, null, finishedReceiver, 11451 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11452 null, finishedReceiver != null, false, id); 11453 } 11454 } catch (RemoteException ex) { 11455 } 11456 } 11457 }); 11458 } 11459 11460 /** 11461 * Check if the external storage media is available. This is true if there 11462 * is a mounted external storage medium or if the external storage is 11463 * emulated. 11464 */ 11465 private boolean isExternalMediaAvailable() { 11466 return mMediaMounted || Environment.isExternalStorageEmulated(); 11467 } 11468 11469 @Override 11470 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11471 // writer 11472 synchronized (mPackages) { 11473 if (!isExternalMediaAvailable()) { 11474 // If the external storage is no longer mounted at this point, 11475 // the caller may not have been able to delete all of this 11476 // packages files and can not delete any more. Bail. 11477 return null; 11478 } 11479 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11480 if (lastPackage != null) { 11481 pkgs.remove(lastPackage); 11482 } 11483 if (pkgs.size() > 0) { 11484 return pkgs.get(0); 11485 } 11486 } 11487 return null; 11488 } 11489 11490 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11491 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11492 userId, andCode ? 1 : 0, packageName); 11493 if (mSystemReady) { 11494 msg.sendToTarget(); 11495 } else { 11496 if (mPostSystemReadyMessages == null) { 11497 mPostSystemReadyMessages = new ArrayList<>(); 11498 } 11499 mPostSystemReadyMessages.add(msg); 11500 } 11501 } 11502 11503 void startCleaningPackages() { 11504 // reader 11505 if (!isExternalMediaAvailable()) { 11506 return; 11507 } 11508 synchronized (mPackages) { 11509 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11510 return; 11511 } 11512 } 11513 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11514 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11515 IActivityManager am = ActivityManagerNative.getDefault(); 11516 if (am != null) { 11517 try { 11518 am.startService(null, intent, null, mContext.getOpPackageName(), 11519 UserHandle.USER_SYSTEM); 11520 } catch (RemoteException e) { 11521 } 11522 } 11523 } 11524 11525 @Override 11526 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11527 int installFlags, String installerPackageName, int userId) { 11528 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11529 11530 final int callingUid = Binder.getCallingUid(); 11531 enforceCrossUserPermission(callingUid, userId, 11532 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11533 11534 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11535 try { 11536 if (observer != null) { 11537 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11538 } 11539 } catch (RemoteException re) { 11540 } 11541 return; 11542 } 11543 11544 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11545 installFlags |= PackageManager.INSTALL_FROM_ADB; 11546 11547 } else { 11548 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11549 // about installerPackageName. 11550 11551 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11552 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11553 } 11554 11555 UserHandle user; 11556 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11557 user = UserHandle.ALL; 11558 } else { 11559 user = new UserHandle(userId); 11560 } 11561 11562 // Only system components can circumvent runtime permissions when installing. 11563 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11564 && mContext.checkCallingOrSelfPermission(Manifest.permission 11565 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11566 throw new SecurityException("You need the " 11567 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11568 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11569 } 11570 11571 final File originFile = new File(originPath); 11572 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11573 11574 final Message msg = mHandler.obtainMessage(INIT_COPY); 11575 final VerificationInfo verificationInfo = new VerificationInfo( 11576 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11577 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11578 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11579 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11580 null /*certificates*/); 11581 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11582 msg.obj = params; 11583 11584 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11585 System.identityHashCode(msg.obj)); 11586 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11587 System.identityHashCode(msg.obj)); 11588 11589 mHandler.sendMessage(msg); 11590 } 11591 11592 void installStage(String packageName, File stagedDir, String stagedCid, 11593 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11594 String installerPackageName, int installerUid, UserHandle user, 11595 Certificate[][] certificates) { 11596 if (DEBUG_EPHEMERAL) { 11597 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11598 Slog.d(TAG, "Ephemeral install of " + packageName); 11599 } 11600 } 11601 final VerificationInfo verificationInfo = new VerificationInfo( 11602 sessionParams.originatingUri, sessionParams.referrerUri, 11603 sessionParams.originatingUid, installerUid); 11604 11605 final OriginInfo origin; 11606 if (stagedDir != null) { 11607 origin = OriginInfo.fromStagedFile(stagedDir); 11608 } else { 11609 origin = OriginInfo.fromStagedContainer(stagedCid); 11610 } 11611 11612 final Message msg = mHandler.obtainMessage(INIT_COPY); 11613 final InstallParams params = new InstallParams(origin, null, observer, 11614 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11615 verificationInfo, user, sessionParams.abiOverride, 11616 sessionParams.grantedRuntimePermissions, certificates); 11617 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11618 msg.obj = params; 11619 11620 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11621 System.identityHashCode(msg.obj)); 11622 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11623 System.identityHashCode(msg.obj)); 11624 11625 mHandler.sendMessage(msg); 11626 } 11627 11628 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11629 int userId) { 11630 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11631 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11632 } 11633 11634 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11635 int appId, int userId) { 11636 Bundle extras = new Bundle(1); 11637 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11638 11639 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11640 packageName, extras, 0, null, null, new int[] {userId}); 11641 try { 11642 IActivityManager am = ActivityManagerNative.getDefault(); 11643 if (isSystem && am.isUserRunning(userId, 0)) { 11644 // The just-installed/enabled app is bundled on the system, so presumed 11645 // to be able to run automatically without needing an explicit launch. 11646 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11647 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11648 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11649 .setPackage(packageName); 11650 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11651 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11652 } 11653 } catch (RemoteException e) { 11654 // shouldn't happen 11655 Slog.w(TAG, "Unable to bootstrap installed package", e); 11656 } 11657 } 11658 11659 @Override 11660 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11661 int userId) { 11662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11663 PackageSetting pkgSetting; 11664 final int uid = Binder.getCallingUid(); 11665 enforceCrossUserPermission(uid, userId, 11666 true /* requireFullPermission */, true /* checkShell */, 11667 "setApplicationHiddenSetting for user " + userId); 11668 11669 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11670 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11671 return false; 11672 } 11673 11674 long callingId = Binder.clearCallingIdentity(); 11675 try { 11676 boolean sendAdded = false; 11677 boolean sendRemoved = false; 11678 // writer 11679 synchronized (mPackages) { 11680 pkgSetting = mSettings.mPackages.get(packageName); 11681 if (pkgSetting == null) { 11682 return false; 11683 } 11684 // Do not allow "android" is being disabled 11685 if ("android".equals(packageName)) { 11686 Slog.w(TAG, "Cannot hide package: android"); 11687 return false; 11688 } 11689 // Only allow protected packages to hide themselves. 11690 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11691 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11692 Slog.w(TAG, "Not hiding protected package: " + packageName); 11693 return false; 11694 } 11695 11696 if (pkgSetting.getHidden(userId) != hidden) { 11697 pkgSetting.setHidden(hidden, userId); 11698 mSettings.writePackageRestrictionsLPr(userId); 11699 if (hidden) { 11700 sendRemoved = true; 11701 } else { 11702 sendAdded = true; 11703 } 11704 } 11705 } 11706 if (sendAdded) { 11707 sendPackageAddedForUser(packageName, pkgSetting, userId); 11708 return true; 11709 } 11710 if (sendRemoved) { 11711 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11712 "hiding pkg"); 11713 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11714 return true; 11715 } 11716 } finally { 11717 Binder.restoreCallingIdentity(callingId); 11718 } 11719 return false; 11720 } 11721 11722 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11723 int userId) { 11724 final PackageRemovedInfo info = new PackageRemovedInfo(); 11725 info.removedPackage = packageName; 11726 info.removedUsers = new int[] {userId}; 11727 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11728 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11729 } 11730 11731 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11732 if (pkgList.length > 0) { 11733 Bundle extras = new Bundle(1); 11734 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11735 11736 sendPackageBroadcast( 11737 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11738 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11739 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11740 new int[] {userId}); 11741 } 11742 } 11743 11744 /** 11745 * Returns true if application is not found or there was an error. Otherwise it returns 11746 * the hidden state of the package for the given user. 11747 */ 11748 @Override 11749 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11750 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11751 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11752 true /* requireFullPermission */, false /* checkShell */, 11753 "getApplicationHidden for user " + userId); 11754 PackageSetting pkgSetting; 11755 long callingId = Binder.clearCallingIdentity(); 11756 try { 11757 // writer 11758 synchronized (mPackages) { 11759 pkgSetting = mSettings.mPackages.get(packageName); 11760 if (pkgSetting == null) { 11761 return true; 11762 } 11763 return pkgSetting.getHidden(userId); 11764 } 11765 } finally { 11766 Binder.restoreCallingIdentity(callingId); 11767 } 11768 } 11769 11770 /** 11771 * @hide 11772 */ 11773 @Override 11774 public int installExistingPackageAsUser(String packageName, int userId) { 11775 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11776 null); 11777 PackageSetting pkgSetting; 11778 final int uid = Binder.getCallingUid(); 11779 enforceCrossUserPermission(uid, userId, 11780 true /* requireFullPermission */, true /* checkShell */, 11781 "installExistingPackage for user " + userId); 11782 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11783 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11784 } 11785 11786 long callingId = Binder.clearCallingIdentity(); 11787 try { 11788 boolean installed = false; 11789 11790 // writer 11791 synchronized (mPackages) { 11792 pkgSetting = mSettings.mPackages.get(packageName); 11793 if (pkgSetting == null) { 11794 return PackageManager.INSTALL_FAILED_INVALID_URI; 11795 } 11796 if (!pkgSetting.getInstalled(userId)) { 11797 pkgSetting.setInstalled(true, userId); 11798 pkgSetting.setHidden(false, userId); 11799 mSettings.writePackageRestrictionsLPr(userId); 11800 installed = true; 11801 } 11802 } 11803 11804 if (installed) { 11805 if (pkgSetting.pkg != null) { 11806 synchronized (mInstallLock) { 11807 // We don't need to freeze for a brand new install 11808 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11809 } 11810 } 11811 sendPackageAddedForUser(packageName, pkgSetting, userId); 11812 } 11813 } finally { 11814 Binder.restoreCallingIdentity(callingId); 11815 } 11816 11817 return PackageManager.INSTALL_SUCCEEDED; 11818 } 11819 11820 boolean isUserRestricted(int userId, String restrictionKey) { 11821 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11822 if (restrictions.getBoolean(restrictionKey, false)) { 11823 Log.w(TAG, "User is restricted: " + restrictionKey); 11824 return true; 11825 } 11826 return false; 11827 } 11828 11829 @Override 11830 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11831 int userId) { 11832 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11833 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11834 true /* requireFullPermission */, true /* checkShell */, 11835 "setPackagesSuspended for user " + userId); 11836 11837 if (ArrayUtils.isEmpty(packageNames)) { 11838 return packageNames; 11839 } 11840 11841 // List of package names for whom the suspended state has changed. 11842 List<String> changedPackages = new ArrayList<>(packageNames.length); 11843 // List of package names for whom the suspended state is not set as requested in this 11844 // method. 11845 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11846 long callingId = Binder.clearCallingIdentity(); 11847 try { 11848 for (int i = 0; i < packageNames.length; i++) { 11849 String packageName = packageNames[i]; 11850 boolean changed = false; 11851 final int appId; 11852 synchronized (mPackages) { 11853 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11854 if (pkgSetting == null) { 11855 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11856 + "\". Skipping suspending/un-suspending."); 11857 unactionedPackages.add(packageName); 11858 continue; 11859 } 11860 appId = pkgSetting.appId; 11861 if (pkgSetting.getSuspended(userId) != suspended) { 11862 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11863 unactionedPackages.add(packageName); 11864 continue; 11865 } 11866 pkgSetting.setSuspended(suspended, userId); 11867 mSettings.writePackageRestrictionsLPr(userId); 11868 changed = true; 11869 changedPackages.add(packageName); 11870 } 11871 } 11872 11873 if (changed && suspended) { 11874 killApplication(packageName, UserHandle.getUid(userId, appId), 11875 "suspending package"); 11876 } 11877 } 11878 } finally { 11879 Binder.restoreCallingIdentity(callingId); 11880 } 11881 11882 if (!changedPackages.isEmpty()) { 11883 sendPackagesSuspendedForUser(changedPackages.toArray( 11884 new String[changedPackages.size()]), userId, suspended); 11885 } 11886 11887 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11888 } 11889 11890 @Override 11891 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11892 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11893 true /* requireFullPermission */, false /* checkShell */, 11894 "isPackageSuspendedForUser for user " + userId); 11895 synchronized (mPackages) { 11896 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11897 if (pkgSetting == null) { 11898 throw new IllegalArgumentException("Unknown target package: " + packageName); 11899 } 11900 return pkgSetting.getSuspended(userId); 11901 } 11902 } 11903 11904 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11905 if (isPackageDeviceAdmin(packageName, userId)) { 11906 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11907 + "\": has an active device admin"); 11908 return false; 11909 } 11910 11911 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11912 if (packageName.equals(activeLauncherPackageName)) { 11913 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11914 + "\": contains the active launcher"); 11915 return false; 11916 } 11917 11918 if (packageName.equals(mRequiredInstallerPackage)) { 11919 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11920 + "\": required for package installation"); 11921 return false; 11922 } 11923 11924 if (packageName.equals(mRequiredUninstallerPackage)) { 11925 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11926 + "\": required for package uninstallation"); 11927 return false; 11928 } 11929 11930 if (packageName.equals(mRequiredVerifierPackage)) { 11931 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11932 + "\": required for package verification"); 11933 return false; 11934 } 11935 11936 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11937 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11938 + "\": is the default dialer"); 11939 return false; 11940 } 11941 11942 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11943 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11944 + "\": protected package"); 11945 return false; 11946 } 11947 11948 return true; 11949 } 11950 11951 private String getActiveLauncherPackageName(int userId) { 11952 Intent intent = new Intent(Intent.ACTION_MAIN); 11953 intent.addCategory(Intent.CATEGORY_HOME); 11954 ResolveInfo resolveInfo = resolveIntent( 11955 intent, 11956 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11957 PackageManager.MATCH_DEFAULT_ONLY, 11958 userId); 11959 11960 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11961 } 11962 11963 private String getDefaultDialerPackageName(int userId) { 11964 synchronized (mPackages) { 11965 return mSettings.getDefaultDialerPackageNameLPw(userId); 11966 } 11967 } 11968 11969 @Override 11970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11971 mContext.enforceCallingOrSelfPermission( 11972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11973 "Only package verification agents can verify applications"); 11974 11975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11976 final PackageVerificationResponse response = new PackageVerificationResponse( 11977 verificationCode, Binder.getCallingUid()); 11978 msg.arg1 = id; 11979 msg.obj = response; 11980 mHandler.sendMessage(msg); 11981 } 11982 11983 @Override 11984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11985 long millisecondsToDelay) { 11986 mContext.enforceCallingOrSelfPermission( 11987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11988 "Only package verification agents can extend verification timeouts"); 11989 11990 final PackageVerificationState state = mPendingVerification.get(id); 11991 final PackageVerificationResponse response = new PackageVerificationResponse( 11992 verificationCodeAtTimeout, Binder.getCallingUid()); 11993 11994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11996 } 11997 if (millisecondsToDelay < 0) { 11998 millisecondsToDelay = 0; 11999 } 12000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12003 } 12004 12005 if ((state != null) && !state.timeoutExtended()) { 12006 state.extendTimeout(); 12007 12008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12009 msg.arg1 = id; 12010 msg.obj = response; 12011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12012 } 12013 } 12014 12015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12016 int verificationCode, UserHandle user) { 12017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12022 12023 mContext.sendBroadcastAsUser(intent, user, 12024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12025 } 12026 12027 private ComponentName matchComponentForVerifier(String packageName, 12028 List<ResolveInfo> receivers) { 12029 ActivityInfo targetReceiver = null; 12030 12031 final int NR = receivers.size(); 12032 for (int i = 0; i < NR; i++) { 12033 final ResolveInfo info = receivers.get(i); 12034 if (info.activityInfo == null) { 12035 continue; 12036 } 12037 12038 if (packageName.equals(info.activityInfo.packageName)) { 12039 targetReceiver = info.activityInfo; 12040 break; 12041 } 12042 } 12043 12044 if (targetReceiver == null) { 12045 return null; 12046 } 12047 12048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12049 } 12050 12051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12053 if (pkgInfo.verifiers.length == 0) { 12054 return null; 12055 } 12056 12057 final int N = pkgInfo.verifiers.length; 12058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12059 for (int i = 0; i < N; i++) { 12060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12061 12062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12063 receivers); 12064 if (comp == null) { 12065 continue; 12066 } 12067 12068 final int verifierUid = getUidForVerifier(verifierInfo); 12069 if (verifierUid == -1) { 12070 continue; 12071 } 12072 12073 if (DEBUG_VERIFY) { 12074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12075 + " with the correct signature"); 12076 } 12077 sufficientVerifiers.add(comp); 12078 verificationState.addSufficientVerifier(verifierUid); 12079 } 12080 12081 return sufficientVerifiers; 12082 } 12083 12084 private int getUidForVerifier(VerifierInfo verifierInfo) { 12085 synchronized (mPackages) { 12086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12087 if (pkg == null) { 12088 return -1; 12089 } else if (pkg.mSignatures.length != 1) { 12090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12091 + " has more than one signature; ignoring"); 12092 return -1; 12093 } 12094 12095 /* 12096 * If the public key of the package's signature does not match 12097 * our expected public key, then this is a different package and 12098 * we should skip. 12099 */ 12100 12101 final byte[] expectedPublicKey; 12102 try { 12103 final Signature verifierSig = pkg.mSignatures[0]; 12104 final PublicKey publicKey = verifierSig.getPublicKey(); 12105 expectedPublicKey = publicKey.getEncoded(); 12106 } catch (CertificateException e) { 12107 return -1; 12108 } 12109 12110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12111 12112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12114 + " does not have the expected public key; ignoring"); 12115 return -1; 12116 } 12117 12118 return pkg.applicationInfo.uid; 12119 } 12120 } 12121 12122 @Override 12123 public void finishPackageInstall(int token, boolean didLaunch) { 12124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12125 12126 if (DEBUG_INSTALL) { 12127 Slog.v(TAG, "BM finishing package install for " + token); 12128 } 12129 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12130 12131 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12132 mHandler.sendMessage(msg); 12133 } 12134 12135 /** 12136 * Get the verification agent timeout. 12137 * 12138 * @return verification timeout in milliseconds 12139 */ 12140 private long getVerificationTimeout() { 12141 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12142 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12143 DEFAULT_VERIFICATION_TIMEOUT); 12144 } 12145 12146 /** 12147 * Get the default verification agent response code. 12148 * 12149 * @return default verification response code 12150 */ 12151 private int getDefaultVerificationResponse() { 12152 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12153 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12154 DEFAULT_VERIFICATION_RESPONSE); 12155 } 12156 12157 /** 12158 * Check whether or not package verification has been enabled. 12159 * 12160 * @return true if verification should be performed 12161 */ 12162 private boolean isVerificationEnabled(int userId, int installFlags) { 12163 if (!DEFAULT_VERIFY_ENABLE) { 12164 return false; 12165 } 12166 // Ephemeral apps don't get the full verification treatment 12167 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12168 if (DEBUG_EPHEMERAL) { 12169 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12170 } 12171 return false; 12172 } 12173 12174 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12175 12176 // Check if installing from ADB 12177 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12178 // Do not run verification in a test harness environment 12179 if (ActivityManager.isRunningInTestHarness()) { 12180 return false; 12181 } 12182 if (ensureVerifyAppsEnabled) { 12183 return true; 12184 } 12185 // Check if the developer does not want package verification for ADB installs 12186 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12187 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12188 return false; 12189 } 12190 } 12191 12192 if (ensureVerifyAppsEnabled) { 12193 return true; 12194 } 12195 12196 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12197 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12198 } 12199 12200 @Override 12201 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12202 throws RemoteException { 12203 mContext.enforceCallingOrSelfPermission( 12204 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12205 "Only intentfilter verification agents can verify applications"); 12206 12207 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12208 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12209 Binder.getCallingUid(), verificationCode, failedDomains); 12210 msg.arg1 = id; 12211 msg.obj = response; 12212 mHandler.sendMessage(msg); 12213 } 12214 12215 @Override 12216 public int getIntentVerificationStatus(String packageName, int userId) { 12217 synchronized (mPackages) { 12218 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12219 } 12220 } 12221 12222 @Override 12223 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12224 mContext.enforceCallingOrSelfPermission( 12225 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12226 12227 boolean result = false; 12228 synchronized (mPackages) { 12229 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12230 } 12231 if (result) { 12232 scheduleWritePackageRestrictionsLocked(userId); 12233 } 12234 return result; 12235 } 12236 12237 @Override 12238 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12239 String packageName) { 12240 synchronized (mPackages) { 12241 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12242 } 12243 } 12244 12245 @Override 12246 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12247 if (TextUtils.isEmpty(packageName)) { 12248 return ParceledListSlice.emptyList(); 12249 } 12250 synchronized (mPackages) { 12251 PackageParser.Package pkg = mPackages.get(packageName); 12252 if (pkg == null || pkg.activities == null) { 12253 return ParceledListSlice.emptyList(); 12254 } 12255 final int count = pkg.activities.size(); 12256 ArrayList<IntentFilter> result = new ArrayList<>(); 12257 for (int n=0; n<count; n++) { 12258 PackageParser.Activity activity = pkg.activities.get(n); 12259 if (activity.intents != null && activity.intents.size() > 0) { 12260 result.addAll(activity.intents); 12261 } 12262 } 12263 return new ParceledListSlice<>(result); 12264 } 12265 } 12266 12267 @Override 12268 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12269 mContext.enforceCallingOrSelfPermission( 12270 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12271 12272 synchronized (mPackages) { 12273 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12274 if (packageName != null) { 12275 result |= updateIntentVerificationStatus(packageName, 12276 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12277 userId); 12278 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12279 packageName, userId); 12280 } 12281 return result; 12282 } 12283 } 12284 12285 @Override 12286 public String getDefaultBrowserPackageName(int userId) { 12287 synchronized (mPackages) { 12288 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12289 } 12290 } 12291 12292 /** 12293 * Get the "allow unknown sources" setting. 12294 * 12295 * @return the current "allow unknown sources" setting 12296 */ 12297 private int getUnknownSourcesSettings() { 12298 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12299 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12300 -1); 12301 } 12302 12303 @Override 12304 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12305 final int uid = Binder.getCallingUid(); 12306 // writer 12307 synchronized (mPackages) { 12308 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12309 if (targetPackageSetting == null) { 12310 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12311 } 12312 12313 PackageSetting installerPackageSetting; 12314 if (installerPackageName != null) { 12315 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12316 if (installerPackageSetting == null) { 12317 throw new IllegalArgumentException("Unknown installer package: " 12318 + installerPackageName); 12319 } 12320 } else { 12321 installerPackageSetting = null; 12322 } 12323 12324 Signature[] callerSignature; 12325 Object obj = mSettings.getUserIdLPr(uid); 12326 if (obj != null) { 12327 if (obj instanceof SharedUserSetting) { 12328 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12329 } else if (obj instanceof PackageSetting) { 12330 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12331 } else { 12332 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12333 } 12334 } else { 12335 throw new SecurityException("Unknown calling UID: " + uid); 12336 } 12337 12338 // Verify: can't set installerPackageName to a package that is 12339 // not signed with the same cert as the caller. 12340 if (installerPackageSetting != null) { 12341 if (compareSignatures(callerSignature, 12342 installerPackageSetting.signatures.mSignatures) 12343 != PackageManager.SIGNATURE_MATCH) { 12344 throw new SecurityException( 12345 "Caller does not have same cert as new installer package " 12346 + installerPackageName); 12347 } 12348 } 12349 12350 // Verify: if target already has an installer package, it must 12351 // be signed with the same cert as the caller. 12352 if (targetPackageSetting.installerPackageName != null) { 12353 PackageSetting setting = mSettings.mPackages.get( 12354 targetPackageSetting.installerPackageName); 12355 // If the currently set package isn't valid, then it's always 12356 // okay to change it. 12357 if (setting != null) { 12358 if (compareSignatures(callerSignature, 12359 setting.signatures.mSignatures) 12360 != PackageManager.SIGNATURE_MATCH) { 12361 throw new SecurityException( 12362 "Caller does not have same cert as old installer package " 12363 + targetPackageSetting.installerPackageName); 12364 } 12365 } 12366 } 12367 12368 // Okay! 12369 targetPackageSetting.installerPackageName = installerPackageName; 12370 if (installerPackageName != null) { 12371 mSettings.mInstallerPackages.add(installerPackageName); 12372 } 12373 scheduleWriteSettingsLocked(); 12374 } 12375 } 12376 12377 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12378 // Queue up an async operation since the package installation may take a little while. 12379 mHandler.post(new Runnable() { 12380 public void run() { 12381 mHandler.removeCallbacks(this); 12382 // Result object to be returned 12383 PackageInstalledInfo res = new PackageInstalledInfo(); 12384 res.setReturnCode(currentStatus); 12385 res.uid = -1; 12386 res.pkg = null; 12387 res.removedInfo = null; 12388 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12389 args.doPreInstall(res.returnCode); 12390 synchronized (mInstallLock) { 12391 installPackageTracedLI(args, res); 12392 } 12393 args.doPostInstall(res.returnCode, res.uid); 12394 } 12395 12396 // A restore should be performed at this point if (a) the install 12397 // succeeded, (b) the operation is not an update, and (c) the new 12398 // package has not opted out of backup participation. 12399 final boolean update = res.removedInfo != null 12400 && res.removedInfo.removedPackage != null; 12401 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12402 boolean doRestore = !update 12403 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12404 12405 // Set up the post-install work request bookkeeping. This will be used 12406 // and cleaned up by the post-install event handling regardless of whether 12407 // there's a restore pass performed. Token values are >= 1. 12408 int token; 12409 if (mNextInstallToken < 0) mNextInstallToken = 1; 12410 token = mNextInstallToken++; 12411 12412 PostInstallData data = new PostInstallData(args, res); 12413 mRunningInstalls.put(token, data); 12414 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12415 12416 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12417 // Pass responsibility to the Backup Manager. It will perform a 12418 // restore if appropriate, then pass responsibility back to the 12419 // Package Manager to run the post-install observer callbacks 12420 // and broadcasts. 12421 IBackupManager bm = IBackupManager.Stub.asInterface( 12422 ServiceManager.getService(Context.BACKUP_SERVICE)); 12423 if (bm != null) { 12424 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12425 + " to BM for possible restore"); 12426 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12427 try { 12428 // TODO: http://b/22388012 12429 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12430 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12431 } else { 12432 doRestore = false; 12433 } 12434 } catch (RemoteException e) { 12435 // can't happen; the backup manager is local 12436 } catch (Exception e) { 12437 Slog.e(TAG, "Exception trying to enqueue restore", e); 12438 doRestore = false; 12439 } 12440 } else { 12441 Slog.e(TAG, "Backup Manager not found!"); 12442 doRestore = false; 12443 } 12444 } 12445 12446 if (!doRestore) { 12447 // No restore possible, or the Backup Manager was mysteriously not 12448 // available -- just fire the post-install work request directly. 12449 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12450 12451 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12452 12453 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12454 mHandler.sendMessage(msg); 12455 } 12456 } 12457 }); 12458 } 12459 12460 /** 12461 * Callback from PackageSettings whenever an app is first transitioned out of the 12462 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12463 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12464 * here whether the app is the target of an ongoing install, and only send the 12465 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12466 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12467 * handling. 12468 */ 12469 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12470 // Serialize this with the rest of the install-process message chain. In the 12471 // restore-at-install case, this Runnable will necessarily run before the 12472 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12473 // are coherent. In the non-restore case, the app has already completed install 12474 // and been launched through some other means, so it is not in a problematic 12475 // state for observers to see the FIRST_LAUNCH signal. 12476 mHandler.post(new Runnable() { 12477 @Override 12478 public void run() { 12479 for (int i = 0; i < mRunningInstalls.size(); i++) { 12480 final PostInstallData data = mRunningInstalls.valueAt(i); 12481 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12482 continue; 12483 } 12484 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12485 // right package; but is it for the right user? 12486 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12487 if (userId == data.res.newUsers[uIndex]) { 12488 if (DEBUG_BACKUP) { 12489 Slog.i(TAG, "Package " + pkgName 12490 + " being restored so deferring FIRST_LAUNCH"); 12491 } 12492 return; 12493 } 12494 } 12495 } 12496 } 12497 // didn't find it, so not being restored 12498 if (DEBUG_BACKUP) { 12499 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12500 } 12501 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12502 } 12503 }); 12504 } 12505 12506 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12507 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12508 installerPkg, null, userIds); 12509 } 12510 12511 private abstract class HandlerParams { 12512 private static final int MAX_RETRIES = 4; 12513 12514 /** 12515 * Number of times startCopy() has been attempted and had a non-fatal 12516 * error. 12517 */ 12518 private int mRetries = 0; 12519 12520 /** User handle for the user requesting the information or installation. */ 12521 private final UserHandle mUser; 12522 String traceMethod; 12523 int traceCookie; 12524 12525 HandlerParams(UserHandle user) { 12526 mUser = user; 12527 } 12528 12529 UserHandle getUser() { 12530 return mUser; 12531 } 12532 12533 HandlerParams setTraceMethod(String traceMethod) { 12534 this.traceMethod = traceMethod; 12535 return this; 12536 } 12537 12538 HandlerParams setTraceCookie(int traceCookie) { 12539 this.traceCookie = traceCookie; 12540 return this; 12541 } 12542 12543 final boolean startCopy() { 12544 boolean res; 12545 try { 12546 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12547 12548 if (++mRetries > MAX_RETRIES) { 12549 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12550 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12551 handleServiceError(); 12552 return false; 12553 } else { 12554 handleStartCopy(); 12555 res = true; 12556 } 12557 } catch (RemoteException e) { 12558 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12559 mHandler.sendEmptyMessage(MCS_RECONNECT); 12560 res = false; 12561 } 12562 handleReturnCode(); 12563 return res; 12564 } 12565 12566 final void serviceError() { 12567 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12568 handleServiceError(); 12569 handleReturnCode(); 12570 } 12571 12572 abstract void handleStartCopy() throws RemoteException; 12573 abstract void handleServiceError(); 12574 abstract void handleReturnCode(); 12575 } 12576 12577 class MeasureParams extends HandlerParams { 12578 private final PackageStats mStats; 12579 private boolean mSuccess; 12580 12581 private final IPackageStatsObserver mObserver; 12582 12583 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12584 super(new UserHandle(stats.userHandle)); 12585 mObserver = observer; 12586 mStats = stats; 12587 } 12588 12589 @Override 12590 public String toString() { 12591 return "MeasureParams{" 12592 + Integer.toHexString(System.identityHashCode(this)) 12593 + " " + mStats.packageName + "}"; 12594 } 12595 12596 @Override 12597 void handleStartCopy() throws RemoteException { 12598 synchronized (mInstallLock) { 12599 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12600 } 12601 12602 if (mSuccess) { 12603 boolean mounted = false; 12604 try { 12605 final String status = Environment.getExternalStorageState(); 12606 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12607 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12608 } catch (Exception e) { 12609 } 12610 12611 if (mounted) { 12612 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12613 12614 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12615 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12616 12617 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12618 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12619 12620 // Always subtract cache size, since it's a subdirectory 12621 mStats.externalDataSize -= mStats.externalCacheSize; 12622 12623 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12624 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12625 12626 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12627 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12628 } 12629 } 12630 } 12631 12632 @Override 12633 void handleReturnCode() { 12634 if (mObserver != null) { 12635 try { 12636 mObserver.onGetStatsCompleted(mStats, mSuccess); 12637 } catch (RemoteException e) { 12638 Slog.i(TAG, "Observer no longer exists."); 12639 } 12640 } 12641 } 12642 12643 @Override 12644 void handleServiceError() { 12645 Slog.e(TAG, "Could not measure application " + mStats.packageName 12646 + " external storage"); 12647 } 12648 } 12649 12650 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12651 throws RemoteException { 12652 long result = 0; 12653 for (File path : paths) { 12654 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12655 } 12656 return result; 12657 } 12658 12659 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12660 for (File path : paths) { 12661 try { 12662 mcs.clearDirectory(path.getAbsolutePath()); 12663 } catch (RemoteException e) { 12664 } 12665 } 12666 } 12667 12668 static class OriginInfo { 12669 /** 12670 * Location where install is coming from, before it has been 12671 * copied/renamed into place. This could be a single monolithic APK 12672 * file, or a cluster directory. This location may be untrusted. 12673 */ 12674 final File file; 12675 final String cid; 12676 12677 /** 12678 * Flag indicating that {@link #file} or {@link #cid} has already been 12679 * staged, meaning downstream users don't need to defensively copy the 12680 * contents. 12681 */ 12682 final boolean staged; 12683 12684 /** 12685 * Flag indicating that {@link #file} or {@link #cid} is an already 12686 * installed app that is being moved. 12687 */ 12688 final boolean existing; 12689 12690 final String resolvedPath; 12691 final File resolvedFile; 12692 12693 static OriginInfo fromNothing() { 12694 return new OriginInfo(null, null, false, false); 12695 } 12696 12697 static OriginInfo fromUntrustedFile(File file) { 12698 return new OriginInfo(file, null, false, false); 12699 } 12700 12701 static OriginInfo fromExistingFile(File file) { 12702 return new OriginInfo(file, null, false, true); 12703 } 12704 12705 static OriginInfo fromStagedFile(File file) { 12706 return new OriginInfo(file, null, true, false); 12707 } 12708 12709 static OriginInfo fromStagedContainer(String cid) { 12710 return new OriginInfo(null, cid, true, false); 12711 } 12712 12713 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12714 this.file = file; 12715 this.cid = cid; 12716 this.staged = staged; 12717 this.existing = existing; 12718 12719 if (cid != null) { 12720 resolvedPath = PackageHelper.getSdDir(cid); 12721 resolvedFile = new File(resolvedPath); 12722 } else if (file != null) { 12723 resolvedPath = file.getAbsolutePath(); 12724 resolvedFile = file; 12725 } else { 12726 resolvedPath = null; 12727 resolvedFile = null; 12728 } 12729 } 12730 } 12731 12732 static class MoveInfo { 12733 final int moveId; 12734 final String fromUuid; 12735 final String toUuid; 12736 final String packageName; 12737 final String dataAppName; 12738 final int appId; 12739 final String seinfo; 12740 final int targetSdkVersion; 12741 12742 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12743 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12744 this.moveId = moveId; 12745 this.fromUuid = fromUuid; 12746 this.toUuid = toUuid; 12747 this.packageName = packageName; 12748 this.dataAppName = dataAppName; 12749 this.appId = appId; 12750 this.seinfo = seinfo; 12751 this.targetSdkVersion = targetSdkVersion; 12752 } 12753 } 12754 12755 static class VerificationInfo { 12756 /** A constant used to indicate that a uid value is not present. */ 12757 public static final int NO_UID = -1; 12758 12759 /** URI referencing where the package was downloaded from. */ 12760 final Uri originatingUri; 12761 12762 /** HTTP referrer URI associated with the originatingURI. */ 12763 final Uri referrer; 12764 12765 /** UID of the application that the install request originated from. */ 12766 final int originatingUid; 12767 12768 /** UID of application requesting the install */ 12769 final int installerUid; 12770 12771 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12772 this.originatingUri = originatingUri; 12773 this.referrer = referrer; 12774 this.originatingUid = originatingUid; 12775 this.installerUid = installerUid; 12776 } 12777 } 12778 12779 class InstallParams extends HandlerParams { 12780 final OriginInfo origin; 12781 final MoveInfo move; 12782 final IPackageInstallObserver2 observer; 12783 int installFlags; 12784 final String installerPackageName; 12785 final String volumeUuid; 12786 private InstallArgs mArgs; 12787 private int mRet; 12788 final String packageAbiOverride; 12789 final String[] grantedRuntimePermissions; 12790 final VerificationInfo verificationInfo; 12791 final Certificate[][] certificates; 12792 12793 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12794 int installFlags, String installerPackageName, String volumeUuid, 12795 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12796 String[] grantedPermissions, Certificate[][] certificates) { 12797 super(user); 12798 this.origin = origin; 12799 this.move = move; 12800 this.observer = observer; 12801 this.installFlags = installFlags; 12802 this.installerPackageName = installerPackageName; 12803 this.volumeUuid = volumeUuid; 12804 this.verificationInfo = verificationInfo; 12805 this.packageAbiOverride = packageAbiOverride; 12806 this.grantedRuntimePermissions = grantedPermissions; 12807 this.certificates = certificates; 12808 } 12809 12810 @Override 12811 public String toString() { 12812 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12813 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12814 } 12815 12816 private int installLocationPolicy(PackageInfoLite pkgLite) { 12817 String packageName = pkgLite.packageName; 12818 int installLocation = pkgLite.installLocation; 12819 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12820 // reader 12821 synchronized (mPackages) { 12822 // Currently installed package which the new package is attempting to replace or 12823 // null if no such package is installed. 12824 PackageParser.Package installedPkg = mPackages.get(packageName); 12825 // Package which currently owns the data which the new package will own if installed. 12826 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12827 // will be null whereas dataOwnerPkg will contain information about the package 12828 // which was uninstalled while keeping its data. 12829 PackageParser.Package dataOwnerPkg = installedPkg; 12830 if (dataOwnerPkg == null) { 12831 PackageSetting ps = mSettings.mPackages.get(packageName); 12832 if (ps != null) { 12833 dataOwnerPkg = ps.pkg; 12834 } 12835 } 12836 12837 if (dataOwnerPkg != null) { 12838 // If installed, the package will get access to data left on the device by its 12839 // predecessor. As a security measure, this is permited only if this is not a 12840 // version downgrade or if the predecessor package is marked as debuggable and 12841 // a downgrade is explicitly requested. 12842 // 12843 // On debuggable platform builds, downgrades are permitted even for 12844 // non-debuggable packages to make testing easier. Debuggable platform builds do 12845 // not offer security guarantees and thus it's OK to disable some security 12846 // mechanisms to make debugging/testing easier on those builds. However, even on 12847 // debuggable builds downgrades of packages are permitted only if requested via 12848 // installFlags. This is because we aim to keep the behavior of debuggable 12849 // platform builds as close as possible to the behavior of non-debuggable 12850 // platform builds. 12851 final boolean downgradeRequested = 12852 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12853 final boolean packageDebuggable = 12854 (dataOwnerPkg.applicationInfo.flags 12855 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12856 final boolean downgradePermitted = 12857 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12858 if (!downgradePermitted) { 12859 try { 12860 checkDowngrade(dataOwnerPkg, pkgLite); 12861 } catch (PackageManagerException e) { 12862 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12863 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12864 } 12865 } 12866 } 12867 12868 if (installedPkg != null) { 12869 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12870 // Check for updated system application. 12871 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12872 if (onSd) { 12873 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12874 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12875 } 12876 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12877 } else { 12878 if (onSd) { 12879 // Install flag overrides everything. 12880 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12881 } 12882 // If current upgrade specifies particular preference 12883 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12884 // Application explicitly specified internal. 12885 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12886 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12887 // App explictly prefers external. Let policy decide 12888 } else { 12889 // Prefer previous location 12890 if (isExternal(installedPkg)) { 12891 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12892 } 12893 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12894 } 12895 } 12896 } else { 12897 // Invalid install. Return error code 12898 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12899 } 12900 } 12901 } 12902 // All the special cases have been taken care of. 12903 // Return result based on recommended install location. 12904 if (onSd) { 12905 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12906 } 12907 return pkgLite.recommendedInstallLocation; 12908 } 12909 12910 /* 12911 * Invoke remote method to get package information and install 12912 * location values. Override install location based on default 12913 * policy if needed and then create install arguments based 12914 * on the install location. 12915 */ 12916 public void handleStartCopy() throws RemoteException { 12917 int ret = PackageManager.INSTALL_SUCCEEDED; 12918 12919 // If we're already staged, we've firmly committed to an install location 12920 if (origin.staged) { 12921 if (origin.file != null) { 12922 installFlags |= PackageManager.INSTALL_INTERNAL; 12923 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12924 } else if (origin.cid != null) { 12925 installFlags |= PackageManager.INSTALL_EXTERNAL; 12926 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12927 } else { 12928 throw new IllegalStateException("Invalid stage location"); 12929 } 12930 } 12931 12932 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12933 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12934 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12935 PackageInfoLite pkgLite = null; 12936 12937 if (onInt && onSd) { 12938 // Check if both bits are set. 12939 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12940 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12941 } else if (onSd && ephemeral) { 12942 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12943 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12944 } else { 12945 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12946 packageAbiOverride); 12947 12948 if (DEBUG_EPHEMERAL && ephemeral) { 12949 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12950 } 12951 12952 /* 12953 * If we have too little free space, try to free cache 12954 * before giving up. 12955 */ 12956 if (!origin.staged && pkgLite.recommendedInstallLocation 12957 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12958 // TODO: focus freeing disk space on the target device 12959 final StorageManager storage = StorageManager.from(mContext); 12960 final long lowThreshold = storage.getStorageLowBytes( 12961 Environment.getDataDirectory()); 12962 12963 final long sizeBytes = mContainerService.calculateInstalledSize( 12964 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12965 12966 try { 12967 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12968 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12969 installFlags, packageAbiOverride); 12970 } catch (InstallerException e) { 12971 Slog.w(TAG, "Failed to free cache", e); 12972 } 12973 12974 /* 12975 * The cache free must have deleted the file we 12976 * downloaded to install. 12977 * 12978 * TODO: fix the "freeCache" call to not delete 12979 * the file we care about. 12980 */ 12981 if (pkgLite.recommendedInstallLocation 12982 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12983 pkgLite.recommendedInstallLocation 12984 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12985 } 12986 } 12987 } 12988 12989 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12990 int loc = pkgLite.recommendedInstallLocation; 12991 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12992 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12993 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12994 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12995 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12996 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12997 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12998 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12999 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13000 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13001 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13002 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13003 } else { 13004 // Override with defaults if needed. 13005 loc = installLocationPolicy(pkgLite); 13006 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13007 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13008 } else if (!onSd && !onInt) { 13009 // Override install location with flags 13010 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13011 // Set the flag to install on external media. 13012 installFlags |= PackageManager.INSTALL_EXTERNAL; 13013 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13014 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13015 if (DEBUG_EPHEMERAL) { 13016 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13017 } 13018 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13019 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13020 |PackageManager.INSTALL_INTERNAL); 13021 } else { 13022 // Make sure the flag for installing on external 13023 // media is unset 13024 installFlags |= PackageManager.INSTALL_INTERNAL; 13025 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13026 } 13027 } 13028 } 13029 } 13030 13031 final InstallArgs args = createInstallArgs(this); 13032 mArgs = args; 13033 13034 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13035 // TODO: http://b/22976637 13036 // Apps installed for "all" users use the device owner to verify the app 13037 UserHandle verifierUser = getUser(); 13038 if (verifierUser == UserHandle.ALL) { 13039 verifierUser = UserHandle.SYSTEM; 13040 } 13041 13042 /* 13043 * Determine if we have any installed package verifiers. If we 13044 * do, then we'll defer to them to verify the packages. 13045 */ 13046 final int requiredUid = mRequiredVerifierPackage == null ? -1 13047 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13048 verifierUser.getIdentifier()); 13049 if (!origin.existing && requiredUid != -1 13050 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13051 final Intent verification = new Intent( 13052 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13053 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13054 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13055 PACKAGE_MIME_TYPE); 13056 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13057 13058 // Query all live verifiers based on current user state 13059 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13060 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13061 13062 if (DEBUG_VERIFY) { 13063 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13064 + verification.toString() + " with " + pkgLite.verifiers.length 13065 + " optional verifiers"); 13066 } 13067 13068 final int verificationId = mPendingVerificationToken++; 13069 13070 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13071 13072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13073 installerPackageName); 13074 13075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13076 installFlags); 13077 13078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13079 pkgLite.packageName); 13080 13081 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13082 pkgLite.versionCode); 13083 13084 if (verificationInfo != null) { 13085 if (verificationInfo.originatingUri != null) { 13086 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13087 verificationInfo.originatingUri); 13088 } 13089 if (verificationInfo.referrer != null) { 13090 verification.putExtra(Intent.EXTRA_REFERRER, 13091 verificationInfo.referrer); 13092 } 13093 if (verificationInfo.originatingUid >= 0) { 13094 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13095 verificationInfo.originatingUid); 13096 } 13097 if (verificationInfo.installerUid >= 0) { 13098 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13099 verificationInfo.installerUid); 13100 } 13101 } 13102 13103 final PackageVerificationState verificationState = new PackageVerificationState( 13104 requiredUid, args); 13105 13106 mPendingVerification.append(verificationId, verificationState); 13107 13108 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13109 receivers, verificationState); 13110 13111 /* 13112 * If any sufficient verifiers were listed in the package 13113 * manifest, attempt to ask them. 13114 */ 13115 if (sufficientVerifiers != null) { 13116 final int N = sufficientVerifiers.size(); 13117 if (N == 0) { 13118 Slog.i(TAG, "Additional verifiers required, but none installed."); 13119 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13120 } else { 13121 for (int i = 0; i < N; i++) { 13122 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13123 13124 final Intent sufficientIntent = new Intent(verification); 13125 sufficientIntent.setComponent(verifierComponent); 13126 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13127 } 13128 } 13129 } 13130 13131 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13132 mRequiredVerifierPackage, receivers); 13133 if (ret == PackageManager.INSTALL_SUCCEEDED 13134 && mRequiredVerifierPackage != null) { 13135 Trace.asyncTraceBegin( 13136 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13137 /* 13138 * Send the intent to the required verification agent, 13139 * but only start the verification timeout after the 13140 * target BroadcastReceivers have run. 13141 */ 13142 verification.setComponent(requiredVerifierComponent); 13143 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13144 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13145 new BroadcastReceiver() { 13146 @Override 13147 public void onReceive(Context context, Intent intent) { 13148 final Message msg = mHandler 13149 .obtainMessage(CHECK_PENDING_VERIFICATION); 13150 msg.arg1 = verificationId; 13151 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13152 } 13153 }, null, 0, null, null); 13154 13155 /* 13156 * We don't want the copy to proceed until verification 13157 * succeeds, so null out this field. 13158 */ 13159 mArgs = null; 13160 } 13161 } else { 13162 /* 13163 * No package verification is enabled, so immediately start 13164 * the remote call to initiate copy using temporary file. 13165 */ 13166 ret = args.copyApk(mContainerService, true); 13167 } 13168 } 13169 13170 mRet = ret; 13171 } 13172 13173 @Override 13174 void handleReturnCode() { 13175 // If mArgs is null, then MCS couldn't be reached. When it 13176 // reconnects, it will try again to install. At that point, this 13177 // will succeed. 13178 if (mArgs != null) { 13179 processPendingInstall(mArgs, mRet); 13180 } 13181 } 13182 13183 @Override 13184 void handleServiceError() { 13185 mArgs = createInstallArgs(this); 13186 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13187 } 13188 13189 public boolean isForwardLocked() { 13190 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13191 } 13192 } 13193 13194 /** 13195 * Used during creation of InstallArgs 13196 * 13197 * @param installFlags package installation flags 13198 * @return true if should be installed on external storage 13199 */ 13200 private static boolean installOnExternalAsec(int installFlags) { 13201 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13202 return false; 13203 } 13204 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13205 return true; 13206 } 13207 return false; 13208 } 13209 13210 /** 13211 * Used during creation of InstallArgs 13212 * 13213 * @param installFlags package installation flags 13214 * @return true if should be installed as forward locked 13215 */ 13216 private static boolean installForwardLocked(int installFlags) { 13217 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13218 } 13219 13220 private InstallArgs createInstallArgs(InstallParams params) { 13221 if (params.move != null) { 13222 return new MoveInstallArgs(params); 13223 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13224 return new AsecInstallArgs(params); 13225 } else { 13226 return new FileInstallArgs(params); 13227 } 13228 } 13229 13230 /** 13231 * Create args that describe an existing installed package. Typically used 13232 * when cleaning up old installs, or used as a move source. 13233 */ 13234 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13235 String resourcePath, String[] instructionSets) { 13236 final boolean isInAsec; 13237 if (installOnExternalAsec(installFlags)) { 13238 /* Apps on SD card are always in ASEC containers. */ 13239 isInAsec = true; 13240 } else if (installForwardLocked(installFlags) 13241 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13242 /* 13243 * Forward-locked apps are only in ASEC containers if they're the 13244 * new style 13245 */ 13246 isInAsec = true; 13247 } else { 13248 isInAsec = false; 13249 } 13250 13251 if (isInAsec) { 13252 return new AsecInstallArgs(codePath, instructionSets, 13253 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13254 } else { 13255 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13256 } 13257 } 13258 13259 static abstract class InstallArgs { 13260 /** @see InstallParams#origin */ 13261 final OriginInfo origin; 13262 /** @see InstallParams#move */ 13263 final MoveInfo move; 13264 13265 final IPackageInstallObserver2 observer; 13266 // Always refers to PackageManager flags only 13267 final int installFlags; 13268 final String installerPackageName; 13269 final String volumeUuid; 13270 final UserHandle user; 13271 final String abiOverride; 13272 final String[] installGrantPermissions; 13273 /** If non-null, drop an async trace when the install completes */ 13274 final String traceMethod; 13275 final int traceCookie; 13276 final Certificate[][] certificates; 13277 13278 // The list of instruction sets supported by this app. This is currently 13279 // only used during the rmdex() phase to clean up resources. We can get rid of this 13280 // if we move dex files under the common app path. 13281 /* nullable */ String[] instructionSets; 13282 13283 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13284 int installFlags, String installerPackageName, String volumeUuid, 13285 UserHandle user, String[] instructionSets, 13286 String abiOverride, String[] installGrantPermissions, 13287 String traceMethod, int traceCookie, Certificate[][] certificates) { 13288 this.origin = origin; 13289 this.move = move; 13290 this.installFlags = installFlags; 13291 this.observer = observer; 13292 this.installerPackageName = installerPackageName; 13293 this.volumeUuid = volumeUuid; 13294 this.user = user; 13295 this.instructionSets = instructionSets; 13296 this.abiOverride = abiOverride; 13297 this.installGrantPermissions = installGrantPermissions; 13298 this.traceMethod = traceMethod; 13299 this.traceCookie = traceCookie; 13300 this.certificates = certificates; 13301 } 13302 13303 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13304 abstract int doPreInstall(int status); 13305 13306 /** 13307 * Rename package into final resting place. All paths on the given 13308 * scanned package should be updated to reflect the rename. 13309 */ 13310 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13311 abstract int doPostInstall(int status, int uid); 13312 13313 /** @see PackageSettingBase#codePathString */ 13314 abstract String getCodePath(); 13315 /** @see PackageSettingBase#resourcePathString */ 13316 abstract String getResourcePath(); 13317 13318 // Need installer lock especially for dex file removal. 13319 abstract void cleanUpResourcesLI(); 13320 abstract boolean doPostDeleteLI(boolean delete); 13321 13322 /** 13323 * Called before the source arguments are copied. This is used mostly 13324 * for MoveParams when it needs to read the source file to put it in the 13325 * destination. 13326 */ 13327 int doPreCopy() { 13328 return PackageManager.INSTALL_SUCCEEDED; 13329 } 13330 13331 /** 13332 * Called after the source arguments are copied. This is used mostly for 13333 * MoveParams when it needs to read the source file to put it in the 13334 * destination. 13335 */ 13336 int doPostCopy(int uid) { 13337 return PackageManager.INSTALL_SUCCEEDED; 13338 } 13339 13340 protected boolean isFwdLocked() { 13341 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13342 } 13343 13344 protected boolean isExternalAsec() { 13345 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13346 } 13347 13348 protected boolean isEphemeral() { 13349 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13350 } 13351 13352 UserHandle getUser() { 13353 return user; 13354 } 13355 } 13356 13357 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13358 if (!allCodePaths.isEmpty()) { 13359 if (instructionSets == null) { 13360 throw new IllegalStateException("instructionSet == null"); 13361 } 13362 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13363 for (String codePath : allCodePaths) { 13364 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13365 try { 13366 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13367 } catch (InstallerException ignored) { 13368 } 13369 } 13370 } 13371 } 13372 } 13373 13374 /** 13375 * Logic to handle installation of non-ASEC applications, including copying 13376 * and renaming logic. 13377 */ 13378 class FileInstallArgs extends InstallArgs { 13379 private File codeFile; 13380 private File resourceFile; 13381 13382 // Example topology: 13383 // /data/app/com.example/base.apk 13384 // /data/app/com.example/split_foo.apk 13385 // /data/app/com.example/lib/arm/libfoo.so 13386 // /data/app/com.example/lib/arm64/libfoo.so 13387 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13388 13389 /** New install */ 13390 FileInstallArgs(InstallParams params) { 13391 super(params.origin, params.move, params.observer, params.installFlags, 13392 params.installerPackageName, params.volumeUuid, 13393 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13394 params.grantedRuntimePermissions, 13395 params.traceMethod, params.traceCookie, params.certificates); 13396 if (isFwdLocked()) { 13397 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13398 } 13399 } 13400 13401 /** Existing install */ 13402 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13403 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13404 null, null, null, 0, null /*certificates*/); 13405 this.codeFile = (codePath != null) ? new File(codePath) : null; 13406 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13407 } 13408 13409 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13410 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13411 try { 13412 return doCopyApk(imcs, temp); 13413 } finally { 13414 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13415 } 13416 } 13417 13418 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13419 if (origin.staged) { 13420 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13421 codeFile = origin.file; 13422 resourceFile = origin.file; 13423 return PackageManager.INSTALL_SUCCEEDED; 13424 } 13425 13426 try { 13427 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13428 final File tempDir = 13429 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13430 codeFile = tempDir; 13431 resourceFile = tempDir; 13432 } catch (IOException e) { 13433 Slog.w(TAG, "Failed to create copy file: " + e); 13434 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13435 } 13436 13437 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13438 @Override 13439 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13440 if (!FileUtils.isValidExtFilename(name)) { 13441 throw new IllegalArgumentException("Invalid filename: " + name); 13442 } 13443 try { 13444 final File file = new File(codeFile, name); 13445 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13446 O_RDWR | O_CREAT, 0644); 13447 Os.chmod(file.getAbsolutePath(), 0644); 13448 return new ParcelFileDescriptor(fd); 13449 } catch (ErrnoException e) { 13450 throw new RemoteException("Failed to open: " + e.getMessage()); 13451 } 13452 } 13453 }; 13454 13455 int ret = PackageManager.INSTALL_SUCCEEDED; 13456 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13457 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13458 Slog.e(TAG, "Failed to copy package"); 13459 return ret; 13460 } 13461 13462 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13463 NativeLibraryHelper.Handle handle = null; 13464 try { 13465 handle = NativeLibraryHelper.Handle.create(codeFile); 13466 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13467 abiOverride); 13468 } catch (IOException e) { 13469 Slog.e(TAG, "Copying native libraries failed", e); 13470 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13471 } finally { 13472 IoUtils.closeQuietly(handle); 13473 } 13474 13475 return ret; 13476 } 13477 13478 int doPreInstall(int status) { 13479 if (status != PackageManager.INSTALL_SUCCEEDED) { 13480 cleanUp(); 13481 } 13482 return status; 13483 } 13484 13485 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13486 if (status != PackageManager.INSTALL_SUCCEEDED) { 13487 cleanUp(); 13488 return false; 13489 } 13490 13491 final File targetDir = codeFile.getParentFile(); 13492 final File beforeCodeFile = codeFile; 13493 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13494 13495 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13496 try { 13497 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13498 } catch (ErrnoException e) { 13499 Slog.w(TAG, "Failed to rename", e); 13500 return false; 13501 } 13502 13503 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13504 Slog.w(TAG, "Failed to restorecon"); 13505 return false; 13506 } 13507 13508 // Reflect the rename internally 13509 codeFile = afterCodeFile; 13510 resourceFile = afterCodeFile; 13511 13512 // Reflect the rename in scanned details 13513 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13514 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13515 afterCodeFile, pkg.baseCodePath)); 13516 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13517 afterCodeFile, pkg.splitCodePaths)); 13518 13519 // Reflect the rename in app info 13520 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13521 pkg.setApplicationInfoCodePath(pkg.codePath); 13522 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13523 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13524 pkg.setApplicationInfoResourcePath(pkg.codePath); 13525 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13526 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13527 13528 return true; 13529 } 13530 13531 int doPostInstall(int status, int uid) { 13532 if (status != PackageManager.INSTALL_SUCCEEDED) { 13533 cleanUp(); 13534 } 13535 return status; 13536 } 13537 13538 @Override 13539 String getCodePath() { 13540 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13541 } 13542 13543 @Override 13544 String getResourcePath() { 13545 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13546 } 13547 13548 private boolean cleanUp() { 13549 if (codeFile == null || !codeFile.exists()) { 13550 return false; 13551 } 13552 13553 removeCodePathLI(codeFile); 13554 13555 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13556 resourceFile.delete(); 13557 } 13558 13559 return true; 13560 } 13561 13562 void cleanUpResourcesLI() { 13563 // Try enumerating all code paths before deleting 13564 List<String> allCodePaths = Collections.EMPTY_LIST; 13565 if (codeFile != null && codeFile.exists()) { 13566 try { 13567 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13568 allCodePaths = pkg.getAllCodePaths(); 13569 } catch (PackageParserException e) { 13570 // Ignored; we tried our best 13571 } 13572 } 13573 13574 cleanUp(); 13575 removeDexFiles(allCodePaths, instructionSets); 13576 } 13577 13578 boolean doPostDeleteLI(boolean delete) { 13579 // XXX err, shouldn't we respect the delete flag? 13580 cleanUpResourcesLI(); 13581 return true; 13582 } 13583 } 13584 13585 private boolean isAsecExternal(String cid) { 13586 final String asecPath = PackageHelper.getSdFilesystem(cid); 13587 return !asecPath.startsWith(mAsecInternalPath); 13588 } 13589 13590 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13591 PackageManagerException { 13592 if (copyRet < 0) { 13593 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13594 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13595 throw new PackageManagerException(copyRet, message); 13596 } 13597 } 13598 } 13599 13600 /** 13601 * Extract the MountService "container ID" from the full code path of an 13602 * .apk. 13603 */ 13604 static String cidFromCodePath(String fullCodePath) { 13605 int eidx = fullCodePath.lastIndexOf("/"); 13606 String subStr1 = fullCodePath.substring(0, eidx); 13607 int sidx = subStr1.lastIndexOf("/"); 13608 return subStr1.substring(sidx+1, eidx); 13609 } 13610 13611 /** 13612 * Logic to handle installation of ASEC applications, including copying and 13613 * renaming logic. 13614 */ 13615 class AsecInstallArgs extends InstallArgs { 13616 static final String RES_FILE_NAME = "pkg.apk"; 13617 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13618 13619 String cid; 13620 String packagePath; 13621 String resourcePath; 13622 13623 /** New install */ 13624 AsecInstallArgs(InstallParams params) { 13625 super(params.origin, params.move, params.observer, params.installFlags, 13626 params.installerPackageName, params.volumeUuid, 13627 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13628 params.grantedRuntimePermissions, 13629 params.traceMethod, params.traceCookie, params.certificates); 13630 } 13631 13632 /** Existing install */ 13633 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13634 boolean isExternal, boolean isForwardLocked) { 13635 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13636 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13637 instructionSets, null, null, null, 0, null /*certificates*/); 13638 // Hackily pretend we're still looking at a full code path 13639 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13640 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13641 } 13642 13643 // Extract cid from fullCodePath 13644 int eidx = fullCodePath.lastIndexOf("/"); 13645 String subStr1 = fullCodePath.substring(0, eidx); 13646 int sidx = subStr1.lastIndexOf("/"); 13647 cid = subStr1.substring(sidx+1, eidx); 13648 setMountPath(subStr1); 13649 } 13650 13651 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13652 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13653 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13654 instructionSets, null, null, null, 0, null /*certificates*/); 13655 this.cid = cid; 13656 setMountPath(PackageHelper.getSdDir(cid)); 13657 } 13658 13659 void createCopyFile() { 13660 cid = mInstallerService.allocateExternalStageCidLegacy(); 13661 } 13662 13663 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13664 if (origin.staged && origin.cid != null) { 13665 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13666 cid = origin.cid; 13667 setMountPath(PackageHelper.getSdDir(cid)); 13668 return PackageManager.INSTALL_SUCCEEDED; 13669 } 13670 13671 if (temp) { 13672 createCopyFile(); 13673 } else { 13674 /* 13675 * Pre-emptively destroy the container since it's destroyed if 13676 * copying fails due to it existing anyway. 13677 */ 13678 PackageHelper.destroySdDir(cid); 13679 } 13680 13681 final String newMountPath = imcs.copyPackageToContainer( 13682 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13683 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13684 13685 if (newMountPath != null) { 13686 setMountPath(newMountPath); 13687 return PackageManager.INSTALL_SUCCEEDED; 13688 } else { 13689 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13690 } 13691 } 13692 13693 @Override 13694 String getCodePath() { 13695 return packagePath; 13696 } 13697 13698 @Override 13699 String getResourcePath() { 13700 return resourcePath; 13701 } 13702 13703 int doPreInstall(int status) { 13704 if (status != PackageManager.INSTALL_SUCCEEDED) { 13705 // Destroy container 13706 PackageHelper.destroySdDir(cid); 13707 } else { 13708 boolean mounted = PackageHelper.isContainerMounted(cid); 13709 if (!mounted) { 13710 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13711 Process.SYSTEM_UID); 13712 if (newMountPath != null) { 13713 setMountPath(newMountPath); 13714 } else { 13715 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13716 } 13717 } 13718 } 13719 return status; 13720 } 13721 13722 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13723 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13724 String newMountPath = null; 13725 if (PackageHelper.isContainerMounted(cid)) { 13726 // Unmount the container 13727 if (!PackageHelper.unMountSdDir(cid)) { 13728 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13729 return false; 13730 } 13731 } 13732 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13733 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13734 " which might be stale. Will try to clean up."); 13735 // Clean up the stale container and proceed to recreate. 13736 if (!PackageHelper.destroySdDir(newCacheId)) { 13737 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13738 return false; 13739 } 13740 // Successfully cleaned up stale container. Try to rename again. 13741 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13742 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13743 + " inspite of cleaning it up."); 13744 return false; 13745 } 13746 } 13747 if (!PackageHelper.isContainerMounted(newCacheId)) { 13748 Slog.w(TAG, "Mounting container " + newCacheId); 13749 newMountPath = PackageHelper.mountSdDir(newCacheId, 13750 getEncryptKey(), Process.SYSTEM_UID); 13751 } else { 13752 newMountPath = PackageHelper.getSdDir(newCacheId); 13753 } 13754 if (newMountPath == null) { 13755 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13756 return false; 13757 } 13758 Log.i(TAG, "Succesfully renamed " + cid + 13759 " to " + newCacheId + 13760 " at new path: " + newMountPath); 13761 cid = newCacheId; 13762 13763 final File beforeCodeFile = new File(packagePath); 13764 setMountPath(newMountPath); 13765 final File afterCodeFile = new File(packagePath); 13766 13767 // Reflect the rename in scanned details 13768 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13769 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13770 afterCodeFile, pkg.baseCodePath)); 13771 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13772 afterCodeFile, pkg.splitCodePaths)); 13773 13774 // Reflect the rename in app info 13775 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13776 pkg.setApplicationInfoCodePath(pkg.codePath); 13777 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13778 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13779 pkg.setApplicationInfoResourcePath(pkg.codePath); 13780 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13781 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13782 13783 return true; 13784 } 13785 13786 private void setMountPath(String mountPath) { 13787 final File mountFile = new File(mountPath); 13788 13789 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13790 if (monolithicFile.exists()) { 13791 packagePath = monolithicFile.getAbsolutePath(); 13792 if (isFwdLocked()) { 13793 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13794 } else { 13795 resourcePath = packagePath; 13796 } 13797 } else { 13798 packagePath = mountFile.getAbsolutePath(); 13799 resourcePath = packagePath; 13800 } 13801 } 13802 13803 int doPostInstall(int status, int uid) { 13804 if (status != PackageManager.INSTALL_SUCCEEDED) { 13805 cleanUp(); 13806 } else { 13807 final int groupOwner; 13808 final String protectedFile; 13809 if (isFwdLocked()) { 13810 groupOwner = UserHandle.getSharedAppGid(uid); 13811 protectedFile = RES_FILE_NAME; 13812 } else { 13813 groupOwner = -1; 13814 protectedFile = null; 13815 } 13816 13817 if (uid < Process.FIRST_APPLICATION_UID 13818 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13819 Slog.e(TAG, "Failed to finalize " + cid); 13820 PackageHelper.destroySdDir(cid); 13821 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13822 } 13823 13824 boolean mounted = PackageHelper.isContainerMounted(cid); 13825 if (!mounted) { 13826 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13827 } 13828 } 13829 return status; 13830 } 13831 13832 private void cleanUp() { 13833 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13834 13835 // Destroy secure container 13836 PackageHelper.destroySdDir(cid); 13837 } 13838 13839 private List<String> getAllCodePaths() { 13840 final File codeFile = new File(getCodePath()); 13841 if (codeFile != null && codeFile.exists()) { 13842 try { 13843 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13844 return pkg.getAllCodePaths(); 13845 } catch (PackageParserException e) { 13846 // Ignored; we tried our best 13847 } 13848 } 13849 return Collections.EMPTY_LIST; 13850 } 13851 13852 void cleanUpResourcesLI() { 13853 // Enumerate all code paths before deleting 13854 cleanUpResourcesLI(getAllCodePaths()); 13855 } 13856 13857 private void cleanUpResourcesLI(List<String> allCodePaths) { 13858 cleanUp(); 13859 removeDexFiles(allCodePaths, instructionSets); 13860 } 13861 13862 String getPackageName() { 13863 return getAsecPackageName(cid); 13864 } 13865 13866 boolean doPostDeleteLI(boolean delete) { 13867 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13868 final List<String> allCodePaths = getAllCodePaths(); 13869 boolean mounted = PackageHelper.isContainerMounted(cid); 13870 if (mounted) { 13871 // Unmount first 13872 if (PackageHelper.unMountSdDir(cid)) { 13873 mounted = false; 13874 } 13875 } 13876 if (!mounted && delete) { 13877 cleanUpResourcesLI(allCodePaths); 13878 } 13879 return !mounted; 13880 } 13881 13882 @Override 13883 int doPreCopy() { 13884 if (isFwdLocked()) { 13885 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13886 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13887 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13888 } 13889 } 13890 13891 return PackageManager.INSTALL_SUCCEEDED; 13892 } 13893 13894 @Override 13895 int doPostCopy(int uid) { 13896 if (isFwdLocked()) { 13897 if (uid < Process.FIRST_APPLICATION_UID 13898 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13899 RES_FILE_NAME)) { 13900 Slog.e(TAG, "Failed to finalize " + cid); 13901 PackageHelper.destroySdDir(cid); 13902 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13903 } 13904 } 13905 13906 return PackageManager.INSTALL_SUCCEEDED; 13907 } 13908 } 13909 13910 /** 13911 * Logic to handle movement of existing installed applications. 13912 */ 13913 class MoveInstallArgs extends InstallArgs { 13914 private File codeFile; 13915 private File resourceFile; 13916 13917 /** New install */ 13918 MoveInstallArgs(InstallParams params) { 13919 super(params.origin, params.move, params.observer, params.installFlags, 13920 params.installerPackageName, params.volumeUuid, 13921 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13922 params.grantedRuntimePermissions, 13923 params.traceMethod, params.traceCookie, params.certificates); 13924 } 13925 13926 int copyApk(IMediaContainerService imcs, boolean temp) { 13927 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13928 + move.fromUuid + " to " + move.toUuid); 13929 synchronized (mInstaller) { 13930 try { 13931 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13932 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13933 } catch (InstallerException e) { 13934 Slog.w(TAG, "Failed to move app", e); 13935 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13936 } 13937 } 13938 13939 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13940 resourceFile = codeFile; 13941 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13942 13943 return PackageManager.INSTALL_SUCCEEDED; 13944 } 13945 13946 int doPreInstall(int status) { 13947 if (status != PackageManager.INSTALL_SUCCEEDED) { 13948 cleanUp(move.toUuid); 13949 } 13950 return status; 13951 } 13952 13953 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13954 if (status != PackageManager.INSTALL_SUCCEEDED) { 13955 cleanUp(move.toUuid); 13956 return false; 13957 } 13958 13959 // Reflect the move in app info 13960 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13961 pkg.setApplicationInfoCodePath(pkg.codePath); 13962 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13963 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13964 pkg.setApplicationInfoResourcePath(pkg.codePath); 13965 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13966 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13967 13968 return true; 13969 } 13970 13971 int doPostInstall(int status, int uid) { 13972 if (status == PackageManager.INSTALL_SUCCEEDED) { 13973 cleanUp(move.fromUuid); 13974 } else { 13975 cleanUp(move.toUuid); 13976 } 13977 return status; 13978 } 13979 13980 @Override 13981 String getCodePath() { 13982 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13983 } 13984 13985 @Override 13986 String getResourcePath() { 13987 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13988 } 13989 13990 private boolean cleanUp(String volumeUuid) { 13991 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13992 move.dataAppName); 13993 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13994 final int[] userIds = sUserManager.getUserIds(); 13995 synchronized (mInstallLock) { 13996 // Clean up both app data and code 13997 // All package moves are frozen until finished 13998 for (int userId : userIds) { 13999 try { 14000 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14001 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14002 } catch (InstallerException e) { 14003 Slog.w(TAG, String.valueOf(e)); 14004 } 14005 } 14006 removeCodePathLI(codeFile); 14007 } 14008 return true; 14009 } 14010 14011 void cleanUpResourcesLI() { 14012 throw new UnsupportedOperationException(); 14013 } 14014 14015 boolean doPostDeleteLI(boolean delete) { 14016 throw new UnsupportedOperationException(); 14017 } 14018 } 14019 14020 static String getAsecPackageName(String packageCid) { 14021 int idx = packageCid.lastIndexOf("-"); 14022 if (idx == -1) { 14023 return packageCid; 14024 } 14025 return packageCid.substring(0, idx); 14026 } 14027 14028 // Utility method used to create code paths based on package name and available index. 14029 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14030 String idxStr = ""; 14031 int idx = 1; 14032 // Fall back to default value of idx=1 if prefix is not 14033 // part of oldCodePath 14034 if (oldCodePath != null) { 14035 String subStr = oldCodePath; 14036 // Drop the suffix right away 14037 if (suffix != null && subStr.endsWith(suffix)) { 14038 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14039 } 14040 // If oldCodePath already contains prefix find out the 14041 // ending index to either increment or decrement. 14042 int sidx = subStr.lastIndexOf(prefix); 14043 if (sidx != -1) { 14044 subStr = subStr.substring(sidx + prefix.length()); 14045 if (subStr != null) { 14046 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14047 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14048 } 14049 try { 14050 idx = Integer.parseInt(subStr); 14051 if (idx <= 1) { 14052 idx++; 14053 } else { 14054 idx--; 14055 } 14056 } catch(NumberFormatException e) { 14057 } 14058 } 14059 } 14060 } 14061 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14062 return prefix + idxStr; 14063 } 14064 14065 private File getNextCodePath(File targetDir, String packageName) { 14066 int suffix = 1; 14067 File result; 14068 do { 14069 result = new File(targetDir, packageName + "-" + suffix); 14070 suffix++; 14071 } while (result.exists()); 14072 return result; 14073 } 14074 14075 // Utility method that returns the relative package path with respect 14076 // to the installation directory. Like say for /data/data/com.test-1.apk 14077 // string com.test-1 is returned. 14078 static String deriveCodePathName(String codePath) { 14079 if (codePath == null) { 14080 return null; 14081 } 14082 final File codeFile = new File(codePath); 14083 final String name = codeFile.getName(); 14084 if (codeFile.isDirectory()) { 14085 return name; 14086 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14087 final int lastDot = name.lastIndexOf('.'); 14088 return name.substring(0, lastDot); 14089 } else { 14090 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14091 return null; 14092 } 14093 } 14094 14095 static class PackageInstalledInfo { 14096 String name; 14097 int uid; 14098 // The set of users that originally had this package installed. 14099 int[] origUsers; 14100 // The set of users that now have this package installed. 14101 int[] newUsers; 14102 PackageParser.Package pkg; 14103 int returnCode; 14104 String returnMsg; 14105 PackageRemovedInfo removedInfo; 14106 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14107 14108 public void setError(int code, String msg) { 14109 setReturnCode(code); 14110 setReturnMessage(msg); 14111 Slog.w(TAG, msg); 14112 } 14113 14114 public void setError(String msg, PackageParserException e) { 14115 setReturnCode(e.error); 14116 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14117 Slog.w(TAG, msg, e); 14118 } 14119 14120 public void setError(String msg, PackageManagerException e) { 14121 returnCode = e.error; 14122 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14123 Slog.w(TAG, msg, e); 14124 } 14125 14126 public void setReturnCode(int returnCode) { 14127 this.returnCode = returnCode; 14128 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14129 for (int i = 0; i < childCount; i++) { 14130 addedChildPackages.valueAt(i).returnCode = returnCode; 14131 } 14132 } 14133 14134 private void setReturnMessage(String returnMsg) { 14135 this.returnMsg = returnMsg; 14136 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14137 for (int i = 0; i < childCount; i++) { 14138 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14139 } 14140 } 14141 14142 // In some error cases we want to convey more info back to the observer 14143 String origPackage; 14144 String origPermission; 14145 } 14146 14147 /* 14148 * Install a non-existing package. 14149 */ 14150 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14151 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14152 PackageInstalledInfo res) { 14153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14154 14155 // Remember this for later, in case we need to rollback this install 14156 String pkgName = pkg.packageName; 14157 14158 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14159 14160 synchronized(mPackages) { 14161 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14162 // A package with the same name is already installed, though 14163 // it has been renamed to an older name. The package we 14164 // are trying to install should be installed as an update to 14165 // the existing one, but that has not been requested, so bail. 14166 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14167 + " without first uninstalling package running as " 14168 + mSettings.mRenamedPackages.get(pkgName)); 14169 return; 14170 } 14171 if (mPackages.containsKey(pkgName)) { 14172 // Don't allow installation over an existing package with the same name. 14173 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14174 + " without first uninstalling."); 14175 return; 14176 } 14177 } 14178 14179 try { 14180 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14181 System.currentTimeMillis(), user); 14182 14183 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14184 14185 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14186 prepareAppDataAfterInstallLIF(newPackage); 14187 14188 } else { 14189 // Remove package from internal structures, but keep around any 14190 // data that might have already existed 14191 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14192 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14193 } 14194 } catch (PackageManagerException e) { 14195 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14196 } 14197 14198 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14199 } 14200 14201 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14202 // Can't rotate keys during boot or if sharedUser. 14203 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14204 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14205 return false; 14206 } 14207 // app is using upgradeKeySets; make sure all are valid 14208 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14209 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14210 for (int i = 0; i < upgradeKeySets.length; i++) { 14211 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14212 Slog.wtf(TAG, "Package " 14213 + (oldPs.name != null ? oldPs.name : "<null>") 14214 + " contains upgrade-key-set reference to unknown key-set: " 14215 + upgradeKeySets[i] 14216 + " reverting to signatures check."); 14217 return false; 14218 } 14219 } 14220 return true; 14221 } 14222 14223 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14224 // Upgrade keysets are being used. Determine if new package has a superset of the 14225 // required keys. 14226 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14227 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14228 for (int i = 0; i < upgradeKeySets.length; i++) { 14229 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14230 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14231 return true; 14232 } 14233 } 14234 return false; 14235 } 14236 14237 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14238 try (DigestInputStream digestStream = 14239 new DigestInputStream(new FileInputStream(file), digest)) { 14240 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14241 } 14242 } 14243 14244 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14245 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14246 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14247 14248 final PackageParser.Package oldPackage; 14249 final String pkgName = pkg.packageName; 14250 final int[] allUsers; 14251 final int[] installedUsers; 14252 14253 synchronized(mPackages) { 14254 oldPackage = mPackages.get(pkgName); 14255 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14256 14257 // don't allow upgrade to target a release SDK from a pre-release SDK 14258 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14259 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14260 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14261 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14262 if (oldTargetsPreRelease 14263 && !newTargetsPreRelease 14264 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14265 Slog.w(TAG, "Can't install package targeting released sdk"); 14266 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14267 return; 14268 } 14269 14270 // don't allow an upgrade from full to ephemeral 14271 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14272 if (isEphemeral && !oldIsEphemeral) { 14273 // can't downgrade from full to ephemeral 14274 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14275 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14276 return; 14277 } 14278 14279 // verify signatures are valid 14280 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14281 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14282 if (!checkUpgradeKeySetLP(ps, pkg)) { 14283 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14284 "New package not signed by keys specified by upgrade-keysets: " 14285 + pkgName); 14286 return; 14287 } 14288 } else { 14289 // default to original signature matching 14290 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14291 != PackageManager.SIGNATURE_MATCH) { 14292 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14293 "New package has a different signature: " + pkgName); 14294 return; 14295 } 14296 } 14297 14298 // don't allow a system upgrade unless the upgrade hash matches 14299 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14300 byte[] digestBytes = null; 14301 try { 14302 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14303 updateDigest(digest, new File(pkg.baseCodePath)); 14304 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14305 for (String path : pkg.splitCodePaths) { 14306 updateDigest(digest, new File(path)); 14307 } 14308 } 14309 digestBytes = digest.digest(); 14310 } catch (NoSuchAlgorithmException | IOException e) { 14311 res.setError(INSTALL_FAILED_INVALID_APK, 14312 "Could not compute hash: " + pkgName); 14313 return; 14314 } 14315 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14316 res.setError(INSTALL_FAILED_INVALID_APK, 14317 "New package fails restrict-update check: " + pkgName); 14318 return; 14319 } 14320 // retain upgrade restriction 14321 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14322 } 14323 14324 // Check for shared user id changes 14325 String invalidPackageName = 14326 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14327 if (invalidPackageName != null) { 14328 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14329 "Package " + invalidPackageName + " tried to change user " 14330 + oldPackage.mSharedUserId); 14331 return; 14332 } 14333 14334 // In case of rollback, remember per-user/profile install state 14335 allUsers = sUserManager.getUserIds(); 14336 installedUsers = ps.queryInstalledUsers(allUsers, true); 14337 } 14338 14339 // Update what is removed 14340 res.removedInfo = new PackageRemovedInfo(); 14341 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14342 res.removedInfo.removedPackage = oldPackage.packageName; 14343 res.removedInfo.isUpdate = true; 14344 res.removedInfo.origUsers = installedUsers; 14345 final int childCount = (oldPackage.childPackages != null) 14346 ? oldPackage.childPackages.size() : 0; 14347 for (int i = 0; i < childCount; i++) { 14348 boolean childPackageUpdated = false; 14349 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14350 if (res.addedChildPackages != null) { 14351 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14352 if (childRes != null) { 14353 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14354 childRes.removedInfo.removedPackage = childPkg.packageName; 14355 childRes.removedInfo.isUpdate = true; 14356 childPackageUpdated = true; 14357 } 14358 } 14359 if (!childPackageUpdated) { 14360 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14361 childRemovedRes.removedPackage = childPkg.packageName; 14362 childRemovedRes.isUpdate = false; 14363 childRemovedRes.dataRemoved = true; 14364 synchronized (mPackages) { 14365 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14366 if (childPs != null) { 14367 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14368 } 14369 } 14370 if (res.removedInfo.removedChildPackages == null) { 14371 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14372 } 14373 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14374 } 14375 } 14376 14377 boolean sysPkg = (isSystemApp(oldPackage)); 14378 if (sysPkg) { 14379 // Set the system/privileged flags as needed 14380 final boolean privileged = 14381 (oldPackage.applicationInfo.privateFlags 14382 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14383 final int systemPolicyFlags = policyFlags 14384 | PackageParser.PARSE_IS_SYSTEM 14385 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14386 14387 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14388 user, allUsers, installerPackageName, res); 14389 } else { 14390 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14391 user, allUsers, installerPackageName, res); 14392 } 14393 } 14394 14395 public List<String> getPreviousCodePaths(String packageName) { 14396 final PackageSetting ps = mSettings.mPackages.get(packageName); 14397 final List<String> result = new ArrayList<String>(); 14398 if (ps != null && ps.oldCodePaths != null) { 14399 result.addAll(ps.oldCodePaths); 14400 } 14401 return result; 14402 } 14403 14404 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14405 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14406 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14407 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14408 + deletedPackage); 14409 14410 String pkgName = deletedPackage.packageName; 14411 boolean deletedPkg = true; 14412 boolean addedPkg = false; 14413 boolean updatedSettings = false; 14414 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14415 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14416 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14417 14418 final long origUpdateTime = (pkg.mExtras != null) 14419 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14420 14421 // First delete the existing package while retaining the data directory 14422 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14423 res.removedInfo, true, pkg)) { 14424 // If the existing package wasn't successfully deleted 14425 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14426 deletedPkg = false; 14427 } else { 14428 // Successfully deleted the old package; proceed with replace. 14429 14430 // If deleted package lived in a container, give users a chance to 14431 // relinquish resources before killing. 14432 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14433 if (DEBUG_INSTALL) { 14434 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14435 } 14436 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14437 final ArrayList<String> pkgList = new ArrayList<String>(1); 14438 pkgList.add(deletedPackage.applicationInfo.packageName); 14439 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14440 } 14441 14442 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14443 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14444 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14445 14446 try { 14447 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14448 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14449 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14450 14451 // Update the in-memory copy of the previous code paths. 14452 PackageSetting ps = mSettings.mPackages.get(pkgName); 14453 if (!killApp) { 14454 if (ps.oldCodePaths == null) { 14455 ps.oldCodePaths = new ArraySet<>(); 14456 } 14457 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14458 if (deletedPackage.splitCodePaths != null) { 14459 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14460 } 14461 } else { 14462 ps.oldCodePaths = null; 14463 } 14464 if (ps.childPackageNames != null) { 14465 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14466 final String childPkgName = ps.childPackageNames.get(i); 14467 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14468 childPs.oldCodePaths = ps.oldCodePaths; 14469 } 14470 } 14471 prepareAppDataAfterInstallLIF(newPackage); 14472 addedPkg = true; 14473 } catch (PackageManagerException e) { 14474 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14475 } 14476 } 14477 14478 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14479 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14480 14481 // Revert all internal state mutations and added folders for the failed install 14482 if (addedPkg) { 14483 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14484 res.removedInfo, true, null); 14485 } 14486 14487 // Restore the old package 14488 if (deletedPkg) { 14489 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14490 File restoreFile = new File(deletedPackage.codePath); 14491 // Parse old package 14492 boolean oldExternal = isExternal(deletedPackage); 14493 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14494 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14495 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14496 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14497 try { 14498 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14499 null); 14500 } catch (PackageManagerException e) { 14501 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14502 + e.getMessage()); 14503 return; 14504 } 14505 14506 synchronized (mPackages) { 14507 // Ensure the installer package name up to date 14508 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14509 14510 // Update permissions for restored package 14511 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14512 14513 mSettings.writeLPr(); 14514 } 14515 14516 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14517 } 14518 } else { 14519 synchronized (mPackages) { 14520 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14521 if (ps != null) { 14522 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14523 if (res.removedInfo.removedChildPackages != null) { 14524 final int childCount = res.removedInfo.removedChildPackages.size(); 14525 // Iterate in reverse as we may modify the collection 14526 for (int i = childCount - 1; i >= 0; i--) { 14527 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14528 if (res.addedChildPackages.containsKey(childPackageName)) { 14529 res.removedInfo.removedChildPackages.removeAt(i); 14530 } else { 14531 PackageRemovedInfo childInfo = res.removedInfo 14532 .removedChildPackages.valueAt(i); 14533 childInfo.removedForAllUsers = mPackages.get( 14534 childInfo.removedPackage) == null; 14535 } 14536 } 14537 } 14538 } 14539 } 14540 } 14541 } 14542 14543 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14544 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14545 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14546 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14547 + ", old=" + deletedPackage); 14548 14549 final boolean disabledSystem; 14550 14551 // Remove existing system package 14552 removePackageLI(deletedPackage, true); 14553 14554 synchronized (mPackages) { 14555 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14556 } 14557 if (!disabledSystem) { 14558 // We didn't need to disable the .apk as a current system package, 14559 // which means we are replacing another update that is already 14560 // installed. We need to make sure to delete the older one's .apk. 14561 res.removedInfo.args = createInstallArgsForExisting(0, 14562 deletedPackage.applicationInfo.getCodePath(), 14563 deletedPackage.applicationInfo.getResourcePath(), 14564 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14565 } else { 14566 res.removedInfo.args = null; 14567 } 14568 14569 // Successfully disabled the old package. Now proceed with re-installation 14570 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14571 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14572 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14573 14574 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14575 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14576 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14577 14578 PackageParser.Package newPackage = null; 14579 try { 14580 // Add the package to the internal data structures 14581 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14582 14583 // Set the update and install times 14584 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14585 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14586 System.currentTimeMillis()); 14587 14588 // Update the package dynamic state if succeeded 14589 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14590 // Now that the install succeeded make sure we remove data 14591 // directories for any child package the update removed. 14592 final int deletedChildCount = (deletedPackage.childPackages != null) 14593 ? deletedPackage.childPackages.size() : 0; 14594 final int newChildCount = (newPackage.childPackages != null) 14595 ? newPackage.childPackages.size() : 0; 14596 for (int i = 0; i < deletedChildCount; i++) { 14597 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14598 boolean childPackageDeleted = true; 14599 for (int j = 0; j < newChildCount; j++) { 14600 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14601 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14602 childPackageDeleted = false; 14603 break; 14604 } 14605 } 14606 if (childPackageDeleted) { 14607 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14608 deletedChildPkg.packageName); 14609 if (ps != null && res.removedInfo.removedChildPackages != null) { 14610 PackageRemovedInfo removedChildRes = res.removedInfo 14611 .removedChildPackages.get(deletedChildPkg.packageName); 14612 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14613 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14614 } 14615 } 14616 } 14617 14618 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14619 prepareAppDataAfterInstallLIF(newPackage); 14620 } 14621 } catch (PackageManagerException e) { 14622 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14623 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14624 } 14625 14626 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14627 // Re installation failed. Restore old information 14628 // Remove new pkg information 14629 if (newPackage != null) { 14630 removeInstalledPackageLI(newPackage, true); 14631 } 14632 // Add back the old system package 14633 try { 14634 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14635 } catch (PackageManagerException e) { 14636 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14637 } 14638 14639 synchronized (mPackages) { 14640 if (disabledSystem) { 14641 enableSystemPackageLPw(deletedPackage); 14642 } 14643 14644 // Ensure the installer package name up to date 14645 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14646 14647 // Update permissions for restored package 14648 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14649 14650 mSettings.writeLPr(); 14651 } 14652 14653 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14654 + " after failed upgrade"); 14655 } 14656 } 14657 14658 /** 14659 * Checks whether the parent or any of the child packages have a change shared 14660 * user. For a package to be a valid update the shred users of the parent and 14661 * the children should match. We may later support changing child shared users. 14662 * @param oldPkg The updated package. 14663 * @param newPkg The update package. 14664 * @return The shared user that change between the versions. 14665 */ 14666 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14667 PackageParser.Package newPkg) { 14668 // Check parent shared user 14669 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14670 return newPkg.packageName; 14671 } 14672 // Check child shared users 14673 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14674 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14675 for (int i = 0; i < newChildCount; i++) { 14676 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14677 // If this child was present, did it have the same shared user? 14678 for (int j = 0; j < oldChildCount; j++) { 14679 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14680 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14681 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14682 return newChildPkg.packageName; 14683 } 14684 } 14685 } 14686 return null; 14687 } 14688 14689 private void removeNativeBinariesLI(PackageSetting ps) { 14690 // Remove the lib path for the parent package 14691 if (ps != null) { 14692 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14693 // Remove the lib path for the child packages 14694 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14695 for (int i = 0; i < childCount; i++) { 14696 PackageSetting childPs = null; 14697 synchronized (mPackages) { 14698 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14699 } 14700 if (childPs != null) { 14701 NativeLibraryHelper.removeNativeBinariesLI(childPs 14702 .legacyNativeLibraryPathString); 14703 } 14704 } 14705 } 14706 } 14707 14708 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14709 // Enable the parent package 14710 mSettings.enableSystemPackageLPw(pkg.packageName); 14711 // Enable the child packages 14712 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14713 for (int i = 0; i < childCount; i++) { 14714 PackageParser.Package childPkg = pkg.childPackages.get(i); 14715 mSettings.enableSystemPackageLPw(childPkg.packageName); 14716 } 14717 } 14718 14719 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14720 PackageParser.Package newPkg) { 14721 // Disable the parent package (parent always replaced) 14722 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14723 // Disable the child packages 14724 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14725 for (int i = 0; i < childCount; i++) { 14726 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14727 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14728 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14729 } 14730 return disabled; 14731 } 14732 14733 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14734 String installerPackageName) { 14735 // Enable the parent package 14736 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14737 // Enable the child packages 14738 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14739 for (int i = 0; i < childCount; i++) { 14740 PackageParser.Package childPkg = pkg.childPackages.get(i); 14741 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14742 } 14743 } 14744 14745 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14746 // Collect all used permissions in the UID 14747 ArraySet<String> usedPermissions = new ArraySet<>(); 14748 final int packageCount = su.packages.size(); 14749 for (int i = 0; i < packageCount; i++) { 14750 PackageSetting ps = su.packages.valueAt(i); 14751 if (ps.pkg == null) { 14752 continue; 14753 } 14754 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14755 for (int j = 0; j < requestedPermCount; j++) { 14756 String permission = ps.pkg.requestedPermissions.get(j); 14757 BasePermission bp = mSettings.mPermissions.get(permission); 14758 if (bp != null) { 14759 usedPermissions.add(permission); 14760 } 14761 } 14762 } 14763 14764 PermissionsState permissionsState = su.getPermissionsState(); 14765 // Prune install permissions 14766 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14767 final int installPermCount = installPermStates.size(); 14768 for (int i = installPermCount - 1; i >= 0; i--) { 14769 PermissionState permissionState = installPermStates.get(i); 14770 if (!usedPermissions.contains(permissionState.getName())) { 14771 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14772 if (bp != null) { 14773 permissionsState.revokeInstallPermission(bp); 14774 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14775 PackageManager.MASK_PERMISSION_FLAGS, 0); 14776 } 14777 } 14778 } 14779 14780 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14781 14782 // Prune runtime permissions 14783 for (int userId : allUserIds) { 14784 List<PermissionState> runtimePermStates = permissionsState 14785 .getRuntimePermissionStates(userId); 14786 final int runtimePermCount = runtimePermStates.size(); 14787 for (int i = runtimePermCount - 1; i >= 0; i--) { 14788 PermissionState permissionState = runtimePermStates.get(i); 14789 if (!usedPermissions.contains(permissionState.getName())) { 14790 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14791 if (bp != null) { 14792 permissionsState.revokeRuntimePermission(bp, userId); 14793 permissionsState.updatePermissionFlags(bp, userId, 14794 PackageManager.MASK_PERMISSION_FLAGS, 0); 14795 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14796 runtimePermissionChangedUserIds, userId); 14797 } 14798 } 14799 } 14800 } 14801 14802 return runtimePermissionChangedUserIds; 14803 } 14804 14805 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14806 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14807 // Update the parent package setting 14808 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14809 res, user); 14810 // Update the child packages setting 14811 final int childCount = (newPackage.childPackages != null) 14812 ? newPackage.childPackages.size() : 0; 14813 for (int i = 0; i < childCount; i++) { 14814 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14815 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14816 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14817 childRes.origUsers, childRes, user); 14818 } 14819 } 14820 14821 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14822 String installerPackageName, int[] allUsers, int[] installedForUsers, 14823 PackageInstalledInfo res, UserHandle user) { 14824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14825 14826 String pkgName = newPackage.packageName; 14827 synchronized (mPackages) { 14828 //write settings. the installStatus will be incomplete at this stage. 14829 //note that the new package setting would have already been 14830 //added to mPackages. It hasn't been persisted yet. 14831 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14833 mSettings.writeLPr(); 14834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14835 } 14836 14837 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14838 synchronized (mPackages) { 14839 updatePermissionsLPw(newPackage.packageName, newPackage, 14840 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14841 ? UPDATE_PERMISSIONS_ALL : 0)); 14842 // For system-bundled packages, we assume that installing an upgraded version 14843 // of the package implies that the user actually wants to run that new code, 14844 // so we enable the package. 14845 PackageSetting ps = mSettings.mPackages.get(pkgName); 14846 final int userId = user.getIdentifier(); 14847 if (ps != null) { 14848 if (isSystemApp(newPackage)) { 14849 if (DEBUG_INSTALL) { 14850 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14851 } 14852 // Enable system package for requested users 14853 if (res.origUsers != null) { 14854 for (int origUserId : res.origUsers) { 14855 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14856 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14857 origUserId, installerPackageName); 14858 } 14859 } 14860 } 14861 // Also convey the prior install/uninstall state 14862 if (allUsers != null && installedForUsers != null) { 14863 for (int currentUserId : allUsers) { 14864 final boolean installed = ArrayUtils.contains( 14865 installedForUsers, currentUserId); 14866 if (DEBUG_INSTALL) { 14867 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14868 } 14869 ps.setInstalled(installed, currentUserId); 14870 } 14871 // these install state changes will be persisted in the 14872 // upcoming call to mSettings.writeLPr(). 14873 } 14874 } 14875 // It's implied that when a user requests installation, they want the app to be 14876 // installed and enabled. 14877 if (userId != UserHandle.USER_ALL) { 14878 ps.setInstalled(true, userId); 14879 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14880 } 14881 } 14882 res.name = pkgName; 14883 res.uid = newPackage.applicationInfo.uid; 14884 res.pkg = newPackage; 14885 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14886 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14887 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14888 //to update install status 14889 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14890 mSettings.writeLPr(); 14891 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14892 } 14893 14894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14895 } 14896 14897 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14898 try { 14899 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14900 installPackageLI(args, res); 14901 } finally { 14902 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14903 } 14904 } 14905 14906 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14907 final int installFlags = args.installFlags; 14908 final String installerPackageName = args.installerPackageName; 14909 final String volumeUuid = args.volumeUuid; 14910 final File tmpPackageFile = new File(args.getCodePath()); 14911 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14912 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14913 || (args.volumeUuid != null)); 14914 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14915 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14916 boolean replace = false; 14917 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14918 if (args.move != null) { 14919 // moving a complete application; perform an initial scan on the new install location 14920 scanFlags |= SCAN_INITIAL; 14921 } 14922 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14923 scanFlags |= SCAN_DONT_KILL_APP; 14924 } 14925 14926 // Result object to be returned 14927 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14928 14929 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14930 14931 // Sanity check 14932 if (ephemeral && (forwardLocked || onExternal)) { 14933 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14934 + " external=" + onExternal); 14935 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14936 return; 14937 } 14938 14939 // Retrieve PackageSettings and parse package 14940 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14941 | PackageParser.PARSE_ENFORCE_CODE 14942 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14943 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14944 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14945 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14946 PackageParser pp = new PackageParser(); 14947 pp.setSeparateProcesses(mSeparateProcesses); 14948 pp.setDisplayMetrics(mMetrics); 14949 14950 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14951 final PackageParser.Package pkg; 14952 try { 14953 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14954 } catch (PackageParserException e) { 14955 res.setError("Failed parse during installPackageLI", e); 14956 return; 14957 } finally { 14958 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14959 } 14960 14961 // If we are installing a clustered package add results for the children 14962 if (pkg.childPackages != null) { 14963 synchronized (mPackages) { 14964 final int childCount = pkg.childPackages.size(); 14965 for (int i = 0; i < childCount; i++) { 14966 PackageParser.Package childPkg = pkg.childPackages.get(i); 14967 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14968 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14969 childRes.pkg = childPkg; 14970 childRes.name = childPkg.packageName; 14971 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14972 if (childPs != null) { 14973 childRes.origUsers = childPs.queryInstalledUsers( 14974 sUserManager.getUserIds(), true); 14975 } 14976 if ((mPackages.containsKey(childPkg.packageName))) { 14977 childRes.removedInfo = new PackageRemovedInfo(); 14978 childRes.removedInfo.removedPackage = childPkg.packageName; 14979 } 14980 if (res.addedChildPackages == null) { 14981 res.addedChildPackages = new ArrayMap<>(); 14982 } 14983 res.addedChildPackages.put(childPkg.packageName, childRes); 14984 } 14985 } 14986 } 14987 14988 // If package doesn't declare API override, mark that we have an install 14989 // time CPU ABI override. 14990 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14991 pkg.cpuAbiOverride = args.abiOverride; 14992 } 14993 14994 String pkgName = res.name = pkg.packageName; 14995 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14996 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14997 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14998 return; 14999 } 15000 } 15001 15002 try { 15003 // either use what we've been given or parse directly from the APK 15004 if (args.certificates != null) { 15005 try { 15006 PackageParser.populateCertificates(pkg, args.certificates); 15007 } catch (PackageParserException e) { 15008 // there was something wrong with the certificates we were given; 15009 // try to pull them from the APK 15010 PackageParser.collectCertificates(pkg, parseFlags); 15011 } 15012 } else { 15013 PackageParser.collectCertificates(pkg, parseFlags); 15014 } 15015 } catch (PackageParserException e) { 15016 res.setError("Failed collect during installPackageLI", e); 15017 return; 15018 } 15019 15020 // Get rid of all references to package scan path via parser. 15021 pp = null; 15022 String oldCodePath = null; 15023 boolean systemApp = false; 15024 synchronized (mPackages) { 15025 // Check if installing already existing package 15026 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15027 String oldName = mSettings.mRenamedPackages.get(pkgName); 15028 if (pkg.mOriginalPackages != null 15029 && pkg.mOriginalPackages.contains(oldName) 15030 && mPackages.containsKey(oldName)) { 15031 // This package is derived from an original package, 15032 // and this device has been updating from that original 15033 // name. We must continue using the original name, so 15034 // rename the new package here. 15035 pkg.setPackageName(oldName); 15036 pkgName = pkg.packageName; 15037 replace = true; 15038 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15039 + oldName + " pkgName=" + pkgName); 15040 } else if (mPackages.containsKey(pkgName)) { 15041 // This package, under its official name, already exists 15042 // on the device; we should replace it. 15043 replace = true; 15044 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15045 } 15046 15047 // Child packages are installed through the parent package 15048 if (pkg.parentPackage != null) { 15049 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15050 "Package " + pkg.packageName + " is child of package " 15051 + pkg.parentPackage.parentPackage + ". Child packages " 15052 + "can be updated only through the parent package."); 15053 return; 15054 } 15055 15056 if (replace) { 15057 // Prevent apps opting out from runtime permissions 15058 PackageParser.Package oldPackage = mPackages.get(pkgName); 15059 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15060 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15061 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15062 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15063 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15064 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15065 + " doesn't support runtime permissions but the old" 15066 + " target SDK " + oldTargetSdk + " does."); 15067 return; 15068 } 15069 15070 // Prevent installing of child packages 15071 if (oldPackage.parentPackage != null) { 15072 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15073 "Package " + pkg.packageName + " is child of package " 15074 + oldPackage.parentPackage + ". Child packages " 15075 + "can be updated only through the parent package."); 15076 return; 15077 } 15078 } 15079 } 15080 15081 PackageSetting ps = mSettings.mPackages.get(pkgName); 15082 if (ps != null) { 15083 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15084 15085 // Quick sanity check that we're signed correctly if updating; 15086 // we'll check this again later when scanning, but we want to 15087 // bail early here before tripping over redefined permissions. 15088 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15089 if (!checkUpgradeKeySetLP(ps, pkg)) { 15090 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15091 + pkg.packageName + " upgrade keys do not match the " 15092 + "previously installed version"); 15093 return; 15094 } 15095 } else { 15096 try { 15097 verifySignaturesLP(ps, pkg); 15098 } catch (PackageManagerException e) { 15099 res.setError(e.error, e.getMessage()); 15100 return; 15101 } 15102 } 15103 15104 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15105 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15106 systemApp = (ps.pkg.applicationInfo.flags & 15107 ApplicationInfo.FLAG_SYSTEM) != 0; 15108 } 15109 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15110 } 15111 15112 // Check whether the newly-scanned package wants to define an already-defined perm 15113 int N = pkg.permissions.size(); 15114 for (int i = N-1; i >= 0; i--) { 15115 PackageParser.Permission perm = pkg.permissions.get(i); 15116 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15117 if (bp != null) { 15118 // If the defining package is signed with our cert, it's okay. This 15119 // also includes the "updating the same package" case, of course. 15120 // "updating same package" could also involve key-rotation. 15121 final boolean sigsOk; 15122 if (bp.sourcePackage.equals(pkg.packageName) 15123 && (bp.packageSetting instanceof PackageSetting) 15124 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15125 scanFlags))) { 15126 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15127 } else { 15128 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15129 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15130 } 15131 if (!sigsOk) { 15132 // If the owning package is the system itself, we log but allow 15133 // install to proceed; we fail the install on all other permission 15134 // redefinitions. 15135 if (!bp.sourcePackage.equals("android")) { 15136 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15137 + pkg.packageName + " attempting to redeclare permission " 15138 + perm.info.name + " already owned by " + bp.sourcePackage); 15139 res.origPermission = perm.info.name; 15140 res.origPackage = bp.sourcePackage; 15141 return; 15142 } else { 15143 Slog.w(TAG, "Package " + pkg.packageName 15144 + " attempting to redeclare system permission " 15145 + perm.info.name + "; ignoring new declaration"); 15146 pkg.permissions.remove(i); 15147 } 15148 } 15149 } 15150 } 15151 } 15152 15153 if (systemApp) { 15154 if (onExternal) { 15155 // Abort update; system app can't be replaced with app on sdcard 15156 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15157 "Cannot install updates to system apps on sdcard"); 15158 return; 15159 } else if (ephemeral) { 15160 // Abort update; system app can't be replaced with an ephemeral app 15161 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15162 "Cannot update a system app with an ephemeral app"); 15163 return; 15164 } 15165 } 15166 15167 if (args.move != null) { 15168 // We did an in-place move, so dex is ready to roll 15169 scanFlags |= SCAN_NO_DEX; 15170 scanFlags |= SCAN_MOVE; 15171 15172 synchronized (mPackages) { 15173 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15174 if (ps == null) { 15175 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15176 "Missing settings for moved package " + pkgName); 15177 } 15178 15179 // We moved the entire application as-is, so bring over the 15180 // previously derived ABI information. 15181 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15182 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15183 } 15184 15185 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15186 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15187 scanFlags |= SCAN_NO_DEX; 15188 15189 try { 15190 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15191 args.abiOverride : pkg.cpuAbiOverride); 15192 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15193 true /* extract libs */); 15194 } catch (PackageManagerException pme) { 15195 Slog.e(TAG, "Error deriving application ABI", pme); 15196 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15197 return; 15198 } 15199 15200 // Shared libraries for the package need to be updated. 15201 synchronized (mPackages) { 15202 try { 15203 updateSharedLibrariesLPw(pkg, null); 15204 } catch (PackageManagerException e) { 15205 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15206 } 15207 } 15208 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15209 // Do not run PackageDexOptimizer through the local performDexOpt 15210 // method because `pkg` may not be in `mPackages` yet. 15211 // 15212 // Also, don't fail application installs if the dexopt step fails. 15213 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15214 null /* instructionSets */, false /* checkProfiles */, 15215 getCompilerFilterForReason(REASON_INSTALL), 15216 getOrCreateCompilerPackageStats(pkg)); 15217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15218 15219 // Notify BackgroundDexOptService that the package has been changed. 15220 // If this is an update of a package which used to fail to compile, 15221 // BDOS will remove it from its blacklist. 15222 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15223 } 15224 15225 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15226 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15227 return; 15228 } 15229 15230 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15231 15232 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15233 "installPackageLI")) { 15234 if (replace) { 15235 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15236 installerPackageName, res); 15237 } else { 15238 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15239 args.user, installerPackageName, volumeUuid, res); 15240 } 15241 } 15242 synchronized (mPackages) { 15243 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15244 if (ps != null) { 15245 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15246 } 15247 15248 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15249 for (int i = 0; i < childCount; i++) { 15250 PackageParser.Package childPkg = pkg.childPackages.get(i); 15251 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15252 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15253 if (childPs != null) { 15254 childRes.newUsers = childPs.queryInstalledUsers( 15255 sUserManager.getUserIds(), true); 15256 } 15257 } 15258 } 15259 } 15260 15261 private void startIntentFilterVerifications(int userId, boolean replacing, 15262 PackageParser.Package pkg) { 15263 if (mIntentFilterVerifierComponent == null) { 15264 Slog.w(TAG, "No IntentFilter verification will not be done as " 15265 + "there is no IntentFilterVerifier available!"); 15266 return; 15267 } 15268 15269 final int verifierUid = getPackageUid( 15270 mIntentFilterVerifierComponent.getPackageName(), 15271 MATCH_DEBUG_TRIAGED_MISSING, 15272 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15273 15274 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15275 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15276 mHandler.sendMessage(msg); 15277 15278 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15279 for (int i = 0; i < childCount; i++) { 15280 PackageParser.Package childPkg = pkg.childPackages.get(i); 15281 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15282 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15283 mHandler.sendMessage(msg); 15284 } 15285 } 15286 15287 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15288 PackageParser.Package pkg) { 15289 int size = pkg.activities.size(); 15290 if (size == 0) { 15291 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15292 "No activity, so no need to verify any IntentFilter!"); 15293 return; 15294 } 15295 15296 final boolean hasDomainURLs = hasDomainURLs(pkg); 15297 if (!hasDomainURLs) { 15298 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15299 "No domain URLs, so no need to verify any IntentFilter!"); 15300 return; 15301 } 15302 15303 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15304 + " if any IntentFilter from the " + size 15305 + " Activities needs verification ..."); 15306 15307 int count = 0; 15308 final String packageName = pkg.packageName; 15309 15310 synchronized (mPackages) { 15311 // If this is a new install and we see that we've already run verification for this 15312 // package, we have nothing to do: it means the state was restored from backup. 15313 if (!replacing) { 15314 IntentFilterVerificationInfo ivi = 15315 mSettings.getIntentFilterVerificationLPr(packageName); 15316 if (ivi != null) { 15317 if (DEBUG_DOMAIN_VERIFICATION) { 15318 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15319 + ivi.getStatusString()); 15320 } 15321 return; 15322 } 15323 } 15324 15325 // If any filters need to be verified, then all need to be. 15326 boolean needToVerify = false; 15327 for (PackageParser.Activity a : pkg.activities) { 15328 for (ActivityIntentInfo filter : a.intents) { 15329 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15330 if (DEBUG_DOMAIN_VERIFICATION) { 15331 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15332 } 15333 needToVerify = true; 15334 break; 15335 } 15336 } 15337 } 15338 15339 if (needToVerify) { 15340 final int verificationId = mIntentFilterVerificationToken++; 15341 for (PackageParser.Activity a : pkg.activities) { 15342 for (ActivityIntentInfo filter : a.intents) { 15343 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15344 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15345 "Verification needed for IntentFilter:" + filter.toString()); 15346 mIntentFilterVerifier.addOneIntentFilterVerification( 15347 verifierUid, userId, verificationId, filter, packageName); 15348 count++; 15349 } 15350 } 15351 } 15352 } 15353 } 15354 15355 if (count > 0) { 15356 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15357 + " IntentFilter verification" + (count > 1 ? "s" : "") 15358 + " for userId:" + userId); 15359 mIntentFilterVerifier.startVerifications(userId); 15360 } else { 15361 if (DEBUG_DOMAIN_VERIFICATION) { 15362 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15363 } 15364 } 15365 } 15366 15367 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15368 final ComponentName cn = filter.activity.getComponentName(); 15369 final String packageName = cn.getPackageName(); 15370 15371 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15372 packageName); 15373 if (ivi == null) { 15374 return true; 15375 } 15376 int status = ivi.getStatus(); 15377 switch (status) { 15378 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15379 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15380 return true; 15381 15382 default: 15383 // Nothing to do 15384 return false; 15385 } 15386 } 15387 15388 private static boolean isMultiArch(ApplicationInfo info) { 15389 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15390 } 15391 15392 private static boolean isExternal(PackageParser.Package pkg) { 15393 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15394 } 15395 15396 private static boolean isExternal(PackageSetting ps) { 15397 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15398 } 15399 15400 private static boolean isEphemeral(PackageParser.Package pkg) { 15401 return pkg.applicationInfo.isEphemeralApp(); 15402 } 15403 15404 private static boolean isEphemeral(PackageSetting ps) { 15405 return ps.pkg != null && isEphemeral(ps.pkg); 15406 } 15407 15408 private static boolean isSystemApp(PackageParser.Package pkg) { 15409 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15410 } 15411 15412 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15413 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15414 } 15415 15416 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15417 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15418 } 15419 15420 private static boolean isSystemApp(PackageSetting ps) { 15421 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15422 } 15423 15424 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15425 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15426 } 15427 15428 private int packageFlagsToInstallFlags(PackageSetting ps) { 15429 int installFlags = 0; 15430 if (isEphemeral(ps)) { 15431 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15432 } 15433 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15434 // This existing package was an external ASEC install when we have 15435 // the external flag without a UUID 15436 installFlags |= PackageManager.INSTALL_EXTERNAL; 15437 } 15438 if (ps.isForwardLocked()) { 15439 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15440 } 15441 return installFlags; 15442 } 15443 15444 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15445 if (isExternal(pkg)) { 15446 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15447 return StorageManager.UUID_PRIMARY_PHYSICAL; 15448 } else { 15449 return pkg.volumeUuid; 15450 } 15451 } else { 15452 return StorageManager.UUID_PRIVATE_INTERNAL; 15453 } 15454 } 15455 15456 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15457 if (isExternal(pkg)) { 15458 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15459 return mSettings.getExternalVersion(); 15460 } else { 15461 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15462 } 15463 } else { 15464 return mSettings.getInternalVersion(); 15465 } 15466 } 15467 15468 private void deleteTempPackageFiles() { 15469 final FilenameFilter filter = new FilenameFilter() { 15470 public boolean accept(File dir, String name) { 15471 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15472 } 15473 }; 15474 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15475 file.delete(); 15476 } 15477 } 15478 15479 @Override 15480 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15481 int flags) { 15482 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15483 flags); 15484 } 15485 15486 @Override 15487 public void deletePackage(final String packageName, 15488 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15489 mContext.enforceCallingOrSelfPermission( 15490 android.Manifest.permission.DELETE_PACKAGES, null); 15491 Preconditions.checkNotNull(packageName); 15492 Preconditions.checkNotNull(observer); 15493 final int uid = Binder.getCallingUid(); 15494 if (!isOrphaned(packageName) 15495 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15496 try { 15497 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15498 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15499 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15500 observer.onUserActionRequired(intent); 15501 } catch (RemoteException re) { 15502 } 15503 return; 15504 } 15505 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15506 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15507 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15508 mContext.enforceCallingOrSelfPermission( 15509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15510 "deletePackage for user " + userId); 15511 } 15512 15513 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15514 try { 15515 observer.onPackageDeleted(packageName, 15516 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15517 } catch (RemoteException re) { 15518 } 15519 return; 15520 } 15521 15522 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15523 try { 15524 observer.onPackageDeleted(packageName, 15525 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15526 } catch (RemoteException re) { 15527 } 15528 return; 15529 } 15530 15531 if (DEBUG_REMOVE) { 15532 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15533 + " deleteAllUsers: " + deleteAllUsers ); 15534 } 15535 // Queue up an async operation since the package deletion may take a little while. 15536 mHandler.post(new Runnable() { 15537 public void run() { 15538 mHandler.removeCallbacks(this); 15539 int returnCode; 15540 if (!deleteAllUsers) { 15541 returnCode = deletePackageX(packageName, userId, deleteFlags); 15542 } else { 15543 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15544 // If nobody is blocking uninstall, proceed with delete for all users 15545 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15546 returnCode = deletePackageX(packageName, userId, deleteFlags); 15547 } else { 15548 // Otherwise uninstall individually for users with blockUninstalls=false 15549 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15550 for (int userId : users) { 15551 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15552 returnCode = deletePackageX(packageName, userId, userFlags); 15553 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15554 Slog.w(TAG, "Package delete failed for user " + userId 15555 + ", returnCode " + returnCode); 15556 } 15557 } 15558 } 15559 // The app has only been marked uninstalled for certain users. 15560 // We still need to report that delete was blocked 15561 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15562 } 15563 } 15564 try { 15565 observer.onPackageDeleted(packageName, returnCode, null); 15566 } catch (RemoteException e) { 15567 Log.i(TAG, "Observer no longer exists."); 15568 } //end catch 15569 } //end run 15570 }); 15571 } 15572 15573 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15574 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15575 || callingUid == Process.SYSTEM_UID) { 15576 return true; 15577 } 15578 final int callingUserId = UserHandle.getUserId(callingUid); 15579 // If the caller installed the pkgName, then allow it to silently uninstall. 15580 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15581 return true; 15582 } 15583 15584 // Allow package verifier to silently uninstall. 15585 if (mRequiredVerifierPackage != null && 15586 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15587 return true; 15588 } 15589 15590 // Allow package uninstaller to silently uninstall. 15591 if (mRequiredUninstallerPackage != null && 15592 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15593 return true; 15594 } 15595 15596 // Allow storage manager to silently uninstall. 15597 if (mStorageManagerPackage != null && 15598 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15599 return true; 15600 } 15601 return false; 15602 } 15603 15604 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15605 int[] result = EMPTY_INT_ARRAY; 15606 for (int userId : userIds) { 15607 if (getBlockUninstallForUser(packageName, userId)) { 15608 result = ArrayUtils.appendInt(result, userId); 15609 } 15610 } 15611 return result; 15612 } 15613 15614 @Override 15615 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15616 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15617 } 15618 15619 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15620 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15621 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15622 try { 15623 if (dpm != null) { 15624 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15625 /* callingUserOnly =*/ false); 15626 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15627 : deviceOwnerComponentName.getPackageName(); 15628 // Does the package contains the device owner? 15629 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15630 // this check is probably not needed, since DO should be registered as a device 15631 // admin on some user too. (Original bug for this: b/17657954) 15632 if (packageName.equals(deviceOwnerPackageName)) { 15633 return true; 15634 } 15635 // Does it contain a device admin for any user? 15636 int[] users; 15637 if (userId == UserHandle.USER_ALL) { 15638 users = sUserManager.getUserIds(); 15639 } else { 15640 users = new int[]{userId}; 15641 } 15642 for (int i = 0; i < users.length; ++i) { 15643 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15644 return true; 15645 } 15646 } 15647 } 15648 } catch (RemoteException e) { 15649 } 15650 return false; 15651 } 15652 15653 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15654 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15655 } 15656 15657 /** 15658 * This method is an internal method that could be get invoked either 15659 * to delete an installed package or to clean up a failed installation. 15660 * After deleting an installed package, a broadcast is sent to notify any 15661 * listeners that the package has been removed. For cleaning up a failed 15662 * installation, the broadcast is not necessary since the package's 15663 * installation wouldn't have sent the initial broadcast either 15664 * The key steps in deleting a package are 15665 * deleting the package information in internal structures like mPackages, 15666 * deleting the packages base directories through installd 15667 * updating mSettings to reflect current status 15668 * persisting settings for later use 15669 * sending a broadcast if necessary 15670 */ 15671 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15672 final PackageRemovedInfo info = new PackageRemovedInfo(); 15673 final boolean res; 15674 15675 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15676 ? UserHandle.USER_ALL : userId; 15677 15678 if (isPackageDeviceAdmin(packageName, removeUser)) { 15679 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15680 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15681 } 15682 15683 PackageSetting uninstalledPs = null; 15684 15685 // for the uninstall-updates case and restricted profiles, remember the per- 15686 // user handle installed state 15687 int[] allUsers; 15688 synchronized (mPackages) { 15689 uninstalledPs = mSettings.mPackages.get(packageName); 15690 if (uninstalledPs == null) { 15691 Slog.w(TAG, "Not removing non-existent package " + packageName); 15692 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15693 } 15694 allUsers = sUserManager.getUserIds(); 15695 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15696 } 15697 15698 final int freezeUser; 15699 if (isUpdatedSystemApp(uninstalledPs) 15700 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15701 // We're downgrading a system app, which will apply to all users, so 15702 // freeze them all during the downgrade 15703 freezeUser = UserHandle.USER_ALL; 15704 } else { 15705 freezeUser = removeUser; 15706 } 15707 15708 synchronized (mInstallLock) { 15709 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15710 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15711 deleteFlags, "deletePackageX")) { 15712 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15713 deleteFlags | REMOVE_CHATTY, info, true, null); 15714 } 15715 synchronized (mPackages) { 15716 if (res) { 15717 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15718 } 15719 } 15720 } 15721 15722 if (res) { 15723 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15724 info.sendPackageRemovedBroadcasts(killApp); 15725 info.sendSystemPackageUpdatedBroadcasts(); 15726 info.sendSystemPackageAppearedBroadcasts(); 15727 } 15728 // Force a gc here. 15729 Runtime.getRuntime().gc(); 15730 // Delete the resources here after sending the broadcast to let 15731 // other processes clean up before deleting resources. 15732 if (info.args != null) { 15733 synchronized (mInstallLock) { 15734 info.args.doPostDeleteLI(true); 15735 } 15736 } 15737 15738 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15739 } 15740 15741 class PackageRemovedInfo { 15742 String removedPackage; 15743 int uid = -1; 15744 int removedAppId = -1; 15745 int[] origUsers; 15746 int[] removedUsers = null; 15747 boolean isRemovedPackageSystemUpdate = false; 15748 boolean isUpdate; 15749 boolean dataRemoved; 15750 boolean removedForAllUsers; 15751 // Clean up resources deleted packages. 15752 InstallArgs args = null; 15753 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15754 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15755 15756 void sendPackageRemovedBroadcasts(boolean killApp) { 15757 sendPackageRemovedBroadcastInternal(killApp); 15758 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15759 for (int i = 0; i < childCount; i++) { 15760 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15761 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15762 } 15763 } 15764 15765 void sendSystemPackageUpdatedBroadcasts() { 15766 if (isRemovedPackageSystemUpdate) { 15767 sendSystemPackageUpdatedBroadcastsInternal(); 15768 final int childCount = (removedChildPackages != null) 15769 ? removedChildPackages.size() : 0; 15770 for (int i = 0; i < childCount; i++) { 15771 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15772 if (childInfo.isRemovedPackageSystemUpdate) { 15773 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15774 } 15775 } 15776 } 15777 } 15778 15779 void sendSystemPackageAppearedBroadcasts() { 15780 final int packageCount = (appearedChildPackages != null) 15781 ? appearedChildPackages.size() : 0; 15782 for (int i = 0; i < packageCount; i++) { 15783 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15784 for (int userId : installedInfo.newUsers) { 15785 sendPackageAddedForUser(installedInfo.name, true, 15786 UserHandle.getAppId(installedInfo.uid), userId); 15787 } 15788 } 15789 } 15790 15791 private void sendSystemPackageUpdatedBroadcastsInternal() { 15792 Bundle extras = new Bundle(2); 15793 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15794 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15795 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15796 extras, 0, null, null, null); 15797 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15798 extras, 0, null, null, null); 15799 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15800 null, 0, removedPackage, null, null); 15801 } 15802 15803 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15804 Bundle extras = new Bundle(2); 15805 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15806 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15807 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15808 if (isUpdate || isRemovedPackageSystemUpdate) { 15809 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15810 } 15811 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15812 if (removedPackage != null) { 15813 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15814 extras, 0, null, null, removedUsers); 15815 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15816 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15817 removedPackage, extras, 0, null, null, removedUsers); 15818 } 15819 } 15820 if (removedAppId >= 0) { 15821 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15822 removedUsers); 15823 } 15824 } 15825 } 15826 15827 /* 15828 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15829 * flag is not set, the data directory is removed as well. 15830 * make sure this flag is set for partially installed apps. If not its meaningless to 15831 * delete a partially installed application. 15832 */ 15833 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15834 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15835 String packageName = ps.name; 15836 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15837 // Retrieve object to delete permissions for shared user later on 15838 final PackageParser.Package deletedPkg; 15839 final PackageSetting deletedPs; 15840 // reader 15841 synchronized (mPackages) { 15842 deletedPkg = mPackages.get(packageName); 15843 deletedPs = mSettings.mPackages.get(packageName); 15844 if (outInfo != null) { 15845 outInfo.removedPackage = packageName; 15846 outInfo.removedUsers = deletedPs != null 15847 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15848 : null; 15849 } 15850 } 15851 15852 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15853 15854 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15855 final PackageParser.Package resolvedPkg; 15856 if (deletedPkg != null) { 15857 resolvedPkg = deletedPkg; 15858 } else { 15859 // We don't have a parsed package when it lives on an ejected 15860 // adopted storage device, so fake something together 15861 resolvedPkg = new PackageParser.Package(ps.name); 15862 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15863 } 15864 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15865 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15866 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15867 if (outInfo != null) { 15868 outInfo.dataRemoved = true; 15869 } 15870 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15871 } 15872 15873 // writer 15874 synchronized (mPackages) { 15875 if (deletedPs != null) { 15876 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15877 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15878 clearDefaultBrowserIfNeeded(packageName); 15879 if (outInfo != null) { 15880 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15881 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15882 } 15883 updatePermissionsLPw(deletedPs.name, null, 0); 15884 if (deletedPs.sharedUser != null) { 15885 // Remove permissions associated with package. Since runtime 15886 // permissions are per user we have to kill the removed package 15887 // or packages running under the shared user of the removed 15888 // package if revoking the permissions requested only by the removed 15889 // package is successful and this causes a change in gids. 15890 for (int userId : UserManagerService.getInstance().getUserIds()) { 15891 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15892 userId); 15893 if (userIdToKill == UserHandle.USER_ALL 15894 || userIdToKill >= UserHandle.USER_SYSTEM) { 15895 // If gids changed for this user, kill all affected packages. 15896 mHandler.post(new Runnable() { 15897 @Override 15898 public void run() { 15899 // This has to happen with no lock held. 15900 killApplication(deletedPs.name, deletedPs.appId, 15901 KILL_APP_REASON_GIDS_CHANGED); 15902 } 15903 }); 15904 break; 15905 } 15906 } 15907 } 15908 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15909 } 15910 // make sure to preserve per-user disabled state if this removal was just 15911 // a downgrade of a system app to the factory package 15912 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15913 if (DEBUG_REMOVE) { 15914 Slog.d(TAG, "Propagating install state across downgrade"); 15915 } 15916 for (int userId : allUserHandles) { 15917 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15918 if (DEBUG_REMOVE) { 15919 Slog.d(TAG, " user " + userId + " => " + installed); 15920 } 15921 ps.setInstalled(installed, userId); 15922 } 15923 } 15924 } 15925 // can downgrade to reader 15926 if (writeSettings) { 15927 // Save settings now 15928 mSettings.writeLPr(); 15929 } 15930 } 15931 if (outInfo != null) { 15932 // A user ID was deleted here. Go through all users and remove it 15933 // from KeyStore. 15934 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15935 } 15936 } 15937 15938 static boolean locationIsPrivileged(File path) { 15939 try { 15940 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15941 .getCanonicalPath(); 15942 return path.getCanonicalPath().startsWith(privilegedAppDir); 15943 } catch (IOException e) { 15944 Slog.e(TAG, "Unable to access code path " + path); 15945 } 15946 return false; 15947 } 15948 15949 /* 15950 * Tries to delete system package. 15951 */ 15952 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15953 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15954 boolean writeSettings) { 15955 if (deletedPs.parentPackageName != null) { 15956 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15957 return false; 15958 } 15959 15960 final boolean applyUserRestrictions 15961 = (allUserHandles != null) && (outInfo.origUsers != null); 15962 final PackageSetting disabledPs; 15963 // Confirm if the system package has been updated 15964 // An updated system app can be deleted. This will also have to restore 15965 // the system pkg from system partition 15966 // reader 15967 synchronized (mPackages) { 15968 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15969 } 15970 15971 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15972 + " disabledPs=" + disabledPs); 15973 15974 if (disabledPs == null) { 15975 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15976 return false; 15977 } else if (DEBUG_REMOVE) { 15978 Slog.d(TAG, "Deleting system pkg from data partition"); 15979 } 15980 15981 if (DEBUG_REMOVE) { 15982 if (applyUserRestrictions) { 15983 Slog.d(TAG, "Remembering install states:"); 15984 for (int userId : allUserHandles) { 15985 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15986 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15987 } 15988 } 15989 } 15990 15991 // Delete the updated package 15992 outInfo.isRemovedPackageSystemUpdate = true; 15993 if (outInfo.removedChildPackages != null) { 15994 final int childCount = (deletedPs.childPackageNames != null) 15995 ? deletedPs.childPackageNames.size() : 0; 15996 for (int i = 0; i < childCount; i++) { 15997 String childPackageName = deletedPs.childPackageNames.get(i); 15998 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15999 .contains(childPackageName)) { 16000 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16001 childPackageName); 16002 if (childInfo != null) { 16003 childInfo.isRemovedPackageSystemUpdate = true; 16004 } 16005 } 16006 } 16007 } 16008 16009 if (disabledPs.versionCode < deletedPs.versionCode) { 16010 // Delete data for downgrades 16011 flags &= ~PackageManager.DELETE_KEEP_DATA; 16012 } else { 16013 // Preserve data by setting flag 16014 flags |= PackageManager.DELETE_KEEP_DATA; 16015 } 16016 16017 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16018 outInfo, writeSettings, disabledPs.pkg); 16019 if (!ret) { 16020 return false; 16021 } 16022 16023 // writer 16024 synchronized (mPackages) { 16025 // Reinstate the old system package 16026 enableSystemPackageLPw(disabledPs.pkg); 16027 // Remove any native libraries from the upgraded package. 16028 removeNativeBinariesLI(deletedPs); 16029 } 16030 16031 // Install the system package 16032 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16033 int parseFlags = mDefParseFlags 16034 | PackageParser.PARSE_MUST_BE_APK 16035 | PackageParser.PARSE_IS_SYSTEM 16036 | PackageParser.PARSE_IS_SYSTEM_DIR; 16037 if (locationIsPrivileged(disabledPs.codePath)) { 16038 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16039 } 16040 16041 final PackageParser.Package newPkg; 16042 try { 16043 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16044 } catch (PackageManagerException e) { 16045 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16046 + e.getMessage()); 16047 return false; 16048 } 16049 try { 16050 // update shared libraries for the newly re-installed system package 16051 updateSharedLibrariesLPw(newPkg, null); 16052 } catch (PackageManagerException e) { 16053 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16054 } 16055 16056 prepareAppDataAfterInstallLIF(newPkg); 16057 16058 // writer 16059 synchronized (mPackages) { 16060 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16061 16062 // Propagate the permissions state as we do not want to drop on the floor 16063 // runtime permissions. The update permissions method below will take 16064 // care of removing obsolete permissions and grant install permissions. 16065 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16066 updatePermissionsLPw(newPkg.packageName, newPkg, 16067 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16068 16069 if (applyUserRestrictions) { 16070 if (DEBUG_REMOVE) { 16071 Slog.d(TAG, "Propagating install state across reinstall"); 16072 } 16073 for (int userId : allUserHandles) { 16074 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16075 if (DEBUG_REMOVE) { 16076 Slog.d(TAG, " user " + userId + " => " + installed); 16077 } 16078 ps.setInstalled(installed, userId); 16079 16080 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16081 } 16082 // Regardless of writeSettings we need to ensure that this restriction 16083 // state propagation is persisted 16084 mSettings.writeAllUsersPackageRestrictionsLPr(); 16085 } 16086 // can downgrade to reader here 16087 if (writeSettings) { 16088 mSettings.writeLPr(); 16089 } 16090 } 16091 return true; 16092 } 16093 16094 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16095 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16096 PackageRemovedInfo outInfo, boolean writeSettings, 16097 PackageParser.Package replacingPackage) { 16098 synchronized (mPackages) { 16099 if (outInfo != null) { 16100 outInfo.uid = ps.appId; 16101 } 16102 16103 if (outInfo != null && outInfo.removedChildPackages != null) { 16104 final int childCount = (ps.childPackageNames != null) 16105 ? ps.childPackageNames.size() : 0; 16106 for (int i = 0; i < childCount; i++) { 16107 String childPackageName = ps.childPackageNames.get(i); 16108 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16109 if (childPs == null) { 16110 return false; 16111 } 16112 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16113 childPackageName); 16114 if (childInfo != null) { 16115 childInfo.uid = childPs.appId; 16116 } 16117 } 16118 } 16119 } 16120 16121 // Delete package data from internal structures and also remove data if flag is set 16122 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16123 16124 // Delete the child packages data 16125 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16126 for (int i = 0; i < childCount; i++) { 16127 PackageSetting childPs; 16128 synchronized (mPackages) { 16129 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16130 } 16131 if (childPs != null) { 16132 PackageRemovedInfo childOutInfo = (outInfo != null 16133 && outInfo.removedChildPackages != null) 16134 ? outInfo.removedChildPackages.get(childPs.name) : null; 16135 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16136 && (replacingPackage != null 16137 && !replacingPackage.hasChildPackage(childPs.name)) 16138 ? flags & ~DELETE_KEEP_DATA : flags; 16139 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16140 deleteFlags, writeSettings); 16141 } 16142 } 16143 16144 // Delete application code and resources only for parent packages 16145 if (ps.parentPackageName == null) { 16146 if (deleteCodeAndResources && (outInfo != null)) { 16147 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16148 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16149 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16150 } 16151 } 16152 16153 return true; 16154 } 16155 16156 @Override 16157 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16158 int userId) { 16159 mContext.enforceCallingOrSelfPermission( 16160 android.Manifest.permission.DELETE_PACKAGES, null); 16161 synchronized (mPackages) { 16162 PackageSetting ps = mSettings.mPackages.get(packageName); 16163 if (ps == null) { 16164 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16165 return false; 16166 } 16167 if (!ps.getInstalled(userId)) { 16168 // Can't block uninstall for an app that is not installed or enabled. 16169 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16170 return false; 16171 } 16172 ps.setBlockUninstall(blockUninstall, userId); 16173 mSettings.writePackageRestrictionsLPr(userId); 16174 } 16175 return true; 16176 } 16177 16178 @Override 16179 public boolean getBlockUninstallForUser(String packageName, int userId) { 16180 synchronized (mPackages) { 16181 PackageSetting ps = mSettings.mPackages.get(packageName); 16182 if (ps == null) { 16183 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16184 return false; 16185 } 16186 return ps.getBlockUninstall(userId); 16187 } 16188 } 16189 16190 @Override 16191 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16192 int callingUid = Binder.getCallingUid(); 16193 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16194 throw new SecurityException( 16195 "setRequiredForSystemUser can only be run by the system or root"); 16196 } 16197 synchronized (mPackages) { 16198 PackageSetting ps = mSettings.mPackages.get(packageName); 16199 if (ps == null) { 16200 Log.w(TAG, "Package doesn't exist: " + packageName); 16201 return false; 16202 } 16203 if (systemUserApp) { 16204 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16205 } else { 16206 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16207 } 16208 mSettings.writeLPr(); 16209 } 16210 return true; 16211 } 16212 16213 /* 16214 * This method handles package deletion in general 16215 */ 16216 private boolean deletePackageLIF(String packageName, UserHandle user, 16217 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16218 PackageRemovedInfo outInfo, boolean writeSettings, 16219 PackageParser.Package replacingPackage) { 16220 if (packageName == null) { 16221 Slog.w(TAG, "Attempt to delete null packageName."); 16222 return false; 16223 } 16224 16225 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16226 16227 PackageSetting ps; 16228 16229 synchronized (mPackages) { 16230 ps = mSettings.mPackages.get(packageName); 16231 if (ps == null) { 16232 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16233 return false; 16234 } 16235 16236 if (ps.parentPackageName != null && (!isSystemApp(ps) 16237 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16238 if (DEBUG_REMOVE) { 16239 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16240 + ((user == null) ? UserHandle.USER_ALL : user)); 16241 } 16242 final int removedUserId = (user != null) ? user.getIdentifier() 16243 : UserHandle.USER_ALL; 16244 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16245 return false; 16246 } 16247 markPackageUninstalledForUserLPw(ps, user); 16248 scheduleWritePackageRestrictionsLocked(user); 16249 return true; 16250 } 16251 } 16252 16253 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16254 && user.getIdentifier() != UserHandle.USER_ALL)) { 16255 // The caller is asking that the package only be deleted for a single 16256 // user. To do this, we just mark its uninstalled state and delete 16257 // its data. If this is a system app, we only allow this to happen if 16258 // they have set the special DELETE_SYSTEM_APP which requests different 16259 // semantics than normal for uninstalling system apps. 16260 markPackageUninstalledForUserLPw(ps, user); 16261 16262 if (!isSystemApp(ps)) { 16263 // Do not uninstall the APK if an app should be cached 16264 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16265 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16266 // Other user still have this package installed, so all 16267 // we need to do is clear this user's data and save that 16268 // it is uninstalled. 16269 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16270 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16271 return false; 16272 } 16273 scheduleWritePackageRestrictionsLocked(user); 16274 return true; 16275 } else { 16276 // We need to set it back to 'installed' so the uninstall 16277 // broadcasts will be sent correctly. 16278 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16279 ps.setInstalled(true, user.getIdentifier()); 16280 } 16281 } else { 16282 // This is a system app, so we assume that the 16283 // other users still have this package installed, so all 16284 // we need to do is clear this user's data and save that 16285 // it is uninstalled. 16286 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16287 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16288 return false; 16289 } 16290 scheduleWritePackageRestrictionsLocked(user); 16291 return true; 16292 } 16293 } 16294 16295 // If we are deleting a composite package for all users, keep track 16296 // of result for each child. 16297 if (ps.childPackageNames != null && outInfo != null) { 16298 synchronized (mPackages) { 16299 final int childCount = ps.childPackageNames.size(); 16300 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16301 for (int i = 0; i < childCount; i++) { 16302 String childPackageName = ps.childPackageNames.get(i); 16303 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16304 childInfo.removedPackage = childPackageName; 16305 outInfo.removedChildPackages.put(childPackageName, childInfo); 16306 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16307 if (childPs != null) { 16308 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16309 } 16310 } 16311 } 16312 } 16313 16314 boolean ret = false; 16315 if (isSystemApp(ps)) { 16316 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16317 // When an updated system application is deleted we delete the existing resources 16318 // as well and fall back to existing code in system partition 16319 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16320 } else { 16321 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16322 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16323 outInfo, writeSettings, replacingPackage); 16324 } 16325 16326 // Take a note whether we deleted the package for all users 16327 if (outInfo != null) { 16328 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16329 if (outInfo.removedChildPackages != null) { 16330 synchronized (mPackages) { 16331 final int childCount = outInfo.removedChildPackages.size(); 16332 for (int i = 0; i < childCount; i++) { 16333 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16334 if (childInfo != null) { 16335 childInfo.removedForAllUsers = mPackages.get( 16336 childInfo.removedPackage) == null; 16337 } 16338 } 16339 } 16340 } 16341 // If we uninstalled an update to a system app there may be some 16342 // child packages that appeared as they are declared in the system 16343 // app but were not declared in the update. 16344 if (isSystemApp(ps)) { 16345 synchronized (mPackages) { 16346 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16347 final int childCount = (updatedPs.childPackageNames != null) 16348 ? updatedPs.childPackageNames.size() : 0; 16349 for (int i = 0; i < childCount; i++) { 16350 String childPackageName = updatedPs.childPackageNames.get(i); 16351 if (outInfo.removedChildPackages == null 16352 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16353 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16354 if (childPs == null) { 16355 continue; 16356 } 16357 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16358 installRes.name = childPackageName; 16359 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16360 installRes.pkg = mPackages.get(childPackageName); 16361 installRes.uid = childPs.pkg.applicationInfo.uid; 16362 if (outInfo.appearedChildPackages == null) { 16363 outInfo.appearedChildPackages = new ArrayMap<>(); 16364 } 16365 outInfo.appearedChildPackages.put(childPackageName, installRes); 16366 } 16367 } 16368 } 16369 } 16370 } 16371 16372 return ret; 16373 } 16374 16375 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16376 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16377 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16378 for (int nextUserId : userIds) { 16379 if (DEBUG_REMOVE) { 16380 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16381 } 16382 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16383 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16384 false /*hidden*/, false /*suspended*/, null, null, null, 16385 false /*blockUninstall*/, 16386 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16387 } 16388 } 16389 16390 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16391 PackageRemovedInfo outInfo) { 16392 final PackageParser.Package pkg; 16393 synchronized (mPackages) { 16394 pkg = mPackages.get(ps.name); 16395 } 16396 16397 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16398 : new int[] {userId}; 16399 for (int nextUserId : userIds) { 16400 if (DEBUG_REMOVE) { 16401 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16402 + nextUserId); 16403 } 16404 16405 destroyAppDataLIF(pkg, userId, 16406 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16407 destroyAppProfilesLIF(pkg, userId); 16408 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16409 schedulePackageCleaning(ps.name, nextUserId, false); 16410 synchronized (mPackages) { 16411 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16412 scheduleWritePackageRestrictionsLocked(nextUserId); 16413 } 16414 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16415 } 16416 } 16417 16418 if (outInfo != null) { 16419 outInfo.removedPackage = ps.name; 16420 outInfo.removedAppId = ps.appId; 16421 outInfo.removedUsers = userIds; 16422 } 16423 16424 return true; 16425 } 16426 16427 private final class ClearStorageConnection implements ServiceConnection { 16428 IMediaContainerService mContainerService; 16429 16430 @Override 16431 public void onServiceConnected(ComponentName name, IBinder service) { 16432 synchronized (this) { 16433 mContainerService = IMediaContainerService.Stub.asInterface(service); 16434 notifyAll(); 16435 } 16436 } 16437 16438 @Override 16439 public void onServiceDisconnected(ComponentName name) { 16440 } 16441 } 16442 16443 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16444 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16445 16446 final boolean mounted; 16447 if (Environment.isExternalStorageEmulated()) { 16448 mounted = true; 16449 } else { 16450 final String status = Environment.getExternalStorageState(); 16451 16452 mounted = status.equals(Environment.MEDIA_MOUNTED) 16453 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16454 } 16455 16456 if (!mounted) { 16457 return; 16458 } 16459 16460 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16461 int[] users; 16462 if (userId == UserHandle.USER_ALL) { 16463 users = sUserManager.getUserIds(); 16464 } else { 16465 users = new int[] { userId }; 16466 } 16467 final ClearStorageConnection conn = new ClearStorageConnection(); 16468 if (mContext.bindServiceAsUser( 16469 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16470 try { 16471 for (int curUser : users) { 16472 long timeout = SystemClock.uptimeMillis() + 5000; 16473 synchronized (conn) { 16474 long now; 16475 while (conn.mContainerService == null && 16476 (now = SystemClock.uptimeMillis()) < timeout) { 16477 try { 16478 conn.wait(timeout - now); 16479 } catch (InterruptedException e) { 16480 } 16481 } 16482 } 16483 if (conn.mContainerService == null) { 16484 return; 16485 } 16486 16487 final UserEnvironment userEnv = new UserEnvironment(curUser); 16488 clearDirectory(conn.mContainerService, 16489 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16490 if (allData) { 16491 clearDirectory(conn.mContainerService, 16492 userEnv.buildExternalStorageAppDataDirs(packageName)); 16493 clearDirectory(conn.mContainerService, 16494 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16495 } 16496 } 16497 } finally { 16498 mContext.unbindService(conn); 16499 } 16500 } 16501 } 16502 16503 @Override 16504 public void clearApplicationProfileData(String packageName) { 16505 enforceSystemOrRoot("Only the system can clear all profile data"); 16506 16507 final PackageParser.Package pkg; 16508 synchronized (mPackages) { 16509 pkg = mPackages.get(packageName); 16510 } 16511 16512 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16513 synchronized (mInstallLock) { 16514 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16515 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16516 true /* removeBaseMarker */); 16517 } 16518 } 16519 } 16520 16521 @Override 16522 public void clearApplicationUserData(final String packageName, 16523 final IPackageDataObserver observer, final int userId) { 16524 mContext.enforceCallingOrSelfPermission( 16525 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16526 16527 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16528 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16529 16530 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16531 throw new SecurityException("Cannot clear data for a protected package: " 16532 + packageName); 16533 } 16534 // Queue up an async operation since the package deletion may take a little while. 16535 mHandler.post(new Runnable() { 16536 public void run() { 16537 mHandler.removeCallbacks(this); 16538 final boolean succeeded; 16539 try (PackageFreezer freezer = freezePackage(packageName, 16540 "clearApplicationUserData")) { 16541 synchronized (mInstallLock) { 16542 succeeded = clearApplicationUserDataLIF(packageName, userId); 16543 } 16544 clearExternalStorageDataSync(packageName, userId, true); 16545 } 16546 if (succeeded) { 16547 // invoke DeviceStorageMonitor's update method to clear any notifications 16548 DeviceStorageMonitorInternal dsm = LocalServices 16549 .getService(DeviceStorageMonitorInternal.class); 16550 if (dsm != null) { 16551 dsm.checkMemory(); 16552 } 16553 } 16554 if(observer != null) { 16555 try { 16556 observer.onRemoveCompleted(packageName, succeeded); 16557 } catch (RemoteException e) { 16558 Log.i(TAG, "Observer no longer exists."); 16559 } 16560 } //end if observer 16561 } //end run 16562 }); 16563 } 16564 16565 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16566 if (packageName == null) { 16567 Slog.w(TAG, "Attempt to delete null packageName."); 16568 return false; 16569 } 16570 16571 // Try finding details about the requested package 16572 PackageParser.Package pkg; 16573 synchronized (mPackages) { 16574 pkg = mPackages.get(packageName); 16575 if (pkg == null) { 16576 final PackageSetting ps = mSettings.mPackages.get(packageName); 16577 if (ps != null) { 16578 pkg = ps.pkg; 16579 } 16580 } 16581 16582 if (pkg == null) { 16583 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16584 return false; 16585 } 16586 16587 PackageSetting ps = (PackageSetting) pkg.mExtras; 16588 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16589 } 16590 16591 clearAppDataLIF(pkg, userId, 16592 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16593 16594 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16595 removeKeystoreDataIfNeeded(userId, appId); 16596 16597 UserManagerInternal umInternal = getUserManagerInternal(); 16598 final int flags; 16599 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16600 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16601 } else if (umInternal.isUserRunning(userId)) { 16602 flags = StorageManager.FLAG_STORAGE_DE; 16603 } else { 16604 flags = 0; 16605 } 16606 prepareAppDataContentsLIF(pkg, userId, flags); 16607 16608 return true; 16609 } 16610 16611 /** 16612 * Reverts user permission state changes (permissions and flags) in 16613 * all packages for a given user. 16614 * 16615 * @param userId The device user for which to do a reset. 16616 */ 16617 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16618 final int packageCount = mPackages.size(); 16619 for (int i = 0; i < packageCount; i++) { 16620 PackageParser.Package pkg = mPackages.valueAt(i); 16621 PackageSetting ps = (PackageSetting) pkg.mExtras; 16622 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16623 } 16624 } 16625 16626 private void resetNetworkPolicies(int userId) { 16627 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16628 } 16629 16630 /** 16631 * Reverts user permission state changes (permissions and flags). 16632 * 16633 * @param ps The package for which to reset. 16634 * @param userId The device user for which to do a reset. 16635 */ 16636 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16637 final PackageSetting ps, final int userId) { 16638 if (ps.pkg == null) { 16639 return; 16640 } 16641 16642 // These are flags that can change base on user actions. 16643 final int userSettableMask = FLAG_PERMISSION_USER_SET 16644 | FLAG_PERMISSION_USER_FIXED 16645 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16646 | FLAG_PERMISSION_REVIEW_REQUIRED; 16647 16648 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16649 | FLAG_PERMISSION_POLICY_FIXED; 16650 16651 boolean writeInstallPermissions = false; 16652 boolean writeRuntimePermissions = false; 16653 16654 final int permissionCount = ps.pkg.requestedPermissions.size(); 16655 for (int i = 0; i < permissionCount; i++) { 16656 String permission = ps.pkg.requestedPermissions.get(i); 16657 16658 BasePermission bp = mSettings.mPermissions.get(permission); 16659 if (bp == null) { 16660 continue; 16661 } 16662 16663 // If shared user we just reset the state to which only this app contributed. 16664 if (ps.sharedUser != null) { 16665 boolean used = false; 16666 final int packageCount = ps.sharedUser.packages.size(); 16667 for (int j = 0; j < packageCount; j++) { 16668 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16669 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16670 && pkg.pkg.requestedPermissions.contains(permission)) { 16671 used = true; 16672 break; 16673 } 16674 } 16675 if (used) { 16676 continue; 16677 } 16678 } 16679 16680 PermissionsState permissionsState = ps.getPermissionsState(); 16681 16682 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16683 16684 // Always clear the user settable flags. 16685 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16686 bp.name) != null; 16687 // If permission review is enabled and this is a legacy app, mark the 16688 // permission as requiring a review as this is the initial state. 16689 int flags = 0; 16690 if (Build.PERMISSIONS_REVIEW_REQUIRED 16691 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16692 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16693 } 16694 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16695 if (hasInstallState) { 16696 writeInstallPermissions = true; 16697 } else { 16698 writeRuntimePermissions = true; 16699 } 16700 } 16701 16702 // Below is only runtime permission handling. 16703 if (!bp.isRuntime()) { 16704 continue; 16705 } 16706 16707 // Never clobber system or policy. 16708 if ((oldFlags & policyOrSystemFlags) != 0) { 16709 continue; 16710 } 16711 16712 // If this permission was granted by default, make sure it is. 16713 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16714 if (permissionsState.grantRuntimePermission(bp, userId) 16715 != PERMISSION_OPERATION_FAILURE) { 16716 writeRuntimePermissions = true; 16717 } 16718 // If permission review is enabled the permissions for a legacy apps 16719 // are represented as constantly granted runtime ones, so don't revoke. 16720 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16721 // Otherwise, reset the permission. 16722 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16723 switch (revokeResult) { 16724 case PERMISSION_OPERATION_SUCCESS: 16725 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16726 writeRuntimePermissions = true; 16727 final int appId = ps.appId; 16728 mHandler.post(new Runnable() { 16729 @Override 16730 public void run() { 16731 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16732 } 16733 }); 16734 } break; 16735 } 16736 } 16737 } 16738 16739 // Synchronously write as we are taking permissions away. 16740 if (writeRuntimePermissions) { 16741 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16742 } 16743 16744 // Synchronously write as we are taking permissions away. 16745 if (writeInstallPermissions) { 16746 mSettings.writeLPr(); 16747 } 16748 } 16749 16750 /** 16751 * Remove entries from the keystore daemon. Will only remove it if the 16752 * {@code appId} is valid. 16753 */ 16754 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16755 if (appId < 0) { 16756 return; 16757 } 16758 16759 final KeyStore keyStore = KeyStore.getInstance(); 16760 if (keyStore != null) { 16761 if (userId == UserHandle.USER_ALL) { 16762 for (final int individual : sUserManager.getUserIds()) { 16763 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16764 } 16765 } else { 16766 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16767 } 16768 } else { 16769 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16770 } 16771 } 16772 16773 @Override 16774 public void deleteApplicationCacheFiles(final String packageName, 16775 final IPackageDataObserver observer) { 16776 final int userId = UserHandle.getCallingUserId(); 16777 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16778 } 16779 16780 @Override 16781 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16782 final IPackageDataObserver observer) { 16783 mContext.enforceCallingOrSelfPermission( 16784 android.Manifest.permission.DELETE_CACHE_FILES, null); 16785 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16786 /* requireFullPermission= */ true, /* checkShell= */ false, 16787 "delete application cache files"); 16788 16789 final PackageParser.Package pkg; 16790 synchronized (mPackages) { 16791 pkg = mPackages.get(packageName); 16792 } 16793 16794 // Queue up an async operation since the package deletion may take a little while. 16795 mHandler.post(new Runnable() { 16796 public void run() { 16797 synchronized (mInstallLock) { 16798 final int flags = StorageManager.FLAG_STORAGE_DE 16799 | StorageManager.FLAG_STORAGE_CE; 16800 // We're only clearing cache files, so we don't care if the 16801 // app is unfrozen and still able to run 16802 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16803 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16804 } 16805 clearExternalStorageDataSync(packageName, userId, false); 16806 if (observer != null) { 16807 try { 16808 observer.onRemoveCompleted(packageName, true); 16809 } catch (RemoteException e) { 16810 Log.i(TAG, "Observer no longer exists."); 16811 } 16812 } 16813 } 16814 }); 16815 } 16816 16817 @Override 16818 public void getPackageSizeInfo(final String packageName, int userHandle, 16819 final IPackageStatsObserver observer) { 16820 mContext.enforceCallingOrSelfPermission( 16821 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16822 if (packageName == null) { 16823 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16824 } 16825 16826 PackageStats stats = new PackageStats(packageName, userHandle); 16827 16828 /* 16829 * Queue up an async operation since the package measurement may take a 16830 * little while. 16831 */ 16832 Message msg = mHandler.obtainMessage(INIT_COPY); 16833 msg.obj = new MeasureParams(stats, observer); 16834 mHandler.sendMessage(msg); 16835 } 16836 16837 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16838 final PackageSetting ps; 16839 synchronized (mPackages) { 16840 ps = mSettings.mPackages.get(packageName); 16841 if (ps == null) { 16842 Slog.w(TAG, "Failed to find settings for " + packageName); 16843 return false; 16844 } 16845 } 16846 try { 16847 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16848 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16849 ps.getCeDataInode(userId), ps.codePathString, stats); 16850 } catch (InstallerException e) { 16851 Slog.w(TAG, String.valueOf(e)); 16852 return false; 16853 } 16854 16855 // For now, ignore code size of packages on system partition 16856 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16857 stats.codeSize = 0; 16858 } 16859 16860 return true; 16861 } 16862 16863 private int getUidTargetSdkVersionLockedLPr(int uid) { 16864 Object obj = mSettings.getUserIdLPr(uid); 16865 if (obj instanceof SharedUserSetting) { 16866 final SharedUserSetting sus = (SharedUserSetting) obj; 16867 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16868 final Iterator<PackageSetting> it = sus.packages.iterator(); 16869 while (it.hasNext()) { 16870 final PackageSetting ps = it.next(); 16871 if (ps.pkg != null) { 16872 int v = ps.pkg.applicationInfo.targetSdkVersion; 16873 if (v < vers) vers = v; 16874 } 16875 } 16876 return vers; 16877 } else if (obj instanceof PackageSetting) { 16878 final PackageSetting ps = (PackageSetting) obj; 16879 if (ps.pkg != null) { 16880 return ps.pkg.applicationInfo.targetSdkVersion; 16881 } 16882 } 16883 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16884 } 16885 16886 @Override 16887 public void addPreferredActivity(IntentFilter filter, int match, 16888 ComponentName[] set, ComponentName activity, int userId) { 16889 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16890 "Adding preferred"); 16891 } 16892 16893 private void addPreferredActivityInternal(IntentFilter filter, int match, 16894 ComponentName[] set, ComponentName activity, boolean always, int userId, 16895 String opname) { 16896 // writer 16897 int callingUid = Binder.getCallingUid(); 16898 enforceCrossUserPermission(callingUid, userId, 16899 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16900 if (filter.countActions() == 0) { 16901 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16902 return; 16903 } 16904 synchronized (mPackages) { 16905 if (mContext.checkCallingOrSelfPermission( 16906 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16907 != PackageManager.PERMISSION_GRANTED) { 16908 if (getUidTargetSdkVersionLockedLPr(callingUid) 16909 < Build.VERSION_CODES.FROYO) { 16910 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16911 + callingUid); 16912 return; 16913 } 16914 mContext.enforceCallingOrSelfPermission( 16915 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16916 } 16917 16918 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16919 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16920 + userId + ":"); 16921 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16922 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16923 scheduleWritePackageRestrictionsLocked(userId); 16924 postPreferredActivityChangedBroadcast(userId); 16925 } 16926 } 16927 16928 private void postPreferredActivityChangedBroadcast(int userId) { 16929 mHandler.post(() -> { 16930 final IActivityManager am = ActivityManagerNative.getDefault(); 16931 if (am == null) { 16932 return; 16933 } 16934 16935 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16936 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16937 try { 16938 am.broadcastIntent(null, intent, null, null, 16939 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16940 null, false, false, userId); 16941 } catch (RemoteException e) { 16942 } 16943 }); 16944 } 16945 16946 @Override 16947 public void replacePreferredActivity(IntentFilter filter, int match, 16948 ComponentName[] set, ComponentName activity, int userId) { 16949 if (filter.countActions() != 1) { 16950 throw new IllegalArgumentException( 16951 "replacePreferredActivity expects filter to have only 1 action."); 16952 } 16953 if (filter.countDataAuthorities() != 0 16954 || filter.countDataPaths() != 0 16955 || filter.countDataSchemes() > 1 16956 || filter.countDataTypes() != 0) { 16957 throw new IllegalArgumentException( 16958 "replacePreferredActivity expects filter to have no data authorities, " + 16959 "paths, or types; and at most one scheme."); 16960 } 16961 16962 final int callingUid = Binder.getCallingUid(); 16963 enforceCrossUserPermission(callingUid, userId, 16964 true /* requireFullPermission */, false /* checkShell */, 16965 "replace preferred activity"); 16966 synchronized (mPackages) { 16967 if (mContext.checkCallingOrSelfPermission( 16968 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16969 != PackageManager.PERMISSION_GRANTED) { 16970 if (getUidTargetSdkVersionLockedLPr(callingUid) 16971 < Build.VERSION_CODES.FROYO) { 16972 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16973 + Binder.getCallingUid()); 16974 return; 16975 } 16976 mContext.enforceCallingOrSelfPermission( 16977 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16978 } 16979 16980 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16981 if (pir != null) { 16982 // Get all of the existing entries that exactly match this filter. 16983 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16984 if (existing != null && existing.size() == 1) { 16985 PreferredActivity cur = existing.get(0); 16986 if (DEBUG_PREFERRED) { 16987 Slog.i(TAG, "Checking replace of preferred:"); 16988 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16989 if (!cur.mPref.mAlways) { 16990 Slog.i(TAG, " -- CUR; not mAlways!"); 16991 } else { 16992 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16993 Slog.i(TAG, " -- CUR: mSet=" 16994 + Arrays.toString(cur.mPref.mSetComponents)); 16995 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16996 Slog.i(TAG, " -- NEW: mMatch=" 16997 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16998 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16999 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17000 } 17001 } 17002 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17003 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17004 && cur.mPref.sameSet(set)) { 17005 // Setting the preferred activity to what it happens to be already 17006 if (DEBUG_PREFERRED) { 17007 Slog.i(TAG, "Replacing with same preferred activity " 17008 + cur.mPref.mShortComponent + " for user " 17009 + userId + ":"); 17010 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17011 } 17012 return; 17013 } 17014 } 17015 17016 if (existing != null) { 17017 if (DEBUG_PREFERRED) { 17018 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17019 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17020 } 17021 for (int i = 0; i < existing.size(); i++) { 17022 PreferredActivity pa = existing.get(i); 17023 if (DEBUG_PREFERRED) { 17024 Slog.i(TAG, "Removing existing preferred activity " 17025 + pa.mPref.mComponent + ":"); 17026 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17027 } 17028 pir.removeFilter(pa); 17029 } 17030 } 17031 } 17032 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17033 "Replacing preferred"); 17034 } 17035 } 17036 17037 @Override 17038 public void clearPackagePreferredActivities(String packageName) { 17039 final int uid = Binder.getCallingUid(); 17040 // writer 17041 synchronized (mPackages) { 17042 PackageParser.Package pkg = mPackages.get(packageName); 17043 if (pkg == null || pkg.applicationInfo.uid != uid) { 17044 if (mContext.checkCallingOrSelfPermission( 17045 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17046 != PackageManager.PERMISSION_GRANTED) { 17047 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17048 < Build.VERSION_CODES.FROYO) { 17049 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17050 + Binder.getCallingUid()); 17051 return; 17052 } 17053 mContext.enforceCallingOrSelfPermission( 17054 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17055 } 17056 } 17057 17058 int user = UserHandle.getCallingUserId(); 17059 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17060 scheduleWritePackageRestrictionsLocked(user); 17061 } 17062 } 17063 } 17064 17065 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17066 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17067 ArrayList<PreferredActivity> removed = null; 17068 boolean changed = false; 17069 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17070 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17071 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17072 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17073 continue; 17074 } 17075 Iterator<PreferredActivity> it = pir.filterIterator(); 17076 while (it.hasNext()) { 17077 PreferredActivity pa = it.next(); 17078 // Mark entry for removal only if it matches the package name 17079 // and the entry is of type "always". 17080 if (packageName == null || 17081 (pa.mPref.mComponent.getPackageName().equals(packageName) 17082 && pa.mPref.mAlways)) { 17083 if (removed == null) { 17084 removed = new ArrayList<PreferredActivity>(); 17085 } 17086 removed.add(pa); 17087 } 17088 } 17089 if (removed != null) { 17090 for (int j=0; j<removed.size(); j++) { 17091 PreferredActivity pa = removed.get(j); 17092 pir.removeFilter(pa); 17093 } 17094 changed = true; 17095 } 17096 } 17097 if (changed) { 17098 postPreferredActivityChangedBroadcast(userId); 17099 } 17100 return changed; 17101 } 17102 17103 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17104 private void clearIntentFilterVerificationsLPw(int userId) { 17105 final int packageCount = mPackages.size(); 17106 for (int i = 0; i < packageCount; i++) { 17107 PackageParser.Package pkg = mPackages.valueAt(i); 17108 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17109 } 17110 } 17111 17112 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17113 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17114 if (userId == UserHandle.USER_ALL) { 17115 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17116 sUserManager.getUserIds())) { 17117 for (int oneUserId : sUserManager.getUserIds()) { 17118 scheduleWritePackageRestrictionsLocked(oneUserId); 17119 } 17120 } 17121 } else { 17122 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17123 scheduleWritePackageRestrictionsLocked(userId); 17124 } 17125 } 17126 } 17127 17128 void clearDefaultBrowserIfNeeded(String packageName) { 17129 for (int oneUserId : sUserManager.getUserIds()) { 17130 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17131 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17132 if (packageName.equals(defaultBrowserPackageName)) { 17133 setDefaultBrowserPackageName(null, oneUserId); 17134 } 17135 } 17136 } 17137 17138 @Override 17139 public void resetApplicationPreferences(int userId) { 17140 mContext.enforceCallingOrSelfPermission( 17141 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17142 final long identity = Binder.clearCallingIdentity(); 17143 // writer 17144 try { 17145 synchronized (mPackages) { 17146 clearPackagePreferredActivitiesLPw(null, userId); 17147 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17148 // TODO: We have to reset the default SMS and Phone. This requires 17149 // significant refactoring to keep all default apps in the package 17150 // manager (cleaner but more work) or have the services provide 17151 // callbacks to the package manager to request a default app reset. 17152 applyFactoryDefaultBrowserLPw(userId); 17153 clearIntentFilterVerificationsLPw(userId); 17154 primeDomainVerificationsLPw(userId); 17155 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17156 scheduleWritePackageRestrictionsLocked(userId); 17157 } 17158 resetNetworkPolicies(userId); 17159 } finally { 17160 Binder.restoreCallingIdentity(identity); 17161 } 17162 } 17163 17164 @Override 17165 public int getPreferredActivities(List<IntentFilter> outFilters, 17166 List<ComponentName> outActivities, String packageName) { 17167 17168 int num = 0; 17169 final int userId = UserHandle.getCallingUserId(); 17170 // reader 17171 synchronized (mPackages) { 17172 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17173 if (pir != null) { 17174 final Iterator<PreferredActivity> it = pir.filterIterator(); 17175 while (it.hasNext()) { 17176 final PreferredActivity pa = it.next(); 17177 if (packageName == null 17178 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17179 && pa.mPref.mAlways)) { 17180 if (outFilters != null) { 17181 outFilters.add(new IntentFilter(pa)); 17182 } 17183 if (outActivities != null) { 17184 outActivities.add(pa.mPref.mComponent); 17185 } 17186 } 17187 } 17188 } 17189 } 17190 17191 return num; 17192 } 17193 17194 @Override 17195 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17196 int userId) { 17197 int callingUid = Binder.getCallingUid(); 17198 if (callingUid != Process.SYSTEM_UID) { 17199 throw new SecurityException( 17200 "addPersistentPreferredActivity can only be run by the system"); 17201 } 17202 if (filter.countActions() == 0) { 17203 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17204 return; 17205 } 17206 synchronized (mPackages) { 17207 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17208 ":"); 17209 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17210 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17211 new PersistentPreferredActivity(filter, activity)); 17212 scheduleWritePackageRestrictionsLocked(userId); 17213 postPreferredActivityChangedBroadcast(userId); 17214 } 17215 } 17216 17217 @Override 17218 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17219 int callingUid = Binder.getCallingUid(); 17220 if (callingUid != Process.SYSTEM_UID) { 17221 throw new SecurityException( 17222 "clearPackagePersistentPreferredActivities can only be run by the system"); 17223 } 17224 ArrayList<PersistentPreferredActivity> removed = null; 17225 boolean changed = false; 17226 synchronized (mPackages) { 17227 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17228 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17229 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17230 .valueAt(i); 17231 if (userId != thisUserId) { 17232 continue; 17233 } 17234 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17235 while (it.hasNext()) { 17236 PersistentPreferredActivity ppa = it.next(); 17237 // Mark entry for removal only if it matches the package name. 17238 if (ppa.mComponent.getPackageName().equals(packageName)) { 17239 if (removed == null) { 17240 removed = new ArrayList<PersistentPreferredActivity>(); 17241 } 17242 removed.add(ppa); 17243 } 17244 } 17245 if (removed != null) { 17246 for (int j=0; j<removed.size(); j++) { 17247 PersistentPreferredActivity ppa = removed.get(j); 17248 ppir.removeFilter(ppa); 17249 } 17250 changed = true; 17251 } 17252 } 17253 17254 if (changed) { 17255 scheduleWritePackageRestrictionsLocked(userId); 17256 postPreferredActivityChangedBroadcast(userId); 17257 } 17258 } 17259 } 17260 17261 /** 17262 * Common machinery for picking apart a restored XML blob and passing 17263 * it to a caller-supplied functor to be applied to the running system. 17264 */ 17265 private void restoreFromXml(XmlPullParser parser, int userId, 17266 String expectedStartTag, BlobXmlRestorer functor) 17267 throws IOException, XmlPullParserException { 17268 int type; 17269 while ((type = parser.next()) != XmlPullParser.START_TAG 17270 && type != XmlPullParser.END_DOCUMENT) { 17271 } 17272 if (type != XmlPullParser.START_TAG) { 17273 // oops didn't find a start tag?! 17274 if (DEBUG_BACKUP) { 17275 Slog.e(TAG, "Didn't find start tag during restore"); 17276 } 17277 return; 17278 } 17279Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17280 // this is supposed to be TAG_PREFERRED_BACKUP 17281 if (!expectedStartTag.equals(parser.getName())) { 17282 if (DEBUG_BACKUP) { 17283 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17284 } 17285 return; 17286 } 17287 17288 // skip interfering stuff, then we're aligned with the backing implementation 17289 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17290Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17291 functor.apply(parser, userId); 17292 } 17293 17294 private interface BlobXmlRestorer { 17295 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17296 } 17297 17298 /** 17299 * Non-Binder method, support for the backup/restore mechanism: write the 17300 * full set of preferred activities in its canonical XML format. Returns the 17301 * XML output as a byte array, or null if there is none. 17302 */ 17303 @Override 17304 public byte[] getPreferredActivityBackup(int userId) { 17305 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17306 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17307 } 17308 17309 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17310 try { 17311 final XmlSerializer serializer = new FastXmlSerializer(); 17312 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17313 serializer.startDocument(null, true); 17314 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17315 17316 synchronized (mPackages) { 17317 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17318 } 17319 17320 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17321 serializer.endDocument(); 17322 serializer.flush(); 17323 } catch (Exception e) { 17324 if (DEBUG_BACKUP) { 17325 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17326 } 17327 return null; 17328 } 17329 17330 return dataStream.toByteArray(); 17331 } 17332 17333 @Override 17334 public void restorePreferredActivities(byte[] backup, int userId) { 17335 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17336 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17337 } 17338 17339 try { 17340 final XmlPullParser parser = Xml.newPullParser(); 17341 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17342 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17343 new BlobXmlRestorer() { 17344 @Override 17345 public void apply(XmlPullParser parser, int userId) 17346 throws XmlPullParserException, IOException { 17347 synchronized (mPackages) { 17348 mSettings.readPreferredActivitiesLPw(parser, userId); 17349 } 17350 } 17351 } ); 17352 } catch (Exception e) { 17353 if (DEBUG_BACKUP) { 17354 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17355 } 17356 } 17357 } 17358 17359 /** 17360 * Non-Binder method, support for the backup/restore mechanism: write the 17361 * default browser (etc) settings in its canonical XML format. Returns the default 17362 * browser XML representation as a byte array, or null if there is none. 17363 */ 17364 @Override 17365 public byte[] getDefaultAppsBackup(int userId) { 17366 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17367 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17368 } 17369 17370 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17371 try { 17372 final XmlSerializer serializer = new FastXmlSerializer(); 17373 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17374 serializer.startDocument(null, true); 17375 serializer.startTag(null, TAG_DEFAULT_APPS); 17376 17377 synchronized (mPackages) { 17378 mSettings.writeDefaultAppsLPr(serializer, userId); 17379 } 17380 17381 serializer.endTag(null, TAG_DEFAULT_APPS); 17382 serializer.endDocument(); 17383 serializer.flush(); 17384 } catch (Exception e) { 17385 if (DEBUG_BACKUP) { 17386 Slog.e(TAG, "Unable to write default apps for backup", e); 17387 } 17388 return null; 17389 } 17390 17391 return dataStream.toByteArray(); 17392 } 17393 17394 @Override 17395 public void restoreDefaultApps(byte[] backup, int userId) { 17396 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17397 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17398 } 17399 17400 try { 17401 final XmlPullParser parser = Xml.newPullParser(); 17402 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17403 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17404 new BlobXmlRestorer() { 17405 @Override 17406 public void apply(XmlPullParser parser, int userId) 17407 throws XmlPullParserException, IOException { 17408 synchronized (mPackages) { 17409 mSettings.readDefaultAppsLPw(parser, userId); 17410 } 17411 } 17412 } ); 17413 } catch (Exception e) { 17414 if (DEBUG_BACKUP) { 17415 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17416 } 17417 } 17418 } 17419 17420 @Override 17421 public byte[] getIntentFilterVerificationBackup(int userId) { 17422 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17423 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17424 } 17425 17426 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17427 try { 17428 final XmlSerializer serializer = new FastXmlSerializer(); 17429 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17430 serializer.startDocument(null, true); 17431 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17432 17433 synchronized (mPackages) { 17434 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17435 } 17436 17437 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17438 serializer.endDocument(); 17439 serializer.flush(); 17440 } catch (Exception e) { 17441 if (DEBUG_BACKUP) { 17442 Slog.e(TAG, "Unable to write default apps for backup", e); 17443 } 17444 return null; 17445 } 17446 17447 return dataStream.toByteArray(); 17448 } 17449 17450 @Override 17451 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17452 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17453 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17454 } 17455 17456 try { 17457 final XmlPullParser parser = Xml.newPullParser(); 17458 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17459 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17460 new BlobXmlRestorer() { 17461 @Override 17462 public void apply(XmlPullParser parser, int userId) 17463 throws XmlPullParserException, IOException { 17464 synchronized (mPackages) { 17465 mSettings.readAllDomainVerificationsLPr(parser, userId); 17466 mSettings.writeLPr(); 17467 } 17468 } 17469 } ); 17470 } catch (Exception e) { 17471 if (DEBUG_BACKUP) { 17472 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17473 } 17474 } 17475 } 17476 17477 @Override 17478 public byte[] getPermissionGrantBackup(int userId) { 17479 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17480 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17481 } 17482 17483 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17484 try { 17485 final XmlSerializer serializer = new FastXmlSerializer(); 17486 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17487 serializer.startDocument(null, true); 17488 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17489 17490 synchronized (mPackages) { 17491 serializeRuntimePermissionGrantsLPr(serializer, userId); 17492 } 17493 17494 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17495 serializer.endDocument(); 17496 serializer.flush(); 17497 } catch (Exception e) { 17498 if (DEBUG_BACKUP) { 17499 Slog.e(TAG, "Unable to write default apps for backup", e); 17500 } 17501 return null; 17502 } 17503 17504 return dataStream.toByteArray(); 17505 } 17506 17507 @Override 17508 public void restorePermissionGrants(byte[] backup, int userId) { 17509 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17510 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17511 } 17512 17513 try { 17514 final XmlPullParser parser = Xml.newPullParser(); 17515 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17516 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17517 new BlobXmlRestorer() { 17518 @Override 17519 public void apply(XmlPullParser parser, int userId) 17520 throws XmlPullParserException, IOException { 17521 synchronized (mPackages) { 17522 processRestoredPermissionGrantsLPr(parser, userId); 17523 } 17524 } 17525 } ); 17526 } catch (Exception e) { 17527 if (DEBUG_BACKUP) { 17528 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17529 } 17530 } 17531 } 17532 17533 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17534 throws IOException { 17535 serializer.startTag(null, TAG_ALL_GRANTS); 17536 17537 final int N = mSettings.mPackages.size(); 17538 for (int i = 0; i < N; i++) { 17539 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17540 boolean pkgGrantsKnown = false; 17541 17542 PermissionsState packagePerms = ps.getPermissionsState(); 17543 17544 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17545 final int grantFlags = state.getFlags(); 17546 // only look at grants that are not system/policy fixed 17547 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17548 final boolean isGranted = state.isGranted(); 17549 // And only back up the user-twiddled state bits 17550 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17551 final String packageName = mSettings.mPackages.keyAt(i); 17552 if (!pkgGrantsKnown) { 17553 serializer.startTag(null, TAG_GRANT); 17554 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17555 pkgGrantsKnown = true; 17556 } 17557 17558 final boolean userSet = 17559 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17560 final boolean userFixed = 17561 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17562 final boolean revoke = 17563 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17564 17565 serializer.startTag(null, TAG_PERMISSION); 17566 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17567 if (isGranted) { 17568 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17569 } 17570 if (userSet) { 17571 serializer.attribute(null, ATTR_USER_SET, "true"); 17572 } 17573 if (userFixed) { 17574 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17575 } 17576 if (revoke) { 17577 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17578 } 17579 serializer.endTag(null, TAG_PERMISSION); 17580 } 17581 } 17582 } 17583 17584 if (pkgGrantsKnown) { 17585 serializer.endTag(null, TAG_GRANT); 17586 } 17587 } 17588 17589 serializer.endTag(null, TAG_ALL_GRANTS); 17590 } 17591 17592 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17593 throws XmlPullParserException, IOException { 17594 String pkgName = null; 17595 int outerDepth = parser.getDepth(); 17596 int type; 17597 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17598 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17599 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17600 continue; 17601 } 17602 17603 final String tagName = parser.getName(); 17604 if (tagName.equals(TAG_GRANT)) { 17605 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17606 if (DEBUG_BACKUP) { 17607 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17608 } 17609 } else if (tagName.equals(TAG_PERMISSION)) { 17610 17611 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17612 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17613 17614 int newFlagSet = 0; 17615 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17616 newFlagSet |= FLAG_PERMISSION_USER_SET; 17617 } 17618 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17619 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17620 } 17621 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17622 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17623 } 17624 if (DEBUG_BACKUP) { 17625 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17626 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17627 } 17628 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17629 if (ps != null) { 17630 // Already installed so we apply the grant immediately 17631 if (DEBUG_BACKUP) { 17632 Slog.v(TAG, " + already installed; applying"); 17633 } 17634 PermissionsState perms = ps.getPermissionsState(); 17635 BasePermission bp = mSettings.mPermissions.get(permName); 17636 if (bp != null) { 17637 if (isGranted) { 17638 perms.grantRuntimePermission(bp, userId); 17639 } 17640 if (newFlagSet != 0) { 17641 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17642 } 17643 } 17644 } else { 17645 // Need to wait for post-restore install to apply the grant 17646 if (DEBUG_BACKUP) { 17647 Slog.v(TAG, " - not yet installed; saving for later"); 17648 } 17649 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17650 isGranted, newFlagSet, userId); 17651 } 17652 } else { 17653 PackageManagerService.reportSettingsProblem(Log.WARN, 17654 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17655 XmlUtils.skipCurrentTag(parser); 17656 } 17657 } 17658 17659 scheduleWriteSettingsLocked(); 17660 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17661 } 17662 17663 @Override 17664 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17665 int sourceUserId, int targetUserId, int flags) { 17666 mContext.enforceCallingOrSelfPermission( 17667 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17668 int callingUid = Binder.getCallingUid(); 17669 enforceOwnerRights(ownerPackage, callingUid); 17670 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17671 if (intentFilter.countActions() == 0) { 17672 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17673 return; 17674 } 17675 synchronized (mPackages) { 17676 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17677 ownerPackage, targetUserId, flags); 17678 CrossProfileIntentResolver resolver = 17679 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17680 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17681 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17682 if (existing != null) { 17683 int size = existing.size(); 17684 for (int i = 0; i < size; i++) { 17685 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17686 return; 17687 } 17688 } 17689 } 17690 resolver.addFilter(newFilter); 17691 scheduleWritePackageRestrictionsLocked(sourceUserId); 17692 } 17693 } 17694 17695 @Override 17696 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17697 mContext.enforceCallingOrSelfPermission( 17698 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17699 int callingUid = Binder.getCallingUid(); 17700 enforceOwnerRights(ownerPackage, callingUid); 17701 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17702 synchronized (mPackages) { 17703 CrossProfileIntentResolver resolver = 17704 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17705 ArraySet<CrossProfileIntentFilter> set = 17706 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17707 for (CrossProfileIntentFilter filter : set) { 17708 if (filter.getOwnerPackage().equals(ownerPackage)) { 17709 resolver.removeFilter(filter); 17710 } 17711 } 17712 scheduleWritePackageRestrictionsLocked(sourceUserId); 17713 } 17714 } 17715 17716 // Enforcing that callingUid is owning pkg on userId 17717 private void enforceOwnerRights(String pkg, int callingUid) { 17718 // The system owns everything. 17719 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17720 return; 17721 } 17722 int callingUserId = UserHandle.getUserId(callingUid); 17723 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17724 if (pi == null) { 17725 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17726 + callingUserId); 17727 } 17728 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17729 throw new SecurityException("Calling uid " + callingUid 17730 + " does not own package " + pkg); 17731 } 17732 } 17733 17734 @Override 17735 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17736 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17737 } 17738 17739 private Intent getHomeIntent() { 17740 Intent intent = new Intent(Intent.ACTION_MAIN); 17741 intent.addCategory(Intent.CATEGORY_HOME); 17742 intent.addCategory(Intent.CATEGORY_DEFAULT); 17743 return intent; 17744 } 17745 17746 private IntentFilter getHomeFilter() { 17747 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17748 filter.addCategory(Intent.CATEGORY_HOME); 17749 filter.addCategory(Intent.CATEGORY_DEFAULT); 17750 return filter; 17751 } 17752 17753 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17754 int userId) { 17755 Intent intent = getHomeIntent(); 17756 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17757 PackageManager.GET_META_DATA, userId); 17758 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17759 true, false, false, userId); 17760 17761 allHomeCandidates.clear(); 17762 if (list != null) { 17763 for (ResolveInfo ri : list) { 17764 allHomeCandidates.add(ri); 17765 } 17766 } 17767 return (preferred == null || preferred.activityInfo == null) 17768 ? null 17769 : new ComponentName(preferred.activityInfo.packageName, 17770 preferred.activityInfo.name); 17771 } 17772 17773 @Override 17774 public void setHomeActivity(ComponentName comp, int userId) { 17775 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17776 getHomeActivitiesAsUser(homeActivities, userId); 17777 17778 boolean found = false; 17779 17780 final int size = homeActivities.size(); 17781 final ComponentName[] set = new ComponentName[size]; 17782 for (int i = 0; i < size; i++) { 17783 final ResolveInfo candidate = homeActivities.get(i); 17784 final ActivityInfo info = candidate.activityInfo; 17785 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17786 set[i] = activityName; 17787 if (!found && activityName.equals(comp)) { 17788 found = true; 17789 } 17790 } 17791 if (!found) { 17792 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17793 + userId); 17794 } 17795 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17796 set, comp, userId); 17797 } 17798 17799 private @Nullable String getSetupWizardPackageName() { 17800 final Intent intent = new Intent(Intent.ACTION_MAIN); 17801 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17802 17803 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17804 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17805 | MATCH_DISABLED_COMPONENTS, 17806 UserHandle.myUserId()); 17807 if (matches.size() == 1) { 17808 return matches.get(0).getComponentInfo().packageName; 17809 } else { 17810 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17811 + ": matches=" + matches); 17812 return null; 17813 } 17814 } 17815 17816 private @Nullable String getStorageManagerPackageName() { 17817 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17818 17819 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17820 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17821 | MATCH_DISABLED_COMPONENTS, 17822 UserHandle.myUserId()); 17823 if (matches.size() == 1) { 17824 return matches.get(0).getComponentInfo().packageName; 17825 } else { 17826 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17827 + matches.size() + ": matches=" + matches); 17828 return null; 17829 } 17830 } 17831 17832 @Override 17833 public void setApplicationEnabledSetting(String appPackageName, 17834 int newState, int flags, int userId, String callingPackage) { 17835 if (!sUserManager.exists(userId)) return; 17836 if (callingPackage == null) { 17837 callingPackage = Integer.toString(Binder.getCallingUid()); 17838 } 17839 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17840 } 17841 17842 @Override 17843 public void setComponentEnabledSetting(ComponentName componentName, 17844 int newState, int flags, int userId) { 17845 if (!sUserManager.exists(userId)) return; 17846 setEnabledSetting(componentName.getPackageName(), 17847 componentName.getClassName(), newState, flags, userId, null); 17848 } 17849 17850 private void setEnabledSetting(final String packageName, String className, int newState, 17851 final int flags, int userId, String callingPackage) { 17852 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17853 || newState == COMPONENT_ENABLED_STATE_ENABLED 17854 || newState == COMPONENT_ENABLED_STATE_DISABLED 17855 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17856 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17857 throw new IllegalArgumentException("Invalid new component state: " 17858 + newState); 17859 } 17860 PackageSetting pkgSetting; 17861 final int uid = Binder.getCallingUid(); 17862 final int permission; 17863 if (uid == Process.SYSTEM_UID) { 17864 permission = PackageManager.PERMISSION_GRANTED; 17865 } else { 17866 permission = mContext.checkCallingOrSelfPermission( 17867 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17868 } 17869 enforceCrossUserPermission(uid, userId, 17870 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17871 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17872 boolean sendNow = false; 17873 boolean isApp = (className == null); 17874 String componentName = isApp ? packageName : className; 17875 int packageUid = -1; 17876 ArrayList<String> components; 17877 17878 // writer 17879 synchronized (mPackages) { 17880 pkgSetting = mSettings.mPackages.get(packageName); 17881 if (pkgSetting == null) { 17882 if (className == null) { 17883 throw new IllegalArgumentException("Unknown package: " + packageName); 17884 } 17885 throw new IllegalArgumentException( 17886 "Unknown component: " + packageName + "/" + className); 17887 } 17888 } 17889 17890 // Limit who can change which apps 17891 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17892 // Don't allow apps that don't have permission to modify other apps 17893 if (!allowedByPermission) { 17894 throw new SecurityException( 17895 "Permission Denial: attempt to change component state from pid=" 17896 + Binder.getCallingPid() 17897 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17898 } 17899 // Don't allow changing protected packages. 17900 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17901 throw new SecurityException("Cannot disable a protected package: " + packageName); 17902 } 17903 } 17904 17905 synchronized (mPackages) { 17906 if (uid == Process.SHELL_UID) { 17907 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17908 int oldState = pkgSetting.getEnabled(userId); 17909 if (className == null 17910 && 17911 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17912 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17913 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17914 && 17915 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17916 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17917 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17918 // ok 17919 } else { 17920 throw new SecurityException( 17921 "Shell cannot change component state for " + packageName + "/" 17922 + className + " to " + newState); 17923 } 17924 } 17925 if (className == null) { 17926 // We're dealing with an application/package level state change 17927 if (pkgSetting.getEnabled(userId) == newState) { 17928 // Nothing to do 17929 return; 17930 } 17931 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17932 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17933 // Don't care about who enables an app. 17934 callingPackage = null; 17935 } 17936 pkgSetting.setEnabled(newState, userId, callingPackage); 17937 // pkgSetting.pkg.mSetEnabled = newState; 17938 } else { 17939 // We're dealing with a component level state change 17940 // First, verify that this is a valid class name. 17941 PackageParser.Package pkg = pkgSetting.pkg; 17942 if (pkg == null || !pkg.hasComponentClassName(className)) { 17943 if (pkg != null && 17944 pkg.applicationInfo.targetSdkVersion >= 17945 Build.VERSION_CODES.JELLY_BEAN) { 17946 throw new IllegalArgumentException("Component class " + className 17947 + " does not exist in " + packageName); 17948 } else { 17949 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17950 + className + " does not exist in " + packageName); 17951 } 17952 } 17953 switch (newState) { 17954 case COMPONENT_ENABLED_STATE_ENABLED: 17955 if (!pkgSetting.enableComponentLPw(className, userId)) { 17956 return; 17957 } 17958 break; 17959 case COMPONENT_ENABLED_STATE_DISABLED: 17960 if (!pkgSetting.disableComponentLPw(className, userId)) { 17961 return; 17962 } 17963 break; 17964 case COMPONENT_ENABLED_STATE_DEFAULT: 17965 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17966 return; 17967 } 17968 break; 17969 default: 17970 Slog.e(TAG, "Invalid new component state: " + newState); 17971 return; 17972 } 17973 } 17974 scheduleWritePackageRestrictionsLocked(userId); 17975 components = mPendingBroadcasts.get(userId, packageName); 17976 final boolean newPackage = components == null; 17977 if (newPackage) { 17978 components = new ArrayList<String>(); 17979 } 17980 if (!components.contains(componentName)) { 17981 components.add(componentName); 17982 } 17983 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17984 sendNow = true; 17985 // Purge entry from pending broadcast list if another one exists already 17986 // since we are sending one right away. 17987 mPendingBroadcasts.remove(userId, packageName); 17988 } else { 17989 if (newPackage) { 17990 mPendingBroadcasts.put(userId, packageName, components); 17991 } 17992 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17993 // Schedule a message 17994 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17995 } 17996 } 17997 } 17998 17999 long callingId = Binder.clearCallingIdentity(); 18000 try { 18001 if (sendNow) { 18002 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18003 sendPackageChangedBroadcast(packageName, 18004 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18005 } 18006 } finally { 18007 Binder.restoreCallingIdentity(callingId); 18008 } 18009 } 18010 18011 @Override 18012 public void flushPackageRestrictionsAsUser(int userId) { 18013 if (!sUserManager.exists(userId)) { 18014 return; 18015 } 18016 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18017 false /* checkShell */, "flushPackageRestrictions"); 18018 synchronized (mPackages) { 18019 mSettings.writePackageRestrictionsLPr(userId); 18020 mDirtyUsers.remove(userId); 18021 if (mDirtyUsers.isEmpty()) { 18022 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18023 } 18024 } 18025 } 18026 18027 private void sendPackageChangedBroadcast(String packageName, 18028 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18029 if (DEBUG_INSTALL) 18030 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18031 + componentNames); 18032 Bundle extras = new Bundle(4); 18033 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18034 String nameList[] = new String[componentNames.size()]; 18035 componentNames.toArray(nameList); 18036 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18037 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18038 extras.putInt(Intent.EXTRA_UID, packageUid); 18039 // If this is not reporting a change of the overall package, then only send it 18040 // to registered receivers. We don't want to launch a swath of apps for every 18041 // little component state change. 18042 final int flags = !componentNames.contains(packageName) 18043 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18044 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18045 new int[] {UserHandle.getUserId(packageUid)}); 18046 } 18047 18048 @Override 18049 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18050 if (!sUserManager.exists(userId)) return; 18051 final int uid = Binder.getCallingUid(); 18052 final int permission = mContext.checkCallingOrSelfPermission( 18053 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18054 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18055 enforceCrossUserPermission(uid, userId, 18056 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18057 // writer 18058 synchronized (mPackages) { 18059 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18060 allowedByPermission, uid, userId)) { 18061 scheduleWritePackageRestrictionsLocked(userId); 18062 } 18063 } 18064 } 18065 18066 @Override 18067 public String getInstallerPackageName(String packageName) { 18068 // reader 18069 synchronized (mPackages) { 18070 return mSettings.getInstallerPackageNameLPr(packageName); 18071 } 18072 } 18073 18074 public boolean isOrphaned(String packageName) { 18075 // reader 18076 synchronized (mPackages) { 18077 return mSettings.isOrphaned(packageName); 18078 } 18079 } 18080 18081 @Override 18082 public int getApplicationEnabledSetting(String packageName, int userId) { 18083 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18084 int uid = Binder.getCallingUid(); 18085 enforceCrossUserPermission(uid, userId, 18086 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18087 // reader 18088 synchronized (mPackages) { 18089 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18090 } 18091 } 18092 18093 @Override 18094 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18095 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18096 int uid = Binder.getCallingUid(); 18097 enforceCrossUserPermission(uid, userId, 18098 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18099 // reader 18100 synchronized (mPackages) { 18101 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18102 } 18103 } 18104 18105 @Override 18106 public void enterSafeMode() { 18107 enforceSystemOrRoot("Only the system can request entering safe mode"); 18108 18109 if (!mSystemReady) { 18110 mSafeMode = true; 18111 } 18112 } 18113 18114 @Override 18115 public void systemReady() { 18116 mSystemReady = true; 18117 18118 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18119 // disabled after already being started. 18120 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18121 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18122 18123 // Read the compatibilty setting when the system is ready. 18124 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18125 mContext.getContentResolver(), 18126 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18127 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18128 if (DEBUG_SETTINGS) { 18129 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18130 } 18131 18132 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18133 18134 synchronized (mPackages) { 18135 // Verify that all of the preferred activity components actually 18136 // exist. It is possible for applications to be updated and at 18137 // that point remove a previously declared activity component that 18138 // had been set as a preferred activity. We try to clean this up 18139 // the next time we encounter that preferred activity, but it is 18140 // possible for the user flow to never be able to return to that 18141 // situation so here we do a sanity check to make sure we haven't 18142 // left any junk around. 18143 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18144 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18145 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18146 removed.clear(); 18147 for (PreferredActivity pa : pir.filterSet()) { 18148 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18149 removed.add(pa); 18150 } 18151 } 18152 if (removed.size() > 0) { 18153 for (int r=0; r<removed.size(); r++) { 18154 PreferredActivity pa = removed.get(r); 18155 Slog.w(TAG, "Removing dangling preferred activity: " 18156 + pa.mPref.mComponent); 18157 pir.removeFilter(pa); 18158 } 18159 mSettings.writePackageRestrictionsLPr( 18160 mSettings.mPreferredActivities.keyAt(i)); 18161 } 18162 } 18163 18164 for (int userId : UserManagerService.getInstance().getUserIds()) { 18165 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18166 grantPermissionsUserIds = ArrayUtils.appendInt( 18167 grantPermissionsUserIds, userId); 18168 } 18169 } 18170 } 18171 sUserManager.systemReady(); 18172 18173 // If we upgraded grant all default permissions before kicking off. 18174 for (int userId : grantPermissionsUserIds) { 18175 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18176 } 18177 18178 // If we did not grant default permissions, we preload from this the 18179 // default permission exceptions lazily to ensure we don't hit the 18180 // disk on a new user creation. 18181 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18182 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18183 } 18184 18185 // Kick off any messages waiting for system ready 18186 if (mPostSystemReadyMessages != null) { 18187 for (Message msg : mPostSystemReadyMessages) { 18188 msg.sendToTarget(); 18189 } 18190 mPostSystemReadyMessages = null; 18191 } 18192 18193 // Watch for external volumes that come and go over time 18194 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18195 storage.registerListener(mStorageListener); 18196 18197 mInstallerService.systemReady(); 18198 mPackageDexOptimizer.systemReady(); 18199 18200 MountServiceInternal mountServiceInternal = LocalServices.getService( 18201 MountServiceInternal.class); 18202 mountServiceInternal.addExternalStoragePolicy( 18203 new MountServiceInternal.ExternalStorageMountPolicy() { 18204 @Override 18205 public int getMountMode(int uid, String packageName) { 18206 if (Process.isIsolated(uid)) { 18207 return Zygote.MOUNT_EXTERNAL_NONE; 18208 } 18209 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18210 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18211 } 18212 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18213 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18214 } 18215 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18216 return Zygote.MOUNT_EXTERNAL_READ; 18217 } 18218 return Zygote.MOUNT_EXTERNAL_WRITE; 18219 } 18220 18221 @Override 18222 public boolean hasExternalStorage(int uid, String packageName) { 18223 return true; 18224 } 18225 }); 18226 18227 // Now that we're mostly running, clean up stale users and apps 18228 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18229 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18230 } 18231 18232 @Override 18233 public boolean isSafeMode() { 18234 return mSafeMode; 18235 } 18236 18237 @Override 18238 public boolean hasSystemUidErrors() { 18239 return mHasSystemUidErrors; 18240 } 18241 18242 static String arrayToString(int[] array) { 18243 StringBuffer buf = new StringBuffer(128); 18244 buf.append('['); 18245 if (array != null) { 18246 for (int i=0; i<array.length; i++) { 18247 if (i > 0) buf.append(", "); 18248 buf.append(array[i]); 18249 } 18250 } 18251 buf.append(']'); 18252 return buf.toString(); 18253 } 18254 18255 static class DumpState { 18256 public static final int DUMP_LIBS = 1 << 0; 18257 public static final int DUMP_FEATURES = 1 << 1; 18258 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18259 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18260 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18261 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18262 public static final int DUMP_PERMISSIONS = 1 << 6; 18263 public static final int DUMP_PACKAGES = 1 << 7; 18264 public static final int DUMP_SHARED_USERS = 1 << 8; 18265 public static final int DUMP_MESSAGES = 1 << 9; 18266 public static final int DUMP_PROVIDERS = 1 << 10; 18267 public static final int DUMP_VERIFIERS = 1 << 11; 18268 public static final int DUMP_PREFERRED = 1 << 12; 18269 public static final int DUMP_PREFERRED_XML = 1 << 13; 18270 public static final int DUMP_KEYSETS = 1 << 14; 18271 public static final int DUMP_VERSION = 1 << 15; 18272 public static final int DUMP_INSTALLS = 1 << 16; 18273 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18274 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18275 public static final int DUMP_FROZEN = 1 << 19; 18276 public static final int DUMP_DEXOPT = 1 << 20; 18277 public static final int DUMP_COMPILER_STATS = 1 << 21; 18278 18279 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18280 18281 private int mTypes; 18282 18283 private int mOptions; 18284 18285 private boolean mTitlePrinted; 18286 18287 private SharedUserSetting mSharedUser; 18288 18289 public boolean isDumping(int type) { 18290 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18291 return true; 18292 } 18293 18294 return (mTypes & type) != 0; 18295 } 18296 18297 public void setDump(int type) { 18298 mTypes |= type; 18299 } 18300 18301 public boolean isOptionEnabled(int option) { 18302 return (mOptions & option) != 0; 18303 } 18304 18305 public void setOptionEnabled(int option) { 18306 mOptions |= option; 18307 } 18308 18309 public boolean onTitlePrinted() { 18310 final boolean printed = mTitlePrinted; 18311 mTitlePrinted = true; 18312 return printed; 18313 } 18314 18315 public boolean getTitlePrinted() { 18316 return mTitlePrinted; 18317 } 18318 18319 public void setTitlePrinted(boolean enabled) { 18320 mTitlePrinted = enabled; 18321 } 18322 18323 public SharedUserSetting getSharedUser() { 18324 return mSharedUser; 18325 } 18326 18327 public void setSharedUser(SharedUserSetting user) { 18328 mSharedUser = user; 18329 } 18330 } 18331 18332 @Override 18333 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18334 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18335 (new PackageManagerShellCommand(this)).exec( 18336 this, in, out, err, args, resultReceiver); 18337 } 18338 18339 @Override 18340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18341 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18342 != PackageManager.PERMISSION_GRANTED) { 18343 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18344 + Binder.getCallingPid() 18345 + ", uid=" + Binder.getCallingUid() 18346 + " without permission " 18347 + android.Manifest.permission.DUMP); 18348 return; 18349 } 18350 18351 DumpState dumpState = new DumpState(); 18352 boolean fullPreferred = false; 18353 boolean checkin = false; 18354 18355 String packageName = null; 18356 ArraySet<String> permissionNames = null; 18357 18358 int opti = 0; 18359 while (opti < args.length) { 18360 String opt = args[opti]; 18361 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18362 break; 18363 } 18364 opti++; 18365 18366 if ("-a".equals(opt)) { 18367 // Right now we only know how to print all. 18368 } else if ("-h".equals(opt)) { 18369 pw.println("Package manager dump options:"); 18370 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18371 pw.println(" --checkin: dump for a checkin"); 18372 pw.println(" -f: print details of intent filters"); 18373 pw.println(" -h: print this help"); 18374 pw.println(" cmd may be one of:"); 18375 pw.println(" l[ibraries]: list known shared libraries"); 18376 pw.println(" f[eatures]: list device features"); 18377 pw.println(" k[eysets]: print known keysets"); 18378 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18379 pw.println(" perm[issions]: dump permissions"); 18380 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18381 pw.println(" pref[erred]: print preferred package settings"); 18382 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18383 pw.println(" prov[iders]: dump content providers"); 18384 pw.println(" p[ackages]: dump installed packages"); 18385 pw.println(" s[hared-users]: dump shared user IDs"); 18386 pw.println(" m[essages]: print collected runtime messages"); 18387 pw.println(" v[erifiers]: print package verifier info"); 18388 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18389 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18390 pw.println(" version: print database version info"); 18391 pw.println(" write: write current settings now"); 18392 pw.println(" installs: details about install sessions"); 18393 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18394 pw.println(" dexopt: dump dexopt state"); 18395 pw.println(" compiler-stats: dump compiler statistics"); 18396 pw.println(" <package.name>: info about given package"); 18397 return; 18398 } else if ("--checkin".equals(opt)) { 18399 checkin = true; 18400 } else if ("-f".equals(opt)) { 18401 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18402 } else { 18403 pw.println("Unknown argument: " + opt + "; use -h for help"); 18404 } 18405 } 18406 18407 // Is the caller requesting to dump a particular piece of data? 18408 if (opti < args.length) { 18409 String cmd = args[opti]; 18410 opti++; 18411 // Is this a package name? 18412 if ("android".equals(cmd) || cmd.contains(".")) { 18413 packageName = cmd; 18414 // When dumping a single package, we always dump all of its 18415 // filter information since the amount of data will be reasonable. 18416 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18417 } else if ("check-permission".equals(cmd)) { 18418 if (opti >= args.length) { 18419 pw.println("Error: check-permission missing permission argument"); 18420 return; 18421 } 18422 String perm = args[opti]; 18423 opti++; 18424 if (opti >= args.length) { 18425 pw.println("Error: check-permission missing package argument"); 18426 return; 18427 } 18428 String pkg = args[opti]; 18429 opti++; 18430 int user = UserHandle.getUserId(Binder.getCallingUid()); 18431 if (opti < args.length) { 18432 try { 18433 user = Integer.parseInt(args[opti]); 18434 } catch (NumberFormatException e) { 18435 pw.println("Error: check-permission user argument is not a number: " 18436 + args[opti]); 18437 return; 18438 } 18439 } 18440 pw.println(checkPermission(perm, pkg, user)); 18441 return; 18442 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18443 dumpState.setDump(DumpState.DUMP_LIBS); 18444 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18445 dumpState.setDump(DumpState.DUMP_FEATURES); 18446 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18447 if (opti >= args.length) { 18448 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18449 | DumpState.DUMP_SERVICE_RESOLVERS 18450 | DumpState.DUMP_RECEIVER_RESOLVERS 18451 | DumpState.DUMP_CONTENT_RESOLVERS); 18452 } else { 18453 while (opti < args.length) { 18454 String name = args[opti]; 18455 if ("a".equals(name) || "activity".equals(name)) { 18456 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18457 } else if ("s".equals(name) || "service".equals(name)) { 18458 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18459 } else if ("r".equals(name) || "receiver".equals(name)) { 18460 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18461 } else if ("c".equals(name) || "content".equals(name)) { 18462 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18463 } else { 18464 pw.println("Error: unknown resolver table type: " + name); 18465 return; 18466 } 18467 opti++; 18468 } 18469 } 18470 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18471 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18472 } else if ("permission".equals(cmd)) { 18473 if (opti >= args.length) { 18474 pw.println("Error: permission requires permission name"); 18475 return; 18476 } 18477 permissionNames = new ArraySet<>(); 18478 while (opti < args.length) { 18479 permissionNames.add(args[opti]); 18480 opti++; 18481 } 18482 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18483 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18484 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18485 dumpState.setDump(DumpState.DUMP_PREFERRED); 18486 } else if ("preferred-xml".equals(cmd)) { 18487 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18488 if (opti < args.length && "--full".equals(args[opti])) { 18489 fullPreferred = true; 18490 opti++; 18491 } 18492 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18493 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18494 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18495 dumpState.setDump(DumpState.DUMP_PACKAGES); 18496 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18497 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18498 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18499 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18500 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18501 dumpState.setDump(DumpState.DUMP_MESSAGES); 18502 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18503 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18504 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18505 || "intent-filter-verifiers".equals(cmd)) { 18506 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18507 } else if ("version".equals(cmd)) { 18508 dumpState.setDump(DumpState.DUMP_VERSION); 18509 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18510 dumpState.setDump(DumpState.DUMP_KEYSETS); 18511 } else if ("installs".equals(cmd)) { 18512 dumpState.setDump(DumpState.DUMP_INSTALLS); 18513 } else if ("frozen".equals(cmd)) { 18514 dumpState.setDump(DumpState.DUMP_FROZEN); 18515 } else if ("dexopt".equals(cmd)) { 18516 dumpState.setDump(DumpState.DUMP_DEXOPT); 18517 } else if ("compiler-stats".equals(cmd)) { 18518 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18519 } else if ("write".equals(cmd)) { 18520 synchronized (mPackages) { 18521 mSettings.writeLPr(); 18522 pw.println("Settings written."); 18523 return; 18524 } 18525 } 18526 } 18527 18528 if (checkin) { 18529 pw.println("vers,1"); 18530 } 18531 18532 // reader 18533 synchronized (mPackages) { 18534 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18535 if (!checkin) { 18536 if (dumpState.onTitlePrinted()) 18537 pw.println(); 18538 pw.println("Database versions:"); 18539 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18540 } 18541 } 18542 18543 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18544 if (!checkin) { 18545 if (dumpState.onTitlePrinted()) 18546 pw.println(); 18547 pw.println("Verifiers:"); 18548 pw.print(" Required: "); 18549 pw.print(mRequiredVerifierPackage); 18550 pw.print(" (uid="); 18551 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18552 UserHandle.USER_SYSTEM)); 18553 pw.println(")"); 18554 } else if (mRequiredVerifierPackage != null) { 18555 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18556 pw.print(","); 18557 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18558 UserHandle.USER_SYSTEM)); 18559 } 18560 } 18561 18562 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18563 packageName == null) { 18564 if (mIntentFilterVerifierComponent != null) { 18565 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18566 if (!checkin) { 18567 if (dumpState.onTitlePrinted()) 18568 pw.println(); 18569 pw.println("Intent Filter Verifier:"); 18570 pw.print(" Using: "); 18571 pw.print(verifierPackageName); 18572 pw.print(" (uid="); 18573 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18574 UserHandle.USER_SYSTEM)); 18575 pw.println(")"); 18576 } else if (verifierPackageName != null) { 18577 pw.print("ifv,"); pw.print(verifierPackageName); 18578 pw.print(","); 18579 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18580 UserHandle.USER_SYSTEM)); 18581 } 18582 } else { 18583 pw.println(); 18584 pw.println("No Intent Filter Verifier available!"); 18585 } 18586 } 18587 18588 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18589 boolean printedHeader = false; 18590 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18591 while (it.hasNext()) { 18592 String name = it.next(); 18593 SharedLibraryEntry ent = mSharedLibraries.get(name); 18594 if (!checkin) { 18595 if (!printedHeader) { 18596 if (dumpState.onTitlePrinted()) 18597 pw.println(); 18598 pw.println("Libraries:"); 18599 printedHeader = true; 18600 } 18601 pw.print(" "); 18602 } else { 18603 pw.print("lib,"); 18604 } 18605 pw.print(name); 18606 if (!checkin) { 18607 pw.print(" -> "); 18608 } 18609 if (ent.path != null) { 18610 if (!checkin) { 18611 pw.print("(jar) "); 18612 pw.print(ent.path); 18613 } else { 18614 pw.print(",jar,"); 18615 pw.print(ent.path); 18616 } 18617 } else { 18618 if (!checkin) { 18619 pw.print("(apk) "); 18620 pw.print(ent.apk); 18621 } else { 18622 pw.print(",apk,"); 18623 pw.print(ent.apk); 18624 } 18625 } 18626 pw.println(); 18627 } 18628 } 18629 18630 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18631 if (dumpState.onTitlePrinted()) 18632 pw.println(); 18633 if (!checkin) { 18634 pw.println("Features:"); 18635 } 18636 18637 for (FeatureInfo feat : mAvailableFeatures.values()) { 18638 if (checkin) { 18639 pw.print("feat,"); 18640 pw.print(feat.name); 18641 pw.print(","); 18642 pw.println(feat.version); 18643 } else { 18644 pw.print(" "); 18645 pw.print(feat.name); 18646 if (feat.version > 0) { 18647 pw.print(" version="); 18648 pw.print(feat.version); 18649 } 18650 pw.println(); 18651 } 18652 } 18653 } 18654 18655 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18656 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18657 : "Activity Resolver Table:", " ", packageName, 18658 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18659 dumpState.setTitlePrinted(true); 18660 } 18661 } 18662 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18663 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18664 : "Receiver Resolver Table:", " ", packageName, 18665 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18666 dumpState.setTitlePrinted(true); 18667 } 18668 } 18669 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18670 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18671 : "Service Resolver Table:", " ", packageName, 18672 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18673 dumpState.setTitlePrinted(true); 18674 } 18675 } 18676 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18677 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18678 : "Provider Resolver Table:", " ", packageName, 18679 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18680 dumpState.setTitlePrinted(true); 18681 } 18682 } 18683 18684 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18685 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18686 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18687 int user = mSettings.mPreferredActivities.keyAt(i); 18688 if (pir.dump(pw, 18689 dumpState.getTitlePrinted() 18690 ? "\nPreferred Activities User " + user + ":" 18691 : "Preferred Activities User " + user + ":", " ", 18692 packageName, true, false)) { 18693 dumpState.setTitlePrinted(true); 18694 } 18695 } 18696 } 18697 18698 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18699 pw.flush(); 18700 FileOutputStream fout = new FileOutputStream(fd); 18701 BufferedOutputStream str = new BufferedOutputStream(fout); 18702 XmlSerializer serializer = new FastXmlSerializer(); 18703 try { 18704 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18705 serializer.startDocument(null, true); 18706 serializer.setFeature( 18707 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18708 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18709 serializer.endDocument(); 18710 serializer.flush(); 18711 } catch (IllegalArgumentException e) { 18712 pw.println("Failed writing: " + e); 18713 } catch (IllegalStateException e) { 18714 pw.println("Failed writing: " + e); 18715 } catch (IOException e) { 18716 pw.println("Failed writing: " + e); 18717 } 18718 } 18719 18720 if (!checkin 18721 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18722 && packageName == null) { 18723 pw.println(); 18724 int count = mSettings.mPackages.size(); 18725 if (count == 0) { 18726 pw.println("No applications!"); 18727 pw.println(); 18728 } else { 18729 final String prefix = " "; 18730 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18731 if (allPackageSettings.size() == 0) { 18732 pw.println("No domain preferred apps!"); 18733 pw.println(); 18734 } else { 18735 pw.println("App verification status:"); 18736 pw.println(); 18737 count = 0; 18738 for (PackageSetting ps : allPackageSettings) { 18739 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18740 if (ivi == null || ivi.getPackageName() == null) continue; 18741 pw.println(prefix + "Package: " + ivi.getPackageName()); 18742 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18743 pw.println(prefix + "Status: " + ivi.getStatusString()); 18744 pw.println(); 18745 count++; 18746 } 18747 if (count == 0) { 18748 pw.println(prefix + "No app verification established."); 18749 pw.println(); 18750 } 18751 for (int userId : sUserManager.getUserIds()) { 18752 pw.println("App linkages for user " + userId + ":"); 18753 pw.println(); 18754 count = 0; 18755 for (PackageSetting ps : allPackageSettings) { 18756 final long status = ps.getDomainVerificationStatusForUser(userId); 18757 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18758 continue; 18759 } 18760 pw.println(prefix + "Package: " + ps.name); 18761 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18762 String statusStr = IntentFilterVerificationInfo. 18763 getStatusStringFromValue(status); 18764 pw.println(prefix + "Status: " + statusStr); 18765 pw.println(); 18766 count++; 18767 } 18768 if (count == 0) { 18769 pw.println(prefix + "No configured app linkages."); 18770 pw.println(); 18771 } 18772 } 18773 } 18774 } 18775 } 18776 18777 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18778 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18779 if (packageName == null && permissionNames == null) { 18780 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18781 if (iperm == 0) { 18782 if (dumpState.onTitlePrinted()) 18783 pw.println(); 18784 pw.println("AppOp Permissions:"); 18785 } 18786 pw.print(" AppOp Permission "); 18787 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18788 pw.println(":"); 18789 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18790 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18791 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18792 } 18793 } 18794 } 18795 } 18796 18797 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18798 boolean printedSomething = false; 18799 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18800 if (packageName != null && !packageName.equals(p.info.packageName)) { 18801 continue; 18802 } 18803 if (!printedSomething) { 18804 if (dumpState.onTitlePrinted()) 18805 pw.println(); 18806 pw.println("Registered ContentProviders:"); 18807 printedSomething = true; 18808 } 18809 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18810 pw.print(" "); pw.println(p.toString()); 18811 } 18812 printedSomething = false; 18813 for (Map.Entry<String, PackageParser.Provider> entry : 18814 mProvidersByAuthority.entrySet()) { 18815 PackageParser.Provider p = entry.getValue(); 18816 if (packageName != null && !packageName.equals(p.info.packageName)) { 18817 continue; 18818 } 18819 if (!printedSomething) { 18820 if (dumpState.onTitlePrinted()) 18821 pw.println(); 18822 pw.println("ContentProvider Authorities:"); 18823 printedSomething = true; 18824 } 18825 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18826 pw.print(" "); pw.println(p.toString()); 18827 if (p.info != null && p.info.applicationInfo != null) { 18828 final String appInfo = p.info.applicationInfo.toString(); 18829 pw.print(" applicationInfo="); pw.println(appInfo); 18830 } 18831 } 18832 } 18833 18834 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18835 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18836 } 18837 18838 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18839 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18840 } 18841 18842 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18843 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18844 } 18845 18846 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18847 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18848 } 18849 18850 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18851 // XXX should handle packageName != null by dumping only install data that 18852 // the given package is involved with. 18853 if (dumpState.onTitlePrinted()) pw.println(); 18854 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18855 } 18856 18857 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18858 // XXX should handle packageName != null by dumping only install data that 18859 // the given package is involved with. 18860 if (dumpState.onTitlePrinted()) pw.println(); 18861 18862 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18863 ipw.println(); 18864 ipw.println("Frozen packages:"); 18865 ipw.increaseIndent(); 18866 if (mFrozenPackages.size() == 0) { 18867 ipw.println("(none)"); 18868 } else { 18869 for (int i = 0; i < mFrozenPackages.size(); i++) { 18870 ipw.println(mFrozenPackages.valueAt(i)); 18871 } 18872 } 18873 ipw.decreaseIndent(); 18874 } 18875 18876 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18877 if (dumpState.onTitlePrinted()) pw.println(); 18878 dumpDexoptStateLPr(pw, packageName); 18879 } 18880 18881 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18882 if (dumpState.onTitlePrinted()) pw.println(); 18883 dumpCompilerStatsLPr(pw, packageName); 18884 } 18885 18886 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18887 if (dumpState.onTitlePrinted()) pw.println(); 18888 mSettings.dumpReadMessagesLPr(pw, dumpState); 18889 18890 pw.println(); 18891 pw.println("Package warning messages:"); 18892 BufferedReader in = null; 18893 String line = null; 18894 try { 18895 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18896 while ((line = in.readLine()) != null) { 18897 if (line.contains("ignored: updated version")) continue; 18898 pw.println(line); 18899 } 18900 } catch (IOException ignored) { 18901 } finally { 18902 IoUtils.closeQuietly(in); 18903 } 18904 } 18905 18906 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18907 BufferedReader in = null; 18908 String line = null; 18909 try { 18910 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18911 while ((line = in.readLine()) != null) { 18912 if (line.contains("ignored: updated version")) continue; 18913 pw.print("msg,"); 18914 pw.println(line); 18915 } 18916 } catch (IOException ignored) { 18917 } finally { 18918 IoUtils.closeQuietly(in); 18919 } 18920 } 18921 } 18922 } 18923 18924 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18925 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18926 ipw.println(); 18927 ipw.println("Dexopt state:"); 18928 ipw.increaseIndent(); 18929 Collection<PackageParser.Package> packages = null; 18930 if (packageName != null) { 18931 PackageParser.Package targetPackage = mPackages.get(packageName); 18932 if (targetPackage != null) { 18933 packages = Collections.singletonList(targetPackage); 18934 } else { 18935 ipw.println("Unable to find package: " + packageName); 18936 return; 18937 } 18938 } else { 18939 packages = mPackages.values(); 18940 } 18941 18942 for (PackageParser.Package pkg : packages) { 18943 ipw.println("[" + pkg.packageName + "]"); 18944 ipw.increaseIndent(); 18945 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18946 ipw.decreaseIndent(); 18947 } 18948 } 18949 18950 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18951 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18952 ipw.println(); 18953 ipw.println("Compiler stats:"); 18954 ipw.increaseIndent(); 18955 Collection<PackageParser.Package> packages = null; 18956 if (packageName != null) { 18957 PackageParser.Package targetPackage = mPackages.get(packageName); 18958 if (targetPackage != null) { 18959 packages = Collections.singletonList(targetPackage); 18960 } else { 18961 ipw.println("Unable to find package: " + packageName); 18962 return; 18963 } 18964 } else { 18965 packages = mPackages.values(); 18966 } 18967 18968 for (PackageParser.Package pkg : packages) { 18969 ipw.println("[" + pkg.packageName + "]"); 18970 ipw.increaseIndent(); 18971 18972 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18973 if (stats == null) { 18974 ipw.println("(No recorded stats)"); 18975 } else { 18976 stats.dump(ipw); 18977 } 18978 ipw.decreaseIndent(); 18979 } 18980 } 18981 18982 private String dumpDomainString(String packageName) { 18983 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18984 .getList(); 18985 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18986 18987 ArraySet<String> result = new ArraySet<>(); 18988 if (iviList.size() > 0) { 18989 for (IntentFilterVerificationInfo ivi : iviList) { 18990 for (String host : ivi.getDomains()) { 18991 result.add(host); 18992 } 18993 } 18994 } 18995 if (filters != null && filters.size() > 0) { 18996 for (IntentFilter filter : filters) { 18997 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18998 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18999 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19000 result.addAll(filter.getHostsList()); 19001 } 19002 } 19003 } 19004 19005 StringBuilder sb = new StringBuilder(result.size() * 16); 19006 for (String domain : result) { 19007 if (sb.length() > 0) sb.append(" "); 19008 sb.append(domain); 19009 } 19010 return sb.toString(); 19011 } 19012 19013 // ------- apps on sdcard specific code ------- 19014 static final boolean DEBUG_SD_INSTALL = false; 19015 19016 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19017 19018 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19019 19020 private boolean mMediaMounted = false; 19021 19022 static String getEncryptKey() { 19023 try { 19024 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19025 SD_ENCRYPTION_KEYSTORE_NAME); 19026 if (sdEncKey == null) { 19027 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19028 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19029 if (sdEncKey == null) { 19030 Slog.e(TAG, "Failed to create encryption keys"); 19031 return null; 19032 } 19033 } 19034 return sdEncKey; 19035 } catch (NoSuchAlgorithmException nsae) { 19036 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19037 return null; 19038 } catch (IOException ioe) { 19039 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19040 return null; 19041 } 19042 } 19043 19044 /* 19045 * Update media status on PackageManager. 19046 */ 19047 @Override 19048 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19049 int callingUid = Binder.getCallingUid(); 19050 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19051 throw new SecurityException("Media status can only be updated by the system"); 19052 } 19053 // reader; this apparently protects mMediaMounted, but should probably 19054 // be a different lock in that case. 19055 synchronized (mPackages) { 19056 Log.i(TAG, "Updating external media status from " 19057 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19058 + (mediaStatus ? "mounted" : "unmounted")); 19059 if (DEBUG_SD_INSTALL) 19060 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19061 + ", mMediaMounted=" + mMediaMounted); 19062 if (mediaStatus == mMediaMounted) { 19063 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19064 : 0, -1); 19065 mHandler.sendMessage(msg); 19066 return; 19067 } 19068 mMediaMounted = mediaStatus; 19069 } 19070 // Queue up an async operation since the package installation may take a 19071 // little while. 19072 mHandler.post(new Runnable() { 19073 public void run() { 19074 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19075 } 19076 }); 19077 } 19078 19079 /** 19080 * Called by MountService when the initial ASECs to scan are available. 19081 * Should block until all the ASEC containers are finished being scanned. 19082 */ 19083 public void scanAvailableAsecs() { 19084 updateExternalMediaStatusInner(true, false, false); 19085 } 19086 19087 /* 19088 * Collect information of applications on external media, map them against 19089 * existing containers and update information based on current mount status. 19090 * Please note that we always have to report status if reportStatus has been 19091 * set to true especially when unloading packages. 19092 */ 19093 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19094 boolean externalStorage) { 19095 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19096 int[] uidArr = EmptyArray.INT; 19097 19098 final String[] list = PackageHelper.getSecureContainerList(); 19099 if (ArrayUtils.isEmpty(list)) { 19100 Log.i(TAG, "No secure containers found"); 19101 } else { 19102 // Process list of secure containers and categorize them 19103 // as active or stale based on their package internal state. 19104 19105 // reader 19106 synchronized (mPackages) { 19107 for (String cid : list) { 19108 // Leave stages untouched for now; installer service owns them 19109 if (PackageInstallerService.isStageName(cid)) continue; 19110 19111 if (DEBUG_SD_INSTALL) 19112 Log.i(TAG, "Processing container " + cid); 19113 String pkgName = getAsecPackageName(cid); 19114 if (pkgName == null) { 19115 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19116 continue; 19117 } 19118 if (DEBUG_SD_INSTALL) 19119 Log.i(TAG, "Looking for pkg : " + pkgName); 19120 19121 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19122 if (ps == null) { 19123 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19124 continue; 19125 } 19126 19127 /* 19128 * Skip packages that are not external if we're unmounting 19129 * external storage. 19130 */ 19131 if (externalStorage && !isMounted && !isExternal(ps)) { 19132 continue; 19133 } 19134 19135 final AsecInstallArgs args = new AsecInstallArgs(cid, 19136 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19137 // The package status is changed only if the code path 19138 // matches between settings and the container id. 19139 if (ps.codePathString != null 19140 && ps.codePathString.startsWith(args.getCodePath())) { 19141 if (DEBUG_SD_INSTALL) { 19142 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19143 + " at code path: " + ps.codePathString); 19144 } 19145 19146 // We do have a valid package installed on sdcard 19147 processCids.put(args, ps.codePathString); 19148 final int uid = ps.appId; 19149 if (uid != -1) { 19150 uidArr = ArrayUtils.appendInt(uidArr, uid); 19151 } 19152 } else { 19153 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19154 + ps.codePathString); 19155 } 19156 } 19157 } 19158 19159 Arrays.sort(uidArr); 19160 } 19161 19162 // Process packages with valid entries. 19163 if (isMounted) { 19164 if (DEBUG_SD_INSTALL) 19165 Log.i(TAG, "Loading packages"); 19166 loadMediaPackages(processCids, uidArr, externalStorage); 19167 startCleaningPackages(); 19168 mInstallerService.onSecureContainersAvailable(); 19169 } else { 19170 if (DEBUG_SD_INSTALL) 19171 Log.i(TAG, "Unloading packages"); 19172 unloadMediaPackages(processCids, uidArr, reportStatus); 19173 } 19174 } 19175 19176 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19177 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19178 final int size = infos.size(); 19179 final String[] packageNames = new String[size]; 19180 final int[] packageUids = new int[size]; 19181 for (int i = 0; i < size; i++) { 19182 final ApplicationInfo info = infos.get(i); 19183 packageNames[i] = info.packageName; 19184 packageUids[i] = info.uid; 19185 } 19186 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19187 finishedReceiver); 19188 } 19189 19190 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19191 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19192 sendResourcesChangedBroadcast(mediaStatus, replacing, 19193 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19194 } 19195 19196 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19197 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19198 int size = pkgList.length; 19199 if (size > 0) { 19200 // Send broadcasts here 19201 Bundle extras = new Bundle(); 19202 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19203 if (uidArr != null) { 19204 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19205 } 19206 if (replacing) { 19207 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19208 } 19209 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19210 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19211 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19212 } 19213 } 19214 19215 /* 19216 * Look at potentially valid container ids from processCids If package 19217 * information doesn't match the one on record or package scanning fails, 19218 * the cid is added to list of removeCids. We currently don't delete stale 19219 * containers. 19220 */ 19221 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19222 boolean externalStorage) { 19223 ArrayList<String> pkgList = new ArrayList<String>(); 19224 Set<AsecInstallArgs> keys = processCids.keySet(); 19225 19226 for (AsecInstallArgs args : keys) { 19227 String codePath = processCids.get(args); 19228 if (DEBUG_SD_INSTALL) 19229 Log.i(TAG, "Loading container : " + args.cid); 19230 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19231 try { 19232 // Make sure there are no container errors first. 19233 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19234 Slog.e(TAG, "Failed to mount cid : " + args.cid 19235 + " when installing from sdcard"); 19236 continue; 19237 } 19238 // Check code path here. 19239 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19240 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19241 + " does not match one in settings " + codePath); 19242 continue; 19243 } 19244 // Parse package 19245 int parseFlags = mDefParseFlags; 19246 if (args.isExternalAsec()) { 19247 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19248 } 19249 if (args.isFwdLocked()) { 19250 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19251 } 19252 19253 synchronized (mInstallLock) { 19254 PackageParser.Package pkg = null; 19255 try { 19256 // Sadly we don't know the package name yet to freeze it 19257 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19258 SCAN_IGNORE_FROZEN, 0, null); 19259 } catch (PackageManagerException e) { 19260 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19261 } 19262 // Scan the package 19263 if (pkg != null) { 19264 /* 19265 * TODO why is the lock being held? doPostInstall is 19266 * called in other places without the lock. This needs 19267 * to be straightened out. 19268 */ 19269 // writer 19270 synchronized (mPackages) { 19271 retCode = PackageManager.INSTALL_SUCCEEDED; 19272 pkgList.add(pkg.packageName); 19273 // Post process args 19274 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19275 pkg.applicationInfo.uid); 19276 } 19277 } else { 19278 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19279 } 19280 } 19281 19282 } finally { 19283 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19284 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19285 } 19286 } 19287 } 19288 // writer 19289 synchronized (mPackages) { 19290 // If the platform SDK has changed since the last time we booted, 19291 // we need to re-grant app permission to catch any new ones that 19292 // appear. This is really a hack, and means that apps can in some 19293 // cases get permissions that the user didn't initially explicitly 19294 // allow... it would be nice to have some better way to handle 19295 // this situation. 19296 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19297 : mSettings.getInternalVersion(); 19298 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19299 : StorageManager.UUID_PRIVATE_INTERNAL; 19300 19301 int updateFlags = UPDATE_PERMISSIONS_ALL; 19302 if (ver.sdkVersion != mSdkVersion) { 19303 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19304 + mSdkVersion + "; regranting permissions for external"); 19305 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19306 } 19307 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19308 19309 // Yay, everything is now upgraded 19310 ver.forceCurrent(); 19311 19312 // can downgrade to reader 19313 // Persist settings 19314 mSettings.writeLPr(); 19315 } 19316 // Send a broadcast to let everyone know we are done processing 19317 if (pkgList.size() > 0) { 19318 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19319 } 19320 } 19321 19322 /* 19323 * Utility method to unload a list of specified containers 19324 */ 19325 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19326 // Just unmount all valid containers. 19327 for (AsecInstallArgs arg : cidArgs) { 19328 synchronized (mInstallLock) { 19329 arg.doPostDeleteLI(false); 19330 } 19331 } 19332 } 19333 19334 /* 19335 * Unload packages mounted on external media. This involves deleting package 19336 * data from internal structures, sending broadcasts about disabled packages, 19337 * gc'ing to free up references, unmounting all secure containers 19338 * corresponding to packages on external media, and posting a 19339 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19340 * that we always have to post this message if status has been requested no 19341 * matter what. 19342 */ 19343 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19344 final boolean reportStatus) { 19345 if (DEBUG_SD_INSTALL) 19346 Log.i(TAG, "unloading media packages"); 19347 ArrayList<String> pkgList = new ArrayList<String>(); 19348 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19349 final Set<AsecInstallArgs> keys = processCids.keySet(); 19350 for (AsecInstallArgs args : keys) { 19351 String pkgName = args.getPackageName(); 19352 if (DEBUG_SD_INSTALL) 19353 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19354 // Delete package internally 19355 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19356 synchronized (mInstallLock) { 19357 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19358 final boolean res; 19359 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19360 "unloadMediaPackages")) { 19361 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19362 null); 19363 } 19364 if (res) { 19365 pkgList.add(pkgName); 19366 } else { 19367 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19368 failedList.add(args); 19369 } 19370 } 19371 } 19372 19373 // reader 19374 synchronized (mPackages) { 19375 // We didn't update the settings after removing each package; 19376 // write them now for all packages. 19377 mSettings.writeLPr(); 19378 } 19379 19380 // We have to absolutely send UPDATED_MEDIA_STATUS only 19381 // after confirming that all the receivers processed the ordered 19382 // broadcast when packages get disabled, force a gc to clean things up. 19383 // and unload all the containers. 19384 if (pkgList.size() > 0) { 19385 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19386 new IIntentReceiver.Stub() { 19387 public void performReceive(Intent intent, int resultCode, String data, 19388 Bundle extras, boolean ordered, boolean sticky, 19389 int sendingUser) throws RemoteException { 19390 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19391 reportStatus ? 1 : 0, 1, keys); 19392 mHandler.sendMessage(msg); 19393 } 19394 }); 19395 } else { 19396 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19397 keys); 19398 mHandler.sendMessage(msg); 19399 } 19400 } 19401 19402 private void loadPrivatePackages(final VolumeInfo vol) { 19403 mHandler.post(new Runnable() { 19404 @Override 19405 public void run() { 19406 loadPrivatePackagesInner(vol); 19407 } 19408 }); 19409 } 19410 19411 private void loadPrivatePackagesInner(VolumeInfo vol) { 19412 final String volumeUuid = vol.fsUuid; 19413 if (TextUtils.isEmpty(volumeUuid)) { 19414 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19415 return; 19416 } 19417 19418 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19419 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19420 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19421 19422 final VersionInfo ver; 19423 final List<PackageSetting> packages; 19424 synchronized (mPackages) { 19425 ver = mSettings.findOrCreateVersion(volumeUuid); 19426 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19427 } 19428 19429 for (PackageSetting ps : packages) { 19430 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19431 synchronized (mInstallLock) { 19432 final PackageParser.Package pkg; 19433 try { 19434 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19435 loaded.add(pkg.applicationInfo); 19436 19437 } catch (PackageManagerException e) { 19438 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19439 } 19440 19441 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19442 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19443 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19444 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19445 } 19446 } 19447 } 19448 19449 // Reconcile app data for all started/unlocked users 19450 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19451 final UserManager um = mContext.getSystemService(UserManager.class); 19452 UserManagerInternal umInternal = getUserManagerInternal(); 19453 for (UserInfo user : um.getUsers()) { 19454 final int flags; 19455 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19456 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19457 } else if (umInternal.isUserRunning(user.id)) { 19458 flags = StorageManager.FLAG_STORAGE_DE; 19459 } else { 19460 continue; 19461 } 19462 19463 try { 19464 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19465 synchronized (mInstallLock) { 19466 reconcileAppsDataLI(volumeUuid, user.id, flags); 19467 } 19468 } catch (IllegalStateException e) { 19469 // Device was probably ejected, and we'll process that event momentarily 19470 Slog.w(TAG, "Failed to prepare storage: " + e); 19471 } 19472 } 19473 19474 synchronized (mPackages) { 19475 int updateFlags = UPDATE_PERMISSIONS_ALL; 19476 if (ver.sdkVersion != mSdkVersion) { 19477 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19478 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19479 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19480 } 19481 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19482 19483 // Yay, everything is now upgraded 19484 ver.forceCurrent(); 19485 19486 mSettings.writeLPr(); 19487 } 19488 19489 for (PackageFreezer freezer : freezers) { 19490 freezer.close(); 19491 } 19492 19493 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19494 sendResourcesChangedBroadcast(true, false, loaded, null); 19495 } 19496 19497 private void unloadPrivatePackages(final VolumeInfo vol) { 19498 mHandler.post(new Runnable() { 19499 @Override 19500 public void run() { 19501 unloadPrivatePackagesInner(vol); 19502 } 19503 }); 19504 } 19505 19506 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19507 final String volumeUuid = vol.fsUuid; 19508 if (TextUtils.isEmpty(volumeUuid)) { 19509 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19510 return; 19511 } 19512 19513 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19514 synchronized (mInstallLock) { 19515 synchronized (mPackages) { 19516 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19517 for (PackageSetting ps : packages) { 19518 if (ps.pkg == null) continue; 19519 19520 final ApplicationInfo info = ps.pkg.applicationInfo; 19521 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19522 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19523 19524 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19525 "unloadPrivatePackagesInner")) { 19526 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19527 false, null)) { 19528 unloaded.add(info); 19529 } else { 19530 Slog.w(TAG, "Failed to unload " + ps.codePath); 19531 } 19532 } 19533 19534 // Try very hard to release any references to this package 19535 // so we don't risk the system server being killed due to 19536 // open FDs 19537 AttributeCache.instance().removePackage(ps.name); 19538 } 19539 19540 mSettings.writeLPr(); 19541 } 19542 } 19543 19544 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19545 sendResourcesChangedBroadcast(false, false, unloaded, null); 19546 19547 // Try very hard to release any references to this path so we don't risk 19548 // the system server being killed due to open FDs 19549 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19550 19551 for (int i = 0; i < 3; i++) { 19552 System.gc(); 19553 System.runFinalization(); 19554 } 19555 } 19556 19557 /** 19558 * Prepare storage areas for given user on all mounted devices. 19559 */ 19560 void prepareUserData(int userId, int userSerial, int flags) { 19561 synchronized (mInstallLock) { 19562 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19563 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19564 final String volumeUuid = vol.getFsUuid(); 19565 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19566 } 19567 } 19568 } 19569 19570 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19571 boolean allowRecover) { 19572 // Prepare storage and verify that serial numbers are consistent; if 19573 // there's a mismatch we need to destroy to avoid leaking data 19574 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19575 try { 19576 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19577 19578 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19579 UserManagerService.enforceSerialNumber( 19580 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19581 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19582 UserManagerService.enforceSerialNumber( 19583 Environment.getDataSystemDeDirectory(userId), userSerial); 19584 } 19585 } 19586 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19587 UserManagerService.enforceSerialNumber( 19588 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19589 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19590 UserManagerService.enforceSerialNumber( 19591 Environment.getDataSystemCeDirectory(userId), userSerial); 19592 } 19593 } 19594 19595 synchronized (mInstallLock) { 19596 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19597 } 19598 } catch (Exception e) { 19599 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19600 + " because we failed to prepare: " + e); 19601 destroyUserDataLI(volumeUuid, userId, 19602 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19603 19604 if (allowRecover) { 19605 // Try one last time; if we fail again we're really in trouble 19606 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19607 } 19608 } 19609 } 19610 19611 /** 19612 * Destroy storage areas for given user on all mounted devices. 19613 */ 19614 void destroyUserData(int userId, int flags) { 19615 synchronized (mInstallLock) { 19616 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19617 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19618 final String volumeUuid = vol.getFsUuid(); 19619 destroyUserDataLI(volumeUuid, userId, flags); 19620 } 19621 } 19622 } 19623 19624 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19625 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19626 try { 19627 // Clean up app data, profile data, and media data 19628 mInstaller.destroyUserData(volumeUuid, userId, flags); 19629 19630 // Clean up system data 19631 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19632 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19633 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19634 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19635 } 19636 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19637 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19638 } 19639 } 19640 19641 // Data with special labels is now gone, so finish the job 19642 storage.destroyUserStorage(volumeUuid, userId, flags); 19643 19644 } catch (Exception e) { 19645 logCriticalInfo(Log.WARN, 19646 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19647 } 19648 } 19649 19650 /** 19651 * Examine all users present on given mounted volume, and destroy data 19652 * belonging to users that are no longer valid, or whose user ID has been 19653 * recycled. 19654 */ 19655 private void reconcileUsers(String volumeUuid) { 19656 final List<File> files = new ArrayList<>(); 19657 Collections.addAll(files, FileUtils 19658 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19659 Collections.addAll(files, FileUtils 19660 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19661 Collections.addAll(files, FileUtils 19662 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19663 Collections.addAll(files, FileUtils 19664 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19665 for (File file : files) { 19666 if (!file.isDirectory()) continue; 19667 19668 final int userId; 19669 final UserInfo info; 19670 try { 19671 userId = Integer.parseInt(file.getName()); 19672 info = sUserManager.getUserInfo(userId); 19673 } catch (NumberFormatException e) { 19674 Slog.w(TAG, "Invalid user directory " + file); 19675 continue; 19676 } 19677 19678 boolean destroyUser = false; 19679 if (info == null) { 19680 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19681 + " because no matching user was found"); 19682 destroyUser = true; 19683 } else if (!mOnlyCore) { 19684 try { 19685 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19686 } catch (IOException e) { 19687 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19688 + " because we failed to enforce serial number: " + e); 19689 destroyUser = true; 19690 } 19691 } 19692 19693 if (destroyUser) { 19694 synchronized (mInstallLock) { 19695 destroyUserDataLI(volumeUuid, userId, 19696 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19697 } 19698 } 19699 } 19700 } 19701 19702 private void assertPackageKnown(String volumeUuid, String packageName) 19703 throws PackageManagerException { 19704 synchronized (mPackages) { 19705 final PackageSetting ps = mSettings.mPackages.get(packageName); 19706 if (ps == null) { 19707 throw new PackageManagerException("Package " + packageName + " is unknown"); 19708 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19709 throw new PackageManagerException( 19710 "Package " + packageName + " found on unknown volume " + volumeUuid 19711 + "; expected volume " + ps.volumeUuid); 19712 } 19713 } 19714 } 19715 19716 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19717 throws PackageManagerException { 19718 synchronized (mPackages) { 19719 final PackageSetting ps = mSettings.mPackages.get(packageName); 19720 if (ps == null) { 19721 throw new PackageManagerException("Package " + packageName + " is unknown"); 19722 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19723 throw new PackageManagerException( 19724 "Package " + packageName + " found on unknown volume " + volumeUuid 19725 + "; expected volume " + ps.volumeUuid); 19726 } else if (!ps.getInstalled(userId)) { 19727 throw new PackageManagerException( 19728 "Package " + packageName + " not installed for user " + userId); 19729 } 19730 } 19731 } 19732 19733 /** 19734 * Examine all apps present on given mounted volume, and destroy apps that 19735 * aren't expected, either due to uninstallation or reinstallation on 19736 * another volume. 19737 */ 19738 private void reconcileApps(String volumeUuid) { 19739 final File[] files = FileUtils 19740 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19741 for (File file : files) { 19742 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19743 && !PackageInstallerService.isStageName(file.getName()); 19744 if (!isPackage) { 19745 // Ignore entries which are not packages 19746 continue; 19747 } 19748 19749 try { 19750 final PackageLite pkg = PackageParser.parsePackageLite(file, 19751 PackageParser.PARSE_MUST_BE_APK); 19752 assertPackageKnown(volumeUuid, pkg.packageName); 19753 19754 } catch (PackageParserException | PackageManagerException e) { 19755 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19756 synchronized (mInstallLock) { 19757 removeCodePathLI(file); 19758 } 19759 } 19760 } 19761 } 19762 19763 /** 19764 * Reconcile all app data for the given user. 19765 * <p> 19766 * Verifies that directories exist and that ownership and labeling is 19767 * correct for all installed apps on all mounted volumes. 19768 */ 19769 void reconcileAppsData(int userId, int flags) { 19770 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19771 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19772 final String volumeUuid = vol.getFsUuid(); 19773 synchronized (mInstallLock) { 19774 reconcileAppsDataLI(volumeUuid, userId, flags); 19775 } 19776 } 19777 } 19778 19779 /** 19780 * Reconcile all app data on given mounted volume. 19781 * <p> 19782 * Destroys app data that isn't expected, either due to uninstallation or 19783 * reinstallation on another volume. 19784 * <p> 19785 * Verifies that directories exist and that ownership and labeling is 19786 * correct for all installed apps. 19787 */ 19788 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19789 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19790 + Integer.toHexString(flags)); 19791 19792 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19793 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19794 19795 // First look for stale data that doesn't belong, and check if things 19796 // have changed since we did our last restorecon 19797 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19798 if (StorageManager.isFileEncryptedNativeOrEmulated() 19799 && !StorageManager.isUserKeyUnlocked(userId)) { 19800 throw new RuntimeException( 19801 "Yikes, someone asked us to reconcile CE storage while " + userId 19802 + " was still locked; this would have caused massive data loss!"); 19803 } 19804 19805 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19806 for (File file : files) { 19807 final String packageName = file.getName(); 19808 try { 19809 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19810 } catch (PackageManagerException e) { 19811 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19812 try { 19813 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19814 StorageManager.FLAG_STORAGE_CE, 0); 19815 } catch (InstallerException e2) { 19816 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19817 } 19818 } 19819 } 19820 } 19821 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19822 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19823 for (File file : files) { 19824 final String packageName = file.getName(); 19825 try { 19826 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19827 } catch (PackageManagerException e) { 19828 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19829 try { 19830 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19831 StorageManager.FLAG_STORAGE_DE, 0); 19832 } catch (InstallerException e2) { 19833 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19834 } 19835 } 19836 } 19837 } 19838 19839 // Ensure that data directories are ready to roll for all packages 19840 // installed for this volume and user 19841 final List<PackageSetting> packages; 19842 synchronized (mPackages) { 19843 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19844 } 19845 int preparedCount = 0; 19846 for (PackageSetting ps : packages) { 19847 final String packageName = ps.name; 19848 if (ps.pkg == null) { 19849 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19850 // TODO: might be due to legacy ASEC apps; we should circle back 19851 // and reconcile again once they're scanned 19852 continue; 19853 } 19854 19855 if (ps.getInstalled(userId)) { 19856 prepareAppDataLIF(ps.pkg, userId, flags); 19857 19858 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19859 // We may have just shuffled around app data directories, so 19860 // prepare them one more time 19861 prepareAppDataLIF(ps.pkg, userId, flags); 19862 } 19863 19864 preparedCount++; 19865 } 19866 } 19867 19868 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19869 } 19870 19871 /** 19872 * Prepare app data for the given app just after it was installed or 19873 * upgraded. This method carefully only touches users that it's installed 19874 * for, and it forces a restorecon to handle any seinfo changes. 19875 * <p> 19876 * Verifies that directories exist and that ownership and labeling is 19877 * correct for all installed apps. If there is an ownership mismatch, it 19878 * will try recovering system apps by wiping data; third-party app data is 19879 * left intact. 19880 * <p> 19881 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19882 */ 19883 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19884 final PackageSetting ps; 19885 synchronized (mPackages) { 19886 ps = mSettings.mPackages.get(pkg.packageName); 19887 mSettings.writeKernelMappingLPr(ps); 19888 } 19889 19890 final UserManager um = mContext.getSystemService(UserManager.class); 19891 UserManagerInternal umInternal = getUserManagerInternal(); 19892 for (UserInfo user : um.getUsers()) { 19893 final int flags; 19894 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19895 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19896 } else if (umInternal.isUserRunning(user.id)) { 19897 flags = StorageManager.FLAG_STORAGE_DE; 19898 } else { 19899 continue; 19900 } 19901 19902 if (ps.getInstalled(user.id)) { 19903 // TODO: when user data is locked, mark that we're still dirty 19904 prepareAppDataLIF(pkg, user.id, flags); 19905 } 19906 } 19907 } 19908 19909 /** 19910 * Prepare app data for the given app. 19911 * <p> 19912 * Verifies that directories exist and that ownership and labeling is 19913 * correct for all installed apps. If there is an ownership mismatch, this 19914 * will try recovering system apps by wiping data; third-party app data is 19915 * left intact. 19916 */ 19917 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 19918 if (pkg == null) { 19919 Slog.wtf(TAG, "Package was null!", new Throwable()); 19920 return; 19921 } 19922 prepareAppDataLeafLIF(pkg, userId, flags); 19923 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19924 for (int i = 0; i < childCount; i++) { 19925 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 19926 } 19927 } 19928 19929 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19930 if (DEBUG_APP_DATA) { 19931 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19932 + Integer.toHexString(flags)); 19933 } 19934 19935 final String volumeUuid = pkg.volumeUuid; 19936 final String packageName = pkg.packageName; 19937 final ApplicationInfo app = pkg.applicationInfo; 19938 final int appId = UserHandle.getAppId(app.uid); 19939 19940 Preconditions.checkNotNull(app.seinfo); 19941 19942 try { 19943 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19944 appId, app.seinfo, app.targetSdkVersion); 19945 } catch (InstallerException e) { 19946 if (app.isSystemApp()) { 19947 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19948 + ", but trying to recover: " + e); 19949 destroyAppDataLeafLIF(pkg, userId, flags); 19950 try { 19951 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19952 appId, app.seinfo, app.targetSdkVersion); 19953 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19954 } catch (InstallerException e2) { 19955 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19956 } 19957 } else { 19958 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19959 } 19960 } 19961 19962 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19963 try { 19964 // CE storage is unlocked right now, so read out the inode and 19965 // remember for use later when it's locked 19966 // TODO: mark this structure as dirty so we persist it! 19967 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19968 StorageManager.FLAG_STORAGE_CE); 19969 synchronized (mPackages) { 19970 final PackageSetting ps = mSettings.mPackages.get(packageName); 19971 if (ps != null) { 19972 ps.setCeDataInode(ceDataInode, userId); 19973 } 19974 } 19975 } catch (InstallerException e) { 19976 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19977 } 19978 } 19979 19980 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19981 } 19982 19983 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19984 if (pkg == null) { 19985 Slog.wtf(TAG, "Package was null!", new Throwable()); 19986 return; 19987 } 19988 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19989 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19990 for (int i = 0; i < childCount; i++) { 19991 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19992 } 19993 } 19994 19995 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19996 final String volumeUuid = pkg.volumeUuid; 19997 final String packageName = pkg.packageName; 19998 final ApplicationInfo app = pkg.applicationInfo; 19999 20000 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20001 // Create a native library symlink only if we have native libraries 20002 // and if the native libraries are 32 bit libraries. We do not provide 20003 // this symlink for 64 bit libraries. 20004 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20005 final String nativeLibPath = app.nativeLibraryDir; 20006 try { 20007 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20008 nativeLibPath, userId); 20009 } catch (InstallerException e) { 20010 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20011 } 20012 } 20013 } 20014 } 20015 20016 /** 20017 * For system apps on non-FBE devices, this method migrates any existing 20018 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20019 * requested by the app. 20020 */ 20021 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20022 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20023 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20024 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20025 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20026 try { 20027 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20028 storageTarget); 20029 } catch (InstallerException e) { 20030 logCriticalInfo(Log.WARN, 20031 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20032 } 20033 return true; 20034 } else { 20035 return false; 20036 } 20037 } 20038 20039 public PackageFreezer freezePackage(String packageName, String killReason) { 20040 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20041 } 20042 20043 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20044 return new PackageFreezer(packageName, userId, killReason); 20045 } 20046 20047 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20048 String killReason) { 20049 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20050 } 20051 20052 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20053 String killReason) { 20054 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20055 return new PackageFreezer(); 20056 } else { 20057 return freezePackage(packageName, userId, killReason); 20058 } 20059 } 20060 20061 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20062 String killReason) { 20063 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20064 } 20065 20066 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20067 String killReason) { 20068 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20069 return new PackageFreezer(); 20070 } else { 20071 return freezePackage(packageName, userId, killReason); 20072 } 20073 } 20074 20075 /** 20076 * Class that freezes and kills the given package upon creation, and 20077 * unfreezes it upon closing. This is typically used when doing surgery on 20078 * app code/data to prevent the app from running while you're working. 20079 */ 20080 private class PackageFreezer implements AutoCloseable { 20081 private final String mPackageName; 20082 private final PackageFreezer[] mChildren; 20083 20084 private final boolean mWeFroze; 20085 20086 private final AtomicBoolean mClosed = new AtomicBoolean(); 20087 private final CloseGuard mCloseGuard = CloseGuard.get(); 20088 20089 /** 20090 * Create and return a stub freezer that doesn't actually do anything, 20091 * typically used when someone requested 20092 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20093 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20094 */ 20095 public PackageFreezer() { 20096 mPackageName = null; 20097 mChildren = null; 20098 mWeFroze = false; 20099 mCloseGuard.open("close"); 20100 } 20101 20102 public PackageFreezer(String packageName, int userId, String killReason) { 20103 synchronized (mPackages) { 20104 mPackageName = packageName; 20105 mWeFroze = mFrozenPackages.add(mPackageName); 20106 20107 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20108 if (ps != null) { 20109 killApplication(ps.name, ps.appId, userId, killReason); 20110 } 20111 20112 final PackageParser.Package p = mPackages.get(packageName); 20113 if (p != null && p.childPackages != null) { 20114 final int N = p.childPackages.size(); 20115 mChildren = new PackageFreezer[N]; 20116 for (int i = 0; i < N; i++) { 20117 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20118 userId, killReason); 20119 } 20120 } else { 20121 mChildren = null; 20122 } 20123 } 20124 mCloseGuard.open("close"); 20125 } 20126 20127 @Override 20128 protected void finalize() throws Throwable { 20129 try { 20130 mCloseGuard.warnIfOpen(); 20131 close(); 20132 } finally { 20133 super.finalize(); 20134 } 20135 } 20136 20137 @Override 20138 public void close() { 20139 mCloseGuard.close(); 20140 if (mClosed.compareAndSet(false, true)) { 20141 synchronized (mPackages) { 20142 if (mWeFroze) { 20143 mFrozenPackages.remove(mPackageName); 20144 } 20145 20146 if (mChildren != null) { 20147 for (PackageFreezer freezer : mChildren) { 20148 freezer.close(); 20149 } 20150 } 20151 } 20152 } 20153 } 20154 } 20155 20156 /** 20157 * Verify that given package is currently frozen. 20158 */ 20159 private void checkPackageFrozen(String packageName) { 20160 synchronized (mPackages) { 20161 if (!mFrozenPackages.contains(packageName)) { 20162 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20163 } 20164 } 20165 } 20166 20167 @Override 20168 public int movePackage(final String packageName, final String volumeUuid) { 20169 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20170 20171 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20172 final int moveId = mNextMoveId.getAndIncrement(); 20173 mHandler.post(new Runnable() { 20174 @Override 20175 public void run() { 20176 try { 20177 movePackageInternal(packageName, volumeUuid, moveId, user); 20178 } catch (PackageManagerException e) { 20179 Slog.w(TAG, "Failed to move " + packageName, e); 20180 mMoveCallbacks.notifyStatusChanged(moveId, 20181 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20182 } 20183 } 20184 }); 20185 return moveId; 20186 } 20187 20188 private void movePackageInternal(final String packageName, final String volumeUuid, 20189 final int moveId, UserHandle user) throws PackageManagerException { 20190 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20191 final PackageManager pm = mContext.getPackageManager(); 20192 20193 final boolean currentAsec; 20194 final String currentVolumeUuid; 20195 final File codeFile; 20196 final String installerPackageName; 20197 final String packageAbiOverride; 20198 final int appId; 20199 final String seinfo; 20200 final String label; 20201 final int targetSdkVersion; 20202 final PackageFreezer freezer; 20203 final int[] installedUserIds; 20204 20205 // reader 20206 synchronized (mPackages) { 20207 final PackageParser.Package pkg = mPackages.get(packageName); 20208 final PackageSetting ps = mSettings.mPackages.get(packageName); 20209 if (pkg == null || ps == null) { 20210 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20211 } 20212 20213 if (pkg.applicationInfo.isSystemApp()) { 20214 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20215 "Cannot move system application"); 20216 } 20217 20218 if (pkg.applicationInfo.isExternalAsec()) { 20219 currentAsec = true; 20220 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20221 } else if (pkg.applicationInfo.isForwardLocked()) { 20222 currentAsec = true; 20223 currentVolumeUuid = "forward_locked"; 20224 } else { 20225 currentAsec = false; 20226 currentVolumeUuid = ps.volumeUuid; 20227 20228 final File probe = new File(pkg.codePath); 20229 final File probeOat = new File(probe, "oat"); 20230 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20231 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20232 "Move only supported for modern cluster style installs"); 20233 } 20234 } 20235 20236 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20237 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20238 "Package already moved to " + volumeUuid); 20239 } 20240 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20241 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20242 "Device admin cannot be moved"); 20243 } 20244 20245 if (mFrozenPackages.contains(packageName)) { 20246 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20247 "Failed to move already frozen package"); 20248 } 20249 20250 codeFile = new File(pkg.codePath); 20251 installerPackageName = ps.installerPackageName; 20252 packageAbiOverride = ps.cpuAbiOverrideString; 20253 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20254 seinfo = pkg.applicationInfo.seinfo; 20255 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20256 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20257 freezer = freezePackage(packageName, "movePackageInternal"); 20258 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20259 } 20260 20261 final Bundle extras = new Bundle(); 20262 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20263 extras.putString(Intent.EXTRA_TITLE, label); 20264 mMoveCallbacks.notifyCreated(moveId, extras); 20265 20266 int installFlags; 20267 final boolean moveCompleteApp; 20268 final File measurePath; 20269 20270 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20271 installFlags = INSTALL_INTERNAL; 20272 moveCompleteApp = !currentAsec; 20273 measurePath = Environment.getDataAppDirectory(volumeUuid); 20274 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20275 installFlags = INSTALL_EXTERNAL; 20276 moveCompleteApp = false; 20277 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20278 } else { 20279 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20280 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20281 || !volume.isMountedWritable()) { 20282 freezer.close(); 20283 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20284 "Move location not mounted private volume"); 20285 } 20286 20287 Preconditions.checkState(!currentAsec); 20288 20289 installFlags = INSTALL_INTERNAL; 20290 moveCompleteApp = true; 20291 measurePath = Environment.getDataAppDirectory(volumeUuid); 20292 } 20293 20294 final PackageStats stats = new PackageStats(null, -1); 20295 synchronized (mInstaller) { 20296 for (int userId : installedUserIds) { 20297 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20298 freezer.close(); 20299 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20300 "Failed to measure package size"); 20301 } 20302 } 20303 } 20304 20305 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20306 + stats.dataSize); 20307 20308 final long startFreeBytes = measurePath.getFreeSpace(); 20309 final long sizeBytes; 20310 if (moveCompleteApp) { 20311 sizeBytes = stats.codeSize + stats.dataSize; 20312 } else { 20313 sizeBytes = stats.codeSize; 20314 } 20315 20316 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20317 freezer.close(); 20318 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20319 "Not enough free space to move"); 20320 } 20321 20322 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20323 20324 final CountDownLatch installedLatch = new CountDownLatch(1); 20325 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20326 @Override 20327 public void onUserActionRequired(Intent intent) throws RemoteException { 20328 throw new IllegalStateException(); 20329 } 20330 20331 @Override 20332 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20333 Bundle extras) throws RemoteException { 20334 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20335 + PackageManager.installStatusToString(returnCode, msg)); 20336 20337 installedLatch.countDown(); 20338 freezer.close(); 20339 20340 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20341 switch (status) { 20342 case PackageInstaller.STATUS_SUCCESS: 20343 mMoveCallbacks.notifyStatusChanged(moveId, 20344 PackageManager.MOVE_SUCCEEDED); 20345 break; 20346 case PackageInstaller.STATUS_FAILURE_STORAGE: 20347 mMoveCallbacks.notifyStatusChanged(moveId, 20348 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20349 break; 20350 default: 20351 mMoveCallbacks.notifyStatusChanged(moveId, 20352 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20353 break; 20354 } 20355 } 20356 }; 20357 20358 final MoveInfo move; 20359 if (moveCompleteApp) { 20360 // Kick off a thread to report progress estimates 20361 new Thread() { 20362 @Override 20363 public void run() { 20364 while (true) { 20365 try { 20366 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20367 break; 20368 } 20369 } catch (InterruptedException ignored) { 20370 } 20371 20372 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20373 final int progress = 10 + (int) MathUtils.constrain( 20374 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20375 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20376 } 20377 } 20378 }.start(); 20379 20380 final String dataAppName = codeFile.getName(); 20381 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20382 dataAppName, appId, seinfo, targetSdkVersion); 20383 } else { 20384 move = null; 20385 } 20386 20387 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20388 20389 final Message msg = mHandler.obtainMessage(INIT_COPY); 20390 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20391 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20392 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20393 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20394 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20395 msg.obj = params; 20396 20397 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20398 System.identityHashCode(msg.obj)); 20399 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20400 System.identityHashCode(msg.obj)); 20401 20402 mHandler.sendMessage(msg); 20403 } 20404 20405 @Override 20406 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20407 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20408 20409 final int realMoveId = mNextMoveId.getAndIncrement(); 20410 final Bundle extras = new Bundle(); 20411 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20412 mMoveCallbacks.notifyCreated(realMoveId, extras); 20413 20414 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20415 @Override 20416 public void onCreated(int moveId, Bundle extras) { 20417 // Ignored 20418 } 20419 20420 @Override 20421 public void onStatusChanged(int moveId, int status, long estMillis) { 20422 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20423 } 20424 }; 20425 20426 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20427 storage.setPrimaryStorageUuid(volumeUuid, callback); 20428 return realMoveId; 20429 } 20430 20431 @Override 20432 public int getMoveStatus(int moveId) { 20433 mContext.enforceCallingOrSelfPermission( 20434 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20435 return mMoveCallbacks.mLastStatus.get(moveId); 20436 } 20437 20438 @Override 20439 public void registerMoveCallback(IPackageMoveObserver callback) { 20440 mContext.enforceCallingOrSelfPermission( 20441 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20442 mMoveCallbacks.register(callback); 20443 } 20444 20445 @Override 20446 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20447 mContext.enforceCallingOrSelfPermission( 20448 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20449 mMoveCallbacks.unregister(callback); 20450 } 20451 20452 @Override 20453 public boolean setInstallLocation(int loc) { 20454 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20455 null); 20456 if (getInstallLocation() == loc) { 20457 return true; 20458 } 20459 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20460 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20461 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20462 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20463 return true; 20464 } 20465 return false; 20466 } 20467 20468 @Override 20469 public int getInstallLocation() { 20470 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20471 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20472 PackageHelper.APP_INSTALL_AUTO); 20473 } 20474 20475 /** Called by UserManagerService */ 20476 void cleanUpUser(UserManagerService userManager, int userHandle) { 20477 synchronized (mPackages) { 20478 mDirtyUsers.remove(userHandle); 20479 mUserNeedsBadging.delete(userHandle); 20480 mSettings.removeUserLPw(userHandle); 20481 mPendingBroadcasts.remove(userHandle); 20482 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20483 removeUnusedPackagesLPw(userManager, userHandle); 20484 } 20485 } 20486 20487 /** 20488 * We're removing userHandle and would like to remove any downloaded packages 20489 * that are no longer in use by any other user. 20490 * @param userHandle the user being removed 20491 */ 20492 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20493 final boolean DEBUG_CLEAN_APKS = false; 20494 int [] users = userManager.getUserIds(); 20495 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20496 while (psit.hasNext()) { 20497 PackageSetting ps = psit.next(); 20498 if (ps.pkg == null) { 20499 continue; 20500 } 20501 final String packageName = ps.pkg.packageName; 20502 // Skip over if system app 20503 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20504 continue; 20505 } 20506 if (DEBUG_CLEAN_APKS) { 20507 Slog.i(TAG, "Checking package " + packageName); 20508 } 20509 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20510 if (keep) { 20511 if (DEBUG_CLEAN_APKS) { 20512 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20513 } 20514 } else { 20515 for (int i = 0; i < users.length; i++) { 20516 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20517 keep = true; 20518 if (DEBUG_CLEAN_APKS) { 20519 Slog.i(TAG, " Keeping package " + packageName + " for user " 20520 + users[i]); 20521 } 20522 break; 20523 } 20524 } 20525 } 20526 if (!keep) { 20527 if (DEBUG_CLEAN_APKS) { 20528 Slog.i(TAG, " Removing package " + packageName); 20529 } 20530 mHandler.post(new Runnable() { 20531 public void run() { 20532 deletePackageX(packageName, userHandle, 0); 20533 } //end run 20534 }); 20535 } 20536 } 20537 } 20538 20539 /** Called by UserManagerService */ 20540 void createNewUser(int userId) { 20541 synchronized (mInstallLock) { 20542 mSettings.createNewUserLI(this, mInstaller, userId); 20543 } 20544 synchronized (mPackages) { 20545 scheduleWritePackageRestrictionsLocked(userId); 20546 scheduleWritePackageListLocked(userId); 20547 applyFactoryDefaultBrowserLPw(userId); 20548 primeDomainVerificationsLPw(userId); 20549 } 20550 } 20551 20552 void onNewUserCreated(final int userId) { 20553 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20554 // If permission review for legacy apps is required, we represent 20555 // dagerous permissions for such apps as always granted runtime 20556 // permissions to keep per user flag state whether review is needed. 20557 // Hence, if a new user is added we have to propagate dangerous 20558 // permission grants for these legacy apps. 20559 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20560 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20561 | UPDATE_PERMISSIONS_REPLACE_ALL); 20562 } 20563 } 20564 20565 @Override 20566 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20567 mContext.enforceCallingOrSelfPermission( 20568 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20569 "Only package verification agents can read the verifier device identity"); 20570 20571 synchronized (mPackages) { 20572 return mSettings.getVerifierDeviceIdentityLPw(); 20573 } 20574 } 20575 20576 @Override 20577 public void setPermissionEnforced(String permission, boolean enforced) { 20578 // TODO: Now that we no longer change GID for storage, this should to away. 20579 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20580 "setPermissionEnforced"); 20581 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20582 synchronized (mPackages) { 20583 if (mSettings.mReadExternalStorageEnforced == null 20584 || mSettings.mReadExternalStorageEnforced != enforced) { 20585 mSettings.mReadExternalStorageEnforced = enforced; 20586 mSettings.writeLPr(); 20587 } 20588 } 20589 // kill any non-foreground processes so we restart them and 20590 // grant/revoke the GID. 20591 final IActivityManager am = ActivityManagerNative.getDefault(); 20592 if (am != null) { 20593 final long token = Binder.clearCallingIdentity(); 20594 try { 20595 am.killProcessesBelowForeground("setPermissionEnforcement"); 20596 } catch (RemoteException e) { 20597 } finally { 20598 Binder.restoreCallingIdentity(token); 20599 } 20600 } 20601 } else { 20602 throw new IllegalArgumentException("No selective enforcement for " + permission); 20603 } 20604 } 20605 20606 @Override 20607 @Deprecated 20608 public boolean isPermissionEnforced(String permission) { 20609 return true; 20610 } 20611 20612 @Override 20613 public boolean isStorageLow() { 20614 final long token = Binder.clearCallingIdentity(); 20615 try { 20616 final DeviceStorageMonitorInternal 20617 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20618 if (dsm != null) { 20619 return dsm.isMemoryLow(); 20620 } else { 20621 return false; 20622 } 20623 } finally { 20624 Binder.restoreCallingIdentity(token); 20625 } 20626 } 20627 20628 @Override 20629 public IPackageInstaller getPackageInstaller() { 20630 return mInstallerService; 20631 } 20632 20633 private boolean userNeedsBadging(int userId) { 20634 int index = mUserNeedsBadging.indexOfKey(userId); 20635 if (index < 0) { 20636 final UserInfo userInfo; 20637 final long token = Binder.clearCallingIdentity(); 20638 try { 20639 userInfo = sUserManager.getUserInfo(userId); 20640 } finally { 20641 Binder.restoreCallingIdentity(token); 20642 } 20643 final boolean b; 20644 if (userInfo != null && userInfo.isManagedProfile()) { 20645 b = true; 20646 } else { 20647 b = false; 20648 } 20649 mUserNeedsBadging.put(userId, b); 20650 return b; 20651 } 20652 return mUserNeedsBadging.valueAt(index); 20653 } 20654 20655 @Override 20656 public KeySet getKeySetByAlias(String packageName, String alias) { 20657 if (packageName == null || alias == null) { 20658 return null; 20659 } 20660 synchronized(mPackages) { 20661 final PackageParser.Package pkg = mPackages.get(packageName); 20662 if (pkg == null) { 20663 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20664 throw new IllegalArgumentException("Unknown package: " + packageName); 20665 } 20666 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20667 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20668 } 20669 } 20670 20671 @Override 20672 public KeySet getSigningKeySet(String packageName) { 20673 if (packageName == null) { 20674 return null; 20675 } 20676 synchronized(mPackages) { 20677 final PackageParser.Package pkg = mPackages.get(packageName); 20678 if (pkg == null) { 20679 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20680 throw new IllegalArgumentException("Unknown package: " + packageName); 20681 } 20682 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20683 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20684 throw new SecurityException("May not access signing KeySet of other apps."); 20685 } 20686 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20687 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20688 } 20689 } 20690 20691 @Override 20692 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20693 if (packageName == null || ks == null) { 20694 return false; 20695 } 20696 synchronized(mPackages) { 20697 final PackageParser.Package pkg = mPackages.get(packageName); 20698 if (pkg == null) { 20699 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20700 throw new IllegalArgumentException("Unknown package: " + packageName); 20701 } 20702 IBinder ksh = ks.getToken(); 20703 if (ksh instanceof KeySetHandle) { 20704 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20705 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20706 } 20707 return false; 20708 } 20709 } 20710 20711 @Override 20712 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20713 if (packageName == null || ks == null) { 20714 return false; 20715 } 20716 synchronized(mPackages) { 20717 final PackageParser.Package pkg = mPackages.get(packageName); 20718 if (pkg == null) { 20719 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20720 throw new IllegalArgumentException("Unknown package: " + packageName); 20721 } 20722 IBinder ksh = ks.getToken(); 20723 if (ksh instanceof KeySetHandle) { 20724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20725 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20726 } 20727 return false; 20728 } 20729 } 20730 20731 private void deletePackageIfUnusedLPr(final String packageName) { 20732 PackageSetting ps = mSettings.mPackages.get(packageName); 20733 if (ps == null) { 20734 return; 20735 } 20736 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20737 // TODO Implement atomic delete if package is unused 20738 // It is currently possible that the package will be deleted even if it is installed 20739 // after this method returns. 20740 mHandler.post(new Runnable() { 20741 public void run() { 20742 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20743 } 20744 }); 20745 } 20746 } 20747 20748 /** 20749 * Check and throw if the given before/after packages would be considered a 20750 * downgrade. 20751 */ 20752 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20753 throws PackageManagerException { 20754 if (after.versionCode < before.mVersionCode) { 20755 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20756 "Update version code " + after.versionCode + " is older than current " 20757 + before.mVersionCode); 20758 } else if (after.versionCode == before.mVersionCode) { 20759 if (after.baseRevisionCode < before.baseRevisionCode) { 20760 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20761 "Update base revision code " + after.baseRevisionCode 20762 + " is older than current " + before.baseRevisionCode); 20763 } 20764 20765 if (!ArrayUtils.isEmpty(after.splitNames)) { 20766 for (int i = 0; i < after.splitNames.length; i++) { 20767 final String splitName = after.splitNames[i]; 20768 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20769 if (j != -1) { 20770 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20771 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20772 "Update split " + splitName + " revision code " 20773 + after.splitRevisionCodes[i] + " is older than current " 20774 + before.splitRevisionCodes[j]); 20775 } 20776 } 20777 } 20778 } 20779 } 20780 } 20781 20782 private static class MoveCallbacks extends Handler { 20783 private static final int MSG_CREATED = 1; 20784 private static final int MSG_STATUS_CHANGED = 2; 20785 20786 private final RemoteCallbackList<IPackageMoveObserver> 20787 mCallbacks = new RemoteCallbackList<>(); 20788 20789 private final SparseIntArray mLastStatus = new SparseIntArray(); 20790 20791 public MoveCallbacks(Looper looper) { 20792 super(looper); 20793 } 20794 20795 public void register(IPackageMoveObserver callback) { 20796 mCallbacks.register(callback); 20797 } 20798 20799 public void unregister(IPackageMoveObserver callback) { 20800 mCallbacks.unregister(callback); 20801 } 20802 20803 @Override 20804 public void handleMessage(Message msg) { 20805 final SomeArgs args = (SomeArgs) msg.obj; 20806 final int n = mCallbacks.beginBroadcast(); 20807 for (int i = 0; i < n; i++) { 20808 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20809 try { 20810 invokeCallback(callback, msg.what, args); 20811 } catch (RemoteException ignored) { 20812 } 20813 } 20814 mCallbacks.finishBroadcast(); 20815 args.recycle(); 20816 } 20817 20818 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20819 throws RemoteException { 20820 switch (what) { 20821 case MSG_CREATED: { 20822 callback.onCreated(args.argi1, (Bundle) args.arg2); 20823 break; 20824 } 20825 case MSG_STATUS_CHANGED: { 20826 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20827 break; 20828 } 20829 } 20830 } 20831 20832 private void notifyCreated(int moveId, Bundle extras) { 20833 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20834 20835 final SomeArgs args = SomeArgs.obtain(); 20836 args.argi1 = moveId; 20837 args.arg2 = extras; 20838 obtainMessage(MSG_CREATED, args).sendToTarget(); 20839 } 20840 20841 private void notifyStatusChanged(int moveId, int status) { 20842 notifyStatusChanged(moveId, status, -1); 20843 } 20844 20845 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20846 Slog.v(TAG, "Move " + moveId + " status " + status); 20847 20848 final SomeArgs args = SomeArgs.obtain(); 20849 args.argi1 = moveId; 20850 args.argi2 = status; 20851 args.arg3 = estMillis; 20852 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20853 20854 synchronized (mLastStatus) { 20855 mLastStatus.put(moveId, status); 20856 } 20857 } 20858 } 20859 20860 private final static class OnPermissionChangeListeners extends Handler { 20861 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20862 20863 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20864 new RemoteCallbackList<>(); 20865 20866 public OnPermissionChangeListeners(Looper looper) { 20867 super(looper); 20868 } 20869 20870 @Override 20871 public void handleMessage(Message msg) { 20872 switch (msg.what) { 20873 case MSG_ON_PERMISSIONS_CHANGED: { 20874 final int uid = msg.arg1; 20875 handleOnPermissionsChanged(uid); 20876 } break; 20877 } 20878 } 20879 20880 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20881 mPermissionListeners.register(listener); 20882 20883 } 20884 20885 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20886 mPermissionListeners.unregister(listener); 20887 } 20888 20889 public void onPermissionsChanged(int uid) { 20890 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20891 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20892 } 20893 } 20894 20895 private void handleOnPermissionsChanged(int uid) { 20896 final int count = mPermissionListeners.beginBroadcast(); 20897 try { 20898 for (int i = 0; i < count; i++) { 20899 IOnPermissionsChangeListener callback = mPermissionListeners 20900 .getBroadcastItem(i); 20901 try { 20902 callback.onPermissionsChanged(uid); 20903 } catch (RemoteException e) { 20904 Log.e(TAG, "Permission listener is dead", e); 20905 } 20906 } 20907 } finally { 20908 mPermissionListeners.finishBroadcast(); 20909 } 20910 } 20911 } 20912 20913 private class PackageManagerInternalImpl extends PackageManagerInternal { 20914 @Override 20915 public void setLocationPackagesProvider(PackagesProvider provider) { 20916 synchronized (mPackages) { 20917 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20918 } 20919 } 20920 20921 @Override 20922 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20923 synchronized (mPackages) { 20924 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20925 } 20926 } 20927 20928 @Override 20929 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20930 synchronized (mPackages) { 20931 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20932 } 20933 } 20934 20935 @Override 20936 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20937 synchronized (mPackages) { 20938 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20939 } 20940 } 20941 20942 @Override 20943 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20944 synchronized (mPackages) { 20945 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20946 } 20947 } 20948 20949 @Override 20950 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20951 synchronized (mPackages) { 20952 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20953 } 20954 } 20955 20956 @Override 20957 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20958 synchronized (mPackages) { 20959 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20960 packageName, userId); 20961 } 20962 } 20963 20964 @Override 20965 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20966 synchronized (mPackages) { 20967 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20968 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20969 packageName, userId); 20970 } 20971 } 20972 20973 @Override 20974 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20975 synchronized (mPackages) { 20976 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20977 packageName, userId); 20978 } 20979 } 20980 20981 @Override 20982 public void setKeepUninstalledPackages(final List<String> packageList) { 20983 Preconditions.checkNotNull(packageList); 20984 List<String> removedFromList = null; 20985 synchronized (mPackages) { 20986 if (mKeepUninstalledPackages != null) { 20987 final int packagesCount = mKeepUninstalledPackages.size(); 20988 for (int i = 0; i < packagesCount; i++) { 20989 String oldPackage = mKeepUninstalledPackages.get(i); 20990 if (packageList != null && packageList.contains(oldPackage)) { 20991 continue; 20992 } 20993 if (removedFromList == null) { 20994 removedFromList = new ArrayList<>(); 20995 } 20996 removedFromList.add(oldPackage); 20997 } 20998 } 20999 mKeepUninstalledPackages = new ArrayList<>(packageList); 21000 if (removedFromList != null) { 21001 final int removedCount = removedFromList.size(); 21002 for (int i = 0; i < removedCount; i++) { 21003 deletePackageIfUnusedLPr(removedFromList.get(i)); 21004 } 21005 } 21006 } 21007 } 21008 21009 @Override 21010 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21011 synchronized (mPackages) { 21012 // If we do not support permission review, done. 21013 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 21014 return false; 21015 } 21016 21017 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21018 if (packageSetting == null) { 21019 return false; 21020 } 21021 21022 // Permission review applies only to apps not supporting the new permission model. 21023 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21024 return false; 21025 } 21026 21027 // Legacy apps have the permission and get user consent on launch. 21028 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21029 return permissionsState.isPermissionReviewRequired(userId); 21030 } 21031 } 21032 21033 @Override 21034 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21035 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21036 } 21037 21038 @Override 21039 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21040 int userId) { 21041 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21042 } 21043 21044 @Override 21045 public void setDeviceAndProfileOwnerPackages( 21046 int deviceOwnerUserId, String deviceOwnerPackage, 21047 SparseArray<String> profileOwnerPackages) { 21048 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21049 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21050 } 21051 21052 @Override 21053 public boolean isPackageDataProtected(int userId, String packageName) { 21054 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21055 } 21056 21057 @Override 21058 public boolean wasPackageEverLaunched(String packageName, int userId) { 21059 synchronized (mPackages) { 21060 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21061 } 21062 } 21063 } 21064 21065 @Override 21066 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21067 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21068 synchronized (mPackages) { 21069 final long identity = Binder.clearCallingIdentity(); 21070 try { 21071 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21072 packageNames, userId); 21073 } finally { 21074 Binder.restoreCallingIdentity(identity); 21075 } 21076 } 21077 } 21078 21079 private static void enforceSystemOrPhoneCaller(String tag) { 21080 int callingUid = Binder.getCallingUid(); 21081 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21082 throw new SecurityException( 21083 "Cannot call " + tag + " from UID " + callingUid); 21084 } 21085 } 21086 21087 boolean isHistoricalPackageUsageAvailable() { 21088 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21089 } 21090 21091 /** 21092 * Return a <b>copy</b> of the collection of packages known to the package manager. 21093 * @return A copy of the values of mPackages. 21094 */ 21095 Collection<PackageParser.Package> getPackages() { 21096 synchronized (mPackages) { 21097 return new ArrayList<>(mPackages.values()); 21098 } 21099 } 21100 21101 /** 21102 * Logs process start information (including base APK hash) to the security log. 21103 * @hide 21104 */ 21105 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21106 String apkFile, int pid) { 21107 if (!SecurityLog.isLoggingEnabled()) { 21108 return; 21109 } 21110 Bundle data = new Bundle(); 21111 data.putLong("startTimestamp", System.currentTimeMillis()); 21112 data.putString("processName", processName); 21113 data.putInt("uid", uid); 21114 data.putString("seinfo", seinfo); 21115 data.putString("apkFile", apkFile); 21116 data.putInt("pid", pid); 21117 Message msg = mProcessLoggingHandler.obtainMessage( 21118 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21119 msg.setData(data); 21120 mProcessLoggingHandler.sendMessage(msg); 21121 } 21122 21123 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21124 return mCompilerStats.getPackageStats(pkgName); 21125 } 21126 21127 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21128 return getOrCreateCompilerPackageStats(pkg.packageName); 21129 } 21130 21131 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21132 return mCompilerStats.getOrCreatePackageStats(pkgName); 21133 } 21134 21135 public void deleteCompilerPackageStats(String pkgName) { 21136 mCompilerStats.deletePackageStats(pkgName); 21137 } 21138} 21139