PackageManagerService.java revision e69fba3f7fbc8e4fc6c02b80c8fac097804b97f7
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.SomeArgs; 235import com.android.internal.os.Zygote; 236import com.android.internal.telephony.CarrierAppUtils; 237import com.android.internal.util.ArrayUtils; 238import com.android.internal.util.FastPrintWriter; 239import com.android.internal.util.FastXmlSerializer; 240import com.android.internal.util.IndentingPrintWriter; 241import com.android.internal.util.Preconditions; 242import com.android.internal.util.XmlUtils; 243import com.android.server.AttributeCache; 244import com.android.server.EventLogTags; 245import com.android.server.FgThread; 246import com.android.server.IntentResolver; 247import com.android.server.LocalServices; 248import com.android.server.ServiceThread; 249import com.android.server.SystemConfig; 250import com.android.server.Watchdog; 251import com.android.server.net.NetworkPolicyManagerInternal; 252import com.android.server.pm.Installer.InstallerException; 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.pm.dex.DexManager; 257import com.android.server.storage.DeviceStorageMonitorInternal; 258 259import dalvik.system.CloseGuard; 260import dalvik.system.DexFile; 261import dalvik.system.VMRuntime; 262 263import libcore.io.IoUtils; 264import libcore.util.EmptyArray; 265 266import org.xmlpull.v1.XmlPullParser; 267import org.xmlpull.v1.XmlPullParserException; 268import org.xmlpull.v1.XmlSerializer; 269 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.PrintWriter; 283import java.nio.charset.StandardCharsets; 284import java.security.DigestInputStream; 285import java.security.MessageDigest; 286import java.security.NoSuchAlgorithmException; 287import java.security.PublicKey; 288import java.security.cert.Certificate; 289import java.security.cert.CertificateEncodingException; 290import java.security.cert.CertificateException; 291import java.text.SimpleDateFormat; 292import java.util.ArrayList; 293import java.util.Arrays; 294import java.util.Collection; 295import java.util.Collections; 296import java.util.Comparator; 297import java.util.Date; 298import java.util.HashSet; 299import java.util.HashMap; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309 310/** 311 * Keep track of all those APKs everywhere. 312 * <p> 313 * Internally there are two important locks: 314 * <ul> 315 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 316 * and other related state. It is a fine-grained lock that should only be held 317 * momentarily, as it's one of the most contended locks in the system. 318 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 319 * operations typically involve heavy lifting of application data on disk. Since 320 * {@code installd} is single-threaded, and it's operations can often be slow, 321 * this lock should never be acquired while already holding {@link #mPackages}. 322 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 323 * holding {@link #mInstallLock}. 324 * </ul> 325 * Many internal methods rely on the caller to hold the appropriate locks, and 326 * this contract is expressed through method name suffixes: 327 * <ul> 328 * <li>fooLI(): the caller must hold {@link #mInstallLock} 329 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 330 * being modified must be frozen 331 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 332 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 333 * </ul> 334 * <p> 335 * Because this class is very central to the platform's security; please run all 336 * CTS and unit tests whenever making modifications: 337 * 338 * <pre> 339 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 340 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 341 * </pre> 342 */ 343public class PackageManagerService extends IPackageManager.Stub { 344 static final String TAG = "PackageManager"; 345 static final boolean DEBUG_SETTINGS = false; 346 static final boolean DEBUG_PREFERRED = false; 347 static final boolean DEBUG_UPGRADE = false; 348 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 349 private static final boolean DEBUG_BACKUP = false; 350 private static final boolean DEBUG_INSTALL = false; 351 private static final boolean DEBUG_REMOVE = false; 352 private static final boolean DEBUG_BROADCASTS = false; 353 private static final boolean DEBUG_SHOW_INFO = false; 354 private static final boolean DEBUG_PACKAGE_INFO = false; 355 private static final boolean DEBUG_INTENT_MATCHING = false; 356 private static final boolean DEBUG_PACKAGE_SCANNING = false; 357 private static final boolean DEBUG_VERIFY = false; 358 private static final boolean DEBUG_FILTERS = false; 359 360 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 361 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 362 // user, but by default initialize to this. 363 static final boolean DEBUG_DEXOPT = false; 364 365 private static final boolean DEBUG_ABI_SELECTION = false; 366 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 367 private static final boolean DEBUG_TRIAGED_MISSING = false; 368 private static final boolean DEBUG_APP_DATA = false; 369 370 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 371 372 private static final boolean DISABLE_EPHEMERAL_APPS = false; 373 private static final boolean HIDE_EPHEMERAL_APIS = true; 374 375 private static final boolean ENABLE_QUOTA = 376 SystemProperties.getBoolean("persist.fw.quota", false); 377 378 private static final int RADIO_UID = Process.PHONE_UID; 379 private static final int LOG_UID = Process.LOG_UID; 380 private static final int NFC_UID = Process.NFC_UID; 381 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 382 private static final int SHELL_UID = Process.SHELL_UID; 383 384 // Cap the size of permission trees that 3rd party apps can define 385 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 386 387 // Suffix used during package installation when copying/moving 388 // package apks to install directory. 389 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 390 391 static final int SCAN_NO_DEX = 1<<1; 392 static final int SCAN_FORCE_DEX = 1<<2; 393 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 394 static final int SCAN_NEW_INSTALL = 1<<4; 395 static final int SCAN_NO_PATHS = 1<<5; 396 static final int SCAN_UPDATE_TIME = 1<<6; 397 static final int SCAN_DEFER_DEX = 1<<7; 398 static final int SCAN_BOOTING = 1<<8; 399 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 400 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 401 static final int SCAN_REPLACING = 1<<11; 402 static final int SCAN_REQUIRE_KNOWN = 1<<12; 403 static final int SCAN_MOVE = 1<<13; 404 static final int SCAN_INITIAL = 1<<14; 405 static final int SCAN_CHECK_ONLY = 1<<15; 406 static final int SCAN_DONT_KILL_APP = 1<<17; 407 static final int SCAN_IGNORE_FROZEN = 1<<18; 408 409 static final int REMOVE_CHATTY = 1<<16; 410 411 private static final int[] EMPTY_INT_ARRAY = new int[0]; 412 413 /** 414 * Timeout (in milliseconds) after which the watchdog should declare that 415 * our handler thread is wedged. The usual default for such things is one 416 * minute but we sometimes do very lengthy I/O operations on this thread, 417 * such as installing multi-gigabyte applications, so ours needs to be longer. 418 */ 419 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 420 421 /** 422 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 423 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 424 * settings entry if available, otherwise we use the hardcoded default. If it's been 425 * more than this long since the last fstrim, we force one during the boot sequence. 426 * 427 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 428 * one gets run at the next available charging+idle time. This final mandatory 429 * no-fstrim check kicks in only of the other scheduling criteria is never met. 430 */ 431 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 432 433 /** 434 * Whether verification is enabled by default. 435 */ 436 private static final boolean DEFAULT_VERIFY_ENABLE = true; 437 438 /** 439 * The default maximum time to wait for the verification agent to return in 440 * milliseconds. 441 */ 442 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 443 444 /** 445 * The default response for package verification timeout. 446 * 447 * This can be either PackageManager.VERIFICATION_ALLOW or 448 * PackageManager.VERIFICATION_REJECT. 449 */ 450 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 451 452 static final String PLATFORM_PACKAGE_NAME = "android"; 453 454 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 455 456 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 457 DEFAULT_CONTAINER_PACKAGE, 458 "com.android.defcontainer.DefaultContainerService"); 459 460 private static final String KILL_APP_REASON_GIDS_CHANGED = 461 "permission grant or revoke changed gids"; 462 463 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 464 "permissions revoked"; 465 466 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 467 468 private static final String PACKAGE_SCHEME = "package"; 469 470 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 471 /** 472 * If VENDOR_OVERLAY_SKU_PROPERTY is set, search for runtime resource overlay APKs in 473 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in 474 * VENDOR_OVERLAY_DIR. 475 */ 476 private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku"; 477 478 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 479 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 480 481 /** Permission grant: not grant the permission. */ 482 private static final int GRANT_DENIED = 1; 483 484 /** Permission grant: grant the permission as an install permission. */ 485 private static final int GRANT_INSTALL = 2; 486 487 /** Permission grant: grant the permission as a runtime one. */ 488 private static final int GRANT_RUNTIME = 3; 489 490 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 491 private static final int GRANT_UPGRADE = 4; 492 493 /** Canonical intent used to identify what counts as a "web browser" app */ 494 private static final Intent sBrowserIntent; 495 static { 496 sBrowserIntent = new Intent(); 497 sBrowserIntent.setAction(Intent.ACTION_VIEW); 498 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 499 sBrowserIntent.setData(Uri.parse("http:")); 500 } 501 502 /** 503 * The set of all protected actions [i.e. those actions for which a high priority 504 * intent filter is disallowed]. 505 */ 506 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 507 static { 508 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 509 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 510 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 511 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 512 } 513 514 // Compilation reasons. 515 public static final int REASON_FIRST_BOOT = 0; 516 public static final int REASON_BOOT = 1; 517 public static final int REASON_INSTALL = 2; 518 public static final int REASON_BACKGROUND_DEXOPT = 3; 519 public static final int REASON_AB_OTA = 4; 520 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 521 public static final int REASON_SHARED_APK = 6; 522 public static final int REASON_FORCED_DEXOPT = 7; 523 public static final int REASON_CORE_APP = 8; 524 525 public static final int REASON_LAST = REASON_CORE_APP; 526 527 /** Special library name that skips shared libraries check during compilation. */ 528 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 529 530 final ServiceThread mHandlerThread; 531 532 final PackageHandler mHandler; 533 534 private final ProcessLoggingHandler mProcessLoggingHandler; 535 536 /** 537 * Messages for {@link #mHandler} that need to wait for system ready before 538 * being dispatched. 539 */ 540 private ArrayList<Message> mPostSystemReadyMessages; 541 542 final int mSdkVersion = Build.VERSION.SDK_INT; 543 544 final Context mContext; 545 final boolean mFactoryTest; 546 final boolean mOnlyCore; 547 final DisplayMetrics mMetrics; 548 final int mDefParseFlags; 549 final String[] mSeparateProcesses; 550 final boolean mIsUpgrade; 551 final boolean mIsPreNUpgrade; 552 final boolean mIsPreNMR1Upgrade; 553 554 @GuardedBy("mPackages") 555 private boolean mDexOptDialogShown; 556 557 /** The location for ASEC container files on internal storage. */ 558 final String mAsecInternalPath; 559 560 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 561 // LOCK HELD. Can be called with mInstallLock held. 562 @GuardedBy("mInstallLock") 563 final Installer mInstaller; 564 565 /** Directory where installed third-party apps stored */ 566 final File mAppInstallDir; 567 final File mEphemeralInstallDir; 568 569 /** 570 * Directory to which applications installed internally have their 571 * 32 bit native libraries copied. 572 */ 573 private File mAppLib32InstallDir; 574 575 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 576 // apps. 577 final File mDrmAppPrivateInstallDir; 578 579 // ---------------------------------------------------------------- 580 581 // Lock for state used when installing and doing other long running 582 // operations. Methods that must be called with this lock held have 583 // the suffix "LI". 584 final Object mInstallLock = new Object(); 585 586 // ---------------------------------------------------------------- 587 588 // Keys are String (package name), values are Package. This also serves 589 // as the lock for the global state. Methods that must be called with 590 // this lock held have the prefix "LP". 591 @GuardedBy("mPackages") 592 final ArrayMap<String, PackageParser.Package> mPackages = 593 new ArrayMap<String, PackageParser.Package>(); 594 595 final ArrayMap<String, Set<String>> mKnownCodebase = 596 new ArrayMap<String, Set<String>>(); 597 598 // Tracks available target package names -> overlay package paths. 599 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 600 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 601 602 /** 603 * Tracks new system packages [received in an OTA] that we expect to 604 * find updated user-installed versions. Keys are package name, values 605 * are package location. 606 */ 607 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 608 /** 609 * Tracks high priority intent filters for protected actions. During boot, certain 610 * filter actions are protected and should never be allowed to have a high priority 611 * intent filter for them. However, there is one, and only one exception -- the 612 * setup wizard. It must be able to define a high priority intent filter for these 613 * actions to ensure there are no escapes from the wizard. We need to delay processing 614 * of these during boot as we need to look at all of the system packages in order 615 * to know which component is the setup wizard. 616 */ 617 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 618 /** 619 * Whether or not processing protected filters should be deferred. 620 */ 621 private boolean mDeferProtectedFilters = true; 622 623 /** 624 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 625 */ 626 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 627 /** 628 * Whether or not system app permissions should be promoted from install to runtime. 629 */ 630 boolean mPromoteSystemApps; 631 632 @GuardedBy("mPackages") 633 final Settings mSettings; 634 635 /** 636 * Set of package names that are currently "frozen", which means active 637 * surgery is being done on the code/data for that package. The platform 638 * will refuse to launch frozen packages to avoid race conditions. 639 * 640 * @see PackageFreezer 641 */ 642 @GuardedBy("mPackages") 643 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 644 645 final ProtectedPackages mProtectedPackages; 646 647 boolean mFirstBoot; 648 649 // System configuration read by SystemConfig. 650 final int[] mGlobalGids; 651 final SparseArray<ArraySet<String>> mSystemPermissions; 652 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 653 654 // If mac_permissions.xml was found for seinfo labeling. 655 boolean mFoundPolicyFile; 656 657 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 658 659 public static final class SharedLibraryEntry { 660 public final String path; 661 public final String apk; 662 663 SharedLibraryEntry(String _path, String _apk) { 664 path = _path; 665 apk = _apk; 666 } 667 } 668 669 // Currently known shared libraries. 670 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 671 new ArrayMap<String, SharedLibraryEntry>(); 672 673 // All available activities, for your resolving pleasure. 674 final ActivityIntentResolver mActivities = 675 new ActivityIntentResolver(); 676 677 // All available receivers, for your resolving pleasure. 678 final ActivityIntentResolver mReceivers = 679 new ActivityIntentResolver(); 680 681 // All available services, for your resolving pleasure. 682 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 683 684 // All available providers, for your resolving pleasure. 685 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 686 687 // Mapping from provider base names (first directory in content URI codePath) 688 // to the provider information. 689 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 690 new ArrayMap<String, PackageParser.Provider>(); 691 692 // Mapping from instrumentation class names to info about them. 693 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 694 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 695 696 // Mapping from permission names to info about them. 697 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 698 new ArrayMap<String, PackageParser.PermissionGroup>(); 699 700 // Packages whose data we have transfered into another package, thus 701 // should no longer exist. 702 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 703 704 // Broadcast actions that are only available to the system. 705 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 706 707 /** List of packages waiting for verification. */ 708 final SparseArray<PackageVerificationState> mPendingVerification 709 = new SparseArray<PackageVerificationState>(); 710 711 /** Set of packages associated with each app op permission. */ 712 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 713 714 final PackageInstallerService mInstallerService; 715 716 private final PackageDexOptimizer mPackageDexOptimizer; 717 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 718 // is used by other apps). 719 private final DexManager mDexManager; 720 721 private AtomicInteger mNextMoveId = new AtomicInteger(); 722 private final MoveCallbacks mMoveCallbacks; 723 724 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 725 726 // Cache of users who need badging. 727 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 728 729 /** Token for keys in mPendingVerification. */ 730 private int mPendingVerificationToken = 0; 731 732 volatile boolean mSystemReady; 733 volatile boolean mSafeMode; 734 volatile boolean mHasSystemUidErrors; 735 736 ApplicationInfo mAndroidApplication; 737 final ActivityInfo mResolveActivity = new ActivityInfo(); 738 final ResolveInfo mResolveInfo = new ResolveInfo(); 739 ComponentName mResolveComponentName; 740 PackageParser.Package mPlatformPackage; 741 ComponentName mCustomResolverComponentName; 742 743 boolean mResolverReplaced = false; 744 745 private final @Nullable ComponentName mIntentFilterVerifierComponent; 746 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 747 748 private int mIntentFilterVerificationToken = 0; 749 750 /** Component that knows whether or not an ephemeral application exists */ 751 final ComponentName mEphemeralResolverComponent; 752 /** The service connection to the ephemeral resolver */ 753 final EphemeralResolverConnection mEphemeralResolverConnection; 754 755 /** Component used to install ephemeral applications */ 756 final ComponentName mEphemeralInstallerComponent; 757 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 758 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 759 760 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 761 = new SparseArray<IntentFilterVerificationState>(); 762 763 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 764 765 // List of packages names to keep cached, even if they are uninstalled for all users 766 private List<String> mKeepUninstalledPackages; 767 768 private UserManagerInternal mUserManagerInternal; 769 770 private static class IFVerificationParams { 771 PackageParser.Package pkg; 772 boolean replacing; 773 int userId; 774 int verifierUid; 775 776 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 777 int _userId, int _verifierUid) { 778 pkg = _pkg; 779 replacing = _replacing; 780 userId = _userId; 781 replacing = _replacing; 782 verifierUid = _verifierUid; 783 } 784 } 785 786 private interface IntentFilterVerifier<T extends IntentFilter> { 787 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 788 T filter, String packageName); 789 void startVerifications(int userId); 790 void receiveVerificationResponse(int verificationId); 791 } 792 793 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 794 private Context mContext; 795 private ComponentName mIntentFilterVerifierComponent; 796 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 797 798 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 799 mContext = context; 800 mIntentFilterVerifierComponent = verifierComponent; 801 } 802 803 private String getDefaultScheme() { 804 return IntentFilter.SCHEME_HTTPS; 805 } 806 807 @Override 808 public void startVerifications(int userId) { 809 // Launch verifications requests 810 int count = mCurrentIntentFilterVerifications.size(); 811 for (int n=0; n<count; n++) { 812 int verificationId = mCurrentIntentFilterVerifications.get(n); 813 final IntentFilterVerificationState ivs = 814 mIntentFilterVerificationStates.get(verificationId); 815 816 String packageName = ivs.getPackageName(); 817 818 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 819 final int filterCount = filters.size(); 820 ArraySet<String> domainsSet = new ArraySet<>(); 821 for (int m=0; m<filterCount; m++) { 822 PackageParser.ActivityIntentInfo filter = filters.get(m); 823 domainsSet.addAll(filter.getHostsList()); 824 } 825 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 826 synchronized (mPackages) { 827 if (mSettings.createIntentFilterVerificationIfNeededLPw( 828 packageName, domainsList) != null) { 829 scheduleWriteSettingsLocked(); 830 } 831 } 832 sendVerificationRequest(userId, verificationId, ivs); 833 } 834 mCurrentIntentFilterVerifications.clear(); 835 } 836 837 private void sendVerificationRequest(int userId, int verificationId, 838 IntentFilterVerificationState ivs) { 839 840 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 841 verificationIntent.putExtra( 842 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 843 verificationId); 844 verificationIntent.putExtra( 845 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 846 getDefaultScheme()); 847 verificationIntent.putExtra( 848 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 849 ivs.getHostsString()); 850 verificationIntent.putExtra( 851 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 852 ivs.getPackageName()); 853 verificationIntent.setComponent(mIntentFilterVerifierComponent); 854 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 855 856 UserHandle user = new UserHandle(userId); 857 mContext.sendBroadcastAsUser(verificationIntent, user); 858 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 859 "Sending IntentFilter verification broadcast"); 860 } 861 862 public void receiveVerificationResponse(int verificationId) { 863 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 864 865 final boolean verified = ivs.isVerified(); 866 867 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 868 final int count = filters.size(); 869 if (DEBUG_DOMAIN_VERIFICATION) { 870 Slog.i(TAG, "Received verification response " + verificationId 871 + " for " + count + " filters, verified=" + verified); 872 } 873 for (int n=0; n<count; n++) { 874 PackageParser.ActivityIntentInfo filter = filters.get(n); 875 filter.setVerified(verified); 876 877 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 878 + " verified with result:" + verified + " and hosts:" 879 + ivs.getHostsString()); 880 } 881 882 mIntentFilterVerificationStates.remove(verificationId); 883 884 final String packageName = ivs.getPackageName(); 885 IntentFilterVerificationInfo ivi = null; 886 887 synchronized (mPackages) { 888 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 889 } 890 if (ivi == null) { 891 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 892 + verificationId + " packageName:" + packageName); 893 return; 894 } 895 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 896 "Updating IntentFilterVerificationInfo for package " + packageName 897 +" verificationId:" + verificationId); 898 899 synchronized (mPackages) { 900 if (verified) { 901 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 902 } else { 903 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 904 } 905 scheduleWriteSettingsLocked(); 906 907 final int userId = ivs.getUserId(); 908 if (userId != UserHandle.USER_ALL) { 909 final int userStatus = 910 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 911 912 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 913 boolean needUpdate = false; 914 915 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 916 // already been set by the User thru the Disambiguation dialog 917 switch (userStatus) { 918 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 919 if (verified) { 920 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 921 } else { 922 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 923 } 924 needUpdate = true; 925 break; 926 927 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 928 if (verified) { 929 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 930 needUpdate = true; 931 } 932 break; 933 934 default: 935 // Nothing to do 936 } 937 938 if (needUpdate) { 939 mSettings.updateIntentFilterVerificationStatusLPw( 940 packageName, updatedStatus, userId); 941 scheduleWritePackageRestrictionsLocked(userId); 942 } 943 } 944 } 945 } 946 947 @Override 948 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 949 ActivityIntentInfo filter, String packageName) { 950 if (!hasValidDomains(filter)) { 951 return false; 952 } 953 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 954 if (ivs == null) { 955 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 956 packageName); 957 } 958 if (DEBUG_DOMAIN_VERIFICATION) { 959 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 960 } 961 ivs.addFilter(filter); 962 return true; 963 } 964 965 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 966 int userId, int verificationId, String packageName) { 967 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 968 verifierUid, userId, packageName); 969 ivs.setPendingState(); 970 synchronized (mPackages) { 971 mIntentFilterVerificationStates.append(verificationId, ivs); 972 mCurrentIntentFilterVerifications.add(verificationId); 973 } 974 return ivs; 975 } 976 } 977 978 private static boolean hasValidDomains(ActivityIntentInfo filter) { 979 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 980 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 981 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 982 } 983 984 // Set of pending broadcasts for aggregating enable/disable of components. 985 static class PendingPackageBroadcasts { 986 // for each user id, a map of <package name -> components within that package> 987 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 988 989 public PendingPackageBroadcasts() { 990 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 991 } 992 993 public ArrayList<String> get(int userId, String packageName) { 994 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 995 return packages.get(packageName); 996 } 997 998 public void put(int userId, String packageName, ArrayList<String> components) { 999 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1000 packages.put(packageName, components); 1001 } 1002 1003 public void remove(int userId, String packageName) { 1004 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1005 if (packages != null) { 1006 packages.remove(packageName); 1007 } 1008 } 1009 1010 public void remove(int userId) { 1011 mUidMap.remove(userId); 1012 } 1013 1014 public int userIdCount() { 1015 return mUidMap.size(); 1016 } 1017 1018 public int userIdAt(int n) { 1019 return mUidMap.keyAt(n); 1020 } 1021 1022 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1023 return mUidMap.get(userId); 1024 } 1025 1026 public int size() { 1027 // total number of pending broadcast entries across all userIds 1028 int num = 0; 1029 for (int i = 0; i< mUidMap.size(); i++) { 1030 num += mUidMap.valueAt(i).size(); 1031 } 1032 return num; 1033 } 1034 1035 public void clear() { 1036 mUidMap.clear(); 1037 } 1038 1039 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1040 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1041 if (map == null) { 1042 map = new ArrayMap<String, ArrayList<String>>(); 1043 mUidMap.put(userId, map); 1044 } 1045 return map; 1046 } 1047 } 1048 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1049 1050 // Service Connection to remote media container service to copy 1051 // package uri's from external media onto secure containers 1052 // or internal storage. 1053 private IMediaContainerService mContainerService = null; 1054 1055 static final int SEND_PENDING_BROADCAST = 1; 1056 static final int MCS_BOUND = 3; 1057 static final int END_COPY = 4; 1058 static final int INIT_COPY = 5; 1059 static final int MCS_UNBIND = 6; 1060 static final int START_CLEANING_PACKAGE = 7; 1061 static final int FIND_INSTALL_LOC = 8; 1062 static final int POST_INSTALL = 9; 1063 static final int MCS_RECONNECT = 10; 1064 static final int MCS_GIVE_UP = 11; 1065 static final int UPDATED_MEDIA_STATUS = 12; 1066 static final int WRITE_SETTINGS = 13; 1067 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1068 static final int PACKAGE_VERIFIED = 15; 1069 static final int CHECK_PENDING_VERIFICATION = 16; 1070 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1071 static final int INTENT_FILTER_VERIFIED = 18; 1072 static final int WRITE_PACKAGE_LIST = 19; 1073 1074 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1075 1076 // Delay time in millisecs 1077 static final int BROADCAST_DELAY = 10 * 1000; 1078 1079 static UserManagerService sUserManager; 1080 1081 // Stores a list of users whose package restrictions file needs to be updated 1082 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1083 1084 final private DefaultContainerConnection mDefContainerConn = 1085 new DefaultContainerConnection(); 1086 class DefaultContainerConnection implements ServiceConnection { 1087 public void onServiceConnected(ComponentName name, IBinder service) { 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1089 IMediaContainerService imcs = 1090 IMediaContainerService.Stub.asInterface(service); 1091 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1092 } 1093 1094 public void onServiceDisconnected(ComponentName name) { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1096 } 1097 } 1098 1099 // Recordkeeping of restore-after-install operations that are currently in flight 1100 // between the Package Manager and the Backup Manager 1101 static class PostInstallData { 1102 public InstallArgs args; 1103 public PackageInstalledInfo res; 1104 1105 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1106 args = _a; 1107 res = _r; 1108 } 1109 } 1110 1111 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1112 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1113 1114 // XML tags for backup/restore of various bits of state 1115 private static final String TAG_PREFERRED_BACKUP = "pa"; 1116 private static final String TAG_DEFAULT_APPS = "da"; 1117 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1118 1119 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1120 private static final String TAG_ALL_GRANTS = "rt-grants"; 1121 private static final String TAG_GRANT = "grant"; 1122 private static final String ATTR_PACKAGE_NAME = "pkg"; 1123 1124 private static final String TAG_PERMISSION = "perm"; 1125 private static final String ATTR_PERMISSION_NAME = "name"; 1126 private static final String ATTR_IS_GRANTED = "g"; 1127 private static final String ATTR_USER_SET = "set"; 1128 private static final String ATTR_USER_FIXED = "fixed"; 1129 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1130 1131 // System/policy permission grants are not backed up 1132 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1133 FLAG_PERMISSION_POLICY_FIXED 1134 | FLAG_PERMISSION_SYSTEM_FIXED 1135 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1136 1137 // And we back up these user-adjusted states 1138 private static final int USER_RUNTIME_GRANT_MASK = 1139 FLAG_PERMISSION_USER_SET 1140 | FLAG_PERMISSION_USER_FIXED 1141 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1142 1143 final @Nullable String mRequiredVerifierPackage; 1144 final @NonNull String mRequiredInstallerPackage; 1145 final @NonNull String mRequiredUninstallerPackage; 1146 final @Nullable String mSetupWizardPackage; 1147 final @Nullable String mStorageManagerPackage; 1148 final @NonNull String mServicesSystemSharedLibraryPackageName; 1149 final @NonNull String mSharedSystemSharedLibraryPackageName; 1150 1151 final boolean mPermissionReviewRequired; 1152 1153 private final PackageUsage mPackageUsage = new PackageUsage(); 1154 private final CompilerStats mCompilerStats = new CompilerStats(); 1155 1156 class PackageHandler extends Handler { 1157 private boolean mBound = false; 1158 final ArrayList<HandlerParams> mPendingInstalls = 1159 new ArrayList<HandlerParams>(); 1160 1161 private boolean connectToService() { 1162 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1163 " DefaultContainerService"); 1164 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1166 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1167 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1168 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1169 mBound = true; 1170 return true; 1171 } 1172 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1173 return false; 1174 } 1175 1176 private void disconnectService() { 1177 mContainerService = null; 1178 mBound = false; 1179 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1180 mContext.unbindService(mDefContainerConn); 1181 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1182 } 1183 1184 PackageHandler(Looper looper) { 1185 super(looper); 1186 } 1187 1188 public void handleMessage(Message msg) { 1189 try { 1190 doHandleMessage(msg); 1191 } finally { 1192 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1193 } 1194 } 1195 1196 void doHandleMessage(Message msg) { 1197 switch (msg.what) { 1198 case INIT_COPY: { 1199 HandlerParams params = (HandlerParams) msg.obj; 1200 int idx = mPendingInstalls.size(); 1201 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1202 // If a bind was already initiated we dont really 1203 // need to do anything. The pending install 1204 // will be processed later on. 1205 if (!mBound) { 1206 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1207 System.identityHashCode(mHandler)); 1208 // If this is the only one pending we might 1209 // have to bind to the service again. 1210 if (!connectToService()) { 1211 Slog.e(TAG, "Failed to bind to media container service"); 1212 params.serviceError(); 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1214 System.identityHashCode(mHandler)); 1215 if (params.traceMethod != null) { 1216 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1217 params.traceCookie); 1218 } 1219 return; 1220 } else { 1221 // Once we bind to the service, the first 1222 // pending request will be processed. 1223 mPendingInstalls.add(idx, params); 1224 } 1225 } else { 1226 mPendingInstalls.add(idx, params); 1227 // Already bound to the service. Just make 1228 // sure we trigger off processing the first request. 1229 if (idx == 0) { 1230 mHandler.sendEmptyMessage(MCS_BOUND); 1231 } 1232 } 1233 break; 1234 } 1235 case MCS_BOUND: { 1236 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1237 if (msg.obj != null) { 1238 mContainerService = (IMediaContainerService) msg.obj; 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1240 System.identityHashCode(mHandler)); 1241 } 1242 if (mContainerService == null) { 1243 if (!mBound) { 1244 // Something seriously wrong since we are not bound and we are not 1245 // waiting for connection. Bail out. 1246 Slog.e(TAG, "Cannot bind to media container service"); 1247 for (HandlerParams params : mPendingInstalls) { 1248 // Indicate service bind error 1249 params.serviceError(); 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1251 System.identityHashCode(params)); 1252 if (params.traceMethod != null) { 1253 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1254 params.traceMethod, params.traceCookie); 1255 } 1256 return; 1257 } 1258 mPendingInstalls.clear(); 1259 } else { 1260 Slog.w(TAG, "Waiting to connect to media container service"); 1261 } 1262 } else if (mPendingInstalls.size() > 0) { 1263 HandlerParams params = mPendingInstalls.get(0); 1264 if (params != null) { 1265 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1266 System.identityHashCode(params)); 1267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1268 if (params.startCopy()) { 1269 // We are done... look for more work or to 1270 // go idle. 1271 if (DEBUG_SD_INSTALL) Log.i(TAG, 1272 "Checking for more work or unbind..."); 1273 // Delete pending install 1274 if (mPendingInstalls.size() > 0) { 1275 mPendingInstalls.remove(0); 1276 } 1277 if (mPendingInstalls.size() == 0) { 1278 if (mBound) { 1279 if (DEBUG_SD_INSTALL) Log.i(TAG, 1280 "Posting delayed MCS_UNBIND"); 1281 removeMessages(MCS_UNBIND); 1282 Message ubmsg = obtainMessage(MCS_UNBIND); 1283 // Unbind after a little delay, to avoid 1284 // continual thrashing. 1285 sendMessageDelayed(ubmsg, 10000); 1286 } 1287 } else { 1288 // There are more pending requests in queue. 1289 // Just post MCS_BOUND message to trigger processing 1290 // of next pending install. 1291 if (DEBUG_SD_INSTALL) Log.i(TAG, 1292 "Posting MCS_BOUND for next work"); 1293 mHandler.sendEmptyMessage(MCS_BOUND); 1294 } 1295 } 1296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1297 } 1298 } else { 1299 // Should never happen ideally. 1300 Slog.w(TAG, "Empty queue"); 1301 } 1302 break; 1303 } 1304 case MCS_RECONNECT: { 1305 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1306 if (mPendingInstalls.size() > 0) { 1307 if (mBound) { 1308 disconnectService(); 1309 } 1310 if (!connectToService()) { 1311 Slog.e(TAG, "Failed to bind to media container service"); 1312 for (HandlerParams params : mPendingInstalls) { 1313 // Indicate service bind error 1314 params.serviceError(); 1315 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1316 System.identityHashCode(params)); 1317 } 1318 mPendingInstalls.clear(); 1319 } 1320 } 1321 break; 1322 } 1323 case MCS_UNBIND: { 1324 // If there is no actual work left, then time to unbind. 1325 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1326 1327 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1328 if (mBound) { 1329 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1330 1331 disconnectService(); 1332 } 1333 } else if (mPendingInstalls.size() > 0) { 1334 // There are more pending requests in queue. 1335 // Just post MCS_BOUND message to trigger processing 1336 // of next pending install. 1337 mHandler.sendEmptyMessage(MCS_BOUND); 1338 } 1339 1340 break; 1341 } 1342 case MCS_GIVE_UP: { 1343 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1344 HandlerParams params = mPendingInstalls.remove(0); 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1346 System.identityHashCode(params)); 1347 break; 1348 } 1349 case SEND_PENDING_BROADCAST: { 1350 String packages[]; 1351 ArrayList<String> components[]; 1352 int size = 0; 1353 int uids[]; 1354 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1355 synchronized (mPackages) { 1356 if (mPendingBroadcasts == null) { 1357 return; 1358 } 1359 size = mPendingBroadcasts.size(); 1360 if (size <= 0) { 1361 // Nothing to be done. Just return 1362 return; 1363 } 1364 packages = new String[size]; 1365 components = new ArrayList[size]; 1366 uids = new int[size]; 1367 int i = 0; // filling out the above arrays 1368 1369 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1370 int packageUserId = mPendingBroadcasts.userIdAt(n); 1371 Iterator<Map.Entry<String, ArrayList<String>>> it 1372 = mPendingBroadcasts.packagesForUserId(packageUserId) 1373 .entrySet().iterator(); 1374 while (it.hasNext() && i < size) { 1375 Map.Entry<String, ArrayList<String>> ent = it.next(); 1376 packages[i] = ent.getKey(); 1377 components[i] = ent.getValue(); 1378 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1379 uids[i] = (ps != null) 1380 ? UserHandle.getUid(packageUserId, ps.appId) 1381 : -1; 1382 i++; 1383 } 1384 } 1385 size = i; 1386 mPendingBroadcasts.clear(); 1387 } 1388 // Send broadcasts 1389 for (int i = 0; i < size; i++) { 1390 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1391 } 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1393 break; 1394 } 1395 case START_CLEANING_PACKAGE: { 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1397 final String packageName = (String)msg.obj; 1398 final int userId = msg.arg1; 1399 final boolean andCode = msg.arg2 != 0; 1400 synchronized (mPackages) { 1401 if (userId == UserHandle.USER_ALL) { 1402 int[] users = sUserManager.getUserIds(); 1403 for (int user : users) { 1404 mSettings.addPackageToCleanLPw( 1405 new PackageCleanItem(user, packageName, andCode)); 1406 } 1407 } else { 1408 mSettings.addPackageToCleanLPw( 1409 new PackageCleanItem(userId, packageName, andCode)); 1410 } 1411 } 1412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1413 startCleaningPackages(); 1414 } break; 1415 case POST_INSTALL: { 1416 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1417 1418 PostInstallData data = mRunningInstalls.get(msg.arg1); 1419 final boolean didRestore = (msg.arg2 != 0); 1420 mRunningInstalls.delete(msg.arg1); 1421 1422 if (data != null) { 1423 InstallArgs args = data.args; 1424 PackageInstalledInfo parentRes = data.res; 1425 1426 final boolean grantPermissions = (args.installFlags 1427 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1428 final boolean killApp = (args.installFlags 1429 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1430 final String[] grantedPermissions = args.installGrantPermissions; 1431 1432 // Handle the parent package 1433 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1434 grantedPermissions, didRestore, args.installerPackageName, 1435 args.observer); 1436 1437 // Handle the child packages 1438 final int childCount = (parentRes.addedChildPackages != null) 1439 ? parentRes.addedChildPackages.size() : 0; 1440 for (int i = 0; i < childCount; i++) { 1441 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1442 handlePackagePostInstall(childRes, grantPermissions, killApp, 1443 grantedPermissions, false, args.installerPackageName, 1444 args.observer); 1445 } 1446 1447 // Log tracing if needed 1448 if (args.traceMethod != null) { 1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1450 args.traceCookie); 1451 } 1452 } else { 1453 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1454 } 1455 1456 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1457 } break; 1458 case UPDATED_MEDIA_STATUS: { 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1460 boolean reportStatus = msg.arg1 == 1; 1461 boolean doGc = msg.arg2 == 1; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1463 if (doGc) { 1464 // Force a gc to clear up stale containers. 1465 Runtime.getRuntime().gc(); 1466 } 1467 if (msg.obj != null) { 1468 @SuppressWarnings("unchecked") 1469 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1470 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1471 // Unload containers 1472 unloadAllContainers(args); 1473 } 1474 if (reportStatus) { 1475 try { 1476 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1477 PackageHelper.getMountService().finishMediaUpdate(); 1478 } catch (RemoteException e) { 1479 Log.e(TAG, "MountService not running?"); 1480 } 1481 } 1482 } break; 1483 case WRITE_SETTINGS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_SETTINGS); 1487 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1488 mSettings.writeLPr(); 1489 mDirtyUsers.clear(); 1490 } 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1492 } break; 1493 case WRITE_PACKAGE_RESTRICTIONS: { 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1495 synchronized (mPackages) { 1496 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1497 for (int userId : mDirtyUsers) { 1498 mSettings.writePackageRestrictionsLPr(userId); 1499 } 1500 mDirtyUsers.clear(); 1501 } 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1503 } break; 1504 case WRITE_PACKAGE_LIST: { 1505 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1506 synchronized (mPackages) { 1507 removeMessages(WRITE_PACKAGE_LIST); 1508 mSettings.writePackageListLPr(msg.arg1); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case CHECK_PENDING_VERIFICATION: { 1513 final int verificationId = msg.arg1; 1514 final PackageVerificationState state = mPendingVerification.get(verificationId); 1515 1516 if ((state != null) && !state.timeoutExtended()) { 1517 final InstallArgs args = state.getInstallArgs(); 1518 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1519 1520 Slog.i(TAG, "Verification timed out for " + originUri); 1521 mPendingVerification.remove(verificationId); 1522 1523 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1524 1525 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1526 Slog.i(TAG, "Continuing with installation of " + originUri); 1527 state.setVerifierResponse(Binder.getCallingUid(), 1528 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1529 broadcastPackageVerified(verificationId, originUri, 1530 PackageManager.VERIFICATION_ALLOW, 1531 state.getInstallArgs().getUser()); 1532 try { 1533 ret = args.copyApk(mContainerService, true); 1534 } catch (RemoteException e) { 1535 Slog.e(TAG, "Could not contact the ContainerService"); 1536 } 1537 } else { 1538 broadcastPackageVerified(verificationId, originUri, 1539 PackageManager.VERIFICATION_REJECT, 1540 state.getInstallArgs().getUser()); 1541 } 1542 1543 Trace.asyncTraceEnd( 1544 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1545 1546 processPendingInstall(args, ret); 1547 mHandler.sendEmptyMessage(MCS_UNBIND); 1548 } 1549 break; 1550 } 1551 case PACKAGE_VERIFIED: { 1552 final int verificationId = msg.arg1; 1553 1554 final PackageVerificationState state = mPendingVerification.get(verificationId); 1555 if (state == null) { 1556 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1557 break; 1558 } 1559 1560 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1561 1562 state.setVerifierResponse(response.callerUid, response.code); 1563 1564 if (state.isVerificationComplete()) { 1565 mPendingVerification.remove(verificationId); 1566 1567 final InstallArgs args = state.getInstallArgs(); 1568 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1569 1570 int ret; 1571 if (state.isInstallAllowed()) { 1572 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1573 broadcastPackageVerified(verificationId, originUri, 1574 response.code, state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1582 } 1583 1584 Trace.asyncTraceEnd( 1585 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1586 1587 processPendingInstall(args, ret); 1588 mHandler.sendEmptyMessage(MCS_UNBIND); 1589 } 1590 1591 break; 1592 } 1593 case START_INTENT_FILTER_VERIFICATIONS: { 1594 IFVerificationParams params = (IFVerificationParams) msg.obj; 1595 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1596 params.replacing, params.pkg); 1597 break; 1598 } 1599 case INTENT_FILTER_VERIFIED: { 1600 final int verificationId = msg.arg1; 1601 1602 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1603 verificationId); 1604 if (state == null) { 1605 Slog.w(TAG, "Invalid IntentFilter verification token " 1606 + verificationId + " received"); 1607 break; 1608 } 1609 1610 final int userId = state.getUserId(); 1611 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "Processing IntentFilter verification with token:" 1614 + verificationId + " and userId:" + userId); 1615 1616 final IntentFilterVerificationResponse response = 1617 (IntentFilterVerificationResponse) msg.obj; 1618 1619 state.setVerifierResponse(response.callerUid, response.code); 1620 1621 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1622 "IntentFilter verification with token:" + verificationId 1623 + " and userId:" + userId 1624 + " is settings verifier response with response code:" 1625 + response.code); 1626 1627 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1629 + response.getFailedDomainsString()); 1630 } 1631 1632 if (state.isVerificationComplete()) { 1633 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1634 } else { 1635 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1636 "IntentFilter verification with token:" + verificationId 1637 + " was not said to be complete"); 1638 } 1639 1640 break; 1641 } 1642 } 1643 } 1644 } 1645 1646 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1647 boolean killApp, String[] grantedPermissions, 1648 boolean launchedForRestore, String installerPackage, 1649 IPackageInstallObserver2 installObserver) { 1650 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1651 // Send the removed broadcasts 1652 if (res.removedInfo != null) { 1653 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1654 } 1655 1656 // Now that we successfully installed the package, grant runtime 1657 // permissions if requested before broadcasting the install. 1658 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1659 >= Build.VERSION_CODES.M) { 1660 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1661 } 1662 1663 final boolean update = res.removedInfo != null 1664 && res.removedInfo.removedPackage != null; 1665 1666 // If this is the first time we have child packages for a disabled privileged 1667 // app that had no children, we grant requested runtime permissions to the new 1668 // children if the parent on the system image had them already granted. 1669 if (res.pkg.parentPackage != null) { 1670 synchronized (mPackages) { 1671 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1672 } 1673 } 1674 1675 synchronized (mPackages) { 1676 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1677 } 1678 1679 final String packageName = res.pkg.applicationInfo.packageName; 1680 Bundle extras = new Bundle(1); 1681 extras.putInt(Intent.EXTRA_UID, res.uid); 1682 1683 // Determine the set of users who are adding this package for 1684 // the first time vs. those who are seeing an update. 1685 int[] firstUsers = EMPTY_INT_ARRAY; 1686 int[] updateUsers = EMPTY_INT_ARRAY; 1687 if (res.origUsers == null || res.origUsers.length == 0) { 1688 firstUsers = res.newUsers; 1689 } else { 1690 for (int newUser : res.newUsers) { 1691 boolean isNew = true; 1692 for (int origUser : res.origUsers) { 1693 if (origUser == newUser) { 1694 isNew = false; 1695 break; 1696 } 1697 } 1698 if (isNew) { 1699 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1700 } else { 1701 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1702 } 1703 } 1704 } 1705 1706 // Send installed broadcasts if the install/update is not ephemeral 1707 if (!isEphemeral(res.pkg)) { 1708 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1709 1710 // Send added for users that see the package for the first time 1711 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1712 extras, 0 /*flags*/, null /*targetPackage*/, 1713 null /*finishedReceiver*/, firstUsers); 1714 1715 // Send added for users that don't see the package for the first time 1716 if (update) { 1717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1718 } 1719 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1720 extras, 0 /*flags*/, null /*targetPackage*/, 1721 null /*finishedReceiver*/, updateUsers); 1722 1723 // Send replaced for users that don't see the package for the first time 1724 if (update) { 1725 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1726 packageName, extras, 0 /*flags*/, 1727 null /*targetPackage*/, null /*finishedReceiver*/, 1728 updateUsers); 1729 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1730 null /*package*/, null /*extras*/, 0 /*flags*/, 1731 packageName /*targetPackage*/, 1732 null /*finishedReceiver*/, updateUsers); 1733 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1734 // First-install and we did a restore, so we're responsible for the 1735 // first-launch broadcast. 1736 if (DEBUG_BACKUP) { 1737 Slog.i(TAG, "Post-restore of " + packageName 1738 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1739 } 1740 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1741 } 1742 1743 // Send broadcast package appeared if forward locked/external for all users 1744 // treat asec-hosted packages like removable media on upgrade 1745 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1746 if (DEBUG_INSTALL) { 1747 Slog.i(TAG, "upgrading pkg " + res.pkg 1748 + " is ASEC-hosted -> AVAILABLE"); 1749 } 1750 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1751 ArrayList<String> pkgList = new ArrayList<>(1); 1752 pkgList.add(packageName); 1753 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1754 } 1755 } 1756 1757 // Work that needs to happen on first install within each user 1758 if (firstUsers != null && firstUsers.length > 0) { 1759 synchronized (mPackages) { 1760 for (int userId : firstUsers) { 1761 // If this app is a browser and it's newly-installed for some 1762 // users, clear any default-browser state in those users. The 1763 // app's nature doesn't depend on the user, so we can just check 1764 // its browser nature in any user and generalize. 1765 if (packageIsBrowser(packageName, userId)) { 1766 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1767 } 1768 1769 // We may also need to apply pending (restored) runtime 1770 // permission grants within these users. 1771 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1772 } 1773 } 1774 } 1775 1776 // Log current value of "unknown sources" setting 1777 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1778 getUnknownSourcesSettings()); 1779 1780 // Force a gc to clear up things 1781 Runtime.getRuntime().gc(); 1782 1783 // Remove the replaced package's older resources safely now 1784 // We delete after a gc for applications on sdcard. 1785 if (res.removedInfo != null && res.removedInfo.args != null) { 1786 synchronized (mInstallLock) { 1787 res.removedInfo.args.doPostDeleteLI(true); 1788 } 1789 } 1790 1791 if (!isEphemeral(res.pkg)) { 1792 // Notify DexManager that the package was installed for new users. 1793 // The updated users should already be indexed and the package code paths 1794 // should not change. 1795 // Don't notify the manager for ephemeral apps as they are not expected to 1796 // survive long enough to benefit of background optimizations. 1797 for (int userId : firstUsers) { 1798 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1799 mDexManager.notifyPackageInstalled(info, userId); 1800 } 1801 } 1802 } 1803 1804 // If someone is watching installs - notify them 1805 if (installObserver != null) { 1806 try { 1807 Bundle extras = extrasForInstallResult(res); 1808 installObserver.onPackageInstalled(res.name, res.returnCode, 1809 res.returnMsg, extras); 1810 } catch (RemoteException e) { 1811 Slog.i(TAG, "Observer no longer exists."); 1812 } 1813 } 1814 } 1815 1816 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1817 PackageParser.Package pkg) { 1818 if (pkg.parentPackage == null) { 1819 return; 1820 } 1821 if (pkg.requestedPermissions == null) { 1822 return; 1823 } 1824 final PackageSetting disabledSysParentPs = mSettings 1825 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1826 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1827 || !disabledSysParentPs.isPrivileged() 1828 || (disabledSysParentPs.childPackageNames != null 1829 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1830 return; 1831 } 1832 final int[] allUserIds = sUserManager.getUserIds(); 1833 final int permCount = pkg.requestedPermissions.size(); 1834 for (int i = 0; i < permCount; i++) { 1835 String permission = pkg.requestedPermissions.get(i); 1836 BasePermission bp = mSettings.mPermissions.get(permission); 1837 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1838 continue; 1839 } 1840 for (int userId : allUserIds) { 1841 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1842 permission, userId)) { 1843 grantRuntimePermission(pkg.packageName, permission, userId); 1844 } 1845 } 1846 } 1847 } 1848 1849 private StorageEventListener mStorageListener = new StorageEventListener() { 1850 @Override 1851 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1852 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1853 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1854 final String volumeUuid = vol.getFsUuid(); 1855 1856 // Clean up any users or apps that were removed or recreated 1857 // while this volume was missing 1858 reconcileUsers(volumeUuid); 1859 reconcileApps(volumeUuid); 1860 1861 // Clean up any install sessions that expired or were 1862 // cancelled while this volume was missing 1863 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1864 1865 loadPrivatePackages(vol); 1866 1867 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1868 unloadPrivatePackages(vol); 1869 } 1870 } 1871 1872 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1873 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1874 updateExternalMediaStatus(true, false); 1875 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1876 updateExternalMediaStatus(false, false); 1877 } 1878 } 1879 } 1880 1881 @Override 1882 public void onVolumeForgotten(String fsUuid) { 1883 if (TextUtils.isEmpty(fsUuid)) { 1884 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1885 return; 1886 } 1887 1888 // Remove any apps installed on the forgotten volume 1889 synchronized (mPackages) { 1890 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1891 for (PackageSetting ps : packages) { 1892 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1893 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1894 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1895 } 1896 1897 mSettings.onVolumeForgotten(fsUuid); 1898 mSettings.writeLPr(); 1899 } 1900 } 1901 }; 1902 1903 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1904 String[] grantedPermissions) { 1905 for (int userId : userIds) { 1906 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1907 } 1908 1909 // We could have touched GID membership, so flush out packages.list 1910 synchronized (mPackages) { 1911 mSettings.writePackageListLPr(); 1912 } 1913 } 1914 1915 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1916 String[] grantedPermissions) { 1917 SettingBase sb = (SettingBase) pkg.mExtras; 1918 if (sb == null) { 1919 return; 1920 } 1921 1922 PermissionsState permissionsState = sb.getPermissionsState(); 1923 1924 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1925 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1926 1927 for (String permission : pkg.requestedPermissions) { 1928 final BasePermission bp; 1929 synchronized (mPackages) { 1930 bp = mSettings.mPermissions.get(permission); 1931 } 1932 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1933 && (grantedPermissions == null 1934 || ArrayUtils.contains(grantedPermissions, permission))) { 1935 final int flags = permissionsState.getPermissionFlags(permission, userId); 1936 // Installer cannot change immutable permissions. 1937 if ((flags & immutableFlags) == 0) { 1938 grantRuntimePermission(pkg.packageName, permission, userId); 1939 } 1940 } 1941 } 1942 } 1943 1944 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1945 Bundle extras = null; 1946 switch (res.returnCode) { 1947 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1948 extras = new Bundle(); 1949 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1950 res.origPermission); 1951 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1952 res.origPackage); 1953 break; 1954 } 1955 case PackageManager.INSTALL_SUCCEEDED: { 1956 extras = new Bundle(); 1957 extras.putBoolean(Intent.EXTRA_REPLACING, 1958 res.removedInfo != null && res.removedInfo.removedPackage != null); 1959 break; 1960 } 1961 } 1962 return extras; 1963 } 1964 1965 void scheduleWriteSettingsLocked() { 1966 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1967 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1968 } 1969 } 1970 1971 void scheduleWritePackageListLocked(int userId) { 1972 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1973 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1974 msg.arg1 = userId; 1975 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1976 } 1977 } 1978 1979 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1980 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1981 scheduleWritePackageRestrictionsLocked(userId); 1982 } 1983 1984 void scheduleWritePackageRestrictionsLocked(int userId) { 1985 final int[] userIds = (userId == UserHandle.USER_ALL) 1986 ? sUserManager.getUserIds() : new int[]{userId}; 1987 for (int nextUserId : userIds) { 1988 if (!sUserManager.exists(nextUserId)) return; 1989 mDirtyUsers.add(nextUserId); 1990 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1991 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1992 } 1993 } 1994 } 1995 1996 public static PackageManagerService main(Context context, Installer installer, 1997 boolean factoryTest, boolean onlyCore) { 1998 // Self-check for initial settings. 1999 PackageManagerServiceCompilerMapping.checkProperties(); 2000 2001 PackageManagerService m = new PackageManagerService(context, installer, 2002 factoryTest, onlyCore); 2003 m.enableSystemUserPackages(); 2004 ServiceManager.addService("package", m); 2005 return m; 2006 } 2007 2008 private void enableSystemUserPackages() { 2009 if (!UserManager.isSplitSystemUser()) { 2010 return; 2011 } 2012 // For system user, enable apps based on the following conditions: 2013 // - app is whitelisted or belong to one of these groups: 2014 // -- system app which has no launcher icons 2015 // -- system app which has INTERACT_ACROSS_USERS permission 2016 // -- system IME app 2017 // - app is not in the blacklist 2018 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2019 Set<String> enableApps = new ArraySet<>(); 2020 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2021 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2022 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2023 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2024 enableApps.addAll(wlApps); 2025 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2026 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2027 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2028 enableApps.removeAll(blApps); 2029 Log.i(TAG, "Applications installed for system user: " + enableApps); 2030 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2031 UserHandle.SYSTEM); 2032 final int allAppsSize = allAps.size(); 2033 synchronized (mPackages) { 2034 for (int i = 0; i < allAppsSize; i++) { 2035 String pName = allAps.get(i); 2036 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2037 // Should not happen, but we shouldn't be failing if it does 2038 if (pkgSetting == null) { 2039 continue; 2040 } 2041 boolean install = enableApps.contains(pName); 2042 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2043 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2044 + " for system user"); 2045 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2046 } 2047 } 2048 } 2049 } 2050 2051 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2052 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2053 Context.DISPLAY_SERVICE); 2054 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2055 } 2056 2057 /** 2058 * Requests that files preopted on a secondary system partition be copied to the data partition 2059 * if possible. Note that the actual copying of the files is accomplished by init for security 2060 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2061 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2062 */ 2063 private static void requestCopyPreoptedFiles() { 2064 final int WAIT_TIME_MS = 100; 2065 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2066 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2067 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2068 // We will wait for up to 100 seconds. 2069 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2070 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2071 try { 2072 Thread.sleep(WAIT_TIME_MS); 2073 } catch (InterruptedException e) { 2074 // Do nothing 2075 } 2076 if (SystemClock.uptimeMillis() > timeEnd) { 2077 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2078 Slog.wtf(TAG, "cppreopt did not finish!"); 2079 break; 2080 } 2081 } 2082 } 2083 } 2084 2085 public PackageManagerService(Context context, Installer installer, 2086 boolean factoryTest, boolean onlyCore) { 2087 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2088 SystemClock.uptimeMillis()); 2089 2090 if (mSdkVersion <= 0) { 2091 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2092 } 2093 2094 mContext = context; 2095 2096 mPermissionReviewRequired = context.getResources().getBoolean( 2097 R.bool.config_permissionReviewRequired); 2098 2099 mFactoryTest = factoryTest; 2100 mOnlyCore = onlyCore; 2101 mMetrics = new DisplayMetrics(); 2102 mSettings = new Settings(mPackages); 2103 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2104 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2105 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2106 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2107 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2108 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2109 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2110 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2111 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2112 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2113 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2114 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2115 2116 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2117 if (separateProcesses != null && separateProcesses.length() > 0) { 2118 if ("*".equals(separateProcesses)) { 2119 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2120 mSeparateProcesses = null; 2121 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2122 } else { 2123 mDefParseFlags = 0; 2124 mSeparateProcesses = separateProcesses.split(","); 2125 Slog.w(TAG, "Running with debug.separate_processes: " 2126 + separateProcesses); 2127 } 2128 } else { 2129 mDefParseFlags = 0; 2130 mSeparateProcesses = null; 2131 } 2132 2133 mInstaller = installer; 2134 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2135 "*dexopt*"); 2136 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2137 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2138 2139 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2140 FgThread.get().getLooper()); 2141 2142 getDefaultDisplayMetrics(context, mMetrics); 2143 2144 SystemConfig systemConfig = SystemConfig.getInstance(); 2145 mGlobalGids = systemConfig.getGlobalGids(); 2146 mSystemPermissions = systemConfig.getSystemPermissions(); 2147 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2148 2149 mProtectedPackages = new ProtectedPackages(mContext); 2150 2151 synchronized (mInstallLock) { 2152 // writer 2153 synchronized (mPackages) { 2154 mHandlerThread = new ServiceThread(TAG, 2155 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2156 mHandlerThread.start(); 2157 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2158 mProcessLoggingHandler = new ProcessLoggingHandler(); 2159 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2160 2161 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2162 2163 File dataDir = Environment.getDataDirectory(); 2164 mAppInstallDir = new File(dataDir, "app"); 2165 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2166 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2167 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2168 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2169 2170 sUserManager = new UserManagerService(context, this, mPackages); 2171 2172 // Propagate permission configuration in to package manager. 2173 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2174 = systemConfig.getPermissions(); 2175 for (int i=0; i<permConfig.size(); i++) { 2176 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2177 BasePermission bp = mSettings.mPermissions.get(perm.name); 2178 if (bp == null) { 2179 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2180 mSettings.mPermissions.put(perm.name, bp); 2181 } 2182 if (perm.gids != null) { 2183 bp.setGids(perm.gids, perm.perUser); 2184 } 2185 } 2186 2187 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2188 for (int i=0; i<libConfig.size(); i++) { 2189 mSharedLibraries.put(libConfig.keyAt(i), 2190 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2191 } 2192 2193 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2194 2195 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2196 2197 if (mFirstBoot) { 2198 requestCopyPreoptedFiles(); 2199 } 2200 2201 String customResolverActivity = Resources.getSystem().getString( 2202 R.string.config_customResolverActivity); 2203 if (TextUtils.isEmpty(customResolverActivity)) { 2204 customResolverActivity = null; 2205 } else { 2206 mCustomResolverComponentName = ComponentName.unflattenFromString( 2207 customResolverActivity); 2208 } 2209 2210 long startTime = SystemClock.uptimeMillis(); 2211 2212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2213 startTime); 2214 2215 // Set flag to monitor and not change apk file paths when 2216 // scanning install directories. 2217 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2218 2219 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2220 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2221 2222 if (bootClassPath == null) { 2223 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2224 } 2225 2226 if (systemServerClassPath == null) { 2227 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2228 } 2229 2230 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2231 final String[] dexCodeInstructionSets = 2232 getDexCodeInstructionSets( 2233 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2234 2235 /** 2236 * Ensure all external libraries have had dexopt run on them. 2237 */ 2238 if (mSharedLibraries.size() > 0) { 2239 // NOTE: For now, we're compiling these system "shared libraries" 2240 // (and framework jars) into all available architectures. It's possible 2241 // to compile them only when we come across an app that uses them (there's 2242 // already logic for that in scanPackageLI) but that adds some complexity. 2243 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2244 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2245 final String lib = libEntry.path; 2246 if (lib == null) { 2247 continue; 2248 } 2249 2250 try { 2251 // Shared libraries do not have profiles so we perform a full 2252 // AOT compilation (if needed). 2253 int dexoptNeeded = DexFile.getDexOptNeeded( 2254 lib, dexCodeInstructionSet, 2255 getCompilerFilterForReason(REASON_SHARED_APK), 2256 false /* newProfile */); 2257 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2258 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2259 dexCodeInstructionSet, dexoptNeeded, null, 2260 DEXOPT_PUBLIC, 2261 getCompilerFilterForReason(REASON_SHARED_APK), 2262 StorageManager.UUID_PRIVATE_INTERNAL, 2263 SKIP_SHARED_LIBRARY_CHECK); 2264 } 2265 } catch (FileNotFoundException e) { 2266 Slog.w(TAG, "Library not found: " + lib); 2267 } catch (IOException | InstallerException e) { 2268 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2269 + e.getMessage()); 2270 } 2271 } 2272 } 2273 } 2274 2275 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2276 2277 final VersionInfo ver = mSettings.getInternalVersion(); 2278 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2279 2280 // when upgrading from pre-M, promote system app permissions from install to runtime 2281 mPromoteSystemApps = 2282 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2283 2284 // When upgrading from pre-N, we need to handle package extraction like first boot, 2285 // as there is no profiling data available. 2286 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2287 2288 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2289 2290 // save off the names of pre-existing system packages prior to scanning; we don't 2291 // want to automatically grant runtime permissions for new system apps 2292 if (mPromoteSystemApps) { 2293 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2294 while (pkgSettingIter.hasNext()) { 2295 PackageSetting ps = pkgSettingIter.next(); 2296 if (isSystemApp(ps)) { 2297 mExistingSystemPackages.add(ps.name); 2298 } 2299 } 2300 } 2301 2302 // Collect vendor overlay packages. 2303 // (Do this before scanning any apps.) 2304 // For security and version matching reason, only consider 2305 // overlay packages if they reside in the right directory. 2306 File vendorOverlayDir; 2307 String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY); 2308 if (!overlaySkuDir.isEmpty()) { 2309 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir); 2310 } else { 2311 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2312 } 2313 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2314 | PackageParser.PARSE_IS_SYSTEM 2315 | PackageParser.PARSE_IS_SYSTEM_DIR 2316 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2317 2318 // Find base frameworks (resource packages without code). 2319 scanDirTracedLI(frameworkDir, mDefParseFlags 2320 | PackageParser.PARSE_IS_SYSTEM 2321 | PackageParser.PARSE_IS_SYSTEM_DIR 2322 | PackageParser.PARSE_IS_PRIVILEGED, 2323 scanFlags | SCAN_NO_DEX, 0); 2324 2325 // Collected privileged system packages. 2326 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2327 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2328 | PackageParser.PARSE_IS_SYSTEM 2329 | PackageParser.PARSE_IS_SYSTEM_DIR 2330 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2331 2332 // Collect ordinary system packages. 2333 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2334 scanDirTracedLI(systemAppDir, mDefParseFlags 2335 | PackageParser.PARSE_IS_SYSTEM 2336 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2337 2338 // Collect all vendor packages. 2339 File vendorAppDir = new File("/vendor/app"); 2340 try { 2341 vendorAppDir = vendorAppDir.getCanonicalFile(); 2342 } catch (IOException e) { 2343 // failed to look up canonical path, continue with original one 2344 } 2345 scanDirTracedLI(vendorAppDir, mDefParseFlags 2346 | PackageParser.PARSE_IS_SYSTEM 2347 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2348 2349 // Collect all OEM packages. 2350 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2351 scanDirTracedLI(oemAppDir, mDefParseFlags 2352 | PackageParser.PARSE_IS_SYSTEM 2353 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2354 2355 // Prune any system packages that no longer exist. 2356 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2357 if (!mOnlyCore) { 2358 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2359 while (psit.hasNext()) { 2360 PackageSetting ps = psit.next(); 2361 2362 /* 2363 * If this is not a system app, it can't be a 2364 * disable system app. 2365 */ 2366 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2367 continue; 2368 } 2369 2370 /* 2371 * If the package is scanned, it's not erased. 2372 */ 2373 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2374 if (scannedPkg != null) { 2375 /* 2376 * If the system app is both scanned and in the 2377 * disabled packages list, then it must have been 2378 * added via OTA. Remove it from the currently 2379 * scanned package so the previously user-installed 2380 * application can be scanned. 2381 */ 2382 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2383 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2384 + ps.name + "; removing system app. Last known codePath=" 2385 + ps.codePathString + ", installStatus=" + ps.installStatus 2386 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2387 + scannedPkg.mVersionCode); 2388 removePackageLI(scannedPkg, true); 2389 mExpectingBetter.put(ps.name, ps.codePath); 2390 } 2391 2392 continue; 2393 } 2394 2395 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2396 psit.remove(); 2397 logCriticalInfo(Log.WARN, "System package " + ps.name 2398 + " no longer exists; it's data will be wiped"); 2399 // Actual deletion of code and data will be handled by later 2400 // reconciliation step 2401 } else { 2402 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2403 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2404 possiblyDeletedUpdatedSystemApps.add(ps.name); 2405 } 2406 } 2407 } 2408 } 2409 2410 //look for any incomplete package installations 2411 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2412 for (int i = 0; i < deletePkgsList.size(); i++) { 2413 // Actual deletion of code and data will be handled by later 2414 // reconciliation step 2415 final String packageName = deletePkgsList.get(i).name; 2416 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2417 synchronized (mPackages) { 2418 mSettings.removePackageLPw(packageName); 2419 } 2420 } 2421 2422 //delete tmp files 2423 deleteTempPackageFiles(); 2424 2425 // Remove any shared userIDs that have no associated packages 2426 mSettings.pruneSharedUsersLPw(); 2427 2428 if (!mOnlyCore) { 2429 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2430 SystemClock.uptimeMillis()); 2431 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2432 2433 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2434 | PackageParser.PARSE_FORWARD_LOCK, 2435 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2436 2437 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2438 | PackageParser.PARSE_IS_EPHEMERAL, 2439 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2440 2441 /** 2442 * Remove disable package settings for any updated system 2443 * apps that were removed via an OTA. If they're not a 2444 * previously-updated app, remove them completely. 2445 * Otherwise, just revoke their system-level permissions. 2446 */ 2447 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2448 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2449 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2450 2451 String msg; 2452 if (deletedPkg == null) { 2453 msg = "Updated system package " + deletedAppName 2454 + " no longer exists; it's data will be wiped"; 2455 // Actual deletion of code and data will be handled by later 2456 // reconciliation step 2457 } else { 2458 msg = "Updated system app + " + deletedAppName 2459 + " no longer present; removing system privileges for " 2460 + deletedAppName; 2461 2462 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2463 2464 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2465 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2466 } 2467 logCriticalInfo(Log.WARN, msg); 2468 } 2469 2470 /** 2471 * Make sure all system apps that we expected to appear on 2472 * the userdata partition actually showed up. If they never 2473 * appeared, crawl back and revive the system version. 2474 */ 2475 for (int i = 0; i < mExpectingBetter.size(); i++) { 2476 final String packageName = mExpectingBetter.keyAt(i); 2477 if (!mPackages.containsKey(packageName)) { 2478 final File scanFile = mExpectingBetter.valueAt(i); 2479 2480 logCriticalInfo(Log.WARN, "Expected better " + packageName 2481 + " but never showed up; reverting to system"); 2482 2483 int reparseFlags = mDefParseFlags; 2484 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2485 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2486 | PackageParser.PARSE_IS_SYSTEM_DIR 2487 | PackageParser.PARSE_IS_PRIVILEGED; 2488 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR; 2491 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2492 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR; 2494 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2495 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR; 2497 } else { 2498 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2499 continue; 2500 } 2501 2502 mSettings.enableSystemPackageLPw(packageName); 2503 2504 try { 2505 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2506 } catch (PackageManagerException e) { 2507 Slog.e(TAG, "Failed to parse original system package: " 2508 + e.getMessage()); 2509 } 2510 } 2511 } 2512 } 2513 mExpectingBetter.clear(); 2514 2515 // Resolve the storage manager. 2516 mStorageManagerPackage = getStorageManagerPackageName(); 2517 2518 // Resolve protected action filters. Only the setup wizard is allowed to 2519 // have a high priority filter for these actions. 2520 mSetupWizardPackage = getSetupWizardPackageName(); 2521 if (mProtectedFilters.size() > 0) { 2522 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2523 Slog.i(TAG, "No setup wizard;" 2524 + " All protected intents capped to priority 0"); 2525 } 2526 for (ActivityIntentInfo filter : mProtectedFilters) { 2527 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2528 if (DEBUG_FILTERS) { 2529 Slog.i(TAG, "Found setup wizard;" 2530 + " allow priority " + filter.getPriority() + ";" 2531 + " package: " + filter.activity.info.packageName 2532 + " activity: " + filter.activity.className 2533 + " priority: " + filter.getPriority()); 2534 } 2535 // skip setup wizard; allow it to keep the high priority filter 2536 continue; 2537 } 2538 Slog.w(TAG, "Protected action; cap priority to 0;" 2539 + " package: " + filter.activity.info.packageName 2540 + " activity: " + filter.activity.className 2541 + " origPrio: " + filter.getPriority()); 2542 filter.setPriority(0); 2543 } 2544 } 2545 mDeferProtectedFilters = false; 2546 mProtectedFilters.clear(); 2547 2548 // Now that we know all of the shared libraries, update all clients to have 2549 // the correct library paths. 2550 updateAllSharedLibrariesLPw(); 2551 2552 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2553 // NOTE: We ignore potential failures here during a system scan (like 2554 // the rest of the commands above) because there's precious little we 2555 // can do about it. A settings error is reported, though. 2556 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2557 false /* boot complete */); 2558 } 2559 2560 // Now that we know all the packages we are keeping, 2561 // read and update their last usage times. 2562 mPackageUsage.read(mPackages); 2563 mCompilerStats.read(); 2564 2565 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2566 SystemClock.uptimeMillis()); 2567 Slog.i(TAG, "Time to scan packages: " 2568 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2569 + " seconds"); 2570 2571 // If the platform SDK has changed since the last time we booted, 2572 // we need to re-grant app permission to catch any new ones that 2573 // appear. This is really a hack, and means that apps can in some 2574 // cases get permissions that the user didn't initially explicitly 2575 // allow... it would be nice to have some better way to handle 2576 // this situation. 2577 int updateFlags = UPDATE_PERMISSIONS_ALL; 2578 if (ver.sdkVersion != mSdkVersion) { 2579 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2580 + mSdkVersion + "; regranting permissions for internal storage"); 2581 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2582 } 2583 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2584 ver.sdkVersion = mSdkVersion; 2585 2586 // If this is the first boot or an update from pre-M, and it is a normal 2587 // boot, then we need to initialize the default preferred apps across 2588 // all defined users. 2589 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2590 for (UserInfo user : sUserManager.getUsers(true)) { 2591 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2592 applyFactoryDefaultBrowserLPw(user.id); 2593 primeDomainVerificationsLPw(user.id); 2594 } 2595 } 2596 2597 // Prepare storage for system user really early during boot, 2598 // since core system apps like SettingsProvider and SystemUI 2599 // can't wait for user to start 2600 final int storageFlags; 2601 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2602 storageFlags = StorageManager.FLAG_STORAGE_DE; 2603 } else { 2604 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2605 } 2606 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2607 storageFlags); 2608 2609 // If this is first boot after an OTA, and a normal boot, then 2610 // we need to clear code cache directories. 2611 // Note that we do *not* clear the application profiles. These remain valid 2612 // across OTAs and are used to drive profile verification (post OTA) and 2613 // profile compilation (without waiting to collect a fresh set of profiles). 2614 if (mIsUpgrade && !onlyCore) { 2615 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2616 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2617 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2618 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2619 // No apps are running this early, so no need to freeze 2620 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2621 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2622 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2623 } 2624 } 2625 ver.fingerprint = Build.FINGERPRINT; 2626 } 2627 2628 checkDefaultBrowser(); 2629 2630 // clear only after permissions and other defaults have been updated 2631 mExistingSystemPackages.clear(); 2632 mPromoteSystemApps = false; 2633 2634 // All the changes are done during package scanning. 2635 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2636 2637 // can downgrade to reader 2638 mSettings.writeLPr(); 2639 2640 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2641 // early on (before the package manager declares itself as early) because other 2642 // components in the system server might ask for package contexts for these apps. 2643 // 2644 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2645 // (i.e, that the data partition is unavailable). 2646 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2647 long start = System.nanoTime(); 2648 List<PackageParser.Package> coreApps = new ArrayList<>(); 2649 for (PackageParser.Package pkg : mPackages.values()) { 2650 if (pkg.coreApp) { 2651 coreApps.add(pkg); 2652 } 2653 } 2654 2655 int[] stats = performDexOptUpgrade(coreApps, false, 2656 getCompilerFilterForReason(REASON_CORE_APP)); 2657 2658 final int elapsedTimeSeconds = 2659 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2660 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2661 2662 if (DEBUG_DEXOPT) { 2663 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2664 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2665 } 2666 2667 2668 // TODO: Should we log these stats to tron too ? 2669 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2670 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2671 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2672 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2673 } 2674 2675 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2676 SystemClock.uptimeMillis()); 2677 2678 if (!mOnlyCore) { 2679 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2680 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2681 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2682 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2683 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2684 mIntentFilterVerifierComponent); 2685 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2686 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2687 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2688 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2689 } else { 2690 mRequiredVerifierPackage = null; 2691 mRequiredInstallerPackage = null; 2692 mRequiredUninstallerPackage = null; 2693 mIntentFilterVerifierComponent = null; 2694 mIntentFilterVerifier = null; 2695 mServicesSystemSharedLibraryPackageName = null; 2696 mSharedSystemSharedLibraryPackageName = null; 2697 } 2698 2699 mInstallerService = new PackageInstallerService(context, this); 2700 2701 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2702 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2703 // both the installer and resolver must be present to enable ephemeral 2704 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2705 if (DEBUG_EPHEMERAL) { 2706 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2707 + " installer:" + ephemeralInstallerComponent); 2708 } 2709 mEphemeralResolverComponent = ephemeralResolverComponent; 2710 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2711 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2712 mEphemeralResolverConnection = 2713 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2714 } else { 2715 if (DEBUG_EPHEMERAL) { 2716 final String missingComponent = 2717 (ephemeralResolverComponent == null) 2718 ? (ephemeralInstallerComponent == null) 2719 ? "resolver and installer" 2720 : "resolver" 2721 : "installer"; 2722 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2723 } 2724 mEphemeralResolverComponent = null; 2725 mEphemeralInstallerComponent = null; 2726 mEphemeralResolverConnection = null; 2727 } 2728 2729 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2730 2731 // Read and update the usage of dex files. 2732 // Do this at the end of PM init so that all the packages have their 2733 // data directory reconciled. 2734 // At this point we know the code paths of the packages, so we can validate 2735 // the disk file and build the internal cache. 2736 // The usage file is expected to be small so loading and verifying it 2737 // should take a fairly small time compare to the other activities (e.g. package 2738 // scanning). 2739 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2740 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2741 for (int userId : currentUserIds) { 2742 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2743 } 2744 mDexManager.load(userPackages); 2745 } // synchronized (mPackages) 2746 } // synchronized (mInstallLock) 2747 2748 // Now after opening every single application zip, make sure they 2749 // are all flushed. Not really needed, but keeps things nice and 2750 // tidy. 2751 Runtime.getRuntime().gc(); 2752 2753 // The initial scanning above does many calls into installd while 2754 // holding the mPackages lock, but we're mostly interested in yelling 2755 // once we have a booted system. 2756 mInstaller.setWarnIfHeld(mPackages); 2757 2758 // Expose private service for system components to use. 2759 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2760 } 2761 2762 @Override 2763 public boolean isFirstBoot() { 2764 return mFirstBoot; 2765 } 2766 2767 @Override 2768 public boolean isOnlyCoreApps() { 2769 return mOnlyCore; 2770 } 2771 2772 @Override 2773 public boolean isUpgrade() { 2774 return mIsUpgrade; 2775 } 2776 2777 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2778 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2779 2780 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2781 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2782 UserHandle.USER_SYSTEM); 2783 if (matches.size() == 1) { 2784 return matches.get(0).getComponentInfo().packageName; 2785 } else if (matches.size() == 0) { 2786 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2787 return null; 2788 } 2789 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2790 } 2791 2792 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2793 synchronized (mPackages) { 2794 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2795 if (libraryEntry == null) { 2796 throw new IllegalStateException("Missing required shared library:" + libraryName); 2797 } 2798 return libraryEntry.apk; 2799 } 2800 } 2801 2802 private @NonNull String getRequiredInstallerLPr() { 2803 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2804 intent.addCategory(Intent.CATEGORY_DEFAULT); 2805 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2806 2807 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2808 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2809 UserHandle.USER_SYSTEM); 2810 if (matches.size() == 1) { 2811 ResolveInfo resolveInfo = matches.get(0); 2812 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2813 throw new RuntimeException("The installer must be a privileged app"); 2814 } 2815 return matches.get(0).getComponentInfo().packageName; 2816 } else { 2817 throw new RuntimeException("There must be exactly one installer; found " + matches); 2818 } 2819 } 2820 2821 private @NonNull String getRequiredUninstallerLPr() { 2822 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2823 intent.addCategory(Intent.CATEGORY_DEFAULT); 2824 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2825 2826 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2827 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2828 UserHandle.USER_SYSTEM); 2829 if (resolveInfo == null || 2830 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2831 throw new RuntimeException("There must be exactly one uninstaller; found " 2832 + resolveInfo); 2833 } 2834 return resolveInfo.getComponentInfo().packageName; 2835 } 2836 2837 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2838 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2839 2840 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2841 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2842 UserHandle.USER_SYSTEM); 2843 ResolveInfo best = null; 2844 final int N = matches.size(); 2845 for (int i = 0; i < N; i++) { 2846 final ResolveInfo cur = matches.get(i); 2847 final String packageName = cur.getComponentInfo().packageName; 2848 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2849 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2850 continue; 2851 } 2852 2853 if (best == null || cur.priority > best.priority) { 2854 best = cur; 2855 } 2856 } 2857 2858 if (best != null) { 2859 return best.getComponentInfo().getComponentName(); 2860 } else { 2861 throw new RuntimeException("There must be at least one intent filter verifier"); 2862 } 2863 } 2864 2865 private @Nullable ComponentName getEphemeralResolverLPr() { 2866 final String[] packageArray = 2867 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2868 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2869 if (DEBUG_EPHEMERAL) { 2870 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2871 } 2872 return null; 2873 } 2874 2875 final int resolveFlags = 2876 MATCH_DIRECT_BOOT_AWARE 2877 | MATCH_DIRECT_BOOT_UNAWARE 2878 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2879 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2880 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2881 resolveFlags, UserHandle.USER_SYSTEM); 2882 2883 final int N = resolvers.size(); 2884 if (N == 0) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2887 } 2888 return null; 2889 } 2890 2891 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2892 for (int i = 0; i < N; i++) { 2893 final ResolveInfo info = resolvers.get(i); 2894 2895 if (info.serviceInfo == null) { 2896 continue; 2897 } 2898 2899 final String packageName = info.serviceInfo.packageName; 2900 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2901 if (DEBUG_EPHEMERAL) { 2902 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2903 + " pkg: " + packageName + ", info:" + info); 2904 } 2905 continue; 2906 } 2907 2908 if (DEBUG_EPHEMERAL) { 2909 Slog.v(TAG, "Ephemeral resolver found;" 2910 + " pkg: " + packageName + ", info:" + info); 2911 } 2912 return new ComponentName(packageName, info.serviceInfo.name); 2913 } 2914 if (DEBUG_EPHEMERAL) { 2915 Slog.v(TAG, "Ephemeral resolver NOT found"); 2916 } 2917 return null; 2918 } 2919 2920 private @Nullable ComponentName getEphemeralInstallerLPr() { 2921 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2922 intent.addCategory(Intent.CATEGORY_DEFAULT); 2923 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2924 2925 final int resolveFlags = 2926 MATCH_DIRECT_BOOT_AWARE 2927 | MATCH_DIRECT_BOOT_UNAWARE 2928 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2929 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2930 resolveFlags, UserHandle.USER_SYSTEM); 2931 if (matches.size() == 0) { 2932 return null; 2933 } else if (matches.size() == 1) { 2934 return matches.get(0).getComponentInfo().getComponentName(); 2935 } else { 2936 throw new RuntimeException( 2937 "There must be at most one ephemeral installer; found " + matches); 2938 } 2939 } 2940 2941 private void primeDomainVerificationsLPw(int userId) { 2942 if (DEBUG_DOMAIN_VERIFICATION) { 2943 Slog.d(TAG, "Priming domain verifications in user " + userId); 2944 } 2945 2946 SystemConfig systemConfig = SystemConfig.getInstance(); 2947 ArraySet<String> packages = systemConfig.getLinkedApps(); 2948 ArraySet<String> domains = new ArraySet<String>(); 2949 2950 for (String packageName : packages) { 2951 PackageParser.Package pkg = mPackages.get(packageName); 2952 if (pkg != null) { 2953 if (!pkg.isSystemApp()) { 2954 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2955 continue; 2956 } 2957 2958 domains.clear(); 2959 for (PackageParser.Activity a : pkg.activities) { 2960 for (ActivityIntentInfo filter : a.intents) { 2961 if (hasValidDomains(filter)) { 2962 domains.addAll(filter.getHostsList()); 2963 } 2964 } 2965 } 2966 2967 if (domains.size() > 0) { 2968 if (DEBUG_DOMAIN_VERIFICATION) { 2969 Slog.v(TAG, " + " + packageName); 2970 } 2971 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2972 // state w.r.t. the formal app-linkage "no verification attempted" state; 2973 // and then 'always' in the per-user state actually used for intent resolution. 2974 final IntentFilterVerificationInfo ivi; 2975 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2976 new ArrayList<String>(domains)); 2977 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2978 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2979 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2980 } else { 2981 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2982 + "' does not handle web links"); 2983 } 2984 } else { 2985 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2986 } 2987 } 2988 2989 scheduleWritePackageRestrictionsLocked(userId); 2990 scheduleWriteSettingsLocked(); 2991 } 2992 2993 private void applyFactoryDefaultBrowserLPw(int userId) { 2994 // The default browser app's package name is stored in a string resource, 2995 // with a product-specific overlay used for vendor customization. 2996 String browserPkg = mContext.getResources().getString( 2997 com.android.internal.R.string.default_browser); 2998 if (!TextUtils.isEmpty(browserPkg)) { 2999 // non-empty string => required to be a known package 3000 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3001 if (ps == null) { 3002 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3003 browserPkg = null; 3004 } else { 3005 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3006 } 3007 } 3008 3009 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3010 // default. If there's more than one, just leave everything alone. 3011 if (browserPkg == null) { 3012 calculateDefaultBrowserLPw(userId); 3013 } 3014 } 3015 3016 private void calculateDefaultBrowserLPw(int userId) { 3017 List<String> allBrowsers = resolveAllBrowserApps(userId); 3018 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3019 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3020 } 3021 3022 private List<String> resolveAllBrowserApps(int userId) { 3023 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3024 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3025 PackageManager.MATCH_ALL, userId); 3026 3027 final int count = list.size(); 3028 List<String> result = new ArrayList<String>(count); 3029 for (int i=0; i<count; i++) { 3030 ResolveInfo info = list.get(i); 3031 if (info.activityInfo == null 3032 || !info.handleAllWebDataURI 3033 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3034 || result.contains(info.activityInfo.packageName)) { 3035 continue; 3036 } 3037 result.add(info.activityInfo.packageName); 3038 } 3039 3040 return result; 3041 } 3042 3043 private boolean packageIsBrowser(String packageName, int userId) { 3044 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3045 PackageManager.MATCH_ALL, userId); 3046 final int N = list.size(); 3047 for (int i = 0; i < N; i++) { 3048 ResolveInfo info = list.get(i); 3049 if (packageName.equals(info.activityInfo.packageName)) { 3050 return true; 3051 } 3052 } 3053 return false; 3054 } 3055 3056 private void checkDefaultBrowser() { 3057 final int myUserId = UserHandle.myUserId(); 3058 final String packageName = getDefaultBrowserPackageName(myUserId); 3059 if (packageName != null) { 3060 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3061 if (info == null) { 3062 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3063 synchronized (mPackages) { 3064 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3065 } 3066 } 3067 } 3068 } 3069 3070 @Override 3071 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3072 throws RemoteException { 3073 try { 3074 return super.onTransact(code, data, reply, flags); 3075 } catch (RuntimeException e) { 3076 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3077 Slog.wtf(TAG, "Package Manager Crash", e); 3078 } 3079 throw e; 3080 } 3081 } 3082 3083 static int[] appendInts(int[] cur, int[] add) { 3084 if (add == null) return cur; 3085 if (cur == null) return add; 3086 final int N = add.length; 3087 for (int i=0; i<N; i++) { 3088 cur = appendInt(cur, add[i]); 3089 } 3090 return cur; 3091 } 3092 3093 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3094 if (!sUserManager.exists(userId)) return null; 3095 if (ps == null) { 3096 return null; 3097 } 3098 final PackageParser.Package p = ps.pkg; 3099 if (p == null) { 3100 return null; 3101 } 3102 3103 final PermissionsState permissionsState = ps.getPermissionsState(); 3104 3105 // Compute GIDs only if requested 3106 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3107 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3108 // Compute granted permissions only if package has requested permissions 3109 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3110 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3111 final PackageUserState state = ps.readUserState(userId); 3112 3113 return PackageParser.generatePackageInfo(p, gids, flags, 3114 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3115 } 3116 3117 @Override 3118 public void checkPackageStartable(String packageName, int userId) { 3119 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3120 3121 synchronized (mPackages) { 3122 final PackageSetting ps = mSettings.mPackages.get(packageName); 3123 if (ps == null) { 3124 throw new SecurityException("Package " + packageName + " was not found!"); 3125 } 3126 3127 if (!ps.getInstalled(userId)) { 3128 throw new SecurityException( 3129 "Package " + packageName + " was not installed for user " + userId + "!"); 3130 } 3131 3132 if (mSafeMode && !ps.isSystem()) { 3133 throw new SecurityException("Package " + packageName + " not a system app!"); 3134 } 3135 3136 if (mFrozenPackages.contains(packageName)) { 3137 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3138 } 3139 3140 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3141 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3142 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3143 } 3144 } 3145 } 3146 3147 @Override 3148 public boolean isPackageAvailable(String packageName, int userId) { 3149 if (!sUserManager.exists(userId)) return false; 3150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3151 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3152 synchronized (mPackages) { 3153 PackageParser.Package p = mPackages.get(packageName); 3154 if (p != null) { 3155 final PackageSetting ps = (PackageSetting) p.mExtras; 3156 if (ps != null) { 3157 final PackageUserState state = ps.readUserState(userId); 3158 if (state != null) { 3159 return PackageParser.isAvailable(state); 3160 } 3161 } 3162 } 3163 } 3164 return false; 3165 } 3166 3167 @Override 3168 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3169 if (!sUserManager.exists(userId)) return null; 3170 flags = updateFlagsForPackage(flags, userId, packageName); 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3172 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3173 // reader 3174 synchronized (mPackages) { 3175 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3176 PackageParser.Package p = null; 3177 if (matchFactoryOnly) { 3178 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3179 if (ps != null) { 3180 return generatePackageInfo(ps, flags, userId); 3181 } 3182 } 3183 if (p == null) { 3184 p = mPackages.get(packageName); 3185 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3186 return null; 3187 } 3188 } 3189 if (DEBUG_PACKAGE_INFO) 3190 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3191 if (p != null) { 3192 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3193 } 3194 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3195 final PackageSetting ps = mSettings.mPackages.get(packageName); 3196 return generatePackageInfo(ps, flags, userId); 3197 } 3198 } 3199 return null; 3200 } 3201 3202 @Override 3203 public String[] currentToCanonicalPackageNames(String[] names) { 3204 String[] out = new String[names.length]; 3205 // reader 3206 synchronized (mPackages) { 3207 for (int i=names.length-1; i>=0; i--) { 3208 PackageSetting ps = mSettings.mPackages.get(names[i]); 3209 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3210 } 3211 } 3212 return out; 3213 } 3214 3215 @Override 3216 public String[] canonicalToCurrentPackageNames(String[] names) { 3217 String[] out = new String[names.length]; 3218 // reader 3219 synchronized (mPackages) { 3220 for (int i=names.length-1; i>=0; i--) { 3221 String cur = mSettings.mRenamedPackages.get(names[i]); 3222 out[i] = cur != null ? cur : names[i]; 3223 } 3224 } 3225 return out; 3226 } 3227 3228 @Override 3229 public int getPackageUid(String packageName, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return -1; 3231 flags = updateFlagsForPackage(flags, userId, packageName); 3232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3233 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3234 3235 // reader 3236 synchronized (mPackages) { 3237 final PackageParser.Package p = mPackages.get(packageName); 3238 if (p != null && p.isMatch(flags)) { 3239 return UserHandle.getUid(userId, p.applicationInfo.uid); 3240 } 3241 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3242 final PackageSetting ps = mSettings.mPackages.get(packageName); 3243 if (ps != null && ps.isMatch(flags)) { 3244 return UserHandle.getUid(userId, ps.appId); 3245 } 3246 } 3247 } 3248 3249 return -1; 3250 } 3251 3252 @Override 3253 public int[] getPackageGids(String packageName, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return null; 3255 flags = updateFlagsForPackage(flags, userId, packageName); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3257 false /* requireFullPermission */, false /* checkShell */, 3258 "getPackageGids"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 PackageSetting ps = (PackageSetting) p.mExtras; 3265 return ps.getPermissionsState().computeGids(userId); 3266 } 3267 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3268 final PackageSetting ps = mSettings.mPackages.get(packageName); 3269 if (ps != null && ps.isMatch(flags)) { 3270 return ps.getPermissionsState().computeGids(userId); 3271 } 3272 } 3273 } 3274 3275 return null; 3276 } 3277 3278 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3279 if (bp.perm != null) { 3280 return PackageParser.generatePermissionInfo(bp.perm, flags); 3281 } 3282 PermissionInfo pi = new PermissionInfo(); 3283 pi.name = bp.name; 3284 pi.packageName = bp.sourcePackage; 3285 pi.nonLocalizedLabel = bp.name; 3286 pi.protectionLevel = bp.protectionLevel; 3287 return pi; 3288 } 3289 3290 @Override 3291 public PermissionInfo getPermissionInfo(String name, int flags) { 3292 // reader 3293 synchronized (mPackages) { 3294 final BasePermission p = mSettings.mPermissions.get(name); 3295 if (p != null) { 3296 return generatePermissionInfo(p, flags); 3297 } 3298 return null; 3299 } 3300 } 3301 3302 @Override 3303 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3304 int flags) { 3305 // reader 3306 synchronized (mPackages) { 3307 if (group != null && !mPermissionGroups.containsKey(group)) { 3308 // This is thrown as NameNotFoundException 3309 return null; 3310 } 3311 3312 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3313 for (BasePermission p : mSettings.mPermissions.values()) { 3314 if (group == null) { 3315 if (p.perm == null || p.perm.info.group == null) { 3316 out.add(generatePermissionInfo(p, flags)); 3317 } 3318 } else { 3319 if (p.perm != null && group.equals(p.perm.info.group)) { 3320 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3321 } 3322 } 3323 } 3324 return new ParceledListSlice<>(out); 3325 } 3326 } 3327 3328 @Override 3329 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 return PackageParser.generatePermissionGroupInfo( 3333 mPermissionGroups.get(name), flags); 3334 } 3335 } 3336 3337 @Override 3338 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3339 // reader 3340 synchronized (mPackages) { 3341 final int N = mPermissionGroups.size(); 3342 ArrayList<PermissionGroupInfo> out 3343 = new ArrayList<PermissionGroupInfo>(N); 3344 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3345 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3346 } 3347 return new ParceledListSlice<>(out); 3348 } 3349 } 3350 3351 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3352 int userId) { 3353 if (!sUserManager.exists(userId)) return null; 3354 PackageSetting ps = mSettings.mPackages.get(packageName); 3355 if (ps != null) { 3356 if (ps.pkg == null) { 3357 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3358 if (pInfo != null) { 3359 return pInfo.applicationInfo; 3360 } 3361 return null; 3362 } 3363 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3364 ps.readUserState(userId), userId); 3365 } 3366 return null; 3367 } 3368 3369 @Override 3370 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3371 if (!sUserManager.exists(userId)) return null; 3372 flags = updateFlagsForApplication(flags, userId, packageName); 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3374 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3375 // writer 3376 synchronized (mPackages) { 3377 PackageParser.Package p = mPackages.get(packageName); 3378 if (DEBUG_PACKAGE_INFO) Log.v( 3379 TAG, "getApplicationInfo " + packageName 3380 + ": " + p); 3381 if (p != null) { 3382 PackageSetting ps = mSettings.mPackages.get(packageName); 3383 if (ps == null) return null; 3384 // Note: isEnabledLP() does not apply here - always return info 3385 return PackageParser.generateApplicationInfo( 3386 p, flags, ps.readUserState(userId), userId); 3387 } 3388 if ("android".equals(packageName)||"system".equals(packageName)) { 3389 return mAndroidApplication; 3390 } 3391 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3392 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3393 } 3394 } 3395 return null; 3396 } 3397 3398 @Override 3399 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3400 final IPackageDataObserver observer) { 3401 mContext.enforceCallingOrSelfPermission( 3402 android.Manifest.permission.CLEAR_APP_CACHE, null); 3403 // Queue up an async operation since clearing cache may take a little while. 3404 mHandler.post(new Runnable() { 3405 public void run() { 3406 mHandler.removeCallbacks(this); 3407 boolean success = true; 3408 synchronized (mInstallLock) { 3409 try { 3410 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3411 } catch (InstallerException e) { 3412 Slog.w(TAG, "Couldn't clear application caches: " + e); 3413 success = false; 3414 } 3415 } 3416 if (observer != null) { 3417 try { 3418 observer.onRemoveCompleted(null, success); 3419 } catch (RemoteException e) { 3420 Slog.w(TAG, "RemoveException when invoking call back"); 3421 } 3422 } 3423 } 3424 }); 3425 } 3426 3427 @Override 3428 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3429 final IntentSender pi) { 3430 mContext.enforceCallingOrSelfPermission( 3431 android.Manifest.permission.CLEAR_APP_CACHE, null); 3432 // Queue up an async operation since clearing cache may take a little while. 3433 mHandler.post(new Runnable() { 3434 public void run() { 3435 mHandler.removeCallbacks(this); 3436 boolean success = true; 3437 synchronized (mInstallLock) { 3438 try { 3439 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3440 } catch (InstallerException e) { 3441 Slog.w(TAG, "Couldn't clear application caches: " + e); 3442 success = false; 3443 } 3444 } 3445 if(pi != null) { 3446 try { 3447 // Callback via pending intent 3448 int code = success ? 1 : 0; 3449 pi.sendIntent(null, code, null, 3450 null, null); 3451 } catch (SendIntentException e1) { 3452 Slog.i(TAG, "Failed to send pending intent"); 3453 } 3454 } 3455 } 3456 }); 3457 } 3458 3459 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3460 synchronized (mInstallLock) { 3461 try { 3462 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3463 } catch (InstallerException e) { 3464 throw new IOException("Failed to free enough space", e); 3465 } 3466 } 3467 } 3468 3469 /** 3470 * Update given flags based on encryption status of current user. 3471 */ 3472 private int updateFlags(int flags, int userId) { 3473 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3474 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3475 // Caller expressed an explicit opinion about what encryption 3476 // aware/unaware components they want to see, so fall through and 3477 // give them what they want 3478 } else { 3479 // Caller expressed no opinion, so match based on user state 3480 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3481 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3482 } else { 3483 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3484 } 3485 } 3486 return flags; 3487 } 3488 3489 private UserManagerInternal getUserManagerInternal() { 3490 if (mUserManagerInternal == null) { 3491 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3492 } 3493 return mUserManagerInternal; 3494 } 3495 3496 /** 3497 * Update given flags when being used to request {@link PackageInfo}. 3498 */ 3499 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3500 boolean triaged = true; 3501 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3502 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3503 // Caller is asking for component details, so they'd better be 3504 // asking for specific encryption matching behavior, or be triaged 3505 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3506 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3507 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3508 triaged = false; 3509 } 3510 } 3511 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3512 | PackageManager.MATCH_SYSTEM_ONLY 3513 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3514 triaged = false; 3515 } 3516 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3517 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3518 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3519 } 3520 return updateFlags(flags, userId); 3521 } 3522 3523 /** 3524 * Update given flags when being used to request {@link ApplicationInfo}. 3525 */ 3526 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3527 return updateFlagsForPackage(flags, userId, cookie); 3528 } 3529 3530 /** 3531 * Update given flags when being used to request {@link ComponentInfo}. 3532 */ 3533 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3534 if (cookie instanceof Intent) { 3535 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3536 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3537 } 3538 } 3539 3540 boolean triaged = true; 3541 // Caller is asking for component details, so they'd better be 3542 // asking for specific encryption matching behavior, or be triaged 3543 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3544 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3545 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3546 triaged = false; 3547 } 3548 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3549 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3550 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3551 } 3552 3553 return updateFlags(flags, userId); 3554 } 3555 3556 /** 3557 * Update given flags when being used to request {@link ResolveInfo}. 3558 */ 3559 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3560 // Safe mode means we shouldn't match any third-party components 3561 if (mSafeMode) { 3562 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3563 } 3564 3565 return updateFlagsForComponent(flags, userId, cookie); 3566 } 3567 3568 @Override 3569 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3570 if (!sUserManager.exists(userId)) return null; 3571 flags = updateFlagsForComponent(flags, userId, component); 3572 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3573 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3574 synchronized (mPackages) { 3575 PackageParser.Activity a = mActivities.mActivities.get(component); 3576 3577 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3578 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3579 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3580 if (ps == null) return null; 3581 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3582 userId); 3583 } 3584 if (mResolveComponentName.equals(component)) { 3585 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3586 new PackageUserState(), userId); 3587 } 3588 } 3589 return null; 3590 } 3591 3592 @Override 3593 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3594 String resolvedType) { 3595 synchronized (mPackages) { 3596 if (component.equals(mResolveComponentName)) { 3597 // The resolver supports EVERYTHING! 3598 return true; 3599 } 3600 PackageParser.Activity a = mActivities.mActivities.get(component); 3601 if (a == null) { 3602 return false; 3603 } 3604 for (int i=0; i<a.intents.size(); i++) { 3605 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3606 intent.getData(), intent.getCategories(), TAG) >= 0) { 3607 return true; 3608 } 3609 } 3610 return false; 3611 } 3612 } 3613 3614 @Override 3615 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3616 if (!sUserManager.exists(userId)) return null; 3617 flags = updateFlagsForComponent(flags, userId, component); 3618 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3619 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3620 synchronized (mPackages) { 3621 PackageParser.Activity a = mReceivers.mActivities.get(component); 3622 if (DEBUG_PACKAGE_INFO) Log.v( 3623 TAG, "getReceiverInfo " + component + ": " + a); 3624 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3625 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3626 if (ps == null) return null; 3627 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3628 userId); 3629 } 3630 } 3631 return null; 3632 } 3633 3634 @Override 3635 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3636 if (!sUserManager.exists(userId)) return null; 3637 flags = updateFlagsForComponent(flags, userId, component); 3638 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3639 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3640 synchronized (mPackages) { 3641 PackageParser.Service s = mServices.mServices.get(component); 3642 if (DEBUG_PACKAGE_INFO) Log.v( 3643 TAG, "getServiceInfo " + component + ": " + s); 3644 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3645 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3646 if (ps == null) return null; 3647 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3648 userId); 3649 } 3650 } 3651 return null; 3652 } 3653 3654 @Override 3655 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3656 if (!sUserManager.exists(userId)) return null; 3657 flags = updateFlagsForComponent(flags, userId, component); 3658 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3659 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3660 synchronized (mPackages) { 3661 PackageParser.Provider p = mProviders.mProviders.get(component); 3662 if (DEBUG_PACKAGE_INFO) Log.v( 3663 TAG, "getProviderInfo " + component + ": " + p); 3664 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3665 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3666 if (ps == null) return null; 3667 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3668 userId); 3669 } 3670 } 3671 return null; 3672 } 3673 3674 @Override 3675 public String[] getSystemSharedLibraryNames() { 3676 Set<String> libSet; 3677 synchronized (mPackages) { 3678 libSet = mSharedLibraries.keySet(); 3679 int size = libSet.size(); 3680 if (size > 0) { 3681 String[] libs = new String[size]; 3682 libSet.toArray(libs); 3683 return libs; 3684 } 3685 } 3686 return null; 3687 } 3688 3689 @Override 3690 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3691 synchronized (mPackages) { 3692 return mServicesSystemSharedLibraryPackageName; 3693 } 3694 } 3695 3696 @Override 3697 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3698 synchronized (mPackages) { 3699 return mSharedSystemSharedLibraryPackageName; 3700 } 3701 } 3702 3703 @Override 3704 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3705 synchronized (mPackages) { 3706 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3707 3708 final FeatureInfo fi = new FeatureInfo(); 3709 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3710 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3711 res.add(fi); 3712 3713 return new ParceledListSlice<>(res); 3714 } 3715 } 3716 3717 @Override 3718 public boolean hasSystemFeature(String name, int version) { 3719 synchronized (mPackages) { 3720 final FeatureInfo feat = mAvailableFeatures.get(name); 3721 if (feat == null) { 3722 return false; 3723 } else { 3724 return feat.version >= version; 3725 } 3726 } 3727 } 3728 3729 @Override 3730 public int checkPermission(String permName, String pkgName, int userId) { 3731 if (!sUserManager.exists(userId)) { 3732 return PackageManager.PERMISSION_DENIED; 3733 } 3734 3735 synchronized (mPackages) { 3736 final PackageParser.Package p = mPackages.get(pkgName); 3737 if (p != null && p.mExtras != null) { 3738 final PackageSetting ps = (PackageSetting) p.mExtras; 3739 final PermissionsState permissionsState = ps.getPermissionsState(); 3740 if (permissionsState.hasPermission(permName, userId)) { 3741 return PackageManager.PERMISSION_GRANTED; 3742 } 3743 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3744 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3745 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3746 return PackageManager.PERMISSION_GRANTED; 3747 } 3748 } 3749 } 3750 3751 return PackageManager.PERMISSION_DENIED; 3752 } 3753 3754 @Override 3755 public int checkUidPermission(String permName, int uid) { 3756 final int userId = UserHandle.getUserId(uid); 3757 3758 if (!sUserManager.exists(userId)) { 3759 return PackageManager.PERMISSION_DENIED; 3760 } 3761 3762 synchronized (mPackages) { 3763 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3764 if (obj != null) { 3765 final SettingBase ps = (SettingBase) obj; 3766 final PermissionsState permissionsState = ps.getPermissionsState(); 3767 if (permissionsState.hasPermission(permName, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3771 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3772 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3773 return PackageManager.PERMISSION_GRANTED; 3774 } 3775 } else { 3776 ArraySet<String> perms = mSystemPermissions.get(uid); 3777 if (perms != null) { 3778 if (perms.contains(permName)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3782 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3783 return PackageManager.PERMISSION_GRANTED; 3784 } 3785 } 3786 } 3787 } 3788 3789 return PackageManager.PERMISSION_DENIED; 3790 } 3791 3792 @Override 3793 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3794 if (UserHandle.getCallingUserId() != userId) { 3795 mContext.enforceCallingPermission( 3796 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3797 "isPermissionRevokedByPolicy for user " + userId); 3798 } 3799 3800 if (checkPermission(permission, packageName, userId) 3801 == PackageManager.PERMISSION_GRANTED) { 3802 return false; 3803 } 3804 3805 final long identity = Binder.clearCallingIdentity(); 3806 try { 3807 final int flags = getPermissionFlags(permission, packageName, userId); 3808 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3809 } finally { 3810 Binder.restoreCallingIdentity(identity); 3811 } 3812 } 3813 3814 @Override 3815 public String getPermissionControllerPackageName() { 3816 synchronized (mPackages) { 3817 return mRequiredInstallerPackage; 3818 } 3819 } 3820 3821 /** 3822 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3823 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3824 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3825 * @param message the message to log on security exception 3826 */ 3827 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3828 boolean checkShell, String message) { 3829 if (userId < 0) { 3830 throw new IllegalArgumentException("Invalid userId " + userId); 3831 } 3832 if (checkShell) { 3833 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3834 } 3835 if (userId == UserHandle.getUserId(callingUid)) return; 3836 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3837 if (requireFullPermission) { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3840 } else { 3841 try { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3844 } catch (SecurityException se) { 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3847 } 3848 } 3849 } 3850 } 3851 3852 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3853 if (callingUid == Process.SHELL_UID) { 3854 if (userHandle >= 0 3855 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3856 throw new SecurityException("Shell does not have permission to access user " 3857 + userHandle); 3858 } else if (userHandle < 0) { 3859 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3860 + Debug.getCallers(3)); 3861 } 3862 } 3863 } 3864 3865 private BasePermission findPermissionTreeLP(String permName) { 3866 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3867 if (permName.startsWith(bp.name) && 3868 permName.length() > bp.name.length() && 3869 permName.charAt(bp.name.length()) == '.') { 3870 return bp; 3871 } 3872 } 3873 return null; 3874 } 3875 3876 private BasePermission checkPermissionTreeLP(String permName) { 3877 if (permName != null) { 3878 BasePermission bp = findPermissionTreeLP(permName); 3879 if (bp != null) { 3880 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3881 return bp; 3882 } 3883 throw new SecurityException("Calling uid " 3884 + Binder.getCallingUid() 3885 + " is not allowed to add to permission tree " 3886 + bp.name + " owned by uid " + bp.uid); 3887 } 3888 } 3889 throw new SecurityException("No permission tree found for " + permName); 3890 } 3891 3892 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3893 if (s1 == null) { 3894 return s2 == null; 3895 } 3896 if (s2 == null) { 3897 return false; 3898 } 3899 if (s1.getClass() != s2.getClass()) { 3900 return false; 3901 } 3902 return s1.equals(s2); 3903 } 3904 3905 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3906 if (pi1.icon != pi2.icon) return false; 3907 if (pi1.logo != pi2.logo) return false; 3908 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3909 if (!compareStrings(pi1.name, pi2.name)) return false; 3910 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3911 // We'll take care of setting this one. 3912 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3913 // These are not currently stored in settings. 3914 //if (!compareStrings(pi1.group, pi2.group)) return false; 3915 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3916 //if (pi1.labelRes != pi2.labelRes) return false; 3917 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3918 return true; 3919 } 3920 3921 int permissionInfoFootprint(PermissionInfo info) { 3922 int size = info.name.length(); 3923 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3924 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3925 return size; 3926 } 3927 3928 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3929 int size = 0; 3930 for (BasePermission perm : mSettings.mPermissions.values()) { 3931 if (perm.uid == tree.uid) { 3932 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3933 } 3934 } 3935 return size; 3936 } 3937 3938 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3939 // We calculate the max size of permissions defined by this uid and throw 3940 // if that plus the size of 'info' would exceed our stated maximum. 3941 if (tree.uid != Process.SYSTEM_UID) { 3942 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3943 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3944 throw new SecurityException("Permission tree size cap exceeded"); 3945 } 3946 } 3947 } 3948 3949 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3950 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3951 throw new SecurityException("Label must be specified in permission"); 3952 } 3953 BasePermission tree = checkPermissionTreeLP(info.name); 3954 BasePermission bp = mSettings.mPermissions.get(info.name); 3955 boolean added = bp == null; 3956 boolean changed = true; 3957 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3958 if (added) { 3959 enforcePermissionCapLocked(info, tree); 3960 bp = new BasePermission(info.name, tree.sourcePackage, 3961 BasePermission.TYPE_DYNAMIC); 3962 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3963 throw new SecurityException( 3964 "Not allowed to modify non-dynamic permission " 3965 + info.name); 3966 } else { 3967 if (bp.protectionLevel == fixedLevel 3968 && bp.perm.owner.equals(tree.perm.owner) 3969 && bp.uid == tree.uid 3970 && comparePermissionInfos(bp.perm.info, info)) { 3971 changed = false; 3972 } 3973 } 3974 bp.protectionLevel = fixedLevel; 3975 info = new PermissionInfo(info); 3976 info.protectionLevel = fixedLevel; 3977 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3978 bp.perm.info.packageName = tree.perm.info.packageName; 3979 bp.uid = tree.uid; 3980 if (added) { 3981 mSettings.mPermissions.put(info.name, bp); 3982 } 3983 if (changed) { 3984 if (!async) { 3985 mSettings.writeLPr(); 3986 } else { 3987 scheduleWriteSettingsLocked(); 3988 } 3989 } 3990 return added; 3991 } 3992 3993 @Override 3994 public boolean addPermission(PermissionInfo info) { 3995 synchronized (mPackages) { 3996 return addPermissionLocked(info, false); 3997 } 3998 } 3999 4000 @Override 4001 public boolean addPermissionAsync(PermissionInfo info) { 4002 synchronized (mPackages) { 4003 return addPermissionLocked(info, true); 4004 } 4005 } 4006 4007 @Override 4008 public void removePermission(String name) { 4009 synchronized (mPackages) { 4010 checkPermissionTreeLP(name); 4011 BasePermission bp = mSettings.mPermissions.get(name); 4012 if (bp != null) { 4013 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4014 throw new SecurityException( 4015 "Not allowed to modify non-dynamic permission " 4016 + name); 4017 } 4018 mSettings.mPermissions.remove(name); 4019 mSettings.writeLPr(); 4020 } 4021 } 4022 } 4023 4024 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4025 BasePermission bp) { 4026 int index = pkg.requestedPermissions.indexOf(bp.name); 4027 if (index == -1) { 4028 throw new SecurityException("Package " + pkg.packageName 4029 + " has not requested permission " + bp.name); 4030 } 4031 if (!bp.isRuntime() && !bp.isDevelopment()) { 4032 throw new SecurityException("Permission " + bp.name 4033 + " is not a changeable permission type"); 4034 } 4035 } 4036 4037 @Override 4038 public void grantRuntimePermission(String packageName, String name, final int userId) { 4039 if (!sUserManager.exists(userId)) { 4040 Log.e(TAG, "No such user:" + userId); 4041 return; 4042 } 4043 4044 mContext.enforceCallingOrSelfPermission( 4045 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4046 "grantRuntimePermission"); 4047 4048 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4049 true /* requireFullPermission */, true /* checkShell */, 4050 "grantRuntimePermission"); 4051 4052 final int uid; 4053 final SettingBase sb; 4054 4055 synchronized (mPackages) { 4056 final PackageParser.Package pkg = mPackages.get(packageName); 4057 if (pkg == null) { 4058 throw new IllegalArgumentException("Unknown package: " + packageName); 4059 } 4060 4061 final BasePermission bp = mSettings.mPermissions.get(name); 4062 if (bp == null) { 4063 throw new IllegalArgumentException("Unknown permission: " + name); 4064 } 4065 4066 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4067 4068 // If a permission review is required for legacy apps we represent 4069 // their permissions as always granted runtime ones since we need 4070 // to keep the review required permission flag per user while an 4071 // install permission's state is shared across all users. 4072 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4073 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4074 && bp.isRuntime()) { 4075 return; 4076 } 4077 4078 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4079 sb = (SettingBase) pkg.mExtras; 4080 if (sb == null) { 4081 throw new IllegalArgumentException("Unknown package: " + packageName); 4082 } 4083 4084 final PermissionsState permissionsState = sb.getPermissionsState(); 4085 4086 final int flags = permissionsState.getPermissionFlags(name, userId); 4087 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4088 throw new SecurityException("Cannot grant system fixed permission " 4089 + name + " for package " + packageName); 4090 } 4091 4092 if (bp.isDevelopment()) { 4093 // Development permissions must be handled specially, since they are not 4094 // normal runtime permissions. For now they apply to all users. 4095 if (permissionsState.grantInstallPermission(bp) != 4096 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4097 scheduleWriteSettingsLocked(); 4098 } 4099 return; 4100 } 4101 4102 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4103 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4104 return; 4105 } 4106 4107 final int result = permissionsState.grantRuntimePermission(bp, userId); 4108 switch (result) { 4109 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4110 return; 4111 } 4112 4113 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4114 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4115 mHandler.post(new Runnable() { 4116 @Override 4117 public void run() { 4118 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4119 } 4120 }); 4121 } 4122 break; 4123 } 4124 4125 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4126 4127 // Not critical if that is lost - app has to request again. 4128 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4129 } 4130 4131 // Only need to do this if user is initialized. Otherwise it's a new user 4132 // and there are no processes running as the user yet and there's no need 4133 // to make an expensive call to remount processes for the changed permissions. 4134 if (READ_EXTERNAL_STORAGE.equals(name) 4135 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4136 final long token = Binder.clearCallingIdentity(); 4137 try { 4138 if (sUserManager.isInitialized(userId)) { 4139 MountServiceInternal mountServiceInternal = LocalServices.getService( 4140 MountServiceInternal.class); 4141 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4142 } 4143 } finally { 4144 Binder.restoreCallingIdentity(token); 4145 } 4146 } 4147 } 4148 4149 @Override 4150 public void revokeRuntimePermission(String packageName, String name, int userId) { 4151 if (!sUserManager.exists(userId)) { 4152 Log.e(TAG, "No such user:" + userId); 4153 return; 4154 } 4155 4156 mContext.enforceCallingOrSelfPermission( 4157 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4158 "revokeRuntimePermission"); 4159 4160 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4161 true /* requireFullPermission */, true /* checkShell */, 4162 "revokeRuntimePermission"); 4163 4164 final int appId; 4165 4166 synchronized (mPackages) { 4167 final PackageParser.Package pkg = mPackages.get(packageName); 4168 if (pkg == null) { 4169 throw new IllegalArgumentException("Unknown package: " + packageName); 4170 } 4171 4172 final BasePermission bp = mSettings.mPermissions.get(name); 4173 if (bp == null) { 4174 throw new IllegalArgumentException("Unknown permission: " + name); 4175 } 4176 4177 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4178 4179 // If a permission review is required for legacy apps we represent 4180 // their permissions as always granted runtime ones since we need 4181 // to keep the review required permission flag per user while an 4182 // install permission's state is shared across all users. 4183 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4184 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4185 && bp.isRuntime()) { 4186 return; 4187 } 4188 4189 SettingBase sb = (SettingBase) pkg.mExtras; 4190 if (sb == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final PermissionsState permissionsState = sb.getPermissionsState(); 4195 4196 final int flags = permissionsState.getPermissionFlags(name, userId); 4197 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4198 throw new SecurityException("Cannot revoke system fixed permission " 4199 + name + " for package " + packageName); 4200 } 4201 4202 if (bp.isDevelopment()) { 4203 // Development permissions must be handled specially, since they are not 4204 // normal runtime permissions. For now they apply to all users. 4205 if (permissionsState.revokeInstallPermission(bp) != 4206 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4207 scheduleWriteSettingsLocked(); 4208 } 4209 return; 4210 } 4211 4212 if (permissionsState.revokeRuntimePermission(bp, userId) == 4213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4214 return; 4215 } 4216 4217 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4218 4219 // Critical, after this call app should never have the permission. 4220 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4221 4222 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4223 } 4224 4225 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4226 } 4227 4228 @Override 4229 public void resetRuntimePermissions() { 4230 mContext.enforceCallingOrSelfPermission( 4231 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4232 "revokeRuntimePermission"); 4233 4234 int callingUid = Binder.getCallingUid(); 4235 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4236 mContext.enforceCallingOrSelfPermission( 4237 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4238 "resetRuntimePermissions"); 4239 } 4240 4241 synchronized (mPackages) { 4242 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4243 for (int userId : UserManagerService.getInstance().getUserIds()) { 4244 final int packageCount = mPackages.size(); 4245 for (int i = 0; i < packageCount; i++) { 4246 PackageParser.Package pkg = mPackages.valueAt(i); 4247 if (!(pkg.mExtras instanceof PackageSetting)) { 4248 continue; 4249 } 4250 PackageSetting ps = (PackageSetting) pkg.mExtras; 4251 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4252 } 4253 } 4254 } 4255 } 4256 4257 @Override 4258 public int getPermissionFlags(String name, String packageName, int userId) { 4259 if (!sUserManager.exists(userId)) { 4260 return 0; 4261 } 4262 4263 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4264 4265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4266 true /* requireFullPermission */, false /* checkShell */, 4267 "getPermissionFlags"); 4268 4269 synchronized (mPackages) { 4270 final PackageParser.Package pkg = mPackages.get(packageName); 4271 if (pkg == null) { 4272 return 0; 4273 } 4274 4275 final BasePermission bp = mSettings.mPermissions.get(name); 4276 if (bp == null) { 4277 return 0; 4278 } 4279 4280 SettingBase sb = (SettingBase) pkg.mExtras; 4281 if (sb == null) { 4282 return 0; 4283 } 4284 4285 PermissionsState permissionsState = sb.getPermissionsState(); 4286 return permissionsState.getPermissionFlags(name, userId); 4287 } 4288 } 4289 4290 @Override 4291 public void updatePermissionFlags(String name, String packageName, int flagMask, 4292 int flagValues, int userId) { 4293 if (!sUserManager.exists(userId)) { 4294 return; 4295 } 4296 4297 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4298 4299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4300 true /* requireFullPermission */, true /* checkShell */, 4301 "updatePermissionFlags"); 4302 4303 // Only the system can change these flags and nothing else. 4304 if (getCallingUid() != Process.SYSTEM_UID) { 4305 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4306 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4307 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4308 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4309 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4310 } 4311 4312 synchronized (mPackages) { 4313 final PackageParser.Package pkg = mPackages.get(packageName); 4314 if (pkg == null) { 4315 throw new IllegalArgumentException("Unknown package: " + packageName); 4316 } 4317 4318 final BasePermission bp = mSettings.mPermissions.get(name); 4319 if (bp == null) { 4320 throw new IllegalArgumentException("Unknown permission: " + name); 4321 } 4322 4323 SettingBase sb = (SettingBase) pkg.mExtras; 4324 if (sb == null) { 4325 throw new IllegalArgumentException("Unknown package: " + packageName); 4326 } 4327 4328 PermissionsState permissionsState = sb.getPermissionsState(); 4329 4330 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4331 4332 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4333 // Install and runtime permissions are stored in different places, 4334 // so figure out what permission changed and persist the change. 4335 if (permissionsState.getInstallPermissionState(name) != null) { 4336 scheduleWriteSettingsLocked(); 4337 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4338 || hadState) { 4339 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4340 } 4341 } 4342 } 4343 } 4344 4345 /** 4346 * Update the permission flags for all packages and runtime permissions of a user in order 4347 * to allow device or profile owner to remove POLICY_FIXED. 4348 */ 4349 @Override 4350 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4351 if (!sUserManager.exists(userId)) { 4352 return; 4353 } 4354 4355 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4356 4357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4358 true /* requireFullPermission */, true /* checkShell */, 4359 "updatePermissionFlagsForAllApps"); 4360 4361 // Only the system can change system fixed flags. 4362 if (getCallingUid() != Process.SYSTEM_UID) { 4363 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4364 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4365 } 4366 4367 synchronized (mPackages) { 4368 boolean changed = false; 4369 final int packageCount = mPackages.size(); 4370 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4371 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4372 SettingBase sb = (SettingBase) pkg.mExtras; 4373 if (sb == null) { 4374 continue; 4375 } 4376 PermissionsState permissionsState = sb.getPermissionsState(); 4377 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4378 userId, flagMask, flagValues); 4379 } 4380 if (changed) { 4381 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4382 } 4383 } 4384 } 4385 4386 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4387 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4388 != PackageManager.PERMISSION_GRANTED 4389 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4390 != PackageManager.PERMISSION_GRANTED) { 4391 throw new SecurityException(message + " requires " 4392 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4393 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4394 } 4395 } 4396 4397 @Override 4398 public boolean shouldShowRequestPermissionRationale(String permissionName, 4399 String packageName, int userId) { 4400 if (UserHandle.getCallingUserId() != userId) { 4401 mContext.enforceCallingPermission( 4402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4403 "canShowRequestPermissionRationale for user " + userId); 4404 } 4405 4406 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4407 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4408 return false; 4409 } 4410 4411 if (checkPermission(permissionName, packageName, userId) 4412 == PackageManager.PERMISSION_GRANTED) { 4413 return false; 4414 } 4415 4416 final int flags; 4417 4418 final long identity = Binder.clearCallingIdentity(); 4419 try { 4420 flags = getPermissionFlags(permissionName, 4421 packageName, userId); 4422 } finally { 4423 Binder.restoreCallingIdentity(identity); 4424 } 4425 4426 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4427 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4428 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4429 4430 if ((flags & fixedFlags) != 0) { 4431 return false; 4432 } 4433 4434 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4435 } 4436 4437 @Override 4438 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4439 mContext.enforceCallingOrSelfPermission( 4440 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4441 "addOnPermissionsChangeListener"); 4442 4443 synchronized (mPackages) { 4444 mOnPermissionChangeListeners.addListenerLocked(listener); 4445 } 4446 } 4447 4448 @Override 4449 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4450 synchronized (mPackages) { 4451 mOnPermissionChangeListeners.removeListenerLocked(listener); 4452 } 4453 } 4454 4455 @Override 4456 public boolean isProtectedBroadcast(String actionName) { 4457 synchronized (mPackages) { 4458 if (mProtectedBroadcasts.contains(actionName)) { 4459 return true; 4460 } else if (actionName != null) { 4461 // TODO: remove these terrible hacks 4462 if (actionName.startsWith("android.net.netmon.lingerExpired") 4463 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4464 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4465 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4466 return true; 4467 } 4468 } 4469 } 4470 return false; 4471 } 4472 4473 @Override 4474 public int checkSignatures(String pkg1, String pkg2) { 4475 synchronized (mPackages) { 4476 final PackageParser.Package p1 = mPackages.get(pkg1); 4477 final PackageParser.Package p2 = mPackages.get(pkg2); 4478 if (p1 == null || p1.mExtras == null 4479 || p2 == null || p2.mExtras == null) { 4480 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4481 } 4482 return compareSignatures(p1.mSignatures, p2.mSignatures); 4483 } 4484 } 4485 4486 @Override 4487 public int checkUidSignatures(int uid1, int uid2) { 4488 // Map to base uids. 4489 uid1 = UserHandle.getAppId(uid1); 4490 uid2 = UserHandle.getAppId(uid2); 4491 // reader 4492 synchronized (mPackages) { 4493 Signature[] s1; 4494 Signature[] s2; 4495 Object obj = mSettings.getUserIdLPr(uid1); 4496 if (obj != null) { 4497 if (obj instanceof SharedUserSetting) { 4498 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4499 } else if (obj instanceof PackageSetting) { 4500 s1 = ((PackageSetting)obj).signatures.mSignatures; 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 } else { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 obj = mSettings.getUserIdLPr(uid2); 4508 if (obj != null) { 4509 if (obj instanceof SharedUserSetting) { 4510 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4511 } else if (obj instanceof PackageSetting) { 4512 s2 = ((PackageSetting)obj).signatures.mSignatures; 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 } else { 4517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4518 } 4519 return compareSignatures(s1, s2); 4520 } 4521 } 4522 4523 /** 4524 * This method should typically only be used when granting or revoking 4525 * permissions, since the app may immediately restart after this call. 4526 * <p> 4527 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4528 * guard your work against the app being relaunched. 4529 */ 4530 private void killUid(int appId, int userId, String reason) { 4531 final long identity = Binder.clearCallingIdentity(); 4532 try { 4533 IActivityManager am = ActivityManagerNative.getDefault(); 4534 if (am != null) { 4535 try { 4536 am.killUid(appId, userId, reason); 4537 } catch (RemoteException e) { 4538 /* ignore - same process */ 4539 } 4540 } 4541 } finally { 4542 Binder.restoreCallingIdentity(identity); 4543 } 4544 } 4545 4546 /** 4547 * Compares two sets of signatures. Returns: 4548 * <br /> 4549 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4550 * <br /> 4551 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4552 * <br /> 4553 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4558 */ 4559 static int compareSignatures(Signature[] s1, Signature[] s2) { 4560 if (s1 == null) { 4561 return s2 == null 4562 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4563 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4564 } 4565 4566 if (s2 == null) { 4567 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4568 } 4569 4570 if (s1.length != s2.length) { 4571 return PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 // Since both signature sets are of size 1, we can compare without HashSets. 4575 if (s1.length == 1) { 4576 return s1[0].equals(s2[0]) ? 4577 PackageManager.SIGNATURE_MATCH : 4578 PackageManager.SIGNATURE_NO_MATCH; 4579 } 4580 4581 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4582 for (Signature sig : s1) { 4583 set1.add(sig); 4584 } 4585 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4586 for (Signature sig : s2) { 4587 set2.add(sig); 4588 } 4589 // Make sure s2 contains all signatures in s1. 4590 if (set1.equals(set2)) { 4591 return PackageManager.SIGNATURE_MATCH; 4592 } 4593 return PackageManager.SIGNATURE_NO_MATCH; 4594 } 4595 4596 /** 4597 * If the database version for this type of package (internal storage or 4598 * external storage) is less than the version where package signatures 4599 * were updated, return true. 4600 */ 4601 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4602 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4603 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4604 } 4605 4606 /** 4607 * Used for backward compatibility to make sure any packages with 4608 * certificate chains get upgraded to the new style. {@code existingSigs} 4609 * will be in the old format (since they were stored on disk from before the 4610 * system upgrade) and {@code scannedSigs} will be in the newer format. 4611 */ 4612 private int compareSignaturesCompat(PackageSignatures existingSigs, 4613 PackageParser.Package scannedPkg) { 4614 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4615 return PackageManager.SIGNATURE_NO_MATCH; 4616 } 4617 4618 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4619 for (Signature sig : existingSigs.mSignatures) { 4620 existingSet.add(sig); 4621 } 4622 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4623 for (Signature sig : scannedPkg.mSignatures) { 4624 try { 4625 Signature[] chainSignatures = sig.getChainSignatures(); 4626 for (Signature chainSig : chainSignatures) { 4627 scannedCompatSet.add(chainSig); 4628 } 4629 } catch (CertificateEncodingException e) { 4630 scannedCompatSet.add(sig); 4631 } 4632 } 4633 /* 4634 * Make sure the expanded scanned set contains all signatures in the 4635 * existing one. 4636 */ 4637 if (scannedCompatSet.equals(existingSet)) { 4638 // Migrate the old signatures to the new scheme. 4639 existingSigs.assignSignatures(scannedPkg.mSignatures); 4640 // The new KeySets will be re-added later in the scanning process. 4641 synchronized (mPackages) { 4642 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4643 } 4644 return PackageManager.SIGNATURE_MATCH; 4645 } 4646 return PackageManager.SIGNATURE_NO_MATCH; 4647 } 4648 4649 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4650 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4651 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4652 } 4653 4654 private int compareSignaturesRecover(PackageSignatures existingSigs, 4655 PackageParser.Package scannedPkg) { 4656 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4657 return PackageManager.SIGNATURE_NO_MATCH; 4658 } 4659 4660 String msg = null; 4661 try { 4662 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4663 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4664 + scannedPkg.packageName); 4665 return PackageManager.SIGNATURE_MATCH; 4666 } 4667 } catch (CertificateException e) { 4668 msg = e.getMessage(); 4669 } 4670 4671 logCriticalInfo(Log.INFO, 4672 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4673 return PackageManager.SIGNATURE_NO_MATCH; 4674 } 4675 4676 @Override 4677 public List<String> getAllPackages() { 4678 synchronized (mPackages) { 4679 return new ArrayList<String>(mPackages.keySet()); 4680 } 4681 } 4682 4683 @Override 4684 public String[] getPackagesForUid(int uid) { 4685 final int userId = UserHandle.getUserId(uid); 4686 uid = UserHandle.getAppId(uid); 4687 // reader 4688 synchronized (mPackages) { 4689 Object obj = mSettings.getUserIdLPr(uid); 4690 if (obj instanceof SharedUserSetting) { 4691 final SharedUserSetting sus = (SharedUserSetting) obj; 4692 final int N = sus.packages.size(); 4693 String[] res = new String[N]; 4694 final Iterator<PackageSetting> it = sus.packages.iterator(); 4695 int i = 0; 4696 while (it.hasNext()) { 4697 PackageSetting ps = it.next(); 4698 if (ps.getInstalled(userId)) { 4699 res[i++] = ps.name; 4700 } else { 4701 res = ArrayUtils.removeElement(String.class, res, res[i]); 4702 } 4703 } 4704 return res; 4705 } else if (obj instanceof PackageSetting) { 4706 final PackageSetting ps = (PackageSetting) obj; 4707 return new String[] { ps.name }; 4708 } 4709 } 4710 return null; 4711 } 4712 4713 @Override 4714 public String getNameForUid(int uid) { 4715 // reader 4716 synchronized (mPackages) { 4717 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4718 if (obj instanceof SharedUserSetting) { 4719 final SharedUserSetting sus = (SharedUserSetting) obj; 4720 return sus.name + ":" + sus.userId; 4721 } else if (obj instanceof PackageSetting) { 4722 final PackageSetting ps = (PackageSetting) obj; 4723 return ps.name; 4724 } 4725 } 4726 return null; 4727 } 4728 4729 @Override 4730 public int getUidForSharedUser(String sharedUserName) { 4731 if(sharedUserName == null) { 4732 return -1; 4733 } 4734 // reader 4735 synchronized (mPackages) { 4736 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4737 if (suid == null) { 4738 return -1; 4739 } 4740 return suid.userId; 4741 } 4742 } 4743 4744 @Override 4745 public int getFlagsForUid(int uid) { 4746 synchronized (mPackages) { 4747 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4748 if (obj instanceof SharedUserSetting) { 4749 final SharedUserSetting sus = (SharedUserSetting) obj; 4750 return sus.pkgFlags; 4751 } else if (obj instanceof PackageSetting) { 4752 final PackageSetting ps = (PackageSetting) obj; 4753 return ps.pkgFlags; 4754 } 4755 } 4756 return 0; 4757 } 4758 4759 @Override 4760 public int getPrivateFlagsForUid(int uid) { 4761 synchronized (mPackages) { 4762 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4763 if (obj instanceof SharedUserSetting) { 4764 final SharedUserSetting sus = (SharedUserSetting) obj; 4765 return sus.pkgPrivateFlags; 4766 } else if (obj instanceof PackageSetting) { 4767 final PackageSetting ps = (PackageSetting) obj; 4768 return ps.pkgPrivateFlags; 4769 } 4770 } 4771 return 0; 4772 } 4773 4774 @Override 4775 public boolean isUidPrivileged(int uid) { 4776 uid = UserHandle.getAppId(uid); 4777 // reader 4778 synchronized (mPackages) { 4779 Object obj = mSettings.getUserIdLPr(uid); 4780 if (obj instanceof SharedUserSetting) { 4781 final SharedUserSetting sus = (SharedUserSetting) obj; 4782 final Iterator<PackageSetting> it = sus.packages.iterator(); 4783 while (it.hasNext()) { 4784 if (it.next().isPrivileged()) { 4785 return true; 4786 } 4787 } 4788 } else if (obj instanceof PackageSetting) { 4789 final PackageSetting ps = (PackageSetting) obj; 4790 return ps.isPrivileged(); 4791 } 4792 } 4793 return false; 4794 } 4795 4796 @Override 4797 public String[] getAppOpPermissionPackages(String permissionName) { 4798 synchronized (mPackages) { 4799 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4800 if (pkgs == null) { 4801 return null; 4802 } 4803 return pkgs.toArray(new String[pkgs.size()]); 4804 } 4805 } 4806 4807 @Override 4808 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4809 int flags, int userId) { 4810 try { 4811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4812 4813 if (!sUserManager.exists(userId)) return null; 4814 flags = updateFlagsForResolve(flags, userId, intent); 4815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4816 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4817 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4819 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4820 flags, userId); 4821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4822 4823 final ResolveInfo bestChoice = 4824 chooseBestActivity(intent, resolvedType, flags, query, userId); 4825 return bestChoice; 4826 } finally { 4827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4828 } 4829 } 4830 4831 @Override 4832 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4833 IntentFilter filter, int match, ComponentName activity) { 4834 final int userId = UserHandle.getCallingUserId(); 4835 if (DEBUG_PREFERRED) { 4836 Log.v(TAG, "setLastChosenActivity intent=" + intent 4837 + " resolvedType=" + resolvedType 4838 + " flags=" + flags 4839 + " filter=" + filter 4840 + " match=" + match 4841 + " activity=" + activity); 4842 filter.dump(new PrintStreamPrinter(System.out), " "); 4843 } 4844 intent.setComponent(null); 4845 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4846 userId); 4847 // Find any earlier preferred or last chosen entries and nuke them 4848 findPreferredActivity(intent, resolvedType, 4849 flags, query, 0, false, true, false, userId); 4850 // Add the new activity as the last chosen for this filter 4851 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4852 "Setting last chosen"); 4853 } 4854 4855 @Override 4856 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4857 final int userId = UserHandle.getCallingUserId(); 4858 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4859 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4860 userId); 4861 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4862 false, false, false, userId); 4863 } 4864 4865 private boolean isEphemeralDisabled() { 4866 // ephemeral apps have been disabled across the board 4867 if (DISABLE_EPHEMERAL_APPS) { 4868 return true; 4869 } 4870 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4871 if (!mSystemReady) { 4872 return true; 4873 } 4874 // we can't get a content resolver until the system is ready; these checks must happen last 4875 final ContentResolver resolver = mContext.getContentResolver(); 4876 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4877 return true; 4878 } 4879 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4880 } 4881 4882 private boolean isEphemeralAllowed( 4883 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4884 boolean skipPackageCheck) { 4885 // Short circuit and return early if possible. 4886 if (isEphemeralDisabled()) { 4887 return false; 4888 } 4889 final int callingUser = UserHandle.getCallingUserId(); 4890 if (callingUser != UserHandle.USER_SYSTEM) { 4891 return false; 4892 } 4893 if (mEphemeralResolverConnection == null) { 4894 return false; 4895 } 4896 if (intent.getComponent() != null) { 4897 return false; 4898 } 4899 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4900 return false; 4901 } 4902 if (!skipPackageCheck && intent.getPackage() != null) { 4903 return false; 4904 } 4905 final boolean isWebUri = hasWebURI(intent); 4906 if (!isWebUri || intent.getData().getHost() == null) { 4907 return false; 4908 } 4909 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4910 synchronized (mPackages) { 4911 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4912 for (int n = 0; n < count; n++) { 4913 ResolveInfo info = resolvedActivities.get(n); 4914 String packageName = info.activityInfo.packageName; 4915 PackageSetting ps = mSettings.mPackages.get(packageName); 4916 if (ps != null) { 4917 // Try to get the status from User settings first 4918 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4919 int status = (int) (packedStatus >> 32); 4920 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4921 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4922 if (DEBUG_EPHEMERAL) { 4923 Slog.v(TAG, "DENY ephemeral apps;" 4924 + " pkg: " + packageName + ", status: " + status); 4925 } 4926 return false; 4927 } 4928 } 4929 } 4930 } 4931 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4932 return true; 4933 } 4934 4935 private static EphemeralResolveInfo getEphemeralResolveInfo( 4936 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4937 String resolvedType, int userId, String packageName) { 4938 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4939 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4940 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4941 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4942 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4943 ephemeralPrefixCount); 4944 final int[] shaPrefix = digest.getDigestPrefix(); 4945 final byte[][] digestBytes = digest.getDigestBytes(); 4946 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4947 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4948 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4949 // No hash prefix match; there are no ephemeral apps for this domain. 4950 return null; 4951 } 4952 4953 // Go in reverse order so we match the narrowest scope first. 4954 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4955 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4956 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4957 continue; 4958 } 4959 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4960 // No filters; this should never happen. 4961 if (filters.isEmpty()) { 4962 continue; 4963 } 4964 if (packageName != null 4965 && !packageName.equals(ephemeralApplication.getPackageName())) { 4966 continue; 4967 } 4968 // We have a domain match; resolve the filters to see if anything matches. 4969 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4970 for (int j = filters.size() - 1; j >= 0; --j) { 4971 final EphemeralResolveIntentInfo intentInfo = 4972 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4973 ephemeralResolver.addFilter(intentInfo); 4974 } 4975 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4976 intent, resolvedType, false /*defaultOnly*/, userId); 4977 if (!matchedResolveInfoList.isEmpty()) { 4978 return matchedResolveInfoList.get(0); 4979 } 4980 } 4981 } 4982 // Hash or filter mis-match; no ephemeral apps for this domain. 4983 return null; 4984 } 4985 4986 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4987 int flags, List<ResolveInfo> query, int userId) { 4988 if (query != null) { 4989 final int N = query.size(); 4990 if (N == 1) { 4991 return query.get(0); 4992 } else if (N > 1) { 4993 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4994 // If there is more than one activity with the same priority, 4995 // then let the user decide between them. 4996 ResolveInfo r0 = query.get(0); 4997 ResolveInfo r1 = query.get(1); 4998 if (DEBUG_INTENT_MATCHING || debug) { 4999 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5000 + r1.activityInfo.name + "=" + r1.priority); 5001 } 5002 // If the first activity has a higher priority, or a different 5003 // default, then it is always desirable to pick it. 5004 if (r0.priority != r1.priority 5005 || r0.preferredOrder != r1.preferredOrder 5006 || r0.isDefault != r1.isDefault) { 5007 return query.get(0); 5008 } 5009 // If we have saved a preference for a preferred activity for 5010 // this Intent, use that. 5011 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5012 flags, query, r0.priority, true, false, debug, userId); 5013 if (ri != null) { 5014 return ri; 5015 } 5016 ri = new ResolveInfo(mResolveInfo); 5017 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5018 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5019 // If all of the options come from the same package, show the application's 5020 // label and icon instead of the generic resolver's. 5021 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5022 // and then throw away the ResolveInfo itself, meaning that the caller loses 5023 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5024 // a fallback for this case; we only set the target package's resources on 5025 // the ResolveInfo, not the ActivityInfo. 5026 final String intentPackage = intent.getPackage(); 5027 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5028 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5029 ri.resolvePackageName = intentPackage; 5030 if (userNeedsBadging(userId)) { 5031 ri.noResourceId = true; 5032 } else { 5033 ri.icon = appi.icon; 5034 } 5035 ri.iconResourceId = appi.icon; 5036 ri.labelRes = appi.labelRes; 5037 } 5038 ri.activityInfo.applicationInfo = new ApplicationInfo( 5039 ri.activityInfo.applicationInfo); 5040 if (userId != 0) { 5041 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5042 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5043 } 5044 // Make sure that the resolver is displayable in car mode 5045 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5046 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5047 return ri; 5048 } 5049 } 5050 return null; 5051 } 5052 5053 /** 5054 * Return true if the given list is not empty and all of its contents have 5055 * an activityInfo with the given package name. 5056 */ 5057 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5058 if (ArrayUtils.isEmpty(list)) { 5059 return false; 5060 } 5061 for (int i = 0, N = list.size(); i < N; i++) { 5062 final ResolveInfo ri = list.get(i); 5063 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5064 if (ai == null || !packageName.equals(ai.packageName)) { 5065 return false; 5066 } 5067 } 5068 return true; 5069 } 5070 5071 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5072 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5073 final int N = query.size(); 5074 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5075 .get(userId); 5076 // Get the list of persistent preferred activities that handle the intent 5077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5078 List<PersistentPreferredActivity> pprefs = ppir != null 5079 ? ppir.queryIntent(intent, resolvedType, 5080 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5081 : null; 5082 if (pprefs != null && pprefs.size() > 0) { 5083 final int M = pprefs.size(); 5084 for (int i=0; i<M; i++) { 5085 final PersistentPreferredActivity ppa = pprefs.get(i); 5086 if (DEBUG_PREFERRED || debug) { 5087 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5088 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5089 + "\n component=" + ppa.mComponent); 5090 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5091 } 5092 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5093 flags | MATCH_DISABLED_COMPONENTS, userId); 5094 if (DEBUG_PREFERRED || debug) { 5095 Slog.v(TAG, "Found persistent preferred activity:"); 5096 if (ai != null) { 5097 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5098 } else { 5099 Slog.v(TAG, " null"); 5100 } 5101 } 5102 if (ai == null) { 5103 // This previously registered persistent preferred activity 5104 // component is no longer known. Ignore it and do NOT remove it. 5105 continue; 5106 } 5107 for (int j=0; j<N; j++) { 5108 final ResolveInfo ri = query.get(j); 5109 if (!ri.activityInfo.applicationInfo.packageName 5110 .equals(ai.applicationInfo.packageName)) { 5111 continue; 5112 } 5113 if (!ri.activityInfo.name.equals(ai.name)) { 5114 continue; 5115 } 5116 // Found a persistent preference that can handle the intent. 5117 if (DEBUG_PREFERRED || debug) { 5118 Slog.v(TAG, "Returning persistent preferred activity: " + 5119 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5120 } 5121 return ri; 5122 } 5123 } 5124 } 5125 return null; 5126 } 5127 5128 // TODO: handle preferred activities missing while user has amnesia 5129 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5130 List<ResolveInfo> query, int priority, boolean always, 5131 boolean removeMatches, boolean debug, int userId) { 5132 if (!sUserManager.exists(userId)) return null; 5133 flags = updateFlagsForResolve(flags, userId, intent); 5134 // writer 5135 synchronized (mPackages) { 5136 if (intent.getSelector() != null) { 5137 intent = intent.getSelector(); 5138 } 5139 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5140 5141 // Try to find a matching persistent preferred activity. 5142 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5143 debug, userId); 5144 5145 // If a persistent preferred activity matched, use it. 5146 if (pri != null) { 5147 return pri; 5148 } 5149 5150 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5151 // Get the list of preferred activities that handle the intent 5152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5153 List<PreferredActivity> prefs = pir != null 5154 ? pir.queryIntent(intent, resolvedType, 5155 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5156 : null; 5157 if (prefs != null && prefs.size() > 0) { 5158 boolean changed = false; 5159 try { 5160 // First figure out how good the original match set is. 5161 // We will only allow preferred activities that came 5162 // from the same match quality. 5163 int match = 0; 5164 5165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5166 5167 final int N = query.size(); 5168 for (int j=0; j<N; j++) { 5169 final ResolveInfo ri = query.get(j); 5170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5171 + ": 0x" + Integer.toHexString(match)); 5172 if (ri.match > match) { 5173 match = ri.match; 5174 } 5175 } 5176 5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5178 + Integer.toHexString(match)); 5179 5180 match &= IntentFilter.MATCH_CATEGORY_MASK; 5181 final int M = prefs.size(); 5182 for (int i=0; i<M; i++) { 5183 final PreferredActivity pa = prefs.get(i); 5184 if (DEBUG_PREFERRED || debug) { 5185 Slog.v(TAG, "Checking PreferredActivity ds=" 5186 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5187 + "\n component=" + pa.mPref.mComponent); 5188 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5189 } 5190 if (pa.mPref.mMatch != match) { 5191 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5192 + Integer.toHexString(pa.mPref.mMatch)); 5193 continue; 5194 } 5195 // If it's not an "always" type preferred activity and that's what we're 5196 // looking for, skip it. 5197 if (always && !pa.mPref.mAlways) { 5198 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5199 continue; 5200 } 5201 final ActivityInfo ai = getActivityInfo( 5202 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5203 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5204 userId); 5205 if (DEBUG_PREFERRED || debug) { 5206 Slog.v(TAG, "Found preferred activity:"); 5207 if (ai != null) { 5208 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5209 } else { 5210 Slog.v(TAG, " null"); 5211 } 5212 } 5213 if (ai == null) { 5214 // This previously registered preferred activity 5215 // component is no longer known. Most likely an update 5216 // to the app was installed and in the new version this 5217 // component no longer exists. Clean it up by removing 5218 // it from the preferred activities list, and skip it. 5219 Slog.w(TAG, "Removing dangling preferred activity: " 5220 + pa.mPref.mComponent); 5221 pir.removeFilter(pa); 5222 changed = true; 5223 continue; 5224 } 5225 for (int j=0; j<N; j++) { 5226 final ResolveInfo ri = query.get(j); 5227 if (!ri.activityInfo.applicationInfo.packageName 5228 .equals(ai.applicationInfo.packageName)) { 5229 continue; 5230 } 5231 if (!ri.activityInfo.name.equals(ai.name)) { 5232 continue; 5233 } 5234 5235 if (removeMatches) { 5236 pir.removeFilter(pa); 5237 changed = true; 5238 if (DEBUG_PREFERRED) { 5239 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5240 } 5241 break; 5242 } 5243 5244 // Okay we found a previously set preferred or last chosen app. 5245 // If the result set is different from when this 5246 // was created, we need to clear it and re-ask the 5247 // user their preference, if we're looking for an "always" type entry. 5248 if (always && !pa.mPref.sameSet(query)) { 5249 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5250 + intent + " type " + resolvedType); 5251 if (DEBUG_PREFERRED) { 5252 Slog.v(TAG, "Removing preferred activity since set changed " 5253 + pa.mPref.mComponent); 5254 } 5255 pir.removeFilter(pa); 5256 // Re-add the filter as a "last chosen" entry (!always) 5257 PreferredActivity lastChosen = new PreferredActivity( 5258 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5259 pir.addFilter(lastChosen); 5260 changed = true; 5261 return null; 5262 } 5263 5264 // Yay! Either the set matched or we're looking for the last chosen 5265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5266 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5267 return ri; 5268 } 5269 } 5270 } finally { 5271 if (changed) { 5272 if (DEBUG_PREFERRED) { 5273 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5274 } 5275 scheduleWritePackageRestrictionsLocked(userId); 5276 } 5277 } 5278 } 5279 } 5280 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5281 return null; 5282 } 5283 5284 /* 5285 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5286 */ 5287 @Override 5288 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5289 int targetUserId) { 5290 mContext.enforceCallingOrSelfPermission( 5291 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5292 List<CrossProfileIntentFilter> matches = 5293 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5294 if (matches != null) { 5295 int size = matches.size(); 5296 for (int i = 0; i < size; i++) { 5297 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5298 } 5299 } 5300 if (hasWebURI(intent)) { 5301 // cross-profile app linking works only towards the parent. 5302 final UserInfo parent = getProfileParent(sourceUserId); 5303 synchronized(mPackages) { 5304 int flags = updateFlagsForResolve(0, parent.id, intent); 5305 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5306 intent, resolvedType, flags, sourceUserId, parent.id); 5307 return xpDomainInfo != null; 5308 } 5309 } 5310 return false; 5311 } 5312 5313 private UserInfo getProfileParent(int userId) { 5314 final long identity = Binder.clearCallingIdentity(); 5315 try { 5316 return sUserManager.getProfileParent(userId); 5317 } finally { 5318 Binder.restoreCallingIdentity(identity); 5319 } 5320 } 5321 5322 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5323 String resolvedType, int userId) { 5324 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5325 if (resolver != null) { 5326 return resolver.queryIntent(intent, resolvedType, false, userId); 5327 } 5328 return null; 5329 } 5330 5331 @Override 5332 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5333 String resolvedType, int flags, int userId) { 5334 try { 5335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5336 5337 return new ParceledListSlice<>( 5338 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5339 } finally { 5340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5341 } 5342 } 5343 5344 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5345 String resolvedType, int flags, int userId) { 5346 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5347 flags = updateFlagsForResolve(flags, userId, intent); 5348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5349 false /* requireFullPermission */, false /* checkShell */, 5350 "query intent activities"); 5351 ComponentName comp = intent.getComponent(); 5352 if (comp == null) { 5353 if (intent.getSelector() != null) { 5354 intent = intent.getSelector(); 5355 comp = intent.getComponent(); 5356 } 5357 } 5358 5359 if (comp != null) { 5360 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5361 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5362 if (ai != null) { 5363 final ResolveInfo ri = new ResolveInfo(); 5364 ri.activityInfo = ai; 5365 list.add(ri); 5366 } 5367 return list; 5368 } 5369 5370 // reader 5371 boolean sortResult = false; 5372 boolean addEphemeral = false; 5373 boolean matchEphemeralPackage = false; 5374 List<ResolveInfo> result; 5375 final String pkgName = intent.getPackage(); 5376 synchronized (mPackages) { 5377 if (pkgName == null) { 5378 List<CrossProfileIntentFilter> matchingFilters = 5379 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5380 // Check for results that need to skip the current profile. 5381 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5382 resolvedType, flags, userId); 5383 if (xpResolveInfo != null) { 5384 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5385 xpResult.add(xpResolveInfo); 5386 return filterIfNotSystemUser(xpResult, userId); 5387 } 5388 5389 // Check for results in the current profile. 5390 result = filterIfNotSystemUser(mActivities.queryIntent( 5391 intent, resolvedType, flags, userId), userId); 5392 addEphemeral = 5393 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5394 5395 // Check for cross profile results. 5396 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5397 xpResolveInfo = queryCrossProfileIntents( 5398 matchingFilters, intent, resolvedType, flags, userId, 5399 hasNonNegativePriorityResult); 5400 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5401 boolean isVisibleToUser = filterIfNotSystemUser( 5402 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5403 if (isVisibleToUser) { 5404 result.add(xpResolveInfo); 5405 sortResult = true; 5406 } 5407 } 5408 if (hasWebURI(intent)) { 5409 CrossProfileDomainInfo xpDomainInfo = null; 5410 final UserInfo parent = getProfileParent(userId); 5411 if (parent != null) { 5412 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5413 flags, userId, parent.id); 5414 } 5415 if (xpDomainInfo != null) { 5416 if (xpResolveInfo != null) { 5417 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5418 // in the result. 5419 result.remove(xpResolveInfo); 5420 } 5421 if (result.size() == 0 && !addEphemeral) { 5422 result.add(xpDomainInfo.resolveInfo); 5423 return result; 5424 } 5425 } 5426 if (result.size() > 1 || addEphemeral) { 5427 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5428 intent, flags, result, xpDomainInfo, userId); 5429 sortResult = true; 5430 } 5431 } 5432 } else { 5433 final PackageParser.Package pkg = mPackages.get(pkgName); 5434 if (pkg != null) { 5435 result = filterIfNotSystemUser( 5436 mActivities.queryIntentForPackage( 5437 intent, resolvedType, flags, pkg.activities, userId), 5438 userId); 5439 } else { 5440 // the caller wants to resolve for a particular package; however, there 5441 // were no installed results, so, try to find an ephemeral result 5442 addEphemeral = isEphemeralAllowed( 5443 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5444 matchEphemeralPackage = true; 5445 result = new ArrayList<ResolveInfo>(); 5446 } 5447 } 5448 } 5449 if (addEphemeral) { 5450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5451 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5452 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5453 matchEphemeralPackage ? pkgName : null); 5454 if (ai != null) { 5455 if (DEBUG_EPHEMERAL) { 5456 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5457 } 5458 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5459 ephemeralInstaller.ephemeralResolveInfo = ai; 5460 // make sure this resolver is the default 5461 ephemeralInstaller.isDefault = true; 5462 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5463 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5464 // add a non-generic filter 5465 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5466 ephemeralInstaller.filter.addDataPath( 5467 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5468 result.add(ephemeralInstaller); 5469 } 5470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5471 } 5472 if (sortResult) { 5473 Collections.sort(result, mResolvePrioritySorter); 5474 } 5475 return result; 5476 } 5477 5478 private static class CrossProfileDomainInfo { 5479 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5480 ResolveInfo resolveInfo; 5481 /* Best domain verification status of the activities found in the other profile */ 5482 int bestDomainVerificationStatus; 5483 } 5484 5485 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5486 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5487 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5488 sourceUserId)) { 5489 return null; 5490 } 5491 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5492 resolvedType, flags, parentUserId); 5493 5494 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5495 return null; 5496 } 5497 CrossProfileDomainInfo result = null; 5498 int size = resultTargetUser.size(); 5499 for (int i = 0; i < size; i++) { 5500 ResolveInfo riTargetUser = resultTargetUser.get(i); 5501 // Intent filter verification is only for filters that specify a host. So don't return 5502 // those that handle all web uris. 5503 if (riTargetUser.handleAllWebDataURI) { 5504 continue; 5505 } 5506 String packageName = riTargetUser.activityInfo.packageName; 5507 PackageSetting ps = mSettings.mPackages.get(packageName); 5508 if (ps == null) { 5509 continue; 5510 } 5511 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5512 int status = (int)(verificationState >> 32); 5513 if (result == null) { 5514 result = new CrossProfileDomainInfo(); 5515 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5516 sourceUserId, parentUserId); 5517 result.bestDomainVerificationStatus = status; 5518 } else { 5519 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5520 result.bestDomainVerificationStatus); 5521 } 5522 } 5523 // Don't consider matches with status NEVER across profiles. 5524 if (result != null && result.bestDomainVerificationStatus 5525 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5526 return null; 5527 } 5528 return result; 5529 } 5530 5531 /** 5532 * Verification statuses are ordered from the worse to the best, except for 5533 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5534 */ 5535 private int bestDomainVerificationStatus(int status1, int status2) { 5536 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5537 return status2; 5538 } 5539 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5540 return status1; 5541 } 5542 return (int) MathUtils.max(status1, status2); 5543 } 5544 5545 private boolean isUserEnabled(int userId) { 5546 long callingId = Binder.clearCallingIdentity(); 5547 try { 5548 UserInfo userInfo = sUserManager.getUserInfo(userId); 5549 return userInfo != null && userInfo.isEnabled(); 5550 } finally { 5551 Binder.restoreCallingIdentity(callingId); 5552 } 5553 } 5554 5555 /** 5556 * Filter out activities with systemUserOnly flag set, when current user is not System. 5557 * 5558 * @return filtered list 5559 */ 5560 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5561 if (userId == UserHandle.USER_SYSTEM) { 5562 return resolveInfos; 5563 } 5564 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5565 ResolveInfo info = resolveInfos.get(i); 5566 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5567 resolveInfos.remove(i); 5568 } 5569 } 5570 return resolveInfos; 5571 } 5572 5573 /** 5574 * @param resolveInfos list of resolve infos in descending priority order 5575 * @return if the list contains a resolve info with non-negative priority 5576 */ 5577 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5578 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5579 } 5580 5581 private static boolean hasWebURI(Intent intent) { 5582 if (intent.getData() == null) { 5583 return false; 5584 } 5585 final String scheme = intent.getScheme(); 5586 if (TextUtils.isEmpty(scheme)) { 5587 return false; 5588 } 5589 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5590 } 5591 5592 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5593 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5594 int userId) { 5595 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5596 5597 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5598 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5599 candidates.size()); 5600 } 5601 5602 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5603 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5604 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5605 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5606 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5607 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5608 5609 synchronized (mPackages) { 5610 final int count = candidates.size(); 5611 // First, try to use linked apps. Partition the candidates into four lists: 5612 // one for the final results, one for the "do not use ever", one for "undefined status" 5613 // and finally one for "browser app type". 5614 for (int n=0; n<count; n++) { 5615 ResolveInfo info = candidates.get(n); 5616 String packageName = info.activityInfo.packageName; 5617 PackageSetting ps = mSettings.mPackages.get(packageName); 5618 if (ps != null) { 5619 // Add to the special match all list (Browser use case) 5620 if (info.handleAllWebDataURI) { 5621 matchAllList.add(info); 5622 continue; 5623 } 5624 // Try to get the status from User settings first 5625 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5626 int status = (int)(packedStatus >> 32); 5627 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5628 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5629 if (DEBUG_DOMAIN_VERIFICATION) { 5630 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5631 + " : linkgen=" + linkGeneration); 5632 } 5633 // Use link-enabled generation as preferredOrder, i.e. 5634 // prefer newly-enabled over earlier-enabled. 5635 info.preferredOrder = linkGeneration; 5636 alwaysList.add(info); 5637 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5638 if (DEBUG_DOMAIN_VERIFICATION) { 5639 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5640 } 5641 neverList.add(info); 5642 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5643 if (DEBUG_DOMAIN_VERIFICATION) { 5644 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5645 } 5646 alwaysAskList.add(info); 5647 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5648 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5649 if (DEBUG_DOMAIN_VERIFICATION) { 5650 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5651 } 5652 undefinedList.add(info); 5653 } 5654 } 5655 } 5656 5657 // We'll want to include browser possibilities in a few cases 5658 boolean includeBrowser = false; 5659 5660 // First try to add the "always" resolution(s) for the current user, if any 5661 if (alwaysList.size() > 0) { 5662 result.addAll(alwaysList); 5663 } else { 5664 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5665 result.addAll(undefinedList); 5666 // Maybe add one for the other profile. 5667 if (xpDomainInfo != null && ( 5668 xpDomainInfo.bestDomainVerificationStatus 5669 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5670 result.add(xpDomainInfo.resolveInfo); 5671 } 5672 includeBrowser = true; 5673 } 5674 5675 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5676 // If there were 'always' entries their preferred order has been set, so we also 5677 // back that off to make the alternatives equivalent 5678 if (alwaysAskList.size() > 0) { 5679 for (ResolveInfo i : result) { 5680 i.preferredOrder = 0; 5681 } 5682 result.addAll(alwaysAskList); 5683 includeBrowser = true; 5684 } 5685 5686 if (includeBrowser) { 5687 // Also add browsers (all of them or only the default one) 5688 if (DEBUG_DOMAIN_VERIFICATION) { 5689 Slog.v(TAG, " ...including browsers in candidate set"); 5690 } 5691 if ((matchFlags & MATCH_ALL) != 0) { 5692 result.addAll(matchAllList); 5693 } else { 5694 // Browser/generic handling case. If there's a default browser, go straight 5695 // to that (but only if there is no other higher-priority match). 5696 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5697 int maxMatchPrio = 0; 5698 ResolveInfo defaultBrowserMatch = null; 5699 final int numCandidates = matchAllList.size(); 5700 for (int n = 0; n < numCandidates; n++) { 5701 ResolveInfo info = matchAllList.get(n); 5702 // track the highest overall match priority... 5703 if (info.priority > maxMatchPrio) { 5704 maxMatchPrio = info.priority; 5705 } 5706 // ...and the highest-priority default browser match 5707 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5708 if (defaultBrowserMatch == null 5709 || (defaultBrowserMatch.priority < info.priority)) { 5710 if (debug) { 5711 Slog.v(TAG, "Considering default browser match " + info); 5712 } 5713 defaultBrowserMatch = info; 5714 } 5715 } 5716 } 5717 if (defaultBrowserMatch != null 5718 && defaultBrowserMatch.priority >= maxMatchPrio 5719 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5720 { 5721 if (debug) { 5722 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5723 } 5724 result.add(defaultBrowserMatch); 5725 } else { 5726 result.addAll(matchAllList); 5727 } 5728 } 5729 5730 // If there is nothing selected, add all candidates and remove the ones that the user 5731 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5732 if (result.size() == 0) { 5733 result.addAll(candidates); 5734 result.removeAll(neverList); 5735 } 5736 } 5737 } 5738 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5739 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5740 result.size()); 5741 for (ResolveInfo info : result) { 5742 Slog.v(TAG, " + " + info.activityInfo); 5743 } 5744 } 5745 return result; 5746 } 5747 5748 // Returns a packed value as a long: 5749 // 5750 // high 'int'-sized word: link status: undefined/ask/never/always. 5751 // low 'int'-sized word: relative priority among 'always' results. 5752 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5753 long result = ps.getDomainVerificationStatusForUser(userId); 5754 // if none available, get the master status 5755 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5756 if (ps.getIntentFilterVerificationInfo() != null) { 5757 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5758 } 5759 } 5760 return result; 5761 } 5762 5763 private ResolveInfo querySkipCurrentProfileIntents( 5764 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5765 int flags, int sourceUserId) { 5766 if (matchingFilters != null) { 5767 int size = matchingFilters.size(); 5768 for (int i = 0; i < size; i ++) { 5769 CrossProfileIntentFilter filter = matchingFilters.get(i); 5770 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5771 // Checking if there are activities in the target user that can handle the 5772 // intent. 5773 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5774 resolvedType, flags, sourceUserId); 5775 if (resolveInfo != null) { 5776 return resolveInfo; 5777 } 5778 } 5779 } 5780 } 5781 return null; 5782 } 5783 5784 // Return matching ResolveInfo in target user if any. 5785 private ResolveInfo queryCrossProfileIntents( 5786 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5787 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5788 if (matchingFilters != null) { 5789 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5790 // match the same intent. For performance reasons, it is better not to 5791 // run queryIntent twice for the same userId 5792 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5793 int size = matchingFilters.size(); 5794 for (int i = 0; i < size; i++) { 5795 CrossProfileIntentFilter filter = matchingFilters.get(i); 5796 int targetUserId = filter.getTargetUserId(); 5797 boolean skipCurrentProfile = 5798 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5799 boolean skipCurrentProfileIfNoMatchFound = 5800 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5801 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5802 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5803 // Checking if there are activities in the target user that can handle the 5804 // intent. 5805 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5806 resolvedType, flags, sourceUserId); 5807 if (resolveInfo != null) return resolveInfo; 5808 alreadyTriedUserIds.put(targetUserId, true); 5809 } 5810 } 5811 } 5812 return null; 5813 } 5814 5815 /** 5816 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5817 * will forward the intent to the filter's target user. 5818 * Otherwise, returns null. 5819 */ 5820 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5821 String resolvedType, int flags, int sourceUserId) { 5822 int targetUserId = filter.getTargetUserId(); 5823 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5824 resolvedType, flags, targetUserId); 5825 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5826 // If all the matches in the target profile are suspended, return null. 5827 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5828 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5829 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5830 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5831 targetUserId); 5832 } 5833 } 5834 } 5835 return null; 5836 } 5837 5838 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5839 int sourceUserId, int targetUserId) { 5840 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5841 long ident = Binder.clearCallingIdentity(); 5842 boolean targetIsProfile; 5843 try { 5844 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5845 } finally { 5846 Binder.restoreCallingIdentity(ident); 5847 } 5848 String className; 5849 if (targetIsProfile) { 5850 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5851 } else { 5852 className = FORWARD_INTENT_TO_PARENT; 5853 } 5854 ComponentName forwardingActivityComponentName = new ComponentName( 5855 mAndroidApplication.packageName, className); 5856 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5857 sourceUserId); 5858 if (!targetIsProfile) { 5859 forwardingActivityInfo.showUserIcon = targetUserId; 5860 forwardingResolveInfo.noResourceId = true; 5861 } 5862 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5863 forwardingResolveInfo.priority = 0; 5864 forwardingResolveInfo.preferredOrder = 0; 5865 forwardingResolveInfo.match = 0; 5866 forwardingResolveInfo.isDefault = true; 5867 forwardingResolveInfo.filter = filter; 5868 forwardingResolveInfo.targetUserId = targetUserId; 5869 return forwardingResolveInfo; 5870 } 5871 5872 @Override 5873 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5874 Intent[] specifics, String[] specificTypes, Intent intent, 5875 String resolvedType, int flags, int userId) { 5876 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5877 specificTypes, intent, resolvedType, flags, userId)); 5878 } 5879 5880 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5881 Intent[] specifics, String[] specificTypes, Intent intent, 5882 String resolvedType, int flags, int userId) { 5883 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5884 flags = updateFlagsForResolve(flags, userId, intent); 5885 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5886 false /* requireFullPermission */, false /* checkShell */, 5887 "query intent activity options"); 5888 final String resultsAction = intent.getAction(); 5889 5890 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5891 | PackageManager.GET_RESOLVED_FILTER, userId); 5892 5893 if (DEBUG_INTENT_MATCHING) { 5894 Log.v(TAG, "Query " + intent + ": " + results); 5895 } 5896 5897 int specificsPos = 0; 5898 int N; 5899 5900 // todo: note that the algorithm used here is O(N^2). This 5901 // isn't a problem in our current environment, but if we start running 5902 // into situations where we have more than 5 or 10 matches then this 5903 // should probably be changed to something smarter... 5904 5905 // First we go through and resolve each of the specific items 5906 // that were supplied, taking care of removing any corresponding 5907 // duplicate items in the generic resolve list. 5908 if (specifics != null) { 5909 for (int i=0; i<specifics.length; i++) { 5910 final Intent sintent = specifics[i]; 5911 if (sintent == null) { 5912 continue; 5913 } 5914 5915 if (DEBUG_INTENT_MATCHING) { 5916 Log.v(TAG, "Specific #" + i + ": " + sintent); 5917 } 5918 5919 String action = sintent.getAction(); 5920 if (resultsAction != null && resultsAction.equals(action)) { 5921 // If this action was explicitly requested, then don't 5922 // remove things that have it. 5923 action = null; 5924 } 5925 5926 ResolveInfo ri = null; 5927 ActivityInfo ai = null; 5928 5929 ComponentName comp = sintent.getComponent(); 5930 if (comp == null) { 5931 ri = resolveIntent( 5932 sintent, 5933 specificTypes != null ? specificTypes[i] : null, 5934 flags, userId); 5935 if (ri == null) { 5936 continue; 5937 } 5938 if (ri == mResolveInfo) { 5939 // ACK! Must do something better with this. 5940 } 5941 ai = ri.activityInfo; 5942 comp = new ComponentName(ai.applicationInfo.packageName, 5943 ai.name); 5944 } else { 5945 ai = getActivityInfo(comp, flags, userId); 5946 if (ai == null) { 5947 continue; 5948 } 5949 } 5950 5951 // Look for any generic query activities that are duplicates 5952 // of this specific one, and remove them from the results. 5953 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5954 N = results.size(); 5955 int j; 5956 for (j=specificsPos; j<N; j++) { 5957 ResolveInfo sri = results.get(j); 5958 if ((sri.activityInfo.name.equals(comp.getClassName()) 5959 && sri.activityInfo.applicationInfo.packageName.equals( 5960 comp.getPackageName())) 5961 || (action != null && sri.filter.matchAction(action))) { 5962 results.remove(j); 5963 if (DEBUG_INTENT_MATCHING) Log.v( 5964 TAG, "Removing duplicate item from " + j 5965 + " due to specific " + specificsPos); 5966 if (ri == null) { 5967 ri = sri; 5968 } 5969 j--; 5970 N--; 5971 } 5972 } 5973 5974 // Add this specific item to its proper place. 5975 if (ri == null) { 5976 ri = new ResolveInfo(); 5977 ri.activityInfo = ai; 5978 } 5979 results.add(specificsPos, ri); 5980 ri.specificIndex = i; 5981 specificsPos++; 5982 } 5983 } 5984 5985 // Now we go through the remaining generic results and remove any 5986 // duplicate actions that are found here. 5987 N = results.size(); 5988 for (int i=specificsPos; i<N-1; i++) { 5989 final ResolveInfo rii = results.get(i); 5990 if (rii.filter == null) { 5991 continue; 5992 } 5993 5994 // Iterate over all of the actions of this result's intent 5995 // filter... typically this should be just one. 5996 final Iterator<String> it = rii.filter.actionsIterator(); 5997 if (it == null) { 5998 continue; 5999 } 6000 while (it.hasNext()) { 6001 final String action = it.next(); 6002 if (resultsAction != null && resultsAction.equals(action)) { 6003 // If this action was explicitly requested, then don't 6004 // remove things that have it. 6005 continue; 6006 } 6007 for (int j=i+1; j<N; j++) { 6008 final ResolveInfo rij = results.get(j); 6009 if (rij.filter != null && rij.filter.hasAction(action)) { 6010 results.remove(j); 6011 if (DEBUG_INTENT_MATCHING) Log.v( 6012 TAG, "Removing duplicate item from " + j 6013 + " due to action " + action + " at " + i); 6014 j--; 6015 N--; 6016 } 6017 } 6018 } 6019 6020 // If the caller didn't request filter information, drop it now 6021 // so we don't have to marshall/unmarshall it. 6022 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6023 rii.filter = null; 6024 } 6025 } 6026 6027 // Filter out the caller activity if so requested. 6028 if (caller != null) { 6029 N = results.size(); 6030 for (int i=0; i<N; i++) { 6031 ActivityInfo ainfo = results.get(i).activityInfo; 6032 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6033 && caller.getClassName().equals(ainfo.name)) { 6034 results.remove(i); 6035 break; 6036 } 6037 } 6038 } 6039 6040 // If the caller didn't request filter information, 6041 // drop them now so we don't have to 6042 // marshall/unmarshall it. 6043 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6044 N = results.size(); 6045 for (int i=0; i<N; i++) { 6046 results.get(i).filter = null; 6047 } 6048 } 6049 6050 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6051 return results; 6052 } 6053 6054 @Override 6055 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6056 String resolvedType, int flags, int userId) { 6057 return new ParceledListSlice<>( 6058 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6059 } 6060 6061 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6062 String resolvedType, int flags, int userId) { 6063 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6064 flags = updateFlagsForResolve(flags, userId, intent); 6065 ComponentName comp = intent.getComponent(); 6066 if (comp == null) { 6067 if (intent.getSelector() != null) { 6068 intent = intent.getSelector(); 6069 comp = intent.getComponent(); 6070 } 6071 } 6072 if (comp != null) { 6073 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6074 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6075 if (ai != null) { 6076 ResolveInfo ri = new ResolveInfo(); 6077 ri.activityInfo = ai; 6078 list.add(ri); 6079 } 6080 return list; 6081 } 6082 6083 // reader 6084 synchronized (mPackages) { 6085 String pkgName = intent.getPackage(); 6086 if (pkgName == null) { 6087 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6088 } 6089 final PackageParser.Package pkg = mPackages.get(pkgName); 6090 if (pkg != null) { 6091 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6092 userId); 6093 } 6094 return Collections.emptyList(); 6095 } 6096 } 6097 6098 @Override 6099 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6100 if (!sUserManager.exists(userId)) return null; 6101 flags = updateFlagsForResolve(flags, userId, intent); 6102 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6103 if (query != null) { 6104 if (query.size() >= 1) { 6105 // If there is more than one service with the same priority, 6106 // just arbitrarily pick the first one. 6107 return query.get(0); 6108 } 6109 } 6110 return null; 6111 } 6112 6113 @Override 6114 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6115 String resolvedType, int flags, int userId) { 6116 return new ParceledListSlice<>( 6117 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6118 } 6119 6120 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6121 String resolvedType, int flags, int userId) { 6122 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6123 flags = updateFlagsForResolve(flags, userId, intent); 6124 ComponentName comp = intent.getComponent(); 6125 if (comp == null) { 6126 if (intent.getSelector() != null) { 6127 intent = intent.getSelector(); 6128 comp = intent.getComponent(); 6129 } 6130 } 6131 if (comp != null) { 6132 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6133 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6134 if (si != null) { 6135 final ResolveInfo ri = new ResolveInfo(); 6136 ri.serviceInfo = si; 6137 list.add(ri); 6138 } 6139 return list; 6140 } 6141 6142 // reader 6143 synchronized (mPackages) { 6144 String pkgName = intent.getPackage(); 6145 if (pkgName == null) { 6146 return mServices.queryIntent(intent, resolvedType, flags, userId); 6147 } 6148 final PackageParser.Package pkg = mPackages.get(pkgName); 6149 if (pkg != null) { 6150 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6151 userId); 6152 } 6153 return Collections.emptyList(); 6154 } 6155 } 6156 6157 @Override 6158 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6159 String resolvedType, int flags, int userId) { 6160 return new ParceledListSlice<>( 6161 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6162 } 6163 6164 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6165 Intent intent, String resolvedType, int flags, int userId) { 6166 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6167 flags = updateFlagsForResolve(flags, userId, intent); 6168 ComponentName comp = intent.getComponent(); 6169 if (comp == null) { 6170 if (intent.getSelector() != null) { 6171 intent = intent.getSelector(); 6172 comp = intent.getComponent(); 6173 } 6174 } 6175 if (comp != null) { 6176 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6177 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6178 if (pi != null) { 6179 final ResolveInfo ri = new ResolveInfo(); 6180 ri.providerInfo = pi; 6181 list.add(ri); 6182 } 6183 return list; 6184 } 6185 6186 // reader 6187 synchronized (mPackages) { 6188 String pkgName = intent.getPackage(); 6189 if (pkgName == null) { 6190 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6191 } 6192 final PackageParser.Package pkg = mPackages.get(pkgName); 6193 if (pkg != null) { 6194 return mProviders.queryIntentForPackage( 6195 intent, resolvedType, flags, pkg.providers, userId); 6196 } 6197 return Collections.emptyList(); 6198 } 6199 } 6200 6201 @Override 6202 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6203 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6204 flags = updateFlagsForPackage(flags, userId, null); 6205 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6207 true /* requireFullPermission */, false /* checkShell */, 6208 "get installed packages"); 6209 6210 // writer 6211 synchronized (mPackages) { 6212 ArrayList<PackageInfo> list; 6213 if (listUninstalled) { 6214 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6215 for (PackageSetting ps : mSettings.mPackages.values()) { 6216 final PackageInfo pi; 6217 if (ps.pkg != null) { 6218 pi = generatePackageInfo(ps, flags, userId); 6219 } else { 6220 pi = generatePackageInfo(ps, flags, userId); 6221 } 6222 if (pi != null) { 6223 list.add(pi); 6224 } 6225 } 6226 } else { 6227 list = new ArrayList<PackageInfo>(mPackages.size()); 6228 for (PackageParser.Package p : mPackages.values()) { 6229 final PackageInfo pi = 6230 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6231 if (pi != null) { 6232 list.add(pi); 6233 } 6234 } 6235 } 6236 6237 return new ParceledListSlice<PackageInfo>(list); 6238 } 6239 } 6240 6241 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6242 String[] permissions, boolean[] tmp, int flags, int userId) { 6243 int numMatch = 0; 6244 final PermissionsState permissionsState = ps.getPermissionsState(); 6245 for (int i=0; i<permissions.length; i++) { 6246 final String permission = permissions[i]; 6247 if (permissionsState.hasPermission(permission, userId)) { 6248 tmp[i] = true; 6249 numMatch++; 6250 } else { 6251 tmp[i] = false; 6252 } 6253 } 6254 if (numMatch == 0) { 6255 return; 6256 } 6257 final PackageInfo pi; 6258 if (ps.pkg != null) { 6259 pi = generatePackageInfo(ps, flags, userId); 6260 } else { 6261 pi = generatePackageInfo(ps, flags, userId); 6262 } 6263 // The above might return null in cases of uninstalled apps or install-state 6264 // skew across users/profiles. 6265 if (pi != null) { 6266 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6267 if (numMatch == permissions.length) { 6268 pi.requestedPermissions = permissions; 6269 } else { 6270 pi.requestedPermissions = new String[numMatch]; 6271 numMatch = 0; 6272 for (int i=0; i<permissions.length; i++) { 6273 if (tmp[i]) { 6274 pi.requestedPermissions[numMatch] = permissions[i]; 6275 numMatch++; 6276 } 6277 } 6278 } 6279 } 6280 list.add(pi); 6281 } 6282 } 6283 6284 @Override 6285 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6286 String[] permissions, int flags, int userId) { 6287 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6288 flags = updateFlagsForPackage(flags, userId, permissions); 6289 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6290 6291 // writer 6292 synchronized (mPackages) { 6293 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6294 boolean[] tmpBools = new boolean[permissions.length]; 6295 if (listUninstalled) { 6296 for (PackageSetting ps : mSettings.mPackages.values()) { 6297 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6298 } 6299 } else { 6300 for (PackageParser.Package pkg : mPackages.values()) { 6301 PackageSetting ps = (PackageSetting)pkg.mExtras; 6302 if (ps != null) { 6303 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6304 userId); 6305 } 6306 } 6307 } 6308 6309 return new ParceledListSlice<PackageInfo>(list); 6310 } 6311 } 6312 6313 @Override 6314 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6315 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6316 flags = updateFlagsForApplication(flags, userId, null); 6317 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6318 6319 // writer 6320 synchronized (mPackages) { 6321 ArrayList<ApplicationInfo> list; 6322 if (listUninstalled) { 6323 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6324 for (PackageSetting ps : mSettings.mPackages.values()) { 6325 ApplicationInfo ai; 6326 if (ps.pkg != null) { 6327 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6328 ps.readUserState(userId), userId); 6329 } else { 6330 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6331 } 6332 if (ai != null) { 6333 list.add(ai); 6334 } 6335 } 6336 } else { 6337 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6338 for (PackageParser.Package p : mPackages.values()) { 6339 if (p.mExtras != null) { 6340 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6341 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6342 if (ai != null) { 6343 list.add(ai); 6344 } 6345 } 6346 } 6347 } 6348 6349 return new ParceledListSlice<ApplicationInfo>(list); 6350 } 6351 } 6352 6353 @Override 6354 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6355 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6356 return null; 6357 } 6358 6359 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6360 "getEphemeralApplications"); 6361 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6362 true /* requireFullPermission */, false /* checkShell */, 6363 "getEphemeralApplications"); 6364 synchronized (mPackages) { 6365 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6366 .getEphemeralApplicationsLPw(userId); 6367 if (ephemeralApps != null) { 6368 return new ParceledListSlice<>(ephemeralApps); 6369 } 6370 } 6371 return null; 6372 } 6373 6374 @Override 6375 public boolean isEphemeralApplication(String packageName, int userId) { 6376 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6377 true /* requireFullPermission */, false /* checkShell */, 6378 "isEphemeral"); 6379 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6380 return false; 6381 } 6382 6383 if (!isCallerSameApp(packageName)) { 6384 return false; 6385 } 6386 synchronized (mPackages) { 6387 PackageParser.Package pkg = mPackages.get(packageName); 6388 if (pkg != null) { 6389 return pkg.applicationInfo.isEphemeralApp(); 6390 } 6391 } 6392 return false; 6393 } 6394 6395 @Override 6396 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6397 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6398 return null; 6399 } 6400 6401 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6402 true /* requireFullPermission */, false /* checkShell */, 6403 "getCookie"); 6404 if (!isCallerSameApp(packageName)) { 6405 return null; 6406 } 6407 synchronized (mPackages) { 6408 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6409 packageName, userId); 6410 } 6411 } 6412 6413 @Override 6414 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6415 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6416 return true; 6417 } 6418 6419 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6420 true /* requireFullPermission */, true /* checkShell */, 6421 "setCookie"); 6422 if (!isCallerSameApp(packageName)) { 6423 return false; 6424 } 6425 synchronized (mPackages) { 6426 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6427 packageName, cookie, userId); 6428 } 6429 } 6430 6431 @Override 6432 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6433 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6434 return null; 6435 } 6436 6437 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6438 "getEphemeralApplicationIcon"); 6439 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6440 true /* requireFullPermission */, false /* checkShell */, 6441 "getEphemeralApplicationIcon"); 6442 synchronized (mPackages) { 6443 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6444 packageName, userId); 6445 } 6446 } 6447 6448 private boolean isCallerSameApp(String packageName) { 6449 PackageParser.Package pkg = mPackages.get(packageName); 6450 return pkg != null 6451 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6452 } 6453 6454 @Override 6455 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6456 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6457 } 6458 6459 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6460 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6461 6462 // reader 6463 synchronized (mPackages) { 6464 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6465 final int userId = UserHandle.getCallingUserId(); 6466 while (i.hasNext()) { 6467 final PackageParser.Package p = i.next(); 6468 if (p.applicationInfo == null) continue; 6469 6470 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6471 && !p.applicationInfo.isDirectBootAware(); 6472 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6473 && p.applicationInfo.isDirectBootAware(); 6474 6475 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6476 && (!mSafeMode || isSystemApp(p)) 6477 && (matchesUnaware || matchesAware)) { 6478 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6479 if (ps != null) { 6480 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6481 ps.readUserState(userId), userId); 6482 if (ai != null) { 6483 finalList.add(ai); 6484 } 6485 } 6486 } 6487 } 6488 } 6489 6490 return finalList; 6491 } 6492 6493 @Override 6494 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6495 if (!sUserManager.exists(userId)) return null; 6496 flags = updateFlagsForComponent(flags, userId, name); 6497 // reader 6498 synchronized (mPackages) { 6499 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6500 PackageSetting ps = provider != null 6501 ? mSettings.mPackages.get(provider.owner.packageName) 6502 : null; 6503 return ps != null 6504 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6505 ? PackageParser.generateProviderInfo(provider, flags, 6506 ps.readUserState(userId), userId) 6507 : null; 6508 } 6509 } 6510 6511 /** 6512 * @deprecated 6513 */ 6514 @Deprecated 6515 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6516 // reader 6517 synchronized (mPackages) { 6518 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6519 .entrySet().iterator(); 6520 final int userId = UserHandle.getCallingUserId(); 6521 while (i.hasNext()) { 6522 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6523 PackageParser.Provider p = entry.getValue(); 6524 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6525 6526 if (ps != null && p.syncable 6527 && (!mSafeMode || (p.info.applicationInfo.flags 6528 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6529 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6530 ps.readUserState(userId), userId); 6531 if (info != null) { 6532 outNames.add(entry.getKey()); 6533 outInfo.add(info); 6534 } 6535 } 6536 } 6537 } 6538 } 6539 6540 @Override 6541 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6542 int uid, int flags) { 6543 final int userId = processName != null ? UserHandle.getUserId(uid) 6544 : UserHandle.getCallingUserId(); 6545 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6546 flags = updateFlagsForComponent(flags, userId, processName); 6547 6548 ArrayList<ProviderInfo> finalList = null; 6549 // reader 6550 synchronized (mPackages) { 6551 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6552 while (i.hasNext()) { 6553 final PackageParser.Provider p = i.next(); 6554 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6555 if (ps != null && p.info.authority != null 6556 && (processName == null 6557 || (p.info.processName.equals(processName) 6558 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6559 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6560 if (finalList == null) { 6561 finalList = new ArrayList<ProviderInfo>(3); 6562 } 6563 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6564 ps.readUserState(userId), userId); 6565 if (info != null) { 6566 finalList.add(info); 6567 } 6568 } 6569 } 6570 } 6571 6572 if (finalList != null) { 6573 Collections.sort(finalList, mProviderInitOrderSorter); 6574 return new ParceledListSlice<ProviderInfo>(finalList); 6575 } 6576 6577 return ParceledListSlice.emptyList(); 6578 } 6579 6580 @Override 6581 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6582 // reader 6583 synchronized (mPackages) { 6584 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6585 return PackageParser.generateInstrumentationInfo(i, flags); 6586 } 6587 } 6588 6589 @Override 6590 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6591 String targetPackage, int flags) { 6592 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6593 } 6594 6595 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6596 int flags) { 6597 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6598 6599 // reader 6600 synchronized (mPackages) { 6601 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6602 while (i.hasNext()) { 6603 final PackageParser.Instrumentation p = i.next(); 6604 if (targetPackage == null 6605 || targetPackage.equals(p.info.targetPackage)) { 6606 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6607 flags); 6608 if (ii != null) { 6609 finalList.add(ii); 6610 } 6611 } 6612 } 6613 } 6614 6615 return finalList; 6616 } 6617 6618 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6619 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6620 if (overlays == null) { 6621 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6622 return; 6623 } 6624 for (PackageParser.Package opkg : overlays.values()) { 6625 // Not much to do if idmap fails: we already logged the error 6626 // and we certainly don't want to abort installation of pkg simply 6627 // because an overlay didn't fit properly. For these reasons, 6628 // ignore the return value of createIdmapForPackagePairLI. 6629 createIdmapForPackagePairLI(pkg, opkg); 6630 } 6631 } 6632 6633 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6634 PackageParser.Package opkg) { 6635 if (!opkg.mTrustedOverlay) { 6636 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6637 opkg.baseCodePath + ": overlay not trusted"); 6638 return false; 6639 } 6640 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6641 if (overlaySet == null) { 6642 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6643 opkg.baseCodePath + " but target package has no known overlays"); 6644 return false; 6645 } 6646 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6647 // TODO: generate idmap for split APKs 6648 try { 6649 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6650 } catch (InstallerException e) { 6651 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6652 + opkg.baseCodePath); 6653 return false; 6654 } 6655 PackageParser.Package[] overlayArray = 6656 overlaySet.values().toArray(new PackageParser.Package[0]); 6657 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6658 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6659 return p1.mOverlayPriority - p2.mOverlayPriority; 6660 } 6661 }; 6662 Arrays.sort(overlayArray, cmp); 6663 6664 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6665 int i = 0; 6666 for (PackageParser.Package p : overlayArray) { 6667 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6668 } 6669 return true; 6670 } 6671 6672 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6673 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6674 try { 6675 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6676 } finally { 6677 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6678 } 6679 } 6680 6681 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6682 final File[] files = dir.listFiles(); 6683 if (ArrayUtils.isEmpty(files)) { 6684 Log.d(TAG, "No files in app dir " + dir); 6685 return; 6686 } 6687 6688 if (DEBUG_PACKAGE_SCANNING) { 6689 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6690 + " flags=0x" + Integer.toHexString(parseFlags)); 6691 } 6692 6693 for (File file : files) { 6694 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6695 && !PackageInstallerService.isStageName(file.getName()); 6696 if (!isPackage) { 6697 // Ignore entries which are not packages 6698 continue; 6699 } 6700 try { 6701 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6702 scanFlags, currentTime, null); 6703 } catch (PackageManagerException e) { 6704 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6705 6706 // Delete invalid userdata apps 6707 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6708 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6709 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6710 removeCodePathLI(file); 6711 } 6712 } 6713 } 6714 } 6715 6716 private static File getSettingsProblemFile() { 6717 File dataDir = Environment.getDataDirectory(); 6718 File systemDir = new File(dataDir, "system"); 6719 File fname = new File(systemDir, "uiderrors.txt"); 6720 return fname; 6721 } 6722 6723 static void reportSettingsProblem(int priority, String msg) { 6724 logCriticalInfo(priority, msg); 6725 } 6726 6727 static void logCriticalInfo(int priority, String msg) { 6728 Slog.println(priority, TAG, msg); 6729 EventLogTags.writePmCriticalInfo(msg); 6730 try { 6731 File fname = getSettingsProblemFile(); 6732 FileOutputStream out = new FileOutputStream(fname, true); 6733 PrintWriter pw = new FastPrintWriter(out); 6734 SimpleDateFormat formatter = new SimpleDateFormat(); 6735 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6736 pw.println(dateString + ": " + msg); 6737 pw.close(); 6738 FileUtils.setPermissions( 6739 fname.toString(), 6740 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6741 -1, -1); 6742 } catch (java.io.IOException e) { 6743 } 6744 } 6745 6746 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6747 if (srcFile.isDirectory()) { 6748 final File baseFile = new File(pkg.baseCodePath); 6749 long maxModifiedTime = baseFile.lastModified(); 6750 if (pkg.splitCodePaths != null) { 6751 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6752 final File splitFile = new File(pkg.splitCodePaths[i]); 6753 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6754 } 6755 } 6756 return maxModifiedTime; 6757 } 6758 return srcFile.lastModified(); 6759 } 6760 6761 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6762 final int policyFlags) throws PackageManagerException { 6763 // When upgrading from pre-N MR1, verify the package time stamp using the package 6764 // directory and not the APK file. 6765 final long lastModifiedTime = mIsPreNMR1Upgrade 6766 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6767 if (ps != null 6768 && ps.codePath.equals(srcFile) 6769 && ps.timeStamp == lastModifiedTime 6770 && !isCompatSignatureUpdateNeeded(pkg) 6771 && !isRecoverSignatureUpdateNeeded(pkg)) { 6772 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6773 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6774 ArraySet<PublicKey> signingKs; 6775 synchronized (mPackages) { 6776 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6777 } 6778 if (ps.signatures.mSignatures != null 6779 && ps.signatures.mSignatures.length != 0 6780 && signingKs != null) { 6781 // Optimization: reuse the existing cached certificates 6782 // if the package appears to be unchanged. 6783 pkg.mSignatures = ps.signatures.mSignatures; 6784 pkg.mSigningKeys = signingKs; 6785 return; 6786 } 6787 6788 Slog.w(TAG, "PackageSetting for " + ps.name 6789 + " is missing signatures. Collecting certs again to recover them."); 6790 } else { 6791 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6792 } 6793 6794 try { 6795 PackageParser.collectCertificates(pkg, policyFlags); 6796 } catch (PackageParserException e) { 6797 throw PackageManagerException.from(e); 6798 } 6799 } 6800 6801 /** 6802 * Traces a package scan. 6803 * @see #scanPackageLI(File, int, int, long, UserHandle) 6804 */ 6805 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6806 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6808 try { 6809 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6810 } finally { 6811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6812 } 6813 } 6814 6815 /** 6816 * Scans a package and returns the newly parsed package. 6817 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6818 */ 6819 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6820 long currentTime, UserHandle user) throws PackageManagerException { 6821 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6822 PackageParser pp = new PackageParser(); 6823 pp.setSeparateProcesses(mSeparateProcesses); 6824 pp.setOnlyCoreApps(mOnlyCore); 6825 pp.setDisplayMetrics(mMetrics); 6826 6827 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6828 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6829 } 6830 6831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6832 final PackageParser.Package pkg; 6833 try { 6834 pkg = pp.parsePackage(scanFile, parseFlags); 6835 } catch (PackageParserException e) { 6836 throw PackageManagerException.from(e); 6837 } finally { 6838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6839 } 6840 6841 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6842 } 6843 6844 /** 6845 * Scans a package and returns the newly parsed package. 6846 * @throws PackageManagerException on a parse error. 6847 */ 6848 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6849 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6850 throws PackageManagerException { 6851 // If the package has children and this is the first dive in the function 6852 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6853 // packages (parent and children) would be successfully scanned before the 6854 // actual scan since scanning mutates internal state and we want to atomically 6855 // install the package and its children. 6856 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6857 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6858 scanFlags |= SCAN_CHECK_ONLY; 6859 } 6860 } else { 6861 scanFlags &= ~SCAN_CHECK_ONLY; 6862 } 6863 6864 // Scan the parent 6865 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6866 scanFlags, currentTime, user); 6867 6868 // Scan the children 6869 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6870 for (int i = 0; i < childCount; i++) { 6871 PackageParser.Package childPackage = pkg.childPackages.get(i); 6872 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6873 currentTime, user); 6874 } 6875 6876 6877 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6878 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6879 } 6880 6881 return scannedPkg; 6882 } 6883 6884 /** 6885 * Scans a package and returns the newly parsed package. 6886 * @throws PackageManagerException on a parse error. 6887 */ 6888 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6889 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6890 throws PackageManagerException { 6891 PackageSetting ps = null; 6892 PackageSetting updatedPkg; 6893 // reader 6894 synchronized (mPackages) { 6895 // Look to see if we already know about this package. 6896 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6897 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6898 // This package has been renamed to its original name. Let's 6899 // use that. 6900 ps = mSettings.peekPackageLPr(oldName); 6901 } 6902 // If there was no original package, see one for the real package name. 6903 if (ps == null) { 6904 ps = mSettings.peekPackageLPr(pkg.packageName); 6905 } 6906 // Check to see if this package could be hiding/updating a system 6907 // package. Must look for it either under the original or real 6908 // package name depending on our state. 6909 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6910 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6911 6912 // If this is a package we don't know about on the system partition, we 6913 // may need to remove disabled child packages on the system partition 6914 // or may need to not add child packages if the parent apk is updated 6915 // on the data partition and no longer defines this child package. 6916 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6917 // If this is a parent package for an updated system app and this system 6918 // app got an OTA update which no longer defines some of the child packages 6919 // we have to prune them from the disabled system packages. 6920 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6921 if (disabledPs != null) { 6922 final int scannedChildCount = (pkg.childPackages != null) 6923 ? pkg.childPackages.size() : 0; 6924 final int disabledChildCount = disabledPs.childPackageNames != null 6925 ? disabledPs.childPackageNames.size() : 0; 6926 for (int i = 0; i < disabledChildCount; i++) { 6927 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6928 boolean disabledPackageAvailable = false; 6929 for (int j = 0; j < scannedChildCount; j++) { 6930 PackageParser.Package childPkg = pkg.childPackages.get(j); 6931 if (childPkg.packageName.equals(disabledChildPackageName)) { 6932 disabledPackageAvailable = true; 6933 break; 6934 } 6935 } 6936 if (!disabledPackageAvailable) { 6937 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6938 } 6939 } 6940 } 6941 } 6942 } 6943 6944 boolean updatedPkgBetter = false; 6945 // First check if this is a system package that may involve an update 6946 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6947 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6948 // it needs to drop FLAG_PRIVILEGED. 6949 if (locationIsPrivileged(scanFile)) { 6950 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6951 } else { 6952 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6953 } 6954 6955 if (ps != null && !ps.codePath.equals(scanFile)) { 6956 // The path has changed from what was last scanned... check the 6957 // version of the new path against what we have stored to determine 6958 // what to do. 6959 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6960 if (pkg.mVersionCode <= ps.versionCode) { 6961 // The system package has been updated and the code path does not match 6962 // Ignore entry. Skip it. 6963 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6964 + " ignored: updated version " + ps.versionCode 6965 + " better than this " + pkg.mVersionCode); 6966 if (!updatedPkg.codePath.equals(scanFile)) { 6967 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6968 + ps.name + " changing from " + updatedPkg.codePathString 6969 + " to " + scanFile); 6970 updatedPkg.codePath = scanFile; 6971 updatedPkg.codePathString = scanFile.toString(); 6972 updatedPkg.resourcePath = scanFile; 6973 updatedPkg.resourcePathString = scanFile.toString(); 6974 } 6975 updatedPkg.pkg = pkg; 6976 updatedPkg.versionCode = pkg.mVersionCode; 6977 6978 // Update the disabled system child packages to point to the package too. 6979 final int childCount = updatedPkg.childPackageNames != null 6980 ? updatedPkg.childPackageNames.size() : 0; 6981 for (int i = 0; i < childCount; i++) { 6982 String childPackageName = updatedPkg.childPackageNames.get(i); 6983 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6984 childPackageName); 6985 if (updatedChildPkg != null) { 6986 updatedChildPkg.pkg = pkg; 6987 updatedChildPkg.versionCode = pkg.mVersionCode; 6988 } 6989 } 6990 6991 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6992 + scanFile + " ignored: updated version " + ps.versionCode 6993 + " better than this " + pkg.mVersionCode); 6994 } else { 6995 // The current app on the system partition is better than 6996 // what we have updated to on the data partition; switch 6997 // back to the system partition version. 6998 // At this point, its safely assumed that package installation for 6999 // apps in system partition will go through. If not there won't be a working 7000 // version of the app 7001 // writer 7002 synchronized (mPackages) { 7003 // Just remove the loaded entries from package lists. 7004 mPackages.remove(ps.name); 7005 } 7006 7007 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7008 + " reverting from " + ps.codePathString 7009 + ": new version " + pkg.mVersionCode 7010 + " better than installed " + ps.versionCode); 7011 7012 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7013 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7014 synchronized (mInstallLock) { 7015 args.cleanUpResourcesLI(); 7016 } 7017 synchronized (mPackages) { 7018 mSettings.enableSystemPackageLPw(ps.name); 7019 } 7020 updatedPkgBetter = true; 7021 } 7022 } 7023 } 7024 7025 if (updatedPkg != null) { 7026 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7027 // initially 7028 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7029 7030 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7031 // flag set initially 7032 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7033 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7034 } 7035 } 7036 7037 // Verify certificates against what was last scanned 7038 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7039 7040 /* 7041 * A new system app appeared, but we already had a non-system one of the 7042 * same name installed earlier. 7043 */ 7044 boolean shouldHideSystemApp = false; 7045 if (updatedPkg == null && ps != null 7046 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7047 /* 7048 * Check to make sure the signatures match first. If they don't, 7049 * wipe the installed application and its data. 7050 */ 7051 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7052 != PackageManager.SIGNATURE_MATCH) { 7053 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7054 + " signatures don't match existing userdata copy; removing"); 7055 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7056 "scanPackageInternalLI")) { 7057 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7058 } 7059 ps = null; 7060 } else { 7061 /* 7062 * If the newly-added system app is an older version than the 7063 * already installed version, hide it. It will be scanned later 7064 * and re-added like an update. 7065 */ 7066 if (pkg.mVersionCode <= ps.versionCode) { 7067 shouldHideSystemApp = true; 7068 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7069 + " but new version " + pkg.mVersionCode + " better than installed " 7070 + ps.versionCode + "; hiding system"); 7071 } else { 7072 /* 7073 * The newly found system app is a newer version that the 7074 * one previously installed. Simply remove the 7075 * already-installed application and replace it with our own 7076 * while keeping the application data. 7077 */ 7078 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7079 + " reverting from " + ps.codePathString + ": new version " 7080 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7081 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7082 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7083 synchronized (mInstallLock) { 7084 args.cleanUpResourcesLI(); 7085 } 7086 } 7087 } 7088 } 7089 7090 // The apk is forward locked (not public) if its code and resources 7091 // are kept in different files. (except for app in either system or 7092 // vendor path). 7093 // TODO grab this value from PackageSettings 7094 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7095 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7096 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7097 } 7098 } 7099 7100 // TODO: extend to support forward-locked splits 7101 String resourcePath = null; 7102 String baseResourcePath = null; 7103 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7104 if (ps != null && ps.resourcePathString != null) { 7105 resourcePath = ps.resourcePathString; 7106 baseResourcePath = ps.resourcePathString; 7107 } else { 7108 // Should not happen at all. Just log an error. 7109 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7110 } 7111 } else { 7112 resourcePath = pkg.codePath; 7113 baseResourcePath = pkg.baseCodePath; 7114 } 7115 7116 // Set application objects path explicitly. 7117 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7118 pkg.setApplicationInfoCodePath(pkg.codePath); 7119 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7120 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7121 pkg.setApplicationInfoResourcePath(resourcePath); 7122 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7123 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7124 7125 // Note that we invoke the following method only if we are about to unpack an application 7126 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7127 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7128 7129 /* 7130 * If the system app should be overridden by a previously installed 7131 * data, hide the system app now and let the /data/app scan pick it up 7132 * again. 7133 */ 7134 if (shouldHideSystemApp) { 7135 synchronized (mPackages) { 7136 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7137 } 7138 } 7139 7140 return scannedPkg; 7141 } 7142 7143 private static String fixProcessName(String defProcessName, 7144 String processName, int uid) { 7145 if (processName == null) { 7146 return defProcessName; 7147 } 7148 return processName; 7149 } 7150 7151 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7152 throws PackageManagerException { 7153 if (pkgSetting.signatures.mSignatures != null) { 7154 // Already existing package. Make sure signatures match 7155 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7156 == PackageManager.SIGNATURE_MATCH; 7157 if (!match) { 7158 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7159 == PackageManager.SIGNATURE_MATCH; 7160 } 7161 if (!match) { 7162 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7163 == PackageManager.SIGNATURE_MATCH; 7164 } 7165 if (!match) { 7166 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7167 + pkg.packageName + " signatures do not match the " 7168 + "previously installed version; ignoring!"); 7169 } 7170 } 7171 7172 // Check for shared user signatures 7173 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7174 // Already existing package. Make sure signatures match 7175 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7176 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7177 if (!match) { 7178 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7179 == PackageManager.SIGNATURE_MATCH; 7180 } 7181 if (!match) { 7182 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7183 == PackageManager.SIGNATURE_MATCH; 7184 } 7185 if (!match) { 7186 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7187 "Package " + pkg.packageName 7188 + " has no signatures that match those in shared user " 7189 + pkgSetting.sharedUser.name + "; ignoring!"); 7190 } 7191 } 7192 } 7193 7194 /** 7195 * Enforces that only the system UID or root's UID can call a method exposed 7196 * via Binder. 7197 * 7198 * @param message used as message if SecurityException is thrown 7199 * @throws SecurityException if the caller is not system or root 7200 */ 7201 private static final void enforceSystemOrRoot(String message) { 7202 final int uid = Binder.getCallingUid(); 7203 if (uid != Process.SYSTEM_UID && uid != 0) { 7204 throw new SecurityException(message); 7205 } 7206 } 7207 7208 @Override 7209 public void performFstrimIfNeeded() { 7210 enforceSystemOrRoot("Only the system can request fstrim"); 7211 7212 // Before everything else, see whether we need to fstrim. 7213 try { 7214 IMountService ms = PackageHelper.getMountService(); 7215 if (ms != null) { 7216 boolean doTrim = false; 7217 final long interval = android.provider.Settings.Global.getLong( 7218 mContext.getContentResolver(), 7219 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7220 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7221 if (interval > 0) { 7222 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7223 if (timeSinceLast > interval) { 7224 doTrim = true; 7225 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7226 + "; running immediately"); 7227 } 7228 } 7229 if (doTrim) { 7230 final boolean dexOptDialogShown; 7231 synchronized (mPackages) { 7232 dexOptDialogShown = mDexOptDialogShown; 7233 } 7234 if (!isFirstBoot() && dexOptDialogShown) { 7235 try { 7236 ActivityManagerNative.getDefault().showBootMessage( 7237 mContext.getResources().getString( 7238 R.string.android_upgrading_fstrim), true); 7239 } catch (RemoteException e) { 7240 } 7241 } 7242 ms.runMaintenance(); 7243 } 7244 } else { 7245 Slog.e(TAG, "Mount service unavailable!"); 7246 } 7247 } catch (RemoteException e) { 7248 // Can't happen; MountService is local 7249 } 7250 } 7251 7252 @Override 7253 public void updatePackagesIfNeeded() { 7254 enforceSystemOrRoot("Only the system can request package update"); 7255 7256 // We need to re-extract after an OTA. 7257 boolean causeUpgrade = isUpgrade(); 7258 7259 // First boot or factory reset. 7260 // Note: we also handle devices that are upgrading to N right now as if it is their 7261 // first boot, as they do not have profile data. 7262 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7263 7264 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7265 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7266 7267 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7268 return; 7269 } 7270 7271 List<PackageParser.Package> pkgs; 7272 synchronized (mPackages) { 7273 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7274 } 7275 7276 final long startTime = System.nanoTime(); 7277 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7278 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7279 7280 final int elapsedTimeSeconds = 7281 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7282 7283 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7284 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7285 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7286 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7287 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7288 } 7289 7290 /** 7291 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7292 * containing statistics about the invocation. The array consists of three elements, 7293 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7294 * and {@code numberOfPackagesFailed}. 7295 */ 7296 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7297 String compilerFilter) { 7298 7299 int numberOfPackagesVisited = 0; 7300 int numberOfPackagesOptimized = 0; 7301 int numberOfPackagesSkipped = 0; 7302 int numberOfPackagesFailed = 0; 7303 final int numberOfPackagesToDexopt = pkgs.size(); 7304 7305 for (PackageParser.Package pkg : pkgs) { 7306 numberOfPackagesVisited++; 7307 7308 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7309 if (DEBUG_DEXOPT) { 7310 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7311 } 7312 numberOfPackagesSkipped++; 7313 continue; 7314 } 7315 7316 if (DEBUG_DEXOPT) { 7317 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7318 numberOfPackagesToDexopt + ": " + pkg.packageName); 7319 } 7320 7321 if (showDialog) { 7322 try { 7323 ActivityManagerNative.getDefault().showBootMessage( 7324 mContext.getResources().getString(R.string.android_upgrading_apk, 7325 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7326 } catch (RemoteException e) { 7327 } 7328 synchronized (mPackages) { 7329 mDexOptDialogShown = true; 7330 } 7331 } 7332 7333 // If the OTA updates a system app which was previously preopted to a non-preopted state 7334 // the app might end up being verified at runtime. That's because by default the apps 7335 // are verify-profile but for preopted apps there's no profile. 7336 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7337 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7338 // filter (by default interpret-only). 7339 // Note that at this stage unused apps are already filtered. 7340 if (isSystemApp(pkg) && 7341 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7342 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7343 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7344 } 7345 7346 // If the OTA updates a system app which was previously preopted to a non-preopted state 7347 // the app might end up being verified at runtime. That's because by default the apps 7348 // are verify-profile but for preopted apps there's no profile. 7349 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7350 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7351 // filter (by default interpret-only). 7352 // Note that at this stage unused apps are already filtered. 7353 if (isSystemApp(pkg) && 7354 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7355 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7356 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7357 } 7358 7359 // checkProfiles is false to avoid merging profiles during boot which 7360 // might interfere with background compilation (b/28612421). 7361 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7362 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7363 // trade-off worth doing to save boot time work. 7364 int dexOptStatus = performDexOptTraced(pkg.packageName, 7365 false /* checkProfiles */, 7366 compilerFilter, 7367 false /* force */); 7368 switch (dexOptStatus) { 7369 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7370 numberOfPackagesOptimized++; 7371 break; 7372 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7373 numberOfPackagesSkipped++; 7374 break; 7375 case PackageDexOptimizer.DEX_OPT_FAILED: 7376 numberOfPackagesFailed++; 7377 break; 7378 default: 7379 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7380 break; 7381 } 7382 } 7383 7384 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7385 numberOfPackagesFailed }; 7386 } 7387 7388 @Override 7389 public void notifyPackageUse(String packageName, int reason) { 7390 synchronized (mPackages) { 7391 PackageParser.Package p = mPackages.get(packageName); 7392 if (p == null) { 7393 return; 7394 } 7395 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7396 } 7397 } 7398 7399 @Override 7400 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7401 int userId = UserHandle.getCallingUserId(); 7402 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7403 if (ai == null) { 7404 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7405 + loadingPackageName + ", user=" + userId); 7406 return; 7407 } 7408 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7409 } 7410 7411 // TODO: this is not used nor needed. Delete it. 7412 @Override 7413 public boolean performDexOptIfNeeded(String packageName) { 7414 int dexOptStatus = performDexOptTraced(packageName, 7415 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7416 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7417 } 7418 7419 @Override 7420 public boolean performDexOpt(String packageName, 7421 boolean checkProfiles, int compileReason, boolean force) { 7422 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7423 getCompilerFilterForReason(compileReason), force); 7424 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7425 } 7426 7427 @Override 7428 public boolean performDexOptMode(String packageName, 7429 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7430 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7431 targetCompilerFilter, force); 7432 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7433 } 7434 7435 private int performDexOptTraced(String packageName, 7436 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7438 try { 7439 return performDexOptInternal(packageName, checkProfiles, 7440 targetCompilerFilter, force); 7441 } finally { 7442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7443 } 7444 } 7445 7446 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7447 // if the package can now be considered up to date for the given filter. 7448 private int performDexOptInternal(String packageName, 7449 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7450 PackageParser.Package p; 7451 synchronized (mPackages) { 7452 p = mPackages.get(packageName); 7453 if (p == null) { 7454 // Package could not be found. Report failure. 7455 return PackageDexOptimizer.DEX_OPT_FAILED; 7456 } 7457 mPackageUsage.maybeWriteAsync(mPackages); 7458 mCompilerStats.maybeWriteAsync(); 7459 } 7460 long callingId = Binder.clearCallingIdentity(); 7461 try { 7462 synchronized (mInstallLock) { 7463 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7464 targetCompilerFilter, force); 7465 } 7466 } finally { 7467 Binder.restoreCallingIdentity(callingId); 7468 } 7469 } 7470 7471 public ArraySet<String> getOptimizablePackages() { 7472 ArraySet<String> pkgs = new ArraySet<String>(); 7473 synchronized (mPackages) { 7474 for (PackageParser.Package p : mPackages.values()) { 7475 if (PackageDexOptimizer.canOptimizePackage(p)) { 7476 pkgs.add(p.packageName); 7477 } 7478 } 7479 } 7480 return pkgs; 7481 } 7482 7483 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7484 boolean checkProfiles, String targetCompilerFilter, 7485 boolean force) { 7486 // Select the dex optimizer based on the force parameter. 7487 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7488 // allocate an object here. 7489 PackageDexOptimizer pdo = force 7490 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7491 : mPackageDexOptimizer; 7492 7493 // Optimize all dependencies first. Note: we ignore the return value and march on 7494 // on errors. 7495 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7496 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7497 if (!deps.isEmpty()) { 7498 for (PackageParser.Package depPackage : deps) { 7499 // TODO: Analyze and investigate if we (should) profile libraries. 7500 // Currently this will do a full compilation of the library by default. 7501 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7502 false /* checkProfiles */, 7503 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7504 getOrCreateCompilerPackageStats(depPackage)); 7505 } 7506 } 7507 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7508 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7509 } 7510 7511 // Performs dexopt on the used secondary dex files belonging to the given package. 7512 // Returns true if all dex files were process successfully (which could mean either dexopt or 7513 // skip). Returns false if any of the files caused errors. 7514 @Override 7515 public boolean performDexOptSecondary(String packageName, String compilerFilter, 7516 boolean force) { 7517 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 7518 } 7519 7520 /** 7521 * Reconcile the information we have about the secondary dex files belonging to 7522 * {@code packagName} and the actual dex files. For all dex files that were 7523 * deleted, update the internal records and delete the generated oat files. 7524 */ 7525 @Override 7526 public void reconcileSecondaryDexFiles(String packageName) { 7527 mDexManager.reconcileSecondaryDexFiles(packageName); 7528 } 7529 7530 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7531 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7532 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7533 Set<String> collectedNames = new HashSet<>(); 7534 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7535 7536 retValue.remove(p); 7537 7538 return retValue; 7539 } else { 7540 return Collections.emptyList(); 7541 } 7542 } 7543 7544 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7545 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7546 if (!collectedNames.contains(p.packageName)) { 7547 collectedNames.add(p.packageName); 7548 collected.add(p); 7549 7550 if (p.usesLibraries != null) { 7551 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7552 } 7553 if (p.usesOptionalLibraries != null) { 7554 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7555 collectedNames); 7556 } 7557 } 7558 } 7559 7560 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7561 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7562 for (String libName : libs) { 7563 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7564 if (libPkg != null) { 7565 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7566 } 7567 } 7568 } 7569 7570 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7571 synchronized (mPackages) { 7572 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7573 if (lib != null && lib.apk != null) { 7574 return mPackages.get(lib.apk); 7575 } 7576 } 7577 return null; 7578 } 7579 7580 public void shutdown() { 7581 mPackageUsage.writeNow(mPackages); 7582 mCompilerStats.writeNow(); 7583 } 7584 7585 @Override 7586 public void dumpProfiles(String packageName) { 7587 PackageParser.Package pkg; 7588 synchronized (mPackages) { 7589 pkg = mPackages.get(packageName); 7590 if (pkg == null) { 7591 throw new IllegalArgumentException("Unknown package: " + packageName); 7592 } 7593 } 7594 /* Only the shell, root, or the app user should be able to dump profiles. */ 7595 int callingUid = Binder.getCallingUid(); 7596 if (callingUid != Process.SHELL_UID && 7597 callingUid != Process.ROOT_UID && 7598 callingUid != pkg.applicationInfo.uid) { 7599 throw new SecurityException("dumpProfiles"); 7600 } 7601 7602 synchronized (mInstallLock) { 7603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7604 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7605 try { 7606 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7607 String codePaths = TextUtils.join(";", allCodePaths); 7608 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7609 } catch (InstallerException e) { 7610 Slog.w(TAG, "Failed to dump profiles", e); 7611 } 7612 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7613 } 7614 } 7615 7616 @Override 7617 public void forceDexOpt(String packageName) { 7618 enforceSystemOrRoot("forceDexOpt"); 7619 7620 PackageParser.Package pkg; 7621 synchronized (mPackages) { 7622 pkg = mPackages.get(packageName); 7623 if (pkg == null) { 7624 throw new IllegalArgumentException("Unknown package: " + packageName); 7625 } 7626 } 7627 7628 synchronized (mInstallLock) { 7629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7630 7631 // Whoever is calling forceDexOpt wants a fully compiled package. 7632 // Don't use profiles since that may cause compilation to be skipped. 7633 final int res = performDexOptInternalWithDependenciesLI(pkg, 7634 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7635 true /* force */); 7636 7637 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7638 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7639 throw new IllegalStateException("Failed to dexopt: " + res); 7640 } 7641 } 7642 } 7643 7644 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7645 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7646 Slog.w(TAG, "Unable to update from " + oldPkg.name 7647 + " to " + newPkg.packageName 7648 + ": old package not in system partition"); 7649 return false; 7650 } else if (mPackages.get(oldPkg.name) != null) { 7651 Slog.w(TAG, "Unable to update from " + oldPkg.name 7652 + " to " + newPkg.packageName 7653 + ": old package still exists"); 7654 return false; 7655 } 7656 return true; 7657 } 7658 7659 void removeCodePathLI(File codePath) { 7660 if (codePath.isDirectory()) { 7661 try { 7662 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7663 } catch (InstallerException e) { 7664 Slog.w(TAG, "Failed to remove code path", e); 7665 } 7666 } else { 7667 codePath.delete(); 7668 } 7669 } 7670 7671 private int[] resolveUserIds(int userId) { 7672 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7673 } 7674 7675 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7676 if (pkg == null) { 7677 Slog.wtf(TAG, "Package was null!", new Throwable()); 7678 return; 7679 } 7680 clearAppDataLeafLIF(pkg, userId, flags); 7681 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7682 for (int i = 0; i < childCount; i++) { 7683 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7684 } 7685 } 7686 7687 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7688 final PackageSetting ps; 7689 synchronized (mPackages) { 7690 ps = mSettings.mPackages.get(pkg.packageName); 7691 } 7692 for (int realUserId : resolveUserIds(userId)) { 7693 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7694 try { 7695 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7696 ceDataInode); 7697 } catch (InstallerException e) { 7698 Slog.w(TAG, String.valueOf(e)); 7699 } 7700 } 7701 } 7702 7703 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7704 if (pkg == null) { 7705 Slog.wtf(TAG, "Package was null!", new Throwable()); 7706 return; 7707 } 7708 destroyAppDataLeafLIF(pkg, userId, flags); 7709 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7710 for (int i = 0; i < childCount; i++) { 7711 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7712 } 7713 } 7714 7715 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7716 final PackageSetting ps; 7717 synchronized (mPackages) { 7718 ps = mSettings.mPackages.get(pkg.packageName); 7719 } 7720 for (int realUserId : resolveUserIds(userId)) { 7721 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7722 try { 7723 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7724 ceDataInode); 7725 } catch (InstallerException e) { 7726 Slog.w(TAG, String.valueOf(e)); 7727 } 7728 } 7729 } 7730 7731 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7732 if (pkg == null) { 7733 Slog.wtf(TAG, "Package was null!", new Throwable()); 7734 return; 7735 } 7736 destroyAppProfilesLeafLIF(pkg); 7737 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7738 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7739 for (int i = 0; i < childCount; i++) { 7740 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7741 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7742 true /* removeBaseMarker */); 7743 } 7744 } 7745 7746 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7747 boolean removeBaseMarker) { 7748 if (pkg.isForwardLocked()) { 7749 return; 7750 } 7751 7752 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7753 try { 7754 path = PackageManagerServiceUtils.realpath(new File(path)); 7755 } catch (IOException e) { 7756 // TODO: Should we return early here ? 7757 Slog.w(TAG, "Failed to get canonical path", e); 7758 continue; 7759 } 7760 7761 final String useMarker = path.replace('/', '@'); 7762 for (int realUserId : resolveUserIds(userId)) { 7763 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7764 if (removeBaseMarker) { 7765 File foreignUseMark = new File(profileDir, useMarker); 7766 if (foreignUseMark.exists()) { 7767 if (!foreignUseMark.delete()) { 7768 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7769 + pkg.packageName); 7770 } 7771 } 7772 } 7773 7774 File[] markers = profileDir.listFiles(); 7775 if (markers != null) { 7776 final String searchString = "@" + pkg.packageName + "@"; 7777 // We also delete all markers that contain the package name we're 7778 // uninstalling. These are associated with secondary dex-files belonging 7779 // to the package. Reconstructing the path of these dex files is messy 7780 // in general. 7781 for (File marker : markers) { 7782 if (marker.getName().indexOf(searchString) > 0) { 7783 if (!marker.delete()) { 7784 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7785 + pkg.packageName); 7786 } 7787 } 7788 } 7789 } 7790 } 7791 } 7792 } 7793 7794 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7795 try { 7796 mInstaller.destroyAppProfiles(pkg.packageName); 7797 } catch (InstallerException e) { 7798 Slog.w(TAG, String.valueOf(e)); 7799 } 7800 } 7801 7802 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7803 if (pkg == null) { 7804 Slog.wtf(TAG, "Package was null!", new Throwable()); 7805 return; 7806 } 7807 clearAppProfilesLeafLIF(pkg); 7808 // We don't remove the base foreign use marker when clearing profiles because 7809 // we will rename it when the app is updated. Unlike the actual profile contents, 7810 // the foreign use marker is good across installs. 7811 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7812 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7813 for (int i = 0; i < childCount; i++) { 7814 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7815 } 7816 } 7817 7818 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7819 try { 7820 mInstaller.clearAppProfiles(pkg.packageName); 7821 } catch (InstallerException e) { 7822 Slog.w(TAG, String.valueOf(e)); 7823 } 7824 } 7825 7826 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7827 long lastUpdateTime) { 7828 // Set parent install/update time 7829 PackageSetting ps = (PackageSetting) pkg.mExtras; 7830 if (ps != null) { 7831 ps.firstInstallTime = firstInstallTime; 7832 ps.lastUpdateTime = lastUpdateTime; 7833 } 7834 // Set children install/update time 7835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7836 for (int i = 0; i < childCount; i++) { 7837 PackageParser.Package childPkg = pkg.childPackages.get(i); 7838 ps = (PackageSetting) childPkg.mExtras; 7839 if (ps != null) { 7840 ps.firstInstallTime = firstInstallTime; 7841 ps.lastUpdateTime = lastUpdateTime; 7842 } 7843 } 7844 } 7845 7846 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7847 PackageParser.Package changingLib) { 7848 if (file.path != null) { 7849 usesLibraryFiles.add(file.path); 7850 return; 7851 } 7852 PackageParser.Package p = mPackages.get(file.apk); 7853 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7854 // If we are doing this while in the middle of updating a library apk, 7855 // then we need to make sure to use that new apk for determining the 7856 // dependencies here. (We haven't yet finished committing the new apk 7857 // to the package manager state.) 7858 if (p == null || p.packageName.equals(changingLib.packageName)) { 7859 p = changingLib; 7860 } 7861 } 7862 if (p != null) { 7863 usesLibraryFiles.addAll(p.getAllCodePaths()); 7864 } 7865 } 7866 7867 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7868 PackageParser.Package changingLib) throws PackageManagerException { 7869 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7870 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7871 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7872 for (int i=0; i<N; i++) { 7873 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7874 if (file == null) { 7875 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7876 "Package " + pkg.packageName + " requires unavailable shared library " 7877 + pkg.usesLibraries.get(i) + "; failing!"); 7878 } 7879 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7880 } 7881 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7882 for (int i=0; i<N; i++) { 7883 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7884 if (file == null) { 7885 Slog.w(TAG, "Package " + pkg.packageName 7886 + " desires unavailable shared library " 7887 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7888 } else { 7889 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7890 } 7891 } 7892 N = usesLibraryFiles.size(); 7893 if (N > 0) { 7894 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7895 } else { 7896 pkg.usesLibraryFiles = null; 7897 } 7898 } 7899 } 7900 7901 private static boolean hasString(List<String> list, List<String> which) { 7902 if (list == null) { 7903 return false; 7904 } 7905 for (int i=list.size()-1; i>=0; i--) { 7906 for (int j=which.size()-1; j>=0; j--) { 7907 if (which.get(j).equals(list.get(i))) { 7908 return true; 7909 } 7910 } 7911 } 7912 return false; 7913 } 7914 7915 private void updateAllSharedLibrariesLPw() { 7916 for (PackageParser.Package pkg : mPackages.values()) { 7917 try { 7918 updateSharedLibrariesLPw(pkg, null); 7919 } catch (PackageManagerException e) { 7920 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7921 } 7922 } 7923 } 7924 7925 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7926 PackageParser.Package changingPkg) { 7927 ArrayList<PackageParser.Package> res = null; 7928 for (PackageParser.Package pkg : mPackages.values()) { 7929 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7930 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7931 if (res == null) { 7932 res = new ArrayList<PackageParser.Package>(); 7933 } 7934 res.add(pkg); 7935 try { 7936 updateSharedLibrariesLPw(pkg, changingPkg); 7937 } catch (PackageManagerException e) { 7938 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7939 } 7940 } 7941 } 7942 return res; 7943 } 7944 7945 /** 7946 * Derive the value of the {@code cpuAbiOverride} based on the provided 7947 * value and an optional stored value from the package settings. 7948 */ 7949 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7950 String cpuAbiOverride = null; 7951 7952 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7953 cpuAbiOverride = null; 7954 } else if (abiOverride != null) { 7955 cpuAbiOverride = abiOverride; 7956 } else if (settings != null) { 7957 cpuAbiOverride = settings.cpuAbiOverrideString; 7958 } 7959 7960 return cpuAbiOverride; 7961 } 7962 7963 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7964 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7965 throws PackageManagerException { 7966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7967 // If the package has children and this is the first dive in the function 7968 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7969 // whether all packages (parent and children) would be successfully scanned 7970 // before the actual scan since scanning mutates internal state and we want 7971 // to atomically install the package and its children. 7972 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7973 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7974 scanFlags |= SCAN_CHECK_ONLY; 7975 } 7976 } else { 7977 scanFlags &= ~SCAN_CHECK_ONLY; 7978 } 7979 7980 final PackageParser.Package scannedPkg; 7981 try { 7982 // Scan the parent 7983 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7984 // Scan the children 7985 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7986 for (int i = 0; i < childCount; i++) { 7987 PackageParser.Package childPkg = pkg.childPackages.get(i); 7988 scanPackageLI(childPkg, policyFlags, 7989 scanFlags, currentTime, user); 7990 } 7991 } finally { 7992 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7993 } 7994 7995 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7996 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7997 } 7998 7999 return scannedPkg; 8000 } 8001 8002 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8003 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8004 boolean success = false; 8005 try { 8006 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8007 currentTime, user); 8008 success = true; 8009 return res; 8010 } finally { 8011 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8012 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8013 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8014 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8015 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8016 } 8017 } 8018 } 8019 8020 /** 8021 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8022 */ 8023 private static boolean apkHasCode(String fileName) { 8024 StrictJarFile jarFile = null; 8025 try { 8026 jarFile = new StrictJarFile(fileName, 8027 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8028 return jarFile.findEntry("classes.dex") != null; 8029 } catch (IOException ignore) { 8030 } finally { 8031 try { 8032 if (jarFile != null) { 8033 jarFile.close(); 8034 } 8035 } catch (IOException ignore) {} 8036 } 8037 return false; 8038 } 8039 8040 /** 8041 * Enforces code policy for the package. This ensures that if an APK has 8042 * declared hasCode="true" in its manifest that the APK actually contains 8043 * code. 8044 * 8045 * @throws PackageManagerException If bytecode could not be found when it should exist 8046 */ 8047 private static void enforceCodePolicy(PackageParser.Package pkg) 8048 throws PackageManagerException { 8049 final boolean shouldHaveCode = 8050 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8051 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8052 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8053 "Package " + pkg.baseCodePath + " code is missing"); 8054 } 8055 8056 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8057 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8058 final boolean splitShouldHaveCode = 8059 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8060 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8061 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8062 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8063 } 8064 } 8065 } 8066 } 8067 8068 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8069 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8070 throws PackageManagerException { 8071 final File scanFile = new File(pkg.codePath); 8072 if (pkg.applicationInfo.getCodePath() == null || 8073 pkg.applicationInfo.getResourcePath() == null) { 8074 // Bail out. The resource and code paths haven't been set. 8075 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8076 "Code and resource paths haven't been set correctly"); 8077 } 8078 8079 // Apply policy 8080 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8081 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8082 if (pkg.applicationInfo.isDirectBootAware()) { 8083 // we're direct boot aware; set for all components 8084 for (PackageParser.Service s : pkg.services) { 8085 s.info.encryptionAware = s.info.directBootAware = true; 8086 } 8087 for (PackageParser.Provider p : pkg.providers) { 8088 p.info.encryptionAware = p.info.directBootAware = true; 8089 } 8090 for (PackageParser.Activity a : pkg.activities) { 8091 a.info.encryptionAware = a.info.directBootAware = true; 8092 } 8093 for (PackageParser.Activity r : pkg.receivers) { 8094 r.info.encryptionAware = r.info.directBootAware = true; 8095 } 8096 } 8097 } else { 8098 // Only allow system apps to be flagged as core apps. 8099 pkg.coreApp = false; 8100 // clear flags not applicable to regular apps 8101 pkg.applicationInfo.privateFlags &= 8102 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8103 pkg.applicationInfo.privateFlags &= 8104 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8105 } 8106 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8107 8108 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8109 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8110 } 8111 8112 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8113 enforceCodePolicy(pkg); 8114 } 8115 8116 if (mCustomResolverComponentName != null && 8117 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8118 setUpCustomResolverActivity(pkg); 8119 } 8120 8121 if (pkg.packageName.equals("android")) { 8122 synchronized (mPackages) { 8123 if (mAndroidApplication != null) { 8124 Slog.w(TAG, "*************************************************"); 8125 Slog.w(TAG, "Core android package being redefined. Skipping."); 8126 Slog.w(TAG, " file=" + scanFile); 8127 Slog.w(TAG, "*************************************************"); 8128 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8129 "Core android package being redefined. Skipping."); 8130 } 8131 8132 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8133 // Set up information for our fall-back user intent resolution activity. 8134 mPlatformPackage = pkg; 8135 pkg.mVersionCode = mSdkVersion; 8136 mAndroidApplication = pkg.applicationInfo; 8137 8138 if (!mResolverReplaced) { 8139 mResolveActivity.applicationInfo = mAndroidApplication; 8140 mResolveActivity.name = ResolverActivity.class.getName(); 8141 mResolveActivity.packageName = mAndroidApplication.packageName; 8142 mResolveActivity.processName = "system:ui"; 8143 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8144 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8145 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8146 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8147 mResolveActivity.exported = true; 8148 mResolveActivity.enabled = true; 8149 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8150 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8151 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8152 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8153 | ActivityInfo.CONFIG_ORIENTATION 8154 | ActivityInfo.CONFIG_KEYBOARD 8155 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8156 mResolveInfo.activityInfo = mResolveActivity; 8157 mResolveInfo.priority = 0; 8158 mResolveInfo.preferredOrder = 0; 8159 mResolveInfo.match = 0; 8160 mResolveComponentName = new ComponentName( 8161 mAndroidApplication.packageName, mResolveActivity.name); 8162 } 8163 } 8164 } 8165 } 8166 8167 if (DEBUG_PACKAGE_SCANNING) { 8168 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8169 Log.d(TAG, "Scanning package " + pkg.packageName); 8170 } 8171 8172 synchronized (mPackages) { 8173 if (mPackages.containsKey(pkg.packageName) 8174 || mSharedLibraries.containsKey(pkg.packageName)) { 8175 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8176 "Application package " + pkg.packageName 8177 + " already installed. Skipping duplicate."); 8178 } 8179 8180 // If we're only installing presumed-existing packages, require that the 8181 // scanned APK is both already known and at the path previously established 8182 // for it. Previously unknown packages we pick up normally, but if we have an 8183 // a priori expectation about this package's install presence, enforce it. 8184 // With a singular exception for new system packages. When an OTA contains 8185 // a new system package, we allow the codepath to change from a system location 8186 // to the user-installed location. If we don't allow this change, any newer, 8187 // user-installed version of the application will be ignored. 8188 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8189 if (mExpectingBetter.containsKey(pkg.packageName)) { 8190 logCriticalInfo(Log.WARN, 8191 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8192 } else { 8193 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8194 if (known != null) { 8195 if (DEBUG_PACKAGE_SCANNING) { 8196 Log.d(TAG, "Examining " + pkg.codePath 8197 + " and requiring known paths " + known.codePathString 8198 + " & " + known.resourcePathString); 8199 } 8200 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8201 || !pkg.applicationInfo.getResourcePath().equals( 8202 known.resourcePathString)) { 8203 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8204 "Application package " + pkg.packageName 8205 + " found at " + pkg.applicationInfo.getCodePath() 8206 + " but expected at " + known.codePathString 8207 + "; ignoring."); 8208 } 8209 } 8210 } 8211 } 8212 } 8213 8214 // Initialize package source and resource directories 8215 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8216 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8217 8218 SharedUserSetting suid = null; 8219 PackageSetting pkgSetting = null; 8220 8221 if (!isSystemApp(pkg)) { 8222 // Only system apps can use these features. 8223 pkg.mOriginalPackages = null; 8224 pkg.mRealPackage = null; 8225 pkg.mAdoptPermissions = null; 8226 } 8227 8228 // Getting the package setting may have a side-effect, so if we 8229 // are only checking if scan would succeed, stash a copy of the 8230 // old setting to restore at the end. 8231 PackageSetting nonMutatedPs = null; 8232 8233 // writer 8234 synchronized (mPackages) { 8235 if (pkg.mSharedUserId != null) { 8236 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8237 if (suid == null) { 8238 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8239 "Creating application package " + pkg.packageName 8240 + " for shared user failed"); 8241 } 8242 if (DEBUG_PACKAGE_SCANNING) { 8243 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8244 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8245 + "): packages=" + suid.packages); 8246 } 8247 } 8248 8249 // Check if we are renaming from an original package name. 8250 PackageSetting origPackage = null; 8251 String realName = null; 8252 if (pkg.mOriginalPackages != null) { 8253 // This package may need to be renamed to a previously 8254 // installed name. Let's check on that... 8255 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8256 if (pkg.mOriginalPackages.contains(renamed)) { 8257 // This package had originally been installed as the 8258 // original name, and we have already taken care of 8259 // transitioning to the new one. Just update the new 8260 // one to continue using the old name. 8261 realName = pkg.mRealPackage; 8262 if (!pkg.packageName.equals(renamed)) { 8263 // Callers into this function may have already taken 8264 // care of renaming the package; only do it here if 8265 // it is not already done. 8266 pkg.setPackageName(renamed); 8267 } 8268 8269 } else { 8270 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8271 if ((origPackage = mSettings.peekPackageLPr( 8272 pkg.mOriginalPackages.get(i))) != null) { 8273 // We do have the package already installed under its 8274 // original name... should we use it? 8275 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8276 // New package is not compatible with original. 8277 origPackage = null; 8278 continue; 8279 } else if (origPackage.sharedUser != null) { 8280 // Make sure uid is compatible between packages. 8281 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8282 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8283 + " to " + pkg.packageName + ": old uid " 8284 + origPackage.sharedUser.name 8285 + " differs from " + pkg.mSharedUserId); 8286 origPackage = null; 8287 continue; 8288 } 8289 // TODO: Add case when shared user id is added [b/28144775] 8290 } else { 8291 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8292 + pkg.packageName + " to old name " + origPackage.name); 8293 } 8294 break; 8295 } 8296 } 8297 } 8298 } 8299 8300 if (mTransferedPackages.contains(pkg.packageName)) { 8301 Slog.w(TAG, "Package " + pkg.packageName 8302 + " was transferred to another, but its .apk remains"); 8303 } 8304 8305 // See comments in nonMutatedPs declaration 8306 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8307 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8308 if (foundPs != null) { 8309 nonMutatedPs = new PackageSetting(foundPs); 8310 } 8311 } 8312 8313 // Just create the setting, don't add it yet. For already existing packages 8314 // the PkgSetting exists already and doesn't have to be created. 8315 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8316 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8317 pkg.applicationInfo.primaryCpuAbi, 8318 pkg.applicationInfo.secondaryCpuAbi, 8319 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8320 user, false); 8321 if (pkgSetting == null) { 8322 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8323 "Creating application package " + pkg.packageName + " failed"); 8324 } 8325 8326 if (pkgSetting.origPackage != null) { 8327 // If we are first transitioning from an original package, 8328 // fix up the new package's name now. We need to do this after 8329 // looking up the package under its new name, so getPackageLP 8330 // can take care of fiddling things correctly. 8331 pkg.setPackageName(origPackage.name); 8332 8333 // File a report about this. 8334 String msg = "New package " + pkgSetting.realName 8335 + " renamed to replace old package " + pkgSetting.name; 8336 reportSettingsProblem(Log.WARN, msg); 8337 8338 // Make a note of it. 8339 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8340 mTransferedPackages.add(origPackage.name); 8341 } 8342 8343 // No longer need to retain this. 8344 pkgSetting.origPackage = null; 8345 } 8346 8347 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8348 // Make a note of it. 8349 mTransferedPackages.add(pkg.packageName); 8350 } 8351 8352 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8353 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8354 } 8355 8356 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8357 // Check all shared libraries and map to their actual file path. 8358 // We only do this here for apps not on a system dir, because those 8359 // are the only ones that can fail an install due to this. We 8360 // will take care of the system apps by updating all of their 8361 // library paths after the scan is done. 8362 updateSharedLibrariesLPw(pkg, null); 8363 } 8364 8365 if (mFoundPolicyFile) { 8366 SELinuxMMAC.assignSeinfoValue(pkg); 8367 } 8368 8369 pkg.applicationInfo.uid = pkgSetting.appId; 8370 pkg.mExtras = pkgSetting; 8371 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8372 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8373 // We just determined the app is signed correctly, so bring 8374 // over the latest parsed certs. 8375 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8376 } else { 8377 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8378 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8379 "Package " + pkg.packageName + " upgrade keys do not match the " 8380 + "previously installed version"); 8381 } else { 8382 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8383 String msg = "System package " + pkg.packageName 8384 + " signature changed; retaining data."; 8385 reportSettingsProblem(Log.WARN, msg); 8386 } 8387 } 8388 } else { 8389 try { 8390 verifySignaturesLP(pkgSetting, pkg); 8391 // We just determined the app is signed correctly, so bring 8392 // over the latest parsed certs. 8393 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8394 } catch (PackageManagerException e) { 8395 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8396 throw e; 8397 } 8398 // The signature has changed, but this package is in the system 8399 // image... let's recover! 8400 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8401 // However... if this package is part of a shared user, but it 8402 // doesn't match the signature of the shared user, let's fail. 8403 // What this means is that you can't change the signatures 8404 // associated with an overall shared user, which doesn't seem all 8405 // that unreasonable. 8406 if (pkgSetting.sharedUser != null) { 8407 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8408 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8409 throw new PackageManagerException( 8410 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8411 "Signature mismatch for shared user: " 8412 + pkgSetting.sharedUser); 8413 } 8414 } 8415 // File a report about this. 8416 String msg = "System package " + pkg.packageName 8417 + " signature changed; retaining data."; 8418 reportSettingsProblem(Log.WARN, msg); 8419 } 8420 } 8421 // Verify that this new package doesn't have any content providers 8422 // that conflict with existing packages. Only do this if the 8423 // package isn't already installed, since we don't want to break 8424 // things that are installed. 8425 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8426 final int N = pkg.providers.size(); 8427 int i; 8428 for (i=0; i<N; i++) { 8429 PackageParser.Provider p = pkg.providers.get(i); 8430 if (p.info.authority != null) { 8431 String names[] = p.info.authority.split(";"); 8432 for (int j = 0; j < names.length; j++) { 8433 if (mProvidersByAuthority.containsKey(names[j])) { 8434 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8435 final String otherPackageName = 8436 ((other != null && other.getComponentName() != null) ? 8437 other.getComponentName().getPackageName() : "?"); 8438 throw new PackageManagerException( 8439 INSTALL_FAILED_CONFLICTING_PROVIDER, 8440 "Can't install because provider name " + names[j] 8441 + " (in package " + pkg.applicationInfo.packageName 8442 + ") is already used by " + otherPackageName); 8443 } 8444 } 8445 } 8446 } 8447 } 8448 8449 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8450 // This package wants to adopt ownership of permissions from 8451 // another package. 8452 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8453 final String origName = pkg.mAdoptPermissions.get(i); 8454 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8455 if (orig != null) { 8456 if (verifyPackageUpdateLPr(orig, pkg)) { 8457 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8458 + pkg.packageName); 8459 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8460 } 8461 } 8462 } 8463 } 8464 } 8465 8466 final String pkgName = pkg.packageName; 8467 8468 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8469 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8470 pkg.applicationInfo.processName = fixProcessName( 8471 pkg.applicationInfo.packageName, 8472 pkg.applicationInfo.processName, 8473 pkg.applicationInfo.uid); 8474 8475 if (pkg != mPlatformPackage) { 8476 // Get all of our default paths setup 8477 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8478 } 8479 8480 final String path = scanFile.getPath(); 8481 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8482 8483 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8484 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8485 8486 // Some system apps still use directory structure for native libraries 8487 // in which case we might end up not detecting abi solely based on apk 8488 // structure. Try to detect abi based on directory structure. 8489 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8490 pkg.applicationInfo.primaryCpuAbi == null) { 8491 setBundledAppAbisAndRoots(pkg, pkgSetting); 8492 setNativeLibraryPaths(pkg); 8493 } 8494 8495 } else { 8496 if ((scanFlags & SCAN_MOVE) != 0) { 8497 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8498 // but we already have this packages package info in the PackageSetting. We just 8499 // use that and derive the native library path based on the new codepath. 8500 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8501 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8502 } 8503 8504 // Set native library paths again. For moves, the path will be updated based on the 8505 // ABIs we've determined above. For non-moves, the path will be updated based on the 8506 // ABIs we determined during compilation, but the path will depend on the final 8507 // package path (after the rename away from the stage path). 8508 setNativeLibraryPaths(pkg); 8509 } 8510 8511 // This is a special case for the "system" package, where the ABI is 8512 // dictated by the zygote configuration (and init.rc). We should keep track 8513 // of this ABI so that we can deal with "normal" applications that run under 8514 // the same UID correctly. 8515 if (mPlatformPackage == pkg) { 8516 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8517 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8518 } 8519 8520 // If there's a mismatch between the abi-override in the package setting 8521 // and the abiOverride specified for the install. Warn about this because we 8522 // would've already compiled the app without taking the package setting into 8523 // account. 8524 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8525 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8526 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8527 " for package " + pkg.packageName); 8528 } 8529 } 8530 8531 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8532 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8533 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8534 8535 // Copy the derived override back to the parsed package, so that we can 8536 // update the package settings accordingly. 8537 pkg.cpuAbiOverride = cpuAbiOverride; 8538 8539 if (DEBUG_ABI_SELECTION) { 8540 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8541 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8542 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8543 } 8544 8545 // Push the derived path down into PackageSettings so we know what to 8546 // clean up at uninstall time. 8547 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8548 8549 if (DEBUG_ABI_SELECTION) { 8550 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8551 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8552 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8553 } 8554 8555 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8556 // We don't do this here during boot because we can do it all 8557 // at once after scanning all existing packages. 8558 // 8559 // We also do this *before* we perform dexopt on this package, so that 8560 // we can avoid redundant dexopts, and also to make sure we've got the 8561 // code and package path correct. 8562 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8563 pkg, true /* boot complete */); 8564 } 8565 8566 if (mFactoryTest && pkg.requestedPermissions.contains( 8567 android.Manifest.permission.FACTORY_TEST)) { 8568 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8569 } 8570 8571 if (isSystemApp(pkg)) { 8572 pkgSetting.isOrphaned = true; 8573 } 8574 8575 ArrayList<PackageParser.Package> clientLibPkgs = null; 8576 8577 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8578 if (nonMutatedPs != null) { 8579 synchronized (mPackages) { 8580 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8581 } 8582 } 8583 return pkg; 8584 } 8585 8586 // Only privileged apps and updated privileged apps can add child packages. 8587 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8588 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8589 throw new PackageManagerException("Only privileged apps and updated " 8590 + "privileged apps can add child packages. Ignoring package " 8591 + pkg.packageName); 8592 } 8593 final int childCount = pkg.childPackages.size(); 8594 for (int i = 0; i < childCount; i++) { 8595 PackageParser.Package childPkg = pkg.childPackages.get(i); 8596 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8597 childPkg.packageName)) { 8598 throw new PackageManagerException("Cannot override a child package of " 8599 + "another disabled system app. Ignoring package " + pkg.packageName); 8600 } 8601 } 8602 } 8603 8604 // writer 8605 synchronized (mPackages) { 8606 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8607 // Only system apps can add new shared libraries. 8608 if (pkg.libraryNames != null) { 8609 for (int i=0; i<pkg.libraryNames.size(); i++) { 8610 String name = pkg.libraryNames.get(i); 8611 boolean allowed = false; 8612 if (pkg.isUpdatedSystemApp()) { 8613 // New library entries can only be added through the 8614 // system image. This is important to get rid of a lot 8615 // of nasty edge cases: for example if we allowed a non- 8616 // system update of the app to add a library, then uninstalling 8617 // the update would make the library go away, and assumptions 8618 // we made such as through app install filtering would now 8619 // have allowed apps on the device which aren't compatible 8620 // with it. Better to just have the restriction here, be 8621 // conservative, and create many fewer cases that can negatively 8622 // impact the user experience. 8623 final PackageSetting sysPs = mSettings 8624 .getDisabledSystemPkgLPr(pkg.packageName); 8625 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8626 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8627 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8628 allowed = true; 8629 break; 8630 } 8631 } 8632 } 8633 } else { 8634 allowed = true; 8635 } 8636 if (allowed) { 8637 if (!mSharedLibraries.containsKey(name)) { 8638 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8639 } else if (!name.equals(pkg.packageName)) { 8640 Slog.w(TAG, "Package " + pkg.packageName + " library " 8641 + name + " already exists; skipping"); 8642 } 8643 } else { 8644 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8645 + name + " that is not declared on system image; skipping"); 8646 } 8647 } 8648 if ((scanFlags & SCAN_BOOTING) == 0) { 8649 // If we are not booting, we need to update any applications 8650 // that are clients of our shared library. If we are booting, 8651 // this will all be done once the scan is complete. 8652 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8653 } 8654 } 8655 } 8656 } 8657 8658 if ((scanFlags & SCAN_BOOTING) != 0) { 8659 // No apps can run during boot scan, so they don't need to be frozen 8660 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8661 // Caller asked to not kill app, so it's probably not frozen 8662 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8663 // Caller asked us to ignore frozen check for some reason; they 8664 // probably didn't know the package name 8665 } else { 8666 // We're doing major surgery on this package, so it better be frozen 8667 // right now to keep it from launching 8668 checkPackageFrozen(pkgName); 8669 } 8670 8671 // Also need to kill any apps that are dependent on the library. 8672 if (clientLibPkgs != null) { 8673 for (int i=0; i<clientLibPkgs.size(); i++) { 8674 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8675 killApplication(clientPkg.applicationInfo.packageName, 8676 clientPkg.applicationInfo.uid, "update lib"); 8677 } 8678 } 8679 8680 // Make sure we're not adding any bogus keyset info 8681 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8682 ksms.assertScannedPackageValid(pkg); 8683 8684 // writer 8685 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8686 8687 boolean createIdmapFailed = false; 8688 synchronized (mPackages) { 8689 // We don't expect installation to fail beyond this point 8690 8691 if (pkgSetting.pkg != null) { 8692 // Note that |user| might be null during the initial boot scan. If a codePath 8693 // for an app has changed during a boot scan, it's due to an app update that's 8694 // part of the system partition and marker changes must be applied to all users. 8695 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8696 (user != null) ? user : UserHandle.ALL); 8697 } 8698 8699 // Add the new setting to mSettings 8700 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8701 // Add the new setting to mPackages 8702 mPackages.put(pkg.applicationInfo.packageName, pkg); 8703 // Make sure we don't accidentally delete its data. 8704 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8705 while (iter.hasNext()) { 8706 PackageCleanItem item = iter.next(); 8707 if (pkgName.equals(item.packageName)) { 8708 iter.remove(); 8709 } 8710 } 8711 8712 // Take care of first install / last update times. 8713 if (currentTime != 0) { 8714 if (pkgSetting.firstInstallTime == 0) { 8715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8716 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8717 pkgSetting.lastUpdateTime = currentTime; 8718 } 8719 } else if (pkgSetting.firstInstallTime == 0) { 8720 // We need *something*. Take time time stamp of the file. 8721 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8722 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8723 if (scanFileTime != pkgSetting.timeStamp) { 8724 // A package on the system image has changed; consider this 8725 // to be an update. 8726 pkgSetting.lastUpdateTime = scanFileTime; 8727 } 8728 } 8729 8730 // Add the package's KeySets to the global KeySetManagerService 8731 ksms.addScannedPackageLPw(pkg); 8732 8733 int N = pkg.providers.size(); 8734 StringBuilder r = null; 8735 int i; 8736 for (i=0; i<N; i++) { 8737 PackageParser.Provider p = pkg.providers.get(i); 8738 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8739 p.info.processName, pkg.applicationInfo.uid); 8740 mProviders.addProvider(p); 8741 p.syncable = p.info.isSyncable; 8742 if (p.info.authority != null) { 8743 String names[] = p.info.authority.split(";"); 8744 p.info.authority = null; 8745 for (int j = 0; j < names.length; j++) { 8746 if (j == 1 && p.syncable) { 8747 // We only want the first authority for a provider to possibly be 8748 // syncable, so if we already added this provider using a different 8749 // authority clear the syncable flag. We copy the provider before 8750 // changing it because the mProviders object contains a reference 8751 // to a provider that we don't want to change. 8752 // Only do this for the second authority since the resulting provider 8753 // object can be the same for all future authorities for this provider. 8754 p = new PackageParser.Provider(p); 8755 p.syncable = false; 8756 } 8757 if (!mProvidersByAuthority.containsKey(names[j])) { 8758 mProvidersByAuthority.put(names[j], p); 8759 if (p.info.authority == null) { 8760 p.info.authority = names[j]; 8761 } else { 8762 p.info.authority = p.info.authority + ";" + names[j]; 8763 } 8764 if (DEBUG_PACKAGE_SCANNING) { 8765 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8766 Log.d(TAG, "Registered content provider: " + names[j] 8767 + ", className = " + p.info.name + ", isSyncable = " 8768 + p.info.isSyncable); 8769 } 8770 } else { 8771 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8772 Slog.w(TAG, "Skipping provider name " + names[j] + 8773 " (in package " + pkg.applicationInfo.packageName + 8774 "): name already used by " 8775 + ((other != null && other.getComponentName() != null) 8776 ? other.getComponentName().getPackageName() : "?")); 8777 } 8778 } 8779 } 8780 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8781 if (r == null) { 8782 r = new StringBuilder(256); 8783 } else { 8784 r.append(' '); 8785 } 8786 r.append(p.info.name); 8787 } 8788 } 8789 if (r != null) { 8790 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8791 } 8792 8793 N = pkg.services.size(); 8794 r = null; 8795 for (i=0; i<N; i++) { 8796 PackageParser.Service s = pkg.services.get(i); 8797 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8798 s.info.processName, pkg.applicationInfo.uid); 8799 mServices.addService(s); 8800 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8801 if (r == null) { 8802 r = new StringBuilder(256); 8803 } else { 8804 r.append(' '); 8805 } 8806 r.append(s.info.name); 8807 } 8808 } 8809 if (r != null) { 8810 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8811 } 8812 8813 N = pkg.receivers.size(); 8814 r = null; 8815 for (i=0; i<N; i++) { 8816 PackageParser.Activity a = pkg.receivers.get(i); 8817 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8818 a.info.processName, pkg.applicationInfo.uid); 8819 mReceivers.addActivity(a, "receiver"); 8820 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8821 if (r == null) { 8822 r = new StringBuilder(256); 8823 } else { 8824 r.append(' '); 8825 } 8826 r.append(a.info.name); 8827 } 8828 } 8829 if (r != null) { 8830 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8831 } 8832 8833 N = pkg.activities.size(); 8834 r = null; 8835 for (i=0; i<N; i++) { 8836 PackageParser.Activity a = pkg.activities.get(i); 8837 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8838 a.info.processName, pkg.applicationInfo.uid); 8839 mActivities.addActivity(a, "activity"); 8840 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8841 if (r == null) { 8842 r = new StringBuilder(256); 8843 } else { 8844 r.append(' '); 8845 } 8846 r.append(a.info.name); 8847 } 8848 } 8849 if (r != null) { 8850 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8851 } 8852 8853 N = pkg.permissionGroups.size(); 8854 r = null; 8855 for (i=0; i<N; i++) { 8856 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8857 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8858 final String curPackageName = cur == null ? null : cur.info.packageName; 8859 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8860 if (cur == null || isPackageUpdate) { 8861 mPermissionGroups.put(pg.info.name, pg); 8862 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8863 if (r == null) { 8864 r = new StringBuilder(256); 8865 } else { 8866 r.append(' '); 8867 } 8868 if (isPackageUpdate) { 8869 r.append("UPD:"); 8870 } 8871 r.append(pg.info.name); 8872 } 8873 } else { 8874 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8875 + pg.info.packageName + " ignored: original from " 8876 + cur.info.packageName); 8877 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8878 if (r == null) { 8879 r = new StringBuilder(256); 8880 } else { 8881 r.append(' '); 8882 } 8883 r.append("DUP:"); 8884 r.append(pg.info.name); 8885 } 8886 } 8887 } 8888 if (r != null) { 8889 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8890 } 8891 8892 N = pkg.permissions.size(); 8893 r = null; 8894 for (i=0; i<N; i++) { 8895 PackageParser.Permission p = pkg.permissions.get(i); 8896 8897 // Assume by default that we did not install this permission into the system. 8898 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8899 8900 // Now that permission groups have a special meaning, we ignore permission 8901 // groups for legacy apps to prevent unexpected behavior. In particular, 8902 // permissions for one app being granted to someone just becase they happen 8903 // to be in a group defined by another app (before this had no implications). 8904 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8905 p.group = mPermissionGroups.get(p.info.group); 8906 // Warn for a permission in an unknown group. 8907 if (p.info.group != null && p.group == null) { 8908 Slog.w(TAG, "Permission " + p.info.name + " from package " 8909 + p.info.packageName + " in an unknown group " + p.info.group); 8910 } 8911 } 8912 8913 ArrayMap<String, BasePermission> permissionMap = 8914 p.tree ? mSettings.mPermissionTrees 8915 : mSettings.mPermissions; 8916 BasePermission bp = permissionMap.get(p.info.name); 8917 8918 // Allow system apps to redefine non-system permissions 8919 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8920 final boolean currentOwnerIsSystem = (bp.perm != null 8921 && isSystemApp(bp.perm.owner)); 8922 if (isSystemApp(p.owner)) { 8923 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8924 // It's a built-in permission and no owner, take ownership now 8925 bp.packageSetting = pkgSetting; 8926 bp.perm = p; 8927 bp.uid = pkg.applicationInfo.uid; 8928 bp.sourcePackage = p.info.packageName; 8929 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8930 } else if (!currentOwnerIsSystem) { 8931 String msg = "New decl " + p.owner + " of permission " 8932 + p.info.name + " is system; overriding " + bp.sourcePackage; 8933 reportSettingsProblem(Log.WARN, msg); 8934 bp = null; 8935 } 8936 } 8937 } 8938 8939 if (bp == null) { 8940 bp = new BasePermission(p.info.name, p.info.packageName, 8941 BasePermission.TYPE_NORMAL); 8942 permissionMap.put(p.info.name, bp); 8943 } 8944 8945 if (bp.perm == null) { 8946 if (bp.sourcePackage == null 8947 || bp.sourcePackage.equals(p.info.packageName)) { 8948 BasePermission tree = findPermissionTreeLP(p.info.name); 8949 if (tree == null 8950 || tree.sourcePackage.equals(p.info.packageName)) { 8951 bp.packageSetting = pkgSetting; 8952 bp.perm = p; 8953 bp.uid = pkg.applicationInfo.uid; 8954 bp.sourcePackage = p.info.packageName; 8955 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8956 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8957 if (r == null) { 8958 r = new StringBuilder(256); 8959 } else { 8960 r.append(' '); 8961 } 8962 r.append(p.info.name); 8963 } 8964 } else { 8965 Slog.w(TAG, "Permission " + p.info.name + " from package " 8966 + p.info.packageName + " ignored: base tree " 8967 + tree.name + " is from package " 8968 + tree.sourcePackage); 8969 } 8970 } else { 8971 Slog.w(TAG, "Permission " + p.info.name + " from package " 8972 + p.info.packageName + " ignored: original from " 8973 + bp.sourcePackage); 8974 } 8975 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8976 if (r == null) { 8977 r = new StringBuilder(256); 8978 } else { 8979 r.append(' '); 8980 } 8981 r.append("DUP:"); 8982 r.append(p.info.name); 8983 } 8984 if (bp.perm == p) { 8985 bp.protectionLevel = p.info.protectionLevel; 8986 } 8987 } 8988 8989 if (r != null) { 8990 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8991 } 8992 8993 N = pkg.instrumentation.size(); 8994 r = null; 8995 for (i=0; i<N; i++) { 8996 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8997 a.info.packageName = pkg.applicationInfo.packageName; 8998 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8999 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9000 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9001 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9002 a.info.dataDir = pkg.applicationInfo.dataDir; 9003 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9004 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9005 9006 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9007 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9008 mInstrumentation.put(a.getComponentName(), a); 9009 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 9010 if (r == null) { 9011 r = new StringBuilder(256); 9012 } else { 9013 r.append(' '); 9014 } 9015 r.append(a.info.name); 9016 } 9017 } 9018 if (r != null) { 9019 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9020 } 9021 9022 if (pkg.protectedBroadcasts != null) { 9023 N = pkg.protectedBroadcasts.size(); 9024 for (i=0; i<N; i++) { 9025 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9026 } 9027 } 9028 9029 pkgSetting.setTimeStamp(scanFileTime); 9030 9031 // Create idmap files for pairs of (packages, overlay packages). 9032 // Note: "android", ie framework-res.apk, is handled by native layers. 9033 if (pkg.mOverlayTarget != null) { 9034 // This is an overlay package. 9035 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9036 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9037 mOverlays.put(pkg.mOverlayTarget, 9038 new ArrayMap<String, PackageParser.Package>()); 9039 } 9040 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9041 map.put(pkg.packageName, pkg); 9042 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9043 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9044 createIdmapFailed = true; 9045 } 9046 } 9047 } else if (mOverlays.containsKey(pkg.packageName) && 9048 !pkg.packageName.equals("android")) { 9049 // This is a regular package, with one or more known overlay packages. 9050 createIdmapsForPackageLI(pkg); 9051 } 9052 } 9053 9054 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9055 9056 if (createIdmapFailed) { 9057 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9058 "scanPackageLI failed to createIdmap"); 9059 } 9060 return pkg; 9061 } 9062 9063 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9064 PackageParser.Package update, UserHandle user) { 9065 if (existing.applicationInfo == null || update.applicationInfo == null) { 9066 // This isn't due to an app installation. 9067 return; 9068 } 9069 9070 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9071 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9072 9073 // The codePath hasn't changed, so there's nothing for us to do. 9074 if (Objects.equals(oldCodePath, newCodePath)) { 9075 return; 9076 } 9077 9078 File canonicalNewCodePath; 9079 try { 9080 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9081 } catch (IOException e) { 9082 Slog.w(TAG, "Failed to get canonical path.", e); 9083 return; 9084 } 9085 9086 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9087 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9088 // that the last component of the path (i.e, the name) doesn't need canonicalization 9089 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9090 // but may change in the future. Hopefully this function won't exist at that point. 9091 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9092 oldCodePath.getName()); 9093 9094 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9095 // with "@". 9096 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9097 if (!oldMarkerPrefix.endsWith("@")) { 9098 oldMarkerPrefix += "@"; 9099 } 9100 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9101 if (!newMarkerPrefix.endsWith("@")) { 9102 newMarkerPrefix += "@"; 9103 } 9104 9105 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9106 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9107 for (String updatedPath : updatedPaths) { 9108 String updatedPathName = new File(updatedPath).getName(); 9109 markerSuffixes.add(updatedPathName.replace('/', '@')); 9110 } 9111 9112 for (int userId : resolveUserIds(user.getIdentifier())) { 9113 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9114 9115 for (String markerSuffix : markerSuffixes) { 9116 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9117 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9118 if (oldForeignUseMark.exists()) { 9119 try { 9120 Os.rename(oldForeignUseMark.getAbsolutePath(), 9121 newForeignUseMark.getAbsolutePath()); 9122 } catch (ErrnoException e) { 9123 Slog.w(TAG, "Failed to rename foreign use marker", e); 9124 oldForeignUseMark.delete(); 9125 } 9126 } 9127 } 9128 } 9129 } 9130 9131 /** 9132 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9133 * is derived purely on the basis of the contents of {@code scanFile} and 9134 * {@code cpuAbiOverride}. 9135 * 9136 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9137 */ 9138 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9139 String cpuAbiOverride, boolean extractLibs) 9140 throws PackageManagerException { 9141 // TODO: We can probably be smarter about this stuff. For installed apps, 9142 // we can calculate this information at install time once and for all. For 9143 // system apps, we can probably assume that this information doesn't change 9144 // after the first boot scan. As things stand, we do lots of unnecessary work. 9145 9146 // Give ourselves some initial paths; we'll come back for another 9147 // pass once we've determined ABI below. 9148 setNativeLibraryPaths(pkg); 9149 9150 // We would never need to extract libs for forward-locked and external packages, 9151 // since the container service will do it for us. We shouldn't attempt to 9152 // extract libs from system app when it was not updated. 9153 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9154 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9155 extractLibs = false; 9156 } 9157 9158 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9159 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9160 9161 NativeLibraryHelper.Handle handle = null; 9162 try { 9163 handle = NativeLibraryHelper.Handle.create(pkg); 9164 // TODO(multiArch): This can be null for apps that didn't go through the 9165 // usual installation process. We can calculate it again, like we 9166 // do during install time. 9167 // 9168 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9169 // unnecessary. 9170 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9171 9172 // Null out the abis so that they can be recalculated. 9173 pkg.applicationInfo.primaryCpuAbi = null; 9174 pkg.applicationInfo.secondaryCpuAbi = null; 9175 if (isMultiArch(pkg.applicationInfo)) { 9176 // Warn if we've set an abiOverride for multi-lib packages.. 9177 // By definition, we need to copy both 32 and 64 bit libraries for 9178 // such packages. 9179 if (pkg.cpuAbiOverride != null 9180 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9181 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9182 } 9183 9184 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9185 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9186 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9187 if (extractLibs) { 9188 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9189 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9190 useIsaSpecificSubdirs); 9191 } else { 9192 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9193 } 9194 } 9195 9196 maybeThrowExceptionForMultiArchCopy( 9197 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9198 9199 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9200 if (extractLibs) { 9201 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9202 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9203 useIsaSpecificSubdirs); 9204 } else { 9205 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9206 } 9207 } 9208 9209 maybeThrowExceptionForMultiArchCopy( 9210 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9211 9212 if (abi64 >= 0) { 9213 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9214 } 9215 9216 if (abi32 >= 0) { 9217 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9218 if (abi64 >= 0) { 9219 if (pkg.use32bitAbi) { 9220 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9221 pkg.applicationInfo.primaryCpuAbi = abi; 9222 } else { 9223 pkg.applicationInfo.secondaryCpuAbi = abi; 9224 } 9225 } else { 9226 pkg.applicationInfo.primaryCpuAbi = abi; 9227 } 9228 } 9229 9230 } else { 9231 String[] abiList = (cpuAbiOverride != null) ? 9232 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9233 9234 // Enable gross and lame hacks for apps that are built with old 9235 // SDK tools. We must scan their APKs for renderscript bitcode and 9236 // not launch them if it's present. Don't bother checking on devices 9237 // that don't have 64 bit support. 9238 boolean needsRenderScriptOverride = false; 9239 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9240 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9241 abiList = Build.SUPPORTED_32_BIT_ABIS; 9242 needsRenderScriptOverride = true; 9243 } 9244 9245 final int copyRet; 9246 if (extractLibs) { 9247 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9248 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9249 } else { 9250 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9251 } 9252 9253 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9254 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9255 "Error unpackaging native libs for app, errorCode=" + copyRet); 9256 } 9257 9258 if (copyRet >= 0) { 9259 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9260 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9261 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9262 } else if (needsRenderScriptOverride) { 9263 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9264 } 9265 } 9266 } catch (IOException ioe) { 9267 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9268 } finally { 9269 IoUtils.closeQuietly(handle); 9270 } 9271 9272 // Now that we've calculated the ABIs and determined if it's an internal app, 9273 // we will go ahead and populate the nativeLibraryPath. 9274 setNativeLibraryPaths(pkg); 9275 } 9276 9277 /** 9278 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9279 * i.e, so that all packages can be run inside a single process if required. 9280 * 9281 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9282 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9283 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9284 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9285 * updating a package that belongs to a shared user. 9286 * 9287 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9288 * adds unnecessary complexity. 9289 */ 9290 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9291 PackageParser.Package scannedPackage, boolean bootComplete) { 9292 String requiredInstructionSet = null; 9293 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9294 requiredInstructionSet = VMRuntime.getInstructionSet( 9295 scannedPackage.applicationInfo.primaryCpuAbi); 9296 } 9297 9298 PackageSetting requirer = null; 9299 for (PackageSetting ps : packagesForUser) { 9300 // If packagesForUser contains scannedPackage, we skip it. This will happen 9301 // when scannedPackage is an update of an existing package. Without this check, 9302 // we will never be able to change the ABI of any package belonging to a shared 9303 // user, even if it's compatible with other packages. 9304 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9305 if (ps.primaryCpuAbiString == null) { 9306 continue; 9307 } 9308 9309 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9310 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9311 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9312 // this but there's not much we can do. 9313 String errorMessage = "Instruction set mismatch, " 9314 + ((requirer == null) ? "[caller]" : requirer) 9315 + " requires " + requiredInstructionSet + " whereas " + ps 9316 + " requires " + instructionSet; 9317 Slog.w(TAG, errorMessage); 9318 } 9319 9320 if (requiredInstructionSet == null) { 9321 requiredInstructionSet = instructionSet; 9322 requirer = ps; 9323 } 9324 } 9325 } 9326 9327 if (requiredInstructionSet != null) { 9328 String adjustedAbi; 9329 if (requirer != null) { 9330 // requirer != null implies that either scannedPackage was null or that scannedPackage 9331 // did not require an ABI, in which case we have to adjust scannedPackage to match 9332 // the ABI of the set (which is the same as requirer's ABI) 9333 adjustedAbi = requirer.primaryCpuAbiString; 9334 if (scannedPackage != null) { 9335 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9336 } 9337 } else { 9338 // requirer == null implies that we're updating all ABIs in the set to 9339 // match scannedPackage. 9340 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9341 } 9342 9343 for (PackageSetting ps : packagesForUser) { 9344 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9345 if (ps.primaryCpuAbiString != null) { 9346 continue; 9347 } 9348 9349 ps.primaryCpuAbiString = adjustedAbi; 9350 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9351 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9352 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9353 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9354 + " (requirer=" 9355 + (requirer == null ? "null" : requirer.pkg.packageName) 9356 + ", scannedPackage=" 9357 + (scannedPackage != null ? scannedPackage.packageName : "null") 9358 + ")"); 9359 try { 9360 mInstaller.rmdex(ps.codePathString, 9361 getDexCodeInstructionSet(getPreferredInstructionSet())); 9362 } catch (InstallerException ignored) { 9363 } 9364 } 9365 } 9366 } 9367 } 9368 } 9369 9370 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9371 synchronized (mPackages) { 9372 mResolverReplaced = true; 9373 // Set up information for custom user intent resolution activity. 9374 mResolveActivity.applicationInfo = pkg.applicationInfo; 9375 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9376 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9377 mResolveActivity.processName = pkg.applicationInfo.packageName; 9378 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9379 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9380 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9381 mResolveActivity.theme = 0; 9382 mResolveActivity.exported = true; 9383 mResolveActivity.enabled = true; 9384 mResolveInfo.activityInfo = mResolveActivity; 9385 mResolveInfo.priority = 0; 9386 mResolveInfo.preferredOrder = 0; 9387 mResolveInfo.match = 0; 9388 mResolveComponentName = mCustomResolverComponentName; 9389 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9390 mResolveComponentName); 9391 } 9392 } 9393 9394 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9395 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9396 9397 // Set up information for ephemeral installer activity 9398 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9399 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9400 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9401 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9402 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9403 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9404 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9405 mEphemeralInstallerActivity.theme = 0; 9406 mEphemeralInstallerActivity.exported = true; 9407 mEphemeralInstallerActivity.enabled = true; 9408 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9409 mEphemeralInstallerInfo.priority = 0; 9410 mEphemeralInstallerInfo.preferredOrder = 1; 9411 mEphemeralInstallerInfo.isDefault = true; 9412 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9413 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9414 9415 if (DEBUG_EPHEMERAL) { 9416 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9417 } 9418 } 9419 9420 private static String calculateBundledApkRoot(final String codePathString) { 9421 final File codePath = new File(codePathString); 9422 final File codeRoot; 9423 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9424 codeRoot = Environment.getRootDirectory(); 9425 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9426 codeRoot = Environment.getOemDirectory(); 9427 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9428 codeRoot = Environment.getVendorDirectory(); 9429 } else { 9430 // Unrecognized code path; take its top real segment as the apk root: 9431 // e.g. /something/app/blah.apk => /something 9432 try { 9433 File f = codePath.getCanonicalFile(); 9434 File parent = f.getParentFile(); // non-null because codePath is a file 9435 File tmp; 9436 while ((tmp = parent.getParentFile()) != null) { 9437 f = parent; 9438 parent = tmp; 9439 } 9440 codeRoot = f; 9441 Slog.w(TAG, "Unrecognized code path " 9442 + codePath + " - using " + codeRoot); 9443 } catch (IOException e) { 9444 // Can't canonicalize the code path -- shenanigans? 9445 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9446 return Environment.getRootDirectory().getPath(); 9447 } 9448 } 9449 return codeRoot.getPath(); 9450 } 9451 9452 /** 9453 * Derive and set the location of native libraries for the given package, 9454 * which varies depending on where and how the package was installed. 9455 */ 9456 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9457 final ApplicationInfo info = pkg.applicationInfo; 9458 final String codePath = pkg.codePath; 9459 final File codeFile = new File(codePath); 9460 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9461 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9462 9463 info.nativeLibraryRootDir = null; 9464 info.nativeLibraryRootRequiresIsa = false; 9465 info.nativeLibraryDir = null; 9466 info.secondaryNativeLibraryDir = null; 9467 9468 if (isApkFile(codeFile)) { 9469 // Monolithic install 9470 if (bundledApp) { 9471 // If "/system/lib64/apkname" exists, assume that is the per-package 9472 // native library directory to use; otherwise use "/system/lib/apkname". 9473 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9474 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9475 getPrimaryInstructionSet(info)); 9476 9477 // This is a bundled system app so choose the path based on the ABI. 9478 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9479 // is just the default path. 9480 final String apkName = deriveCodePathName(codePath); 9481 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9482 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9483 apkName).getAbsolutePath(); 9484 9485 if (info.secondaryCpuAbi != null) { 9486 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9487 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9488 secondaryLibDir, apkName).getAbsolutePath(); 9489 } 9490 } else if (asecApp) { 9491 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9492 .getAbsolutePath(); 9493 } else { 9494 final String apkName = deriveCodePathName(codePath); 9495 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9496 .getAbsolutePath(); 9497 } 9498 9499 info.nativeLibraryRootRequiresIsa = false; 9500 info.nativeLibraryDir = info.nativeLibraryRootDir; 9501 } else { 9502 // Cluster install 9503 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9504 info.nativeLibraryRootRequiresIsa = true; 9505 9506 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9507 getPrimaryInstructionSet(info)).getAbsolutePath(); 9508 9509 if (info.secondaryCpuAbi != null) { 9510 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9511 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9512 } 9513 } 9514 } 9515 9516 /** 9517 * Calculate the abis and roots for a bundled app. These can uniquely 9518 * be determined from the contents of the system partition, i.e whether 9519 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9520 * of this information, and instead assume that the system was built 9521 * sensibly. 9522 */ 9523 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9524 PackageSetting pkgSetting) { 9525 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9526 9527 // If "/system/lib64/apkname" exists, assume that is the per-package 9528 // native library directory to use; otherwise use "/system/lib/apkname". 9529 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9530 setBundledAppAbi(pkg, apkRoot, apkName); 9531 // pkgSetting might be null during rescan following uninstall of updates 9532 // to a bundled app, so accommodate that possibility. The settings in 9533 // that case will be established later from the parsed package. 9534 // 9535 // If the settings aren't null, sync them up with what we've just derived. 9536 // note that apkRoot isn't stored in the package settings. 9537 if (pkgSetting != null) { 9538 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9539 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9540 } 9541 } 9542 9543 /** 9544 * Deduces the ABI of a bundled app and sets the relevant fields on the 9545 * parsed pkg object. 9546 * 9547 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9548 * under which system libraries are installed. 9549 * @param apkName the name of the installed package. 9550 */ 9551 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9552 final File codeFile = new File(pkg.codePath); 9553 9554 final boolean has64BitLibs; 9555 final boolean has32BitLibs; 9556 if (isApkFile(codeFile)) { 9557 // Monolithic install 9558 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9559 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9560 } else { 9561 // Cluster install 9562 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9563 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9564 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9565 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9566 has64BitLibs = (new File(rootDir, isa)).exists(); 9567 } else { 9568 has64BitLibs = false; 9569 } 9570 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9571 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9572 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9573 has32BitLibs = (new File(rootDir, isa)).exists(); 9574 } else { 9575 has32BitLibs = false; 9576 } 9577 } 9578 9579 if (has64BitLibs && !has32BitLibs) { 9580 // The package has 64 bit libs, but not 32 bit libs. Its primary 9581 // ABI should be 64 bit. We can safely assume here that the bundled 9582 // native libraries correspond to the most preferred ABI in the list. 9583 9584 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9585 pkg.applicationInfo.secondaryCpuAbi = null; 9586 } else if (has32BitLibs && !has64BitLibs) { 9587 // The package has 32 bit libs but not 64 bit libs. Its primary 9588 // ABI should be 32 bit. 9589 9590 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9591 pkg.applicationInfo.secondaryCpuAbi = null; 9592 } else if (has32BitLibs && has64BitLibs) { 9593 // The application has both 64 and 32 bit bundled libraries. We check 9594 // here that the app declares multiArch support, and warn if it doesn't. 9595 // 9596 // We will be lenient here and record both ABIs. The primary will be the 9597 // ABI that's higher on the list, i.e, a device that's configured to prefer 9598 // 64 bit apps will see a 64 bit primary ABI, 9599 9600 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9601 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9602 } 9603 9604 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9605 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9606 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9607 } else { 9608 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9609 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9610 } 9611 } else { 9612 pkg.applicationInfo.primaryCpuAbi = null; 9613 pkg.applicationInfo.secondaryCpuAbi = null; 9614 } 9615 } 9616 9617 private void killApplication(String pkgName, int appId, String reason) { 9618 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9619 } 9620 9621 private void killApplication(String pkgName, int appId, int userId, String reason) { 9622 // Request the ActivityManager to kill the process(only for existing packages) 9623 // so that we do not end up in a confused state while the user is still using the older 9624 // version of the application while the new one gets installed. 9625 final long token = Binder.clearCallingIdentity(); 9626 try { 9627 IActivityManager am = ActivityManagerNative.getDefault(); 9628 if (am != null) { 9629 try { 9630 am.killApplication(pkgName, appId, userId, reason); 9631 } catch (RemoteException e) { 9632 } 9633 } 9634 } finally { 9635 Binder.restoreCallingIdentity(token); 9636 } 9637 } 9638 9639 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9640 // Remove the parent package setting 9641 PackageSetting ps = (PackageSetting) pkg.mExtras; 9642 if (ps != null) { 9643 removePackageLI(ps, chatty); 9644 } 9645 // Remove the child package setting 9646 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9647 for (int i = 0; i < childCount; i++) { 9648 PackageParser.Package childPkg = pkg.childPackages.get(i); 9649 ps = (PackageSetting) childPkg.mExtras; 9650 if (ps != null) { 9651 removePackageLI(ps, chatty); 9652 } 9653 } 9654 } 9655 9656 void removePackageLI(PackageSetting ps, boolean chatty) { 9657 if (DEBUG_INSTALL) { 9658 if (chatty) 9659 Log.d(TAG, "Removing package " + ps.name); 9660 } 9661 9662 // writer 9663 synchronized (mPackages) { 9664 mPackages.remove(ps.name); 9665 final PackageParser.Package pkg = ps.pkg; 9666 if (pkg != null) { 9667 cleanPackageDataStructuresLILPw(pkg, chatty); 9668 } 9669 } 9670 } 9671 9672 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9673 if (DEBUG_INSTALL) { 9674 if (chatty) 9675 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9676 } 9677 9678 // writer 9679 synchronized (mPackages) { 9680 // Remove the parent package 9681 mPackages.remove(pkg.applicationInfo.packageName); 9682 cleanPackageDataStructuresLILPw(pkg, chatty); 9683 9684 // Remove the child packages 9685 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9686 for (int i = 0; i < childCount; i++) { 9687 PackageParser.Package childPkg = pkg.childPackages.get(i); 9688 mPackages.remove(childPkg.applicationInfo.packageName); 9689 cleanPackageDataStructuresLILPw(childPkg, chatty); 9690 } 9691 } 9692 } 9693 9694 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9695 int N = pkg.providers.size(); 9696 StringBuilder r = null; 9697 int i; 9698 for (i=0; i<N; i++) { 9699 PackageParser.Provider p = pkg.providers.get(i); 9700 mProviders.removeProvider(p); 9701 if (p.info.authority == null) { 9702 9703 /* There was another ContentProvider with this authority when 9704 * this app was installed so this authority is null, 9705 * Ignore it as we don't have to unregister the provider. 9706 */ 9707 continue; 9708 } 9709 String names[] = p.info.authority.split(";"); 9710 for (int j = 0; j < names.length; j++) { 9711 if (mProvidersByAuthority.get(names[j]) == p) { 9712 mProvidersByAuthority.remove(names[j]); 9713 if (DEBUG_REMOVE) { 9714 if (chatty) 9715 Log.d(TAG, "Unregistered content provider: " + names[j] 9716 + ", className = " + p.info.name + ", isSyncable = " 9717 + p.info.isSyncable); 9718 } 9719 } 9720 } 9721 if (DEBUG_REMOVE && chatty) { 9722 if (r == null) { 9723 r = new StringBuilder(256); 9724 } else { 9725 r.append(' '); 9726 } 9727 r.append(p.info.name); 9728 } 9729 } 9730 if (r != null) { 9731 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9732 } 9733 9734 N = pkg.services.size(); 9735 r = null; 9736 for (i=0; i<N; i++) { 9737 PackageParser.Service s = pkg.services.get(i); 9738 mServices.removeService(s); 9739 if (chatty) { 9740 if (r == null) { 9741 r = new StringBuilder(256); 9742 } else { 9743 r.append(' '); 9744 } 9745 r.append(s.info.name); 9746 } 9747 } 9748 if (r != null) { 9749 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9750 } 9751 9752 N = pkg.receivers.size(); 9753 r = null; 9754 for (i=0; i<N; i++) { 9755 PackageParser.Activity a = pkg.receivers.get(i); 9756 mReceivers.removeActivity(a, "receiver"); 9757 if (DEBUG_REMOVE && chatty) { 9758 if (r == null) { 9759 r = new StringBuilder(256); 9760 } else { 9761 r.append(' '); 9762 } 9763 r.append(a.info.name); 9764 } 9765 } 9766 if (r != null) { 9767 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9768 } 9769 9770 N = pkg.activities.size(); 9771 r = null; 9772 for (i=0; i<N; i++) { 9773 PackageParser.Activity a = pkg.activities.get(i); 9774 mActivities.removeActivity(a, "activity"); 9775 if (DEBUG_REMOVE && chatty) { 9776 if (r == null) { 9777 r = new StringBuilder(256); 9778 } else { 9779 r.append(' '); 9780 } 9781 r.append(a.info.name); 9782 } 9783 } 9784 if (r != null) { 9785 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9786 } 9787 9788 N = pkg.permissions.size(); 9789 r = null; 9790 for (i=0; i<N; i++) { 9791 PackageParser.Permission p = pkg.permissions.get(i); 9792 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9793 if (bp == null) { 9794 bp = mSettings.mPermissionTrees.get(p.info.name); 9795 } 9796 if (bp != null && bp.perm == p) { 9797 bp.perm = null; 9798 if (DEBUG_REMOVE && chatty) { 9799 if (r == null) { 9800 r = new StringBuilder(256); 9801 } else { 9802 r.append(' '); 9803 } 9804 r.append(p.info.name); 9805 } 9806 } 9807 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9808 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9809 if (appOpPkgs != null) { 9810 appOpPkgs.remove(pkg.packageName); 9811 } 9812 } 9813 } 9814 if (r != null) { 9815 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9816 } 9817 9818 N = pkg.requestedPermissions.size(); 9819 r = null; 9820 for (i=0; i<N; i++) { 9821 String perm = pkg.requestedPermissions.get(i); 9822 BasePermission bp = mSettings.mPermissions.get(perm); 9823 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9824 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9825 if (appOpPkgs != null) { 9826 appOpPkgs.remove(pkg.packageName); 9827 if (appOpPkgs.isEmpty()) { 9828 mAppOpPermissionPackages.remove(perm); 9829 } 9830 } 9831 } 9832 } 9833 if (r != null) { 9834 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9835 } 9836 9837 N = pkg.instrumentation.size(); 9838 r = null; 9839 for (i=0; i<N; i++) { 9840 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9841 mInstrumentation.remove(a.getComponentName()); 9842 if (DEBUG_REMOVE && chatty) { 9843 if (r == null) { 9844 r = new StringBuilder(256); 9845 } else { 9846 r.append(' '); 9847 } 9848 r.append(a.info.name); 9849 } 9850 } 9851 if (r != null) { 9852 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9853 } 9854 9855 r = null; 9856 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9857 // Only system apps can hold shared libraries. 9858 if (pkg.libraryNames != null) { 9859 for (i=0; i<pkg.libraryNames.size(); i++) { 9860 String name = pkg.libraryNames.get(i); 9861 SharedLibraryEntry cur = mSharedLibraries.get(name); 9862 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9863 mSharedLibraries.remove(name); 9864 if (DEBUG_REMOVE && chatty) { 9865 if (r == null) { 9866 r = new StringBuilder(256); 9867 } else { 9868 r.append(' '); 9869 } 9870 r.append(name); 9871 } 9872 } 9873 } 9874 } 9875 } 9876 if (r != null) { 9877 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9878 } 9879 } 9880 9881 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9882 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9883 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9884 return true; 9885 } 9886 } 9887 return false; 9888 } 9889 9890 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9891 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9892 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9893 9894 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9895 // Update the parent permissions 9896 updatePermissionsLPw(pkg.packageName, pkg, flags); 9897 // Update the child permissions 9898 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9899 for (int i = 0; i < childCount; i++) { 9900 PackageParser.Package childPkg = pkg.childPackages.get(i); 9901 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9902 } 9903 } 9904 9905 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9906 int flags) { 9907 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9908 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9909 } 9910 9911 private void updatePermissionsLPw(String changingPkg, 9912 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9913 // Make sure there are no dangling permission trees. 9914 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9915 while (it.hasNext()) { 9916 final BasePermission bp = it.next(); 9917 if (bp.packageSetting == null) { 9918 // We may not yet have parsed the package, so just see if 9919 // we still know about its settings. 9920 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9921 } 9922 if (bp.packageSetting == null) { 9923 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9924 + " from package " + bp.sourcePackage); 9925 it.remove(); 9926 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9927 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9928 Slog.i(TAG, "Removing old permission tree: " + bp.name 9929 + " from package " + bp.sourcePackage); 9930 flags |= UPDATE_PERMISSIONS_ALL; 9931 it.remove(); 9932 } 9933 } 9934 } 9935 9936 // Make sure all dynamic permissions have been assigned to a package, 9937 // and make sure there are no dangling permissions. 9938 it = mSettings.mPermissions.values().iterator(); 9939 while (it.hasNext()) { 9940 final BasePermission bp = it.next(); 9941 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9942 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9943 + bp.name + " pkg=" + bp.sourcePackage 9944 + " info=" + bp.pendingInfo); 9945 if (bp.packageSetting == null && bp.pendingInfo != null) { 9946 final BasePermission tree = findPermissionTreeLP(bp.name); 9947 if (tree != null && tree.perm != null) { 9948 bp.packageSetting = tree.packageSetting; 9949 bp.perm = new PackageParser.Permission(tree.perm.owner, 9950 new PermissionInfo(bp.pendingInfo)); 9951 bp.perm.info.packageName = tree.perm.info.packageName; 9952 bp.perm.info.name = bp.name; 9953 bp.uid = tree.uid; 9954 } 9955 } 9956 } 9957 if (bp.packageSetting == null) { 9958 // We may not yet have parsed the package, so just see if 9959 // we still know about its settings. 9960 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9961 } 9962 if (bp.packageSetting == null) { 9963 Slog.w(TAG, "Removing dangling permission: " + bp.name 9964 + " from package " + bp.sourcePackage); 9965 it.remove(); 9966 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9967 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9968 Slog.i(TAG, "Removing old permission: " + bp.name 9969 + " from package " + bp.sourcePackage); 9970 flags |= UPDATE_PERMISSIONS_ALL; 9971 it.remove(); 9972 } 9973 } 9974 } 9975 9976 // Now update the permissions for all packages, in particular 9977 // replace the granted permissions of the system packages. 9978 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9979 for (PackageParser.Package pkg : mPackages.values()) { 9980 if (pkg != pkgInfo) { 9981 // Only replace for packages on requested volume 9982 final String volumeUuid = getVolumeUuidForPackage(pkg); 9983 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9984 && Objects.equals(replaceVolumeUuid, volumeUuid); 9985 grantPermissionsLPw(pkg, replace, changingPkg); 9986 } 9987 } 9988 } 9989 9990 if (pkgInfo != null) { 9991 // Only replace for packages on requested volume 9992 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9993 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9994 && Objects.equals(replaceVolumeUuid, volumeUuid); 9995 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9996 } 9997 } 9998 9999 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10000 String packageOfInterest) { 10001 // IMPORTANT: There are two types of permissions: install and runtime. 10002 // Install time permissions are granted when the app is installed to 10003 // all device users and users added in the future. Runtime permissions 10004 // are granted at runtime explicitly to specific users. Normal and signature 10005 // protected permissions are install time permissions. Dangerous permissions 10006 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10007 // otherwise they are runtime permissions. This function does not manage 10008 // runtime permissions except for the case an app targeting Lollipop MR1 10009 // being upgraded to target a newer SDK, in which case dangerous permissions 10010 // are transformed from install time to runtime ones. 10011 10012 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10013 if (ps == null) { 10014 return; 10015 } 10016 10017 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10018 10019 PermissionsState permissionsState = ps.getPermissionsState(); 10020 PermissionsState origPermissions = permissionsState; 10021 10022 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10023 10024 boolean runtimePermissionsRevoked = false; 10025 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10026 10027 boolean changedInstallPermission = false; 10028 10029 if (replace) { 10030 ps.installPermissionsFixed = false; 10031 if (!ps.isSharedUser()) { 10032 origPermissions = new PermissionsState(permissionsState); 10033 permissionsState.reset(); 10034 } else { 10035 // We need to know only about runtime permission changes since the 10036 // calling code always writes the install permissions state but 10037 // the runtime ones are written only if changed. The only cases of 10038 // changed runtime permissions here are promotion of an install to 10039 // runtime and revocation of a runtime from a shared user. 10040 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10041 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10042 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10043 runtimePermissionsRevoked = true; 10044 } 10045 } 10046 } 10047 10048 permissionsState.setGlobalGids(mGlobalGids); 10049 10050 final int N = pkg.requestedPermissions.size(); 10051 for (int i=0; i<N; i++) { 10052 final String name = pkg.requestedPermissions.get(i); 10053 final BasePermission bp = mSettings.mPermissions.get(name); 10054 10055 if (DEBUG_INSTALL) { 10056 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10057 } 10058 10059 if (bp == null || bp.packageSetting == null) { 10060 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10061 Slog.w(TAG, "Unknown permission " + name 10062 + " in package " + pkg.packageName); 10063 } 10064 continue; 10065 } 10066 10067 final String perm = bp.name; 10068 boolean allowedSig = false; 10069 int grant = GRANT_DENIED; 10070 10071 // Keep track of app op permissions. 10072 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10073 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10074 if (pkgs == null) { 10075 pkgs = new ArraySet<>(); 10076 mAppOpPermissionPackages.put(bp.name, pkgs); 10077 } 10078 pkgs.add(pkg.packageName); 10079 } 10080 10081 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10082 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10083 >= Build.VERSION_CODES.M; 10084 switch (level) { 10085 case PermissionInfo.PROTECTION_NORMAL: { 10086 // For all apps normal permissions are install time ones. 10087 grant = GRANT_INSTALL; 10088 } break; 10089 10090 case PermissionInfo.PROTECTION_DANGEROUS: { 10091 // If a permission review is required for legacy apps we represent 10092 // their permissions as always granted runtime ones since we need 10093 // to keep the review required permission flag per user while an 10094 // install permission's state is shared across all users. 10095 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired 10096 && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10097 // For legacy apps dangerous permissions are install time ones. 10098 grant = GRANT_INSTALL; 10099 } else if (origPermissions.hasInstallPermission(bp.name)) { 10100 // For legacy apps that became modern, install becomes runtime. 10101 grant = GRANT_UPGRADE; 10102 } else if (mPromoteSystemApps 10103 && isSystemApp(ps) 10104 && mExistingSystemPackages.contains(ps.name)) { 10105 // For legacy system apps, install becomes runtime. 10106 // We cannot check hasInstallPermission() for system apps since those 10107 // permissions were granted implicitly and not persisted pre-M. 10108 grant = GRANT_UPGRADE; 10109 } else { 10110 // For modern apps keep runtime permissions unchanged. 10111 grant = GRANT_RUNTIME; 10112 } 10113 } break; 10114 10115 case PermissionInfo.PROTECTION_SIGNATURE: { 10116 // For all apps signature permissions are install time ones. 10117 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10118 if (allowedSig) { 10119 grant = GRANT_INSTALL; 10120 } 10121 } break; 10122 } 10123 10124 if (DEBUG_INSTALL) { 10125 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10126 } 10127 10128 if (grant != GRANT_DENIED) { 10129 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10130 // If this is an existing, non-system package, then 10131 // we can't add any new permissions to it. 10132 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10133 // Except... if this is a permission that was added 10134 // to the platform (note: need to only do this when 10135 // updating the platform). 10136 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10137 grant = GRANT_DENIED; 10138 } 10139 } 10140 } 10141 10142 switch (grant) { 10143 case GRANT_INSTALL: { 10144 // Revoke this as runtime permission to handle the case of 10145 // a runtime permission being downgraded to an install one. 10146 // Also in permission review mode we keep dangerous permissions 10147 // for legacy apps 10148 for (int userId : UserManagerService.getInstance().getUserIds()) { 10149 if (origPermissions.getRuntimePermissionState( 10150 bp.name, userId) != null) { 10151 // Revoke the runtime permission and clear the flags. 10152 origPermissions.revokeRuntimePermission(bp, userId); 10153 origPermissions.updatePermissionFlags(bp, userId, 10154 PackageManager.MASK_PERMISSION_FLAGS, 0); 10155 // If we revoked a permission permission, we have to write. 10156 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10157 changedRuntimePermissionUserIds, userId); 10158 } 10159 } 10160 // Grant an install permission. 10161 if (permissionsState.grantInstallPermission(bp) != 10162 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10163 changedInstallPermission = true; 10164 } 10165 } break; 10166 10167 case GRANT_RUNTIME: { 10168 // Grant previously granted runtime permissions. 10169 for (int userId : UserManagerService.getInstance().getUserIds()) { 10170 PermissionState permissionState = origPermissions 10171 .getRuntimePermissionState(bp.name, userId); 10172 int flags = permissionState != null 10173 ? permissionState.getFlags() : 0; 10174 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10175 if (permissionsState.grantRuntimePermission(bp, userId) == 10176 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10177 // If we cannot put the permission as it was, we have to write. 10178 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10179 changedRuntimePermissionUserIds, userId); 10180 } 10181 // If the app supports runtime permissions no need for a review. 10182 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 10183 && appSupportsRuntimePermissions 10184 && (flags & PackageManager 10185 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10186 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10187 // Since we changed the flags, we have to write. 10188 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10189 changedRuntimePermissionUserIds, userId); 10190 } 10191 } else if ((mPermissionReviewRequired 10192 || Build.PERMISSIONS_REVIEW_REQUIRED) 10193 && !appSupportsRuntimePermissions) { 10194 // For legacy apps that need a permission review, every new 10195 // runtime permission is granted but it is pending a review. 10196 // We also need to review only platform defined runtime 10197 // permissions as these are the only ones the platform knows 10198 // how to disable the API to simulate revocation as legacy 10199 // apps don't expect to run with revoked permissions. 10200 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10201 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10202 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10203 // We changed the flags, hence have to write. 10204 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10205 changedRuntimePermissionUserIds, userId); 10206 } 10207 } 10208 if (permissionsState.grantRuntimePermission(bp, userId) 10209 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10210 // We changed the permission, hence have to write. 10211 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10212 changedRuntimePermissionUserIds, userId); 10213 } 10214 } 10215 // Propagate the permission flags. 10216 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10217 } 10218 } break; 10219 10220 case GRANT_UPGRADE: { 10221 // Grant runtime permissions for a previously held install permission. 10222 PermissionState permissionState = origPermissions 10223 .getInstallPermissionState(bp.name); 10224 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10225 10226 if (origPermissions.revokeInstallPermission(bp) 10227 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10228 // We will be transferring the permission flags, so clear them. 10229 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10230 PackageManager.MASK_PERMISSION_FLAGS, 0); 10231 changedInstallPermission = true; 10232 } 10233 10234 // If the permission is not to be promoted to runtime we ignore it and 10235 // also its other flags as they are not applicable to install permissions. 10236 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10237 for (int userId : currentUserIds) { 10238 if (permissionsState.grantRuntimePermission(bp, userId) != 10239 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10240 // Transfer the permission flags. 10241 permissionsState.updatePermissionFlags(bp, userId, 10242 flags, flags); 10243 // If we granted the permission, we have to write. 10244 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10245 changedRuntimePermissionUserIds, userId); 10246 } 10247 } 10248 } 10249 } break; 10250 10251 default: { 10252 if (packageOfInterest == null 10253 || packageOfInterest.equals(pkg.packageName)) { 10254 Slog.w(TAG, "Not granting permission " + perm 10255 + " to package " + pkg.packageName 10256 + " because it was previously installed without"); 10257 } 10258 } break; 10259 } 10260 } else { 10261 if (permissionsState.revokeInstallPermission(bp) != 10262 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10263 // Also drop the permission flags. 10264 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10265 PackageManager.MASK_PERMISSION_FLAGS, 0); 10266 changedInstallPermission = true; 10267 Slog.i(TAG, "Un-granting permission " + perm 10268 + " from package " + pkg.packageName 10269 + " (protectionLevel=" + bp.protectionLevel 10270 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10271 + ")"); 10272 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10273 // Don't print warning for app op permissions, since it is fine for them 10274 // not to be granted, there is a UI for the user to decide. 10275 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10276 Slog.w(TAG, "Not granting permission " + perm 10277 + " to package " + pkg.packageName 10278 + " (protectionLevel=" + bp.protectionLevel 10279 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10280 + ")"); 10281 } 10282 } 10283 } 10284 } 10285 10286 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10287 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10288 // This is the first that we have heard about this package, so the 10289 // permissions we have now selected are fixed until explicitly 10290 // changed. 10291 ps.installPermissionsFixed = true; 10292 } 10293 10294 // Persist the runtime permissions state for users with changes. If permissions 10295 // were revoked because no app in the shared user declares them we have to 10296 // write synchronously to avoid losing runtime permissions state. 10297 for (int userId : changedRuntimePermissionUserIds) { 10298 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10299 } 10300 10301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10302 } 10303 10304 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10305 boolean allowed = false; 10306 final int NP = PackageParser.NEW_PERMISSIONS.length; 10307 for (int ip=0; ip<NP; ip++) { 10308 final PackageParser.NewPermissionInfo npi 10309 = PackageParser.NEW_PERMISSIONS[ip]; 10310 if (npi.name.equals(perm) 10311 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10312 allowed = true; 10313 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10314 + pkg.packageName); 10315 break; 10316 } 10317 } 10318 return allowed; 10319 } 10320 10321 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10322 BasePermission bp, PermissionsState origPermissions) { 10323 boolean allowed; 10324 allowed = (compareSignatures( 10325 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10326 == PackageManager.SIGNATURE_MATCH) 10327 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10328 == PackageManager.SIGNATURE_MATCH); 10329 if (!allowed && (bp.protectionLevel 10330 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10331 if (isSystemApp(pkg)) { 10332 // For updated system applications, a system permission 10333 // is granted only if it had been defined by the original application. 10334 if (pkg.isUpdatedSystemApp()) { 10335 final PackageSetting sysPs = mSettings 10336 .getDisabledSystemPkgLPr(pkg.packageName); 10337 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10338 // If the original was granted this permission, we take 10339 // that grant decision as read and propagate it to the 10340 // update. 10341 if (sysPs.isPrivileged()) { 10342 allowed = true; 10343 } 10344 } else { 10345 // The system apk may have been updated with an older 10346 // version of the one on the data partition, but which 10347 // granted a new system permission that it didn't have 10348 // before. In this case we do want to allow the app to 10349 // now get the new permission if the ancestral apk is 10350 // privileged to get it. 10351 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10352 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10353 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10354 allowed = true; 10355 break; 10356 } 10357 } 10358 } 10359 // Also if a privileged parent package on the system image or any of 10360 // its children requested a privileged permission, the updated child 10361 // packages can also get the permission. 10362 if (pkg.parentPackage != null) { 10363 final PackageSetting disabledSysParentPs = mSettings 10364 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10365 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10366 && disabledSysParentPs.isPrivileged()) { 10367 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10368 allowed = true; 10369 } else if (disabledSysParentPs.pkg.childPackages != null) { 10370 final int count = disabledSysParentPs.pkg.childPackages.size(); 10371 for (int i = 0; i < count; i++) { 10372 PackageParser.Package disabledSysChildPkg = 10373 disabledSysParentPs.pkg.childPackages.get(i); 10374 if (isPackageRequestingPermission(disabledSysChildPkg, 10375 perm)) { 10376 allowed = true; 10377 break; 10378 } 10379 } 10380 } 10381 } 10382 } 10383 } 10384 } else { 10385 allowed = isPrivilegedApp(pkg); 10386 } 10387 } 10388 } 10389 if (!allowed) { 10390 if (!allowed && (bp.protectionLevel 10391 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10392 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10393 // If this was a previously normal/dangerous permission that got moved 10394 // to a system permission as part of the runtime permission redesign, then 10395 // we still want to blindly grant it to old apps. 10396 allowed = true; 10397 } 10398 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10399 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10400 // If this permission is to be granted to the system installer and 10401 // this app is an installer, then it gets the permission. 10402 allowed = true; 10403 } 10404 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10405 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10406 // If this permission is to be granted to the system verifier and 10407 // this app is a verifier, then it gets the permission. 10408 allowed = true; 10409 } 10410 if (!allowed && (bp.protectionLevel 10411 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10412 && isSystemApp(pkg)) { 10413 // Any pre-installed system app is allowed to get this permission. 10414 allowed = true; 10415 } 10416 if (!allowed && (bp.protectionLevel 10417 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10418 // For development permissions, a development permission 10419 // is granted only if it was already granted. 10420 allowed = origPermissions.hasInstallPermission(perm); 10421 } 10422 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10423 && pkg.packageName.equals(mSetupWizardPackage)) { 10424 // If this permission is to be granted to the system setup wizard and 10425 // this app is a setup wizard, then it gets the permission. 10426 allowed = true; 10427 } 10428 } 10429 return allowed; 10430 } 10431 10432 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10433 final int permCount = pkg.requestedPermissions.size(); 10434 for (int j = 0; j < permCount; j++) { 10435 String requestedPermission = pkg.requestedPermissions.get(j); 10436 if (permission.equals(requestedPermission)) { 10437 return true; 10438 } 10439 } 10440 return false; 10441 } 10442 10443 final class ActivityIntentResolver 10444 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10445 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10446 boolean defaultOnly, int userId) { 10447 if (!sUserManager.exists(userId)) return null; 10448 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10449 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10450 } 10451 10452 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10453 int userId) { 10454 if (!sUserManager.exists(userId)) return null; 10455 mFlags = flags; 10456 return super.queryIntent(intent, resolvedType, 10457 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10458 } 10459 10460 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10461 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10462 if (!sUserManager.exists(userId)) return null; 10463 if (packageActivities == null) { 10464 return null; 10465 } 10466 mFlags = flags; 10467 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10468 final int N = packageActivities.size(); 10469 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10470 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10471 10472 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10473 for (int i = 0; i < N; ++i) { 10474 intentFilters = packageActivities.get(i).intents; 10475 if (intentFilters != null && intentFilters.size() > 0) { 10476 PackageParser.ActivityIntentInfo[] array = 10477 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10478 intentFilters.toArray(array); 10479 listCut.add(array); 10480 } 10481 } 10482 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10483 } 10484 10485 /** 10486 * Finds a privileged activity that matches the specified activity names. 10487 */ 10488 private PackageParser.Activity findMatchingActivity( 10489 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10490 for (PackageParser.Activity sysActivity : activityList) { 10491 if (sysActivity.info.name.equals(activityInfo.name)) { 10492 return sysActivity; 10493 } 10494 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10495 return sysActivity; 10496 } 10497 if (sysActivity.info.targetActivity != null) { 10498 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10499 return sysActivity; 10500 } 10501 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10502 return sysActivity; 10503 } 10504 } 10505 } 10506 return null; 10507 } 10508 10509 public class IterGenerator<E> { 10510 public Iterator<E> generate(ActivityIntentInfo info) { 10511 return null; 10512 } 10513 } 10514 10515 public class ActionIterGenerator extends IterGenerator<String> { 10516 @Override 10517 public Iterator<String> generate(ActivityIntentInfo info) { 10518 return info.actionsIterator(); 10519 } 10520 } 10521 10522 public class CategoriesIterGenerator extends IterGenerator<String> { 10523 @Override 10524 public Iterator<String> generate(ActivityIntentInfo info) { 10525 return info.categoriesIterator(); 10526 } 10527 } 10528 10529 public class SchemesIterGenerator extends IterGenerator<String> { 10530 @Override 10531 public Iterator<String> generate(ActivityIntentInfo info) { 10532 return info.schemesIterator(); 10533 } 10534 } 10535 10536 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10537 @Override 10538 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10539 return info.authoritiesIterator(); 10540 } 10541 } 10542 10543 /** 10544 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10545 * MODIFIED. Do not pass in a list that should not be changed. 10546 */ 10547 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10548 IterGenerator<T> generator, Iterator<T> searchIterator) { 10549 // loop through the set of actions; every one must be found in the intent filter 10550 while (searchIterator.hasNext()) { 10551 // we must have at least one filter in the list to consider a match 10552 if (intentList.size() == 0) { 10553 break; 10554 } 10555 10556 final T searchAction = searchIterator.next(); 10557 10558 // loop through the set of intent filters 10559 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10560 while (intentIter.hasNext()) { 10561 final ActivityIntentInfo intentInfo = intentIter.next(); 10562 boolean selectionFound = false; 10563 10564 // loop through the intent filter's selection criteria; at least one 10565 // of them must match the searched criteria 10566 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10567 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10568 final T intentSelection = intentSelectionIter.next(); 10569 if (intentSelection != null && intentSelection.equals(searchAction)) { 10570 selectionFound = true; 10571 break; 10572 } 10573 } 10574 10575 // the selection criteria wasn't found in this filter's set; this filter 10576 // is not a potential match 10577 if (!selectionFound) { 10578 intentIter.remove(); 10579 } 10580 } 10581 } 10582 } 10583 10584 private boolean isProtectedAction(ActivityIntentInfo filter) { 10585 final Iterator<String> actionsIter = filter.actionsIterator(); 10586 while (actionsIter != null && actionsIter.hasNext()) { 10587 final String filterAction = actionsIter.next(); 10588 if (PROTECTED_ACTIONS.contains(filterAction)) { 10589 return true; 10590 } 10591 } 10592 return false; 10593 } 10594 10595 /** 10596 * Adjusts the priority of the given intent filter according to policy. 10597 * <p> 10598 * <ul> 10599 * <li>The priority for non privileged applications is capped to '0'</li> 10600 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10601 * <li>The priority for unbundled updates to privileged applications is capped to the 10602 * priority defined on the system partition</li> 10603 * </ul> 10604 * <p> 10605 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10606 * allowed to obtain any priority on any action. 10607 */ 10608 private void adjustPriority( 10609 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10610 // nothing to do; priority is fine as-is 10611 if (intent.getPriority() <= 0) { 10612 return; 10613 } 10614 10615 final ActivityInfo activityInfo = intent.activity.info; 10616 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10617 10618 final boolean privilegedApp = 10619 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10620 if (!privilegedApp) { 10621 // non-privileged applications can never define a priority >0 10622 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10623 + " package: " + applicationInfo.packageName 10624 + " activity: " + intent.activity.className 10625 + " origPrio: " + intent.getPriority()); 10626 intent.setPriority(0); 10627 return; 10628 } 10629 10630 if (systemActivities == null) { 10631 // the system package is not disabled; we're parsing the system partition 10632 if (isProtectedAction(intent)) { 10633 if (mDeferProtectedFilters) { 10634 // We can't deal with these just yet. No component should ever obtain a 10635 // >0 priority for a protected actions, with ONE exception -- the setup 10636 // wizard. The setup wizard, however, cannot be known until we're able to 10637 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10638 // until all intent filters have been processed. Chicken, meet egg. 10639 // Let the filter temporarily have a high priority and rectify the 10640 // priorities after all system packages have been scanned. 10641 mProtectedFilters.add(intent); 10642 if (DEBUG_FILTERS) { 10643 Slog.i(TAG, "Protected action; save for later;" 10644 + " package: " + applicationInfo.packageName 10645 + " activity: " + intent.activity.className 10646 + " origPrio: " + intent.getPriority()); 10647 } 10648 return; 10649 } else { 10650 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10651 Slog.i(TAG, "No setup wizard;" 10652 + " All protected intents capped to priority 0"); 10653 } 10654 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10655 if (DEBUG_FILTERS) { 10656 Slog.i(TAG, "Found setup wizard;" 10657 + " allow priority " + intent.getPriority() + ";" 10658 + " package: " + intent.activity.info.packageName 10659 + " activity: " + intent.activity.className 10660 + " priority: " + intent.getPriority()); 10661 } 10662 // setup wizard gets whatever it wants 10663 return; 10664 } 10665 Slog.w(TAG, "Protected action; cap priority to 0;" 10666 + " package: " + intent.activity.info.packageName 10667 + " activity: " + intent.activity.className 10668 + " origPrio: " + intent.getPriority()); 10669 intent.setPriority(0); 10670 return; 10671 } 10672 } 10673 // privileged apps on the system image get whatever priority they request 10674 return; 10675 } 10676 10677 // privileged app unbundled update ... try to find the same activity 10678 final PackageParser.Activity foundActivity = 10679 findMatchingActivity(systemActivities, activityInfo); 10680 if (foundActivity == null) { 10681 // this is a new activity; it cannot obtain >0 priority 10682 if (DEBUG_FILTERS) { 10683 Slog.i(TAG, "New activity; cap priority to 0;" 10684 + " package: " + applicationInfo.packageName 10685 + " activity: " + intent.activity.className 10686 + " origPrio: " + intent.getPriority()); 10687 } 10688 intent.setPriority(0); 10689 return; 10690 } 10691 10692 // found activity, now check for filter equivalence 10693 10694 // a shallow copy is enough; we modify the list, not its contents 10695 final List<ActivityIntentInfo> intentListCopy = 10696 new ArrayList<>(foundActivity.intents); 10697 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10698 10699 // find matching action subsets 10700 final Iterator<String> actionsIterator = intent.actionsIterator(); 10701 if (actionsIterator != null) { 10702 getIntentListSubset( 10703 intentListCopy, new ActionIterGenerator(), actionsIterator); 10704 if (intentListCopy.size() == 0) { 10705 // no more intents to match; we're not equivalent 10706 if (DEBUG_FILTERS) { 10707 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10708 + " package: " + applicationInfo.packageName 10709 + " activity: " + intent.activity.className 10710 + " origPrio: " + intent.getPriority()); 10711 } 10712 intent.setPriority(0); 10713 return; 10714 } 10715 } 10716 10717 // find matching category subsets 10718 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10719 if (categoriesIterator != null) { 10720 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10721 categoriesIterator); 10722 if (intentListCopy.size() == 0) { 10723 // no more intents to match; we're not equivalent 10724 if (DEBUG_FILTERS) { 10725 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10726 + " package: " + applicationInfo.packageName 10727 + " activity: " + intent.activity.className 10728 + " origPrio: " + intent.getPriority()); 10729 } 10730 intent.setPriority(0); 10731 return; 10732 } 10733 } 10734 10735 // find matching schemes subsets 10736 final Iterator<String> schemesIterator = intent.schemesIterator(); 10737 if (schemesIterator != null) { 10738 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10739 schemesIterator); 10740 if (intentListCopy.size() == 0) { 10741 // no more intents to match; we're not equivalent 10742 if (DEBUG_FILTERS) { 10743 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10744 + " package: " + applicationInfo.packageName 10745 + " activity: " + intent.activity.className 10746 + " origPrio: " + intent.getPriority()); 10747 } 10748 intent.setPriority(0); 10749 return; 10750 } 10751 } 10752 10753 // find matching authorities subsets 10754 final Iterator<IntentFilter.AuthorityEntry> 10755 authoritiesIterator = intent.authoritiesIterator(); 10756 if (authoritiesIterator != null) { 10757 getIntentListSubset(intentListCopy, 10758 new AuthoritiesIterGenerator(), 10759 authoritiesIterator); 10760 if (intentListCopy.size() == 0) { 10761 // no more intents to match; we're not equivalent 10762 if (DEBUG_FILTERS) { 10763 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10764 + " package: " + applicationInfo.packageName 10765 + " activity: " + intent.activity.className 10766 + " origPrio: " + intent.getPriority()); 10767 } 10768 intent.setPriority(0); 10769 return; 10770 } 10771 } 10772 10773 // we found matching filter(s); app gets the max priority of all intents 10774 int cappedPriority = 0; 10775 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10776 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10777 } 10778 if (intent.getPriority() > cappedPriority) { 10779 if (DEBUG_FILTERS) { 10780 Slog.i(TAG, "Found matching filter(s);" 10781 + " cap priority to " + cappedPriority + ";" 10782 + " package: " + applicationInfo.packageName 10783 + " activity: " + intent.activity.className 10784 + " origPrio: " + intent.getPriority()); 10785 } 10786 intent.setPriority(cappedPriority); 10787 return; 10788 } 10789 // all this for nothing; the requested priority was <= what was on the system 10790 } 10791 10792 public final void addActivity(PackageParser.Activity a, String type) { 10793 mActivities.put(a.getComponentName(), a); 10794 if (DEBUG_SHOW_INFO) 10795 Log.v( 10796 TAG, " " + type + " " + 10797 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10798 if (DEBUG_SHOW_INFO) 10799 Log.v(TAG, " Class=" + a.info.name); 10800 final int NI = a.intents.size(); 10801 for (int j=0; j<NI; j++) { 10802 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10803 if ("activity".equals(type)) { 10804 final PackageSetting ps = 10805 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10806 final List<PackageParser.Activity> systemActivities = 10807 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10808 adjustPriority(systemActivities, intent); 10809 } 10810 if (DEBUG_SHOW_INFO) { 10811 Log.v(TAG, " IntentFilter:"); 10812 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10813 } 10814 if (!intent.debugCheck()) { 10815 Log.w(TAG, "==> For Activity " + a.info.name); 10816 } 10817 addFilter(intent); 10818 } 10819 } 10820 10821 public final void removeActivity(PackageParser.Activity a, String type) { 10822 mActivities.remove(a.getComponentName()); 10823 if (DEBUG_SHOW_INFO) { 10824 Log.v(TAG, " " + type + " " 10825 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10826 : a.info.name) + ":"); 10827 Log.v(TAG, " Class=" + a.info.name); 10828 } 10829 final int NI = a.intents.size(); 10830 for (int j=0; j<NI; j++) { 10831 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10832 if (DEBUG_SHOW_INFO) { 10833 Log.v(TAG, " IntentFilter:"); 10834 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10835 } 10836 removeFilter(intent); 10837 } 10838 } 10839 10840 @Override 10841 protected boolean allowFilterResult( 10842 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10843 ActivityInfo filterAi = filter.activity.info; 10844 for (int i=dest.size()-1; i>=0; i--) { 10845 ActivityInfo destAi = dest.get(i).activityInfo; 10846 if (destAi.name == filterAi.name 10847 && destAi.packageName == filterAi.packageName) { 10848 return false; 10849 } 10850 } 10851 return true; 10852 } 10853 10854 @Override 10855 protected ActivityIntentInfo[] newArray(int size) { 10856 return new ActivityIntentInfo[size]; 10857 } 10858 10859 @Override 10860 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10861 if (!sUserManager.exists(userId)) return true; 10862 PackageParser.Package p = filter.activity.owner; 10863 if (p != null) { 10864 PackageSetting ps = (PackageSetting)p.mExtras; 10865 if (ps != null) { 10866 // System apps are never considered stopped for purposes of 10867 // filtering, because there may be no way for the user to 10868 // actually re-launch them. 10869 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10870 && ps.getStopped(userId); 10871 } 10872 } 10873 return false; 10874 } 10875 10876 @Override 10877 protected boolean isPackageForFilter(String packageName, 10878 PackageParser.ActivityIntentInfo info) { 10879 return packageName.equals(info.activity.owner.packageName); 10880 } 10881 10882 @Override 10883 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10884 int match, int userId) { 10885 if (!sUserManager.exists(userId)) return null; 10886 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10887 return null; 10888 } 10889 final PackageParser.Activity activity = info.activity; 10890 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10891 if (ps == null) { 10892 return null; 10893 } 10894 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10895 ps.readUserState(userId), userId); 10896 if (ai == null) { 10897 return null; 10898 } 10899 final ResolveInfo res = new ResolveInfo(); 10900 res.activityInfo = ai; 10901 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10902 res.filter = info; 10903 } 10904 if (info != null) { 10905 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10906 } 10907 res.priority = info.getPriority(); 10908 res.preferredOrder = activity.owner.mPreferredOrder; 10909 //System.out.println("Result: " + res.activityInfo.className + 10910 // " = " + res.priority); 10911 res.match = match; 10912 res.isDefault = info.hasDefault; 10913 res.labelRes = info.labelRes; 10914 res.nonLocalizedLabel = info.nonLocalizedLabel; 10915 if (userNeedsBadging(userId)) { 10916 res.noResourceId = true; 10917 } else { 10918 res.icon = info.icon; 10919 } 10920 res.iconResourceId = info.icon; 10921 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10922 return res; 10923 } 10924 10925 @Override 10926 protected void sortResults(List<ResolveInfo> results) { 10927 Collections.sort(results, mResolvePrioritySorter); 10928 } 10929 10930 @Override 10931 protected void dumpFilter(PrintWriter out, String prefix, 10932 PackageParser.ActivityIntentInfo filter) { 10933 out.print(prefix); out.print( 10934 Integer.toHexString(System.identityHashCode(filter.activity))); 10935 out.print(' '); 10936 filter.activity.printComponentShortName(out); 10937 out.print(" filter "); 10938 out.println(Integer.toHexString(System.identityHashCode(filter))); 10939 } 10940 10941 @Override 10942 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10943 return filter.activity; 10944 } 10945 10946 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10947 PackageParser.Activity activity = (PackageParser.Activity)label; 10948 out.print(prefix); out.print( 10949 Integer.toHexString(System.identityHashCode(activity))); 10950 out.print(' '); 10951 activity.printComponentShortName(out); 10952 if (count > 1) { 10953 out.print(" ("); out.print(count); out.print(" filters)"); 10954 } 10955 out.println(); 10956 } 10957 10958 // Keys are String (activity class name), values are Activity. 10959 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10960 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10961 private int mFlags; 10962 } 10963 10964 private final class ServiceIntentResolver 10965 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10966 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10967 boolean defaultOnly, int userId) { 10968 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10969 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10970 } 10971 10972 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10973 int userId) { 10974 if (!sUserManager.exists(userId)) return null; 10975 mFlags = flags; 10976 return super.queryIntent(intent, resolvedType, 10977 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10978 } 10979 10980 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10981 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10982 if (!sUserManager.exists(userId)) return null; 10983 if (packageServices == null) { 10984 return null; 10985 } 10986 mFlags = flags; 10987 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10988 final int N = packageServices.size(); 10989 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10990 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10991 10992 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10993 for (int i = 0; i < N; ++i) { 10994 intentFilters = packageServices.get(i).intents; 10995 if (intentFilters != null && intentFilters.size() > 0) { 10996 PackageParser.ServiceIntentInfo[] array = 10997 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10998 intentFilters.toArray(array); 10999 listCut.add(array); 11000 } 11001 } 11002 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11003 } 11004 11005 public final void addService(PackageParser.Service s) { 11006 mServices.put(s.getComponentName(), s); 11007 if (DEBUG_SHOW_INFO) { 11008 Log.v(TAG, " " 11009 + (s.info.nonLocalizedLabel != null 11010 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11011 Log.v(TAG, " Class=" + s.info.name); 11012 } 11013 final int NI = s.intents.size(); 11014 int j; 11015 for (j=0; j<NI; j++) { 11016 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11017 if (DEBUG_SHOW_INFO) { 11018 Log.v(TAG, " IntentFilter:"); 11019 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11020 } 11021 if (!intent.debugCheck()) { 11022 Log.w(TAG, "==> For Service " + s.info.name); 11023 } 11024 addFilter(intent); 11025 } 11026 } 11027 11028 public final void removeService(PackageParser.Service s) { 11029 mServices.remove(s.getComponentName()); 11030 if (DEBUG_SHOW_INFO) { 11031 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11032 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11033 Log.v(TAG, " Class=" + s.info.name); 11034 } 11035 final int NI = s.intents.size(); 11036 int j; 11037 for (j=0; j<NI; j++) { 11038 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11039 if (DEBUG_SHOW_INFO) { 11040 Log.v(TAG, " IntentFilter:"); 11041 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11042 } 11043 removeFilter(intent); 11044 } 11045 } 11046 11047 @Override 11048 protected boolean allowFilterResult( 11049 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11050 ServiceInfo filterSi = filter.service.info; 11051 for (int i=dest.size()-1; i>=0; i--) { 11052 ServiceInfo destAi = dest.get(i).serviceInfo; 11053 if (destAi.name == filterSi.name 11054 && destAi.packageName == filterSi.packageName) { 11055 return false; 11056 } 11057 } 11058 return true; 11059 } 11060 11061 @Override 11062 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11063 return new PackageParser.ServiceIntentInfo[size]; 11064 } 11065 11066 @Override 11067 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11068 if (!sUserManager.exists(userId)) return true; 11069 PackageParser.Package p = filter.service.owner; 11070 if (p != null) { 11071 PackageSetting ps = (PackageSetting)p.mExtras; 11072 if (ps != null) { 11073 // System apps are never considered stopped for purposes of 11074 // filtering, because there may be no way for the user to 11075 // actually re-launch them. 11076 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11077 && ps.getStopped(userId); 11078 } 11079 } 11080 return false; 11081 } 11082 11083 @Override 11084 protected boolean isPackageForFilter(String packageName, 11085 PackageParser.ServiceIntentInfo info) { 11086 return packageName.equals(info.service.owner.packageName); 11087 } 11088 11089 @Override 11090 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11091 int match, int userId) { 11092 if (!sUserManager.exists(userId)) return null; 11093 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11094 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11095 return null; 11096 } 11097 final PackageParser.Service service = info.service; 11098 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11099 if (ps == null) { 11100 return null; 11101 } 11102 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11103 ps.readUserState(userId), userId); 11104 if (si == null) { 11105 return null; 11106 } 11107 final ResolveInfo res = new ResolveInfo(); 11108 res.serviceInfo = si; 11109 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11110 res.filter = filter; 11111 } 11112 res.priority = info.getPriority(); 11113 res.preferredOrder = service.owner.mPreferredOrder; 11114 res.match = match; 11115 res.isDefault = info.hasDefault; 11116 res.labelRes = info.labelRes; 11117 res.nonLocalizedLabel = info.nonLocalizedLabel; 11118 res.icon = info.icon; 11119 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11120 return res; 11121 } 11122 11123 @Override 11124 protected void sortResults(List<ResolveInfo> results) { 11125 Collections.sort(results, mResolvePrioritySorter); 11126 } 11127 11128 @Override 11129 protected void dumpFilter(PrintWriter out, String prefix, 11130 PackageParser.ServiceIntentInfo filter) { 11131 out.print(prefix); out.print( 11132 Integer.toHexString(System.identityHashCode(filter.service))); 11133 out.print(' '); 11134 filter.service.printComponentShortName(out); 11135 out.print(" filter "); 11136 out.println(Integer.toHexString(System.identityHashCode(filter))); 11137 } 11138 11139 @Override 11140 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11141 return filter.service; 11142 } 11143 11144 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11145 PackageParser.Service service = (PackageParser.Service)label; 11146 out.print(prefix); out.print( 11147 Integer.toHexString(System.identityHashCode(service))); 11148 out.print(' '); 11149 service.printComponentShortName(out); 11150 if (count > 1) { 11151 out.print(" ("); out.print(count); out.print(" filters)"); 11152 } 11153 out.println(); 11154 } 11155 11156// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11157// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11158// final List<ResolveInfo> retList = Lists.newArrayList(); 11159// while (i.hasNext()) { 11160// final ResolveInfo resolveInfo = (ResolveInfo) i; 11161// if (isEnabledLP(resolveInfo.serviceInfo)) { 11162// retList.add(resolveInfo); 11163// } 11164// } 11165// return retList; 11166// } 11167 11168 // Keys are String (activity class name), values are Activity. 11169 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11170 = new ArrayMap<ComponentName, PackageParser.Service>(); 11171 private int mFlags; 11172 }; 11173 11174 private final class ProviderIntentResolver 11175 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11176 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11177 boolean defaultOnly, int userId) { 11178 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11179 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11180 } 11181 11182 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11183 int userId) { 11184 if (!sUserManager.exists(userId)) 11185 return null; 11186 mFlags = flags; 11187 return super.queryIntent(intent, resolvedType, 11188 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11189 } 11190 11191 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11192 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11193 if (!sUserManager.exists(userId)) 11194 return null; 11195 if (packageProviders == null) { 11196 return null; 11197 } 11198 mFlags = flags; 11199 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11200 final int N = packageProviders.size(); 11201 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11202 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11203 11204 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11205 for (int i = 0; i < N; ++i) { 11206 intentFilters = packageProviders.get(i).intents; 11207 if (intentFilters != null && intentFilters.size() > 0) { 11208 PackageParser.ProviderIntentInfo[] array = 11209 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11210 intentFilters.toArray(array); 11211 listCut.add(array); 11212 } 11213 } 11214 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11215 } 11216 11217 public final void addProvider(PackageParser.Provider p) { 11218 if (mProviders.containsKey(p.getComponentName())) { 11219 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11220 return; 11221 } 11222 11223 mProviders.put(p.getComponentName(), p); 11224 if (DEBUG_SHOW_INFO) { 11225 Log.v(TAG, " " 11226 + (p.info.nonLocalizedLabel != null 11227 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11228 Log.v(TAG, " Class=" + p.info.name); 11229 } 11230 final int NI = p.intents.size(); 11231 int j; 11232 for (j = 0; j < NI; j++) { 11233 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11234 if (DEBUG_SHOW_INFO) { 11235 Log.v(TAG, " IntentFilter:"); 11236 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11237 } 11238 if (!intent.debugCheck()) { 11239 Log.w(TAG, "==> For Provider " + p.info.name); 11240 } 11241 addFilter(intent); 11242 } 11243 } 11244 11245 public final void removeProvider(PackageParser.Provider p) { 11246 mProviders.remove(p.getComponentName()); 11247 if (DEBUG_SHOW_INFO) { 11248 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11249 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11250 Log.v(TAG, " Class=" + p.info.name); 11251 } 11252 final int NI = p.intents.size(); 11253 int j; 11254 for (j = 0; j < NI; j++) { 11255 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11256 if (DEBUG_SHOW_INFO) { 11257 Log.v(TAG, " IntentFilter:"); 11258 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11259 } 11260 removeFilter(intent); 11261 } 11262 } 11263 11264 @Override 11265 protected boolean allowFilterResult( 11266 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11267 ProviderInfo filterPi = filter.provider.info; 11268 for (int i = dest.size() - 1; i >= 0; i--) { 11269 ProviderInfo destPi = dest.get(i).providerInfo; 11270 if (destPi.name == filterPi.name 11271 && destPi.packageName == filterPi.packageName) { 11272 return false; 11273 } 11274 } 11275 return true; 11276 } 11277 11278 @Override 11279 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11280 return new PackageParser.ProviderIntentInfo[size]; 11281 } 11282 11283 @Override 11284 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11285 if (!sUserManager.exists(userId)) 11286 return true; 11287 PackageParser.Package p = filter.provider.owner; 11288 if (p != null) { 11289 PackageSetting ps = (PackageSetting) p.mExtras; 11290 if (ps != null) { 11291 // System apps are never considered stopped for purposes of 11292 // filtering, because there may be no way for the user to 11293 // actually re-launch them. 11294 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11295 && ps.getStopped(userId); 11296 } 11297 } 11298 return false; 11299 } 11300 11301 @Override 11302 protected boolean isPackageForFilter(String packageName, 11303 PackageParser.ProviderIntentInfo info) { 11304 return packageName.equals(info.provider.owner.packageName); 11305 } 11306 11307 @Override 11308 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11309 int match, int userId) { 11310 if (!sUserManager.exists(userId)) 11311 return null; 11312 final PackageParser.ProviderIntentInfo info = filter; 11313 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11314 return null; 11315 } 11316 final PackageParser.Provider provider = info.provider; 11317 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11318 if (ps == null) { 11319 return null; 11320 } 11321 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11322 ps.readUserState(userId), userId); 11323 if (pi == null) { 11324 return null; 11325 } 11326 final ResolveInfo res = new ResolveInfo(); 11327 res.providerInfo = pi; 11328 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11329 res.filter = filter; 11330 } 11331 res.priority = info.getPriority(); 11332 res.preferredOrder = provider.owner.mPreferredOrder; 11333 res.match = match; 11334 res.isDefault = info.hasDefault; 11335 res.labelRes = info.labelRes; 11336 res.nonLocalizedLabel = info.nonLocalizedLabel; 11337 res.icon = info.icon; 11338 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11339 return res; 11340 } 11341 11342 @Override 11343 protected void sortResults(List<ResolveInfo> results) { 11344 Collections.sort(results, mResolvePrioritySorter); 11345 } 11346 11347 @Override 11348 protected void dumpFilter(PrintWriter out, String prefix, 11349 PackageParser.ProviderIntentInfo filter) { 11350 out.print(prefix); 11351 out.print( 11352 Integer.toHexString(System.identityHashCode(filter.provider))); 11353 out.print(' '); 11354 filter.provider.printComponentShortName(out); 11355 out.print(" filter "); 11356 out.println(Integer.toHexString(System.identityHashCode(filter))); 11357 } 11358 11359 @Override 11360 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11361 return filter.provider; 11362 } 11363 11364 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11365 PackageParser.Provider provider = (PackageParser.Provider)label; 11366 out.print(prefix); out.print( 11367 Integer.toHexString(System.identityHashCode(provider))); 11368 out.print(' '); 11369 provider.printComponentShortName(out); 11370 if (count > 1) { 11371 out.print(" ("); out.print(count); out.print(" filters)"); 11372 } 11373 out.println(); 11374 } 11375 11376 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11377 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11378 private int mFlags; 11379 } 11380 11381 private static final class EphemeralIntentResolver 11382 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11383 /** 11384 * The result that has the highest defined order. Ordering applies on a 11385 * per-package basis. Mapping is from package name to Pair of order and 11386 * EphemeralResolveInfo. 11387 * <p> 11388 * NOTE: This is implemented as a field variable for convenience and efficiency. 11389 * By having a field variable, we're able to track filter ordering as soon as 11390 * a non-zero order is defined. Otherwise, multiple loops across the result set 11391 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11392 * this needs to be contained entirely within {@link #filterResults()}. 11393 */ 11394 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11395 11396 @Override 11397 protected EphemeralResolveIntentInfo[] newArray(int size) { 11398 return new EphemeralResolveIntentInfo[size]; 11399 } 11400 11401 @Override 11402 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11403 return true; 11404 } 11405 11406 @Override 11407 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11408 int userId) { 11409 if (!sUserManager.exists(userId)) { 11410 return null; 11411 } 11412 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11413 final Integer order = info.getOrder(); 11414 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11415 mOrderResult.get(packageName); 11416 // ordering is enabled and this item's order isn't high enough 11417 if (lastOrderResult != null && lastOrderResult.first >= order) { 11418 return null; 11419 } 11420 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11421 if (order > 0) { 11422 // non-zero order, enable ordering 11423 mOrderResult.put(packageName, new Pair<>(order, res)); 11424 } 11425 return res; 11426 } 11427 11428 @Override 11429 protected void filterResults(List<EphemeralResolveInfo> results) { 11430 // only do work if ordering is enabled [most of the time it won't be] 11431 if (mOrderResult.size() == 0) { 11432 return; 11433 } 11434 int resultSize = results.size(); 11435 for (int i = 0; i < resultSize; i++) { 11436 final EphemeralResolveInfo info = results.get(i); 11437 final String packageName = info.getPackageName(); 11438 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11439 if (savedInfo == null) { 11440 // package doesn't having ordering 11441 continue; 11442 } 11443 if (savedInfo.second == info) { 11444 // circled back to the highest ordered item; remove from order list 11445 mOrderResult.remove(savedInfo); 11446 if (mOrderResult.size() == 0) { 11447 // no more ordered items 11448 break; 11449 } 11450 continue; 11451 } 11452 // item has a worse order, remove it from the result list 11453 results.remove(i); 11454 resultSize--; 11455 i--; 11456 } 11457 } 11458 } 11459 11460 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11461 new Comparator<ResolveInfo>() { 11462 public int compare(ResolveInfo r1, ResolveInfo r2) { 11463 int v1 = r1.priority; 11464 int v2 = r2.priority; 11465 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11466 if (v1 != v2) { 11467 return (v1 > v2) ? -1 : 1; 11468 } 11469 v1 = r1.preferredOrder; 11470 v2 = r2.preferredOrder; 11471 if (v1 != v2) { 11472 return (v1 > v2) ? -1 : 1; 11473 } 11474 if (r1.isDefault != r2.isDefault) { 11475 return r1.isDefault ? -1 : 1; 11476 } 11477 v1 = r1.match; 11478 v2 = r2.match; 11479 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11480 if (v1 != v2) { 11481 return (v1 > v2) ? -1 : 1; 11482 } 11483 if (r1.system != r2.system) { 11484 return r1.system ? -1 : 1; 11485 } 11486 if (r1.activityInfo != null) { 11487 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11488 } 11489 if (r1.serviceInfo != null) { 11490 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11491 } 11492 if (r1.providerInfo != null) { 11493 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11494 } 11495 return 0; 11496 } 11497 }; 11498 11499 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11500 new Comparator<ProviderInfo>() { 11501 public int compare(ProviderInfo p1, ProviderInfo p2) { 11502 final int v1 = p1.initOrder; 11503 final int v2 = p2.initOrder; 11504 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11505 } 11506 }; 11507 11508 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11509 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11510 final int[] userIds) { 11511 mHandler.post(new Runnable() { 11512 @Override 11513 public void run() { 11514 try { 11515 final IActivityManager am = ActivityManagerNative.getDefault(); 11516 if (am == null) return; 11517 final int[] resolvedUserIds; 11518 if (userIds == null) { 11519 resolvedUserIds = am.getRunningUserIds(); 11520 } else { 11521 resolvedUserIds = userIds; 11522 } 11523 for (int id : resolvedUserIds) { 11524 final Intent intent = new Intent(action, 11525 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11526 if (extras != null) { 11527 intent.putExtras(extras); 11528 } 11529 if (targetPkg != null) { 11530 intent.setPackage(targetPkg); 11531 } 11532 // Modify the UID when posting to other users 11533 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11534 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11535 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11536 intent.putExtra(Intent.EXTRA_UID, uid); 11537 } 11538 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11539 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11540 if (DEBUG_BROADCASTS) { 11541 RuntimeException here = new RuntimeException("here"); 11542 here.fillInStackTrace(); 11543 Slog.d(TAG, "Sending to user " + id + ": " 11544 + intent.toShortString(false, true, false, false) 11545 + " " + intent.getExtras(), here); 11546 } 11547 am.broadcastIntent(null, intent, null, finishedReceiver, 11548 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11549 null, finishedReceiver != null, false, id); 11550 } 11551 } catch (RemoteException ex) { 11552 } 11553 } 11554 }); 11555 } 11556 11557 /** 11558 * Check if the external storage media is available. This is true if there 11559 * is a mounted external storage medium or if the external storage is 11560 * emulated. 11561 */ 11562 private boolean isExternalMediaAvailable() { 11563 return mMediaMounted || Environment.isExternalStorageEmulated(); 11564 } 11565 11566 @Override 11567 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11568 // writer 11569 synchronized (mPackages) { 11570 if (!isExternalMediaAvailable()) { 11571 // If the external storage is no longer mounted at this point, 11572 // the caller may not have been able to delete all of this 11573 // packages files and can not delete any more. Bail. 11574 return null; 11575 } 11576 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11577 if (lastPackage != null) { 11578 pkgs.remove(lastPackage); 11579 } 11580 if (pkgs.size() > 0) { 11581 return pkgs.get(0); 11582 } 11583 } 11584 return null; 11585 } 11586 11587 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11588 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11589 userId, andCode ? 1 : 0, packageName); 11590 if (mSystemReady) { 11591 msg.sendToTarget(); 11592 } else { 11593 if (mPostSystemReadyMessages == null) { 11594 mPostSystemReadyMessages = new ArrayList<>(); 11595 } 11596 mPostSystemReadyMessages.add(msg); 11597 } 11598 } 11599 11600 void startCleaningPackages() { 11601 // reader 11602 if (!isExternalMediaAvailable()) { 11603 return; 11604 } 11605 synchronized (mPackages) { 11606 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11607 return; 11608 } 11609 } 11610 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11611 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11612 IActivityManager am = ActivityManagerNative.getDefault(); 11613 if (am != null) { 11614 try { 11615 am.startService(null, intent, null, mContext.getOpPackageName(), 11616 UserHandle.USER_SYSTEM); 11617 } catch (RemoteException e) { 11618 } 11619 } 11620 } 11621 11622 @Override 11623 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11624 int installFlags, String installerPackageName, int userId) { 11625 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11626 11627 final int callingUid = Binder.getCallingUid(); 11628 enforceCrossUserPermission(callingUid, userId, 11629 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11630 11631 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11632 try { 11633 if (observer != null) { 11634 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11635 } 11636 } catch (RemoteException re) { 11637 } 11638 return; 11639 } 11640 11641 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11642 installFlags |= PackageManager.INSTALL_FROM_ADB; 11643 11644 } else { 11645 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11646 // about installerPackageName. 11647 11648 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11649 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11650 } 11651 11652 UserHandle user; 11653 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11654 user = UserHandle.ALL; 11655 } else { 11656 user = new UserHandle(userId); 11657 } 11658 11659 // Only system components can circumvent runtime permissions when installing. 11660 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11661 && mContext.checkCallingOrSelfPermission(Manifest.permission 11662 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11663 throw new SecurityException("You need the " 11664 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11665 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11666 } 11667 11668 final File originFile = new File(originPath); 11669 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11670 11671 final Message msg = mHandler.obtainMessage(INIT_COPY); 11672 final VerificationInfo verificationInfo = new VerificationInfo( 11673 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11674 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11675 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11676 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11677 null /*certificates*/); 11678 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11679 msg.obj = params; 11680 11681 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11682 System.identityHashCode(msg.obj)); 11683 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11684 System.identityHashCode(msg.obj)); 11685 11686 mHandler.sendMessage(msg); 11687 } 11688 11689 void installStage(String packageName, File stagedDir, String stagedCid, 11690 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11691 String installerPackageName, int installerUid, UserHandle user, 11692 Certificate[][] certificates) { 11693 if (DEBUG_EPHEMERAL) { 11694 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11695 Slog.d(TAG, "Ephemeral install of " + packageName); 11696 } 11697 } 11698 final VerificationInfo verificationInfo = new VerificationInfo( 11699 sessionParams.originatingUri, sessionParams.referrerUri, 11700 sessionParams.originatingUid, installerUid); 11701 11702 final OriginInfo origin; 11703 if (stagedDir != null) { 11704 origin = OriginInfo.fromStagedFile(stagedDir); 11705 } else { 11706 origin = OriginInfo.fromStagedContainer(stagedCid); 11707 } 11708 11709 final Message msg = mHandler.obtainMessage(INIT_COPY); 11710 final InstallParams params = new InstallParams(origin, null, observer, 11711 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11712 verificationInfo, user, sessionParams.abiOverride, 11713 sessionParams.grantedRuntimePermissions, certificates); 11714 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11715 msg.obj = params; 11716 11717 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11718 System.identityHashCode(msg.obj)); 11719 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11720 System.identityHashCode(msg.obj)); 11721 11722 mHandler.sendMessage(msg); 11723 } 11724 11725 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11726 int userId) { 11727 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11728 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11729 } 11730 11731 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11732 int appId, int userId) { 11733 Bundle extras = new Bundle(1); 11734 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11735 11736 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11737 packageName, extras, 0, null, null, new int[] {userId}); 11738 try { 11739 IActivityManager am = ActivityManagerNative.getDefault(); 11740 if (isSystem && am.isUserRunning(userId, 0)) { 11741 // The just-installed/enabled app is bundled on the system, so presumed 11742 // to be able to run automatically without needing an explicit launch. 11743 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11744 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11745 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11746 .setPackage(packageName); 11747 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11748 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11749 } 11750 } catch (RemoteException e) { 11751 // shouldn't happen 11752 Slog.w(TAG, "Unable to bootstrap installed package", e); 11753 } 11754 } 11755 11756 @Override 11757 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11758 int userId) { 11759 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11760 PackageSetting pkgSetting; 11761 final int uid = Binder.getCallingUid(); 11762 enforceCrossUserPermission(uid, userId, 11763 true /* requireFullPermission */, true /* checkShell */, 11764 "setApplicationHiddenSetting for user " + userId); 11765 11766 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11767 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11768 return false; 11769 } 11770 11771 long callingId = Binder.clearCallingIdentity(); 11772 try { 11773 boolean sendAdded = false; 11774 boolean sendRemoved = false; 11775 // writer 11776 synchronized (mPackages) { 11777 pkgSetting = mSettings.mPackages.get(packageName); 11778 if (pkgSetting == null) { 11779 return false; 11780 } 11781 // Do not allow "android" is being disabled 11782 if ("android".equals(packageName)) { 11783 Slog.w(TAG, "Cannot hide package: android"); 11784 return false; 11785 } 11786 // Only allow protected packages to hide themselves. 11787 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11788 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11789 Slog.w(TAG, "Not hiding protected package: " + packageName); 11790 return false; 11791 } 11792 11793 if (pkgSetting.getHidden(userId) != hidden) { 11794 pkgSetting.setHidden(hidden, userId); 11795 mSettings.writePackageRestrictionsLPr(userId); 11796 if (hidden) { 11797 sendRemoved = true; 11798 } else { 11799 sendAdded = true; 11800 } 11801 } 11802 } 11803 if (sendAdded) { 11804 sendPackageAddedForUser(packageName, pkgSetting, userId); 11805 return true; 11806 } 11807 if (sendRemoved) { 11808 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11809 "hiding pkg"); 11810 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11811 return true; 11812 } 11813 } finally { 11814 Binder.restoreCallingIdentity(callingId); 11815 } 11816 return false; 11817 } 11818 11819 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11820 int userId) { 11821 final PackageRemovedInfo info = new PackageRemovedInfo(); 11822 info.removedPackage = packageName; 11823 info.removedUsers = new int[] {userId}; 11824 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11825 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11826 } 11827 11828 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11829 if (pkgList.length > 0) { 11830 Bundle extras = new Bundle(1); 11831 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11832 11833 sendPackageBroadcast( 11834 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11835 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11836 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11837 new int[] {userId}); 11838 } 11839 } 11840 11841 /** 11842 * Returns true if application is not found or there was an error. Otherwise it returns 11843 * the hidden state of the package for the given user. 11844 */ 11845 @Override 11846 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11848 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11849 true /* requireFullPermission */, false /* checkShell */, 11850 "getApplicationHidden for user " + userId); 11851 PackageSetting pkgSetting; 11852 long callingId = Binder.clearCallingIdentity(); 11853 try { 11854 // writer 11855 synchronized (mPackages) { 11856 pkgSetting = mSettings.mPackages.get(packageName); 11857 if (pkgSetting == null) { 11858 return true; 11859 } 11860 return pkgSetting.getHidden(userId); 11861 } 11862 } finally { 11863 Binder.restoreCallingIdentity(callingId); 11864 } 11865 } 11866 11867 /** 11868 * @hide 11869 */ 11870 @Override 11871 public int installExistingPackageAsUser(String packageName, int userId) { 11872 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11873 null); 11874 PackageSetting pkgSetting; 11875 final int uid = Binder.getCallingUid(); 11876 enforceCrossUserPermission(uid, userId, 11877 true /* requireFullPermission */, true /* checkShell */, 11878 "installExistingPackage for user " + userId); 11879 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11880 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11881 } 11882 11883 long callingId = Binder.clearCallingIdentity(); 11884 try { 11885 boolean installed = false; 11886 11887 // writer 11888 synchronized (mPackages) { 11889 pkgSetting = mSettings.mPackages.get(packageName); 11890 if (pkgSetting == null) { 11891 return PackageManager.INSTALL_FAILED_INVALID_URI; 11892 } 11893 if (!pkgSetting.getInstalled(userId)) { 11894 pkgSetting.setInstalled(true, userId); 11895 pkgSetting.setHidden(false, userId); 11896 mSettings.writePackageRestrictionsLPr(userId); 11897 installed = true; 11898 } 11899 } 11900 11901 if (installed) { 11902 if (pkgSetting.pkg != null) { 11903 synchronized (mInstallLock) { 11904 // We don't need to freeze for a brand new install 11905 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11906 } 11907 } 11908 sendPackageAddedForUser(packageName, pkgSetting, userId); 11909 } 11910 } finally { 11911 Binder.restoreCallingIdentity(callingId); 11912 } 11913 11914 return PackageManager.INSTALL_SUCCEEDED; 11915 } 11916 11917 boolean isUserRestricted(int userId, String restrictionKey) { 11918 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11919 if (restrictions.getBoolean(restrictionKey, false)) { 11920 Log.w(TAG, "User is restricted: " + restrictionKey); 11921 return true; 11922 } 11923 return false; 11924 } 11925 11926 @Override 11927 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11928 int userId) { 11929 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11930 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11931 true /* requireFullPermission */, true /* checkShell */, 11932 "setPackagesSuspended for user " + userId); 11933 11934 if (ArrayUtils.isEmpty(packageNames)) { 11935 return packageNames; 11936 } 11937 11938 // List of package names for whom the suspended state has changed. 11939 List<String> changedPackages = new ArrayList<>(packageNames.length); 11940 // List of package names for whom the suspended state is not set as requested in this 11941 // method. 11942 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11943 long callingId = Binder.clearCallingIdentity(); 11944 try { 11945 for (int i = 0; i < packageNames.length; i++) { 11946 String packageName = packageNames[i]; 11947 boolean changed = false; 11948 final int appId; 11949 synchronized (mPackages) { 11950 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11951 if (pkgSetting == null) { 11952 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11953 + "\". Skipping suspending/un-suspending."); 11954 unactionedPackages.add(packageName); 11955 continue; 11956 } 11957 appId = pkgSetting.appId; 11958 if (pkgSetting.getSuspended(userId) != suspended) { 11959 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11960 unactionedPackages.add(packageName); 11961 continue; 11962 } 11963 pkgSetting.setSuspended(suspended, userId); 11964 mSettings.writePackageRestrictionsLPr(userId); 11965 changed = true; 11966 changedPackages.add(packageName); 11967 } 11968 } 11969 11970 if (changed && suspended) { 11971 killApplication(packageName, UserHandle.getUid(userId, appId), 11972 "suspending package"); 11973 } 11974 } 11975 } finally { 11976 Binder.restoreCallingIdentity(callingId); 11977 } 11978 11979 if (!changedPackages.isEmpty()) { 11980 sendPackagesSuspendedForUser(changedPackages.toArray( 11981 new String[changedPackages.size()]), userId, suspended); 11982 } 11983 11984 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11985 } 11986 11987 @Override 11988 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11989 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11990 true /* requireFullPermission */, false /* checkShell */, 11991 "isPackageSuspendedForUser for user " + userId); 11992 synchronized (mPackages) { 11993 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11994 if (pkgSetting == null) { 11995 throw new IllegalArgumentException("Unknown target package: " + packageName); 11996 } 11997 return pkgSetting.getSuspended(userId); 11998 } 11999 } 12000 12001 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12002 if (isPackageDeviceAdmin(packageName, userId)) { 12003 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12004 + "\": has an active device admin"); 12005 return false; 12006 } 12007 12008 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12009 if (packageName.equals(activeLauncherPackageName)) { 12010 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12011 + "\": contains the active launcher"); 12012 return false; 12013 } 12014 12015 if (packageName.equals(mRequiredInstallerPackage)) { 12016 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12017 + "\": required for package installation"); 12018 return false; 12019 } 12020 12021 if (packageName.equals(mRequiredUninstallerPackage)) { 12022 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12023 + "\": required for package uninstallation"); 12024 return false; 12025 } 12026 12027 if (packageName.equals(mRequiredVerifierPackage)) { 12028 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12029 + "\": required for package verification"); 12030 return false; 12031 } 12032 12033 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12034 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12035 + "\": is the default dialer"); 12036 return false; 12037 } 12038 12039 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12040 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12041 + "\": protected package"); 12042 return false; 12043 } 12044 12045 return true; 12046 } 12047 12048 private String getActiveLauncherPackageName(int userId) { 12049 Intent intent = new Intent(Intent.ACTION_MAIN); 12050 intent.addCategory(Intent.CATEGORY_HOME); 12051 ResolveInfo resolveInfo = resolveIntent( 12052 intent, 12053 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12054 PackageManager.MATCH_DEFAULT_ONLY, 12055 userId); 12056 12057 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12058 } 12059 12060 private String getDefaultDialerPackageName(int userId) { 12061 synchronized (mPackages) { 12062 return mSettings.getDefaultDialerPackageNameLPw(userId); 12063 } 12064 } 12065 12066 @Override 12067 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12068 mContext.enforceCallingOrSelfPermission( 12069 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12070 "Only package verification agents can verify applications"); 12071 12072 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12073 final PackageVerificationResponse response = new PackageVerificationResponse( 12074 verificationCode, Binder.getCallingUid()); 12075 msg.arg1 = id; 12076 msg.obj = response; 12077 mHandler.sendMessage(msg); 12078 } 12079 12080 @Override 12081 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12082 long millisecondsToDelay) { 12083 mContext.enforceCallingOrSelfPermission( 12084 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12085 "Only package verification agents can extend verification timeouts"); 12086 12087 final PackageVerificationState state = mPendingVerification.get(id); 12088 final PackageVerificationResponse response = new PackageVerificationResponse( 12089 verificationCodeAtTimeout, Binder.getCallingUid()); 12090 12091 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12092 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12093 } 12094 if (millisecondsToDelay < 0) { 12095 millisecondsToDelay = 0; 12096 } 12097 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12098 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12099 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12100 } 12101 12102 if ((state != null) && !state.timeoutExtended()) { 12103 state.extendTimeout(); 12104 12105 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12106 msg.arg1 = id; 12107 msg.obj = response; 12108 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12109 } 12110 } 12111 12112 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12113 int verificationCode, UserHandle user) { 12114 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12115 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12116 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12117 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12118 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12119 12120 mContext.sendBroadcastAsUser(intent, user, 12121 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12122 } 12123 12124 private ComponentName matchComponentForVerifier(String packageName, 12125 List<ResolveInfo> receivers) { 12126 ActivityInfo targetReceiver = null; 12127 12128 final int NR = receivers.size(); 12129 for (int i = 0; i < NR; i++) { 12130 final ResolveInfo info = receivers.get(i); 12131 if (info.activityInfo == null) { 12132 continue; 12133 } 12134 12135 if (packageName.equals(info.activityInfo.packageName)) { 12136 targetReceiver = info.activityInfo; 12137 break; 12138 } 12139 } 12140 12141 if (targetReceiver == null) { 12142 return null; 12143 } 12144 12145 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12146 } 12147 12148 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12149 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12150 if (pkgInfo.verifiers.length == 0) { 12151 return null; 12152 } 12153 12154 final int N = pkgInfo.verifiers.length; 12155 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12156 for (int i = 0; i < N; i++) { 12157 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12158 12159 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12160 receivers); 12161 if (comp == null) { 12162 continue; 12163 } 12164 12165 final int verifierUid = getUidForVerifier(verifierInfo); 12166 if (verifierUid == -1) { 12167 continue; 12168 } 12169 12170 if (DEBUG_VERIFY) { 12171 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12172 + " with the correct signature"); 12173 } 12174 sufficientVerifiers.add(comp); 12175 verificationState.addSufficientVerifier(verifierUid); 12176 } 12177 12178 return sufficientVerifiers; 12179 } 12180 12181 private int getUidForVerifier(VerifierInfo verifierInfo) { 12182 synchronized (mPackages) { 12183 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12184 if (pkg == null) { 12185 return -1; 12186 } else if (pkg.mSignatures.length != 1) { 12187 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12188 + " has more than one signature; ignoring"); 12189 return -1; 12190 } 12191 12192 /* 12193 * If the public key of the package's signature does not match 12194 * our expected public key, then this is a different package and 12195 * we should skip. 12196 */ 12197 12198 final byte[] expectedPublicKey; 12199 try { 12200 final Signature verifierSig = pkg.mSignatures[0]; 12201 final PublicKey publicKey = verifierSig.getPublicKey(); 12202 expectedPublicKey = publicKey.getEncoded(); 12203 } catch (CertificateException e) { 12204 return -1; 12205 } 12206 12207 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12208 12209 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12210 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12211 + " does not have the expected public key; ignoring"); 12212 return -1; 12213 } 12214 12215 return pkg.applicationInfo.uid; 12216 } 12217 } 12218 12219 @Override 12220 public void finishPackageInstall(int token, boolean didLaunch) { 12221 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12222 12223 if (DEBUG_INSTALL) { 12224 Slog.v(TAG, "BM finishing package install for " + token); 12225 } 12226 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12227 12228 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12229 mHandler.sendMessage(msg); 12230 } 12231 12232 /** 12233 * Get the verification agent timeout. 12234 * 12235 * @return verification timeout in milliseconds 12236 */ 12237 private long getVerificationTimeout() { 12238 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12239 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12240 DEFAULT_VERIFICATION_TIMEOUT); 12241 } 12242 12243 /** 12244 * Get the default verification agent response code. 12245 * 12246 * @return default verification response code 12247 */ 12248 private int getDefaultVerificationResponse() { 12249 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12250 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12251 DEFAULT_VERIFICATION_RESPONSE); 12252 } 12253 12254 /** 12255 * Check whether or not package verification has been enabled. 12256 * 12257 * @return true if verification should be performed 12258 */ 12259 private boolean isVerificationEnabled(int userId, int installFlags) { 12260 if (!DEFAULT_VERIFY_ENABLE) { 12261 return false; 12262 } 12263 // Ephemeral apps don't get the full verification treatment 12264 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12265 if (DEBUG_EPHEMERAL) { 12266 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12267 } 12268 return false; 12269 } 12270 12271 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12272 12273 // Check if installing from ADB 12274 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12275 // Do not run verification in a test harness environment 12276 if (ActivityManager.isRunningInTestHarness()) { 12277 return false; 12278 } 12279 if (ensureVerifyAppsEnabled) { 12280 return true; 12281 } 12282 // Check if the developer does not want package verification for ADB installs 12283 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12284 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12285 return false; 12286 } 12287 } 12288 12289 if (ensureVerifyAppsEnabled) { 12290 return true; 12291 } 12292 12293 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12294 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12295 } 12296 12297 @Override 12298 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12299 throws RemoteException { 12300 mContext.enforceCallingOrSelfPermission( 12301 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12302 "Only intentfilter verification agents can verify applications"); 12303 12304 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12305 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12306 Binder.getCallingUid(), verificationCode, failedDomains); 12307 msg.arg1 = id; 12308 msg.obj = response; 12309 mHandler.sendMessage(msg); 12310 } 12311 12312 @Override 12313 public int getIntentVerificationStatus(String packageName, int userId) { 12314 synchronized (mPackages) { 12315 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12316 } 12317 } 12318 12319 @Override 12320 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12321 mContext.enforceCallingOrSelfPermission( 12322 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12323 12324 boolean result = false; 12325 synchronized (mPackages) { 12326 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12327 } 12328 if (result) { 12329 scheduleWritePackageRestrictionsLocked(userId); 12330 } 12331 return result; 12332 } 12333 12334 @Override 12335 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12336 String packageName) { 12337 synchronized (mPackages) { 12338 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12339 } 12340 } 12341 12342 @Override 12343 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12344 if (TextUtils.isEmpty(packageName)) { 12345 return ParceledListSlice.emptyList(); 12346 } 12347 synchronized (mPackages) { 12348 PackageParser.Package pkg = mPackages.get(packageName); 12349 if (pkg == null || pkg.activities == null) { 12350 return ParceledListSlice.emptyList(); 12351 } 12352 final int count = pkg.activities.size(); 12353 ArrayList<IntentFilter> result = new ArrayList<>(); 12354 for (int n=0; n<count; n++) { 12355 PackageParser.Activity activity = pkg.activities.get(n); 12356 if (activity.intents != null && activity.intents.size() > 0) { 12357 result.addAll(activity.intents); 12358 } 12359 } 12360 return new ParceledListSlice<>(result); 12361 } 12362 } 12363 12364 @Override 12365 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12366 mContext.enforceCallingOrSelfPermission( 12367 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12368 12369 synchronized (mPackages) { 12370 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12371 if (packageName != null) { 12372 result |= updateIntentVerificationStatus(packageName, 12373 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12374 userId); 12375 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12376 packageName, userId); 12377 } 12378 return result; 12379 } 12380 } 12381 12382 @Override 12383 public String getDefaultBrowserPackageName(int userId) { 12384 synchronized (mPackages) { 12385 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12386 } 12387 } 12388 12389 /** 12390 * Get the "allow unknown sources" setting. 12391 * 12392 * @return the current "allow unknown sources" setting 12393 */ 12394 private int getUnknownSourcesSettings() { 12395 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12396 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12397 -1); 12398 } 12399 12400 @Override 12401 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12402 final int uid = Binder.getCallingUid(); 12403 // writer 12404 synchronized (mPackages) { 12405 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12406 if (targetPackageSetting == null) { 12407 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12408 } 12409 12410 PackageSetting installerPackageSetting; 12411 if (installerPackageName != null) { 12412 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12413 if (installerPackageSetting == null) { 12414 throw new IllegalArgumentException("Unknown installer package: " 12415 + installerPackageName); 12416 } 12417 } else { 12418 installerPackageSetting = null; 12419 } 12420 12421 Signature[] callerSignature; 12422 Object obj = mSettings.getUserIdLPr(uid); 12423 if (obj != null) { 12424 if (obj instanceof SharedUserSetting) { 12425 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12426 } else if (obj instanceof PackageSetting) { 12427 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12428 } else { 12429 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12430 } 12431 } else { 12432 throw new SecurityException("Unknown calling UID: " + uid); 12433 } 12434 12435 // Verify: can't set installerPackageName to a package that is 12436 // not signed with the same cert as the caller. 12437 if (installerPackageSetting != null) { 12438 if (compareSignatures(callerSignature, 12439 installerPackageSetting.signatures.mSignatures) 12440 != PackageManager.SIGNATURE_MATCH) { 12441 throw new SecurityException( 12442 "Caller does not have same cert as new installer package " 12443 + installerPackageName); 12444 } 12445 } 12446 12447 // Verify: if target already has an installer package, it must 12448 // be signed with the same cert as the caller. 12449 if (targetPackageSetting.installerPackageName != null) { 12450 PackageSetting setting = mSettings.mPackages.get( 12451 targetPackageSetting.installerPackageName); 12452 // If the currently set package isn't valid, then it's always 12453 // okay to change it. 12454 if (setting != null) { 12455 if (compareSignatures(callerSignature, 12456 setting.signatures.mSignatures) 12457 != PackageManager.SIGNATURE_MATCH) { 12458 throw new SecurityException( 12459 "Caller does not have same cert as old installer package " 12460 + targetPackageSetting.installerPackageName); 12461 } 12462 } 12463 } 12464 12465 // Okay! 12466 targetPackageSetting.installerPackageName = installerPackageName; 12467 if (installerPackageName != null) { 12468 mSettings.mInstallerPackages.add(installerPackageName); 12469 } 12470 scheduleWriteSettingsLocked(); 12471 } 12472 } 12473 12474 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12475 // Queue up an async operation since the package installation may take a little while. 12476 mHandler.post(new Runnable() { 12477 public void run() { 12478 mHandler.removeCallbacks(this); 12479 // Result object to be returned 12480 PackageInstalledInfo res = new PackageInstalledInfo(); 12481 res.setReturnCode(currentStatus); 12482 res.uid = -1; 12483 res.pkg = null; 12484 res.removedInfo = null; 12485 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12486 args.doPreInstall(res.returnCode); 12487 synchronized (mInstallLock) { 12488 installPackageTracedLI(args, res); 12489 } 12490 args.doPostInstall(res.returnCode, res.uid); 12491 } 12492 12493 // A restore should be performed at this point if (a) the install 12494 // succeeded, (b) the operation is not an update, and (c) the new 12495 // package has not opted out of backup participation. 12496 final boolean update = res.removedInfo != null 12497 && res.removedInfo.removedPackage != null; 12498 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12499 boolean doRestore = !update 12500 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12501 12502 // Set up the post-install work request bookkeeping. This will be used 12503 // and cleaned up by the post-install event handling regardless of whether 12504 // there's a restore pass performed. Token values are >= 1. 12505 int token; 12506 if (mNextInstallToken < 0) mNextInstallToken = 1; 12507 token = mNextInstallToken++; 12508 12509 PostInstallData data = new PostInstallData(args, res); 12510 mRunningInstalls.put(token, data); 12511 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12512 12513 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12514 // Pass responsibility to the Backup Manager. It will perform a 12515 // restore if appropriate, then pass responsibility back to the 12516 // Package Manager to run the post-install observer callbacks 12517 // and broadcasts. 12518 IBackupManager bm = IBackupManager.Stub.asInterface( 12519 ServiceManager.getService(Context.BACKUP_SERVICE)); 12520 if (bm != null) { 12521 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12522 + " to BM for possible restore"); 12523 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12524 try { 12525 // TODO: http://b/22388012 12526 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12527 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12528 } else { 12529 doRestore = false; 12530 } 12531 } catch (RemoteException e) { 12532 // can't happen; the backup manager is local 12533 } catch (Exception e) { 12534 Slog.e(TAG, "Exception trying to enqueue restore", e); 12535 doRestore = false; 12536 } 12537 } else { 12538 Slog.e(TAG, "Backup Manager not found!"); 12539 doRestore = false; 12540 } 12541 } 12542 12543 if (!doRestore) { 12544 // No restore possible, or the Backup Manager was mysteriously not 12545 // available -- just fire the post-install work request directly. 12546 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12547 12548 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12549 12550 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12551 mHandler.sendMessage(msg); 12552 } 12553 } 12554 }); 12555 } 12556 12557 /** 12558 * Callback from PackageSettings whenever an app is first transitioned out of the 12559 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12560 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12561 * here whether the app is the target of an ongoing install, and only send the 12562 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12563 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12564 * handling. 12565 */ 12566 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12567 // Serialize this with the rest of the install-process message chain. In the 12568 // restore-at-install case, this Runnable will necessarily run before the 12569 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12570 // are coherent. In the non-restore case, the app has already completed install 12571 // and been launched through some other means, so it is not in a problematic 12572 // state for observers to see the FIRST_LAUNCH signal. 12573 mHandler.post(new Runnable() { 12574 @Override 12575 public void run() { 12576 for (int i = 0; i < mRunningInstalls.size(); i++) { 12577 final PostInstallData data = mRunningInstalls.valueAt(i); 12578 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12579 continue; 12580 } 12581 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12582 // right package; but is it for the right user? 12583 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12584 if (userId == data.res.newUsers[uIndex]) { 12585 if (DEBUG_BACKUP) { 12586 Slog.i(TAG, "Package " + pkgName 12587 + " being restored so deferring FIRST_LAUNCH"); 12588 } 12589 return; 12590 } 12591 } 12592 } 12593 } 12594 // didn't find it, so not being restored 12595 if (DEBUG_BACKUP) { 12596 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12597 } 12598 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12599 } 12600 }); 12601 } 12602 12603 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12604 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12605 installerPkg, null, userIds); 12606 } 12607 12608 private abstract class HandlerParams { 12609 private static final int MAX_RETRIES = 4; 12610 12611 /** 12612 * Number of times startCopy() has been attempted and had a non-fatal 12613 * error. 12614 */ 12615 private int mRetries = 0; 12616 12617 /** User handle for the user requesting the information or installation. */ 12618 private final UserHandle mUser; 12619 String traceMethod; 12620 int traceCookie; 12621 12622 HandlerParams(UserHandle user) { 12623 mUser = user; 12624 } 12625 12626 UserHandle getUser() { 12627 return mUser; 12628 } 12629 12630 HandlerParams setTraceMethod(String traceMethod) { 12631 this.traceMethod = traceMethod; 12632 return this; 12633 } 12634 12635 HandlerParams setTraceCookie(int traceCookie) { 12636 this.traceCookie = traceCookie; 12637 return this; 12638 } 12639 12640 final boolean startCopy() { 12641 boolean res; 12642 try { 12643 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12644 12645 if (++mRetries > MAX_RETRIES) { 12646 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12647 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12648 handleServiceError(); 12649 return false; 12650 } else { 12651 handleStartCopy(); 12652 res = true; 12653 } 12654 } catch (RemoteException e) { 12655 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12656 mHandler.sendEmptyMessage(MCS_RECONNECT); 12657 res = false; 12658 } 12659 handleReturnCode(); 12660 return res; 12661 } 12662 12663 final void serviceError() { 12664 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12665 handleServiceError(); 12666 handleReturnCode(); 12667 } 12668 12669 abstract void handleStartCopy() throws RemoteException; 12670 abstract void handleServiceError(); 12671 abstract void handleReturnCode(); 12672 } 12673 12674 class MeasureParams extends HandlerParams { 12675 private final PackageStats mStats; 12676 private boolean mSuccess; 12677 12678 private final IPackageStatsObserver mObserver; 12679 12680 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12681 super(new UserHandle(stats.userHandle)); 12682 mObserver = observer; 12683 mStats = stats; 12684 } 12685 12686 @Override 12687 public String toString() { 12688 return "MeasureParams{" 12689 + Integer.toHexString(System.identityHashCode(this)) 12690 + " " + mStats.packageName + "}"; 12691 } 12692 12693 @Override 12694 void handleStartCopy() throws RemoteException { 12695 synchronized (mInstallLock) { 12696 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12697 } 12698 12699 if (mSuccess) { 12700 boolean mounted = false; 12701 try { 12702 final String status = Environment.getExternalStorageState(); 12703 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12704 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12705 } catch (Exception e) { 12706 } 12707 12708 if (mounted) { 12709 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12710 12711 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12712 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12713 12714 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12715 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12716 12717 // Always subtract cache size, since it's a subdirectory 12718 mStats.externalDataSize -= mStats.externalCacheSize; 12719 12720 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12721 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12722 12723 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12724 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12725 } 12726 } 12727 } 12728 12729 @Override 12730 void handleReturnCode() { 12731 if (mObserver != null) { 12732 try { 12733 mObserver.onGetStatsCompleted(mStats, mSuccess); 12734 } catch (RemoteException e) { 12735 Slog.i(TAG, "Observer no longer exists."); 12736 } 12737 } 12738 } 12739 12740 @Override 12741 void handleServiceError() { 12742 Slog.e(TAG, "Could not measure application " + mStats.packageName 12743 + " external storage"); 12744 } 12745 } 12746 12747 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12748 throws RemoteException { 12749 long result = 0; 12750 for (File path : paths) { 12751 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12752 } 12753 return result; 12754 } 12755 12756 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12757 for (File path : paths) { 12758 try { 12759 mcs.clearDirectory(path.getAbsolutePath()); 12760 } catch (RemoteException e) { 12761 } 12762 } 12763 } 12764 12765 static class OriginInfo { 12766 /** 12767 * Location where install is coming from, before it has been 12768 * copied/renamed into place. This could be a single monolithic APK 12769 * file, or a cluster directory. This location may be untrusted. 12770 */ 12771 final File file; 12772 final String cid; 12773 12774 /** 12775 * Flag indicating that {@link #file} or {@link #cid} has already been 12776 * staged, meaning downstream users don't need to defensively copy the 12777 * contents. 12778 */ 12779 final boolean staged; 12780 12781 /** 12782 * Flag indicating that {@link #file} or {@link #cid} is an already 12783 * installed app that is being moved. 12784 */ 12785 final boolean existing; 12786 12787 final String resolvedPath; 12788 final File resolvedFile; 12789 12790 static OriginInfo fromNothing() { 12791 return new OriginInfo(null, null, false, false); 12792 } 12793 12794 static OriginInfo fromUntrustedFile(File file) { 12795 return new OriginInfo(file, null, false, false); 12796 } 12797 12798 static OriginInfo fromExistingFile(File file) { 12799 return new OriginInfo(file, null, false, true); 12800 } 12801 12802 static OriginInfo fromStagedFile(File file) { 12803 return new OriginInfo(file, null, true, false); 12804 } 12805 12806 static OriginInfo fromStagedContainer(String cid) { 12807 return new OriginInfo(null, cid, true, false); 12808 } 12809 12810 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12811 this.file = file; 12812 this.cid = cid; 12813 this.staged = staged; 12814 this.existing = existing; 12815 12816 if (cid != null) { 12817 resolvedPath = PackageHelper.getSdDir(cid); 12818 resolvedFile = new File(resolvedPath); 12819 } else if (file != null) { 12820 resolvedPath = file.getAbsolutePath(); 12821 resolvedFile = file; 12822 } else { 12823 resolvedPath = null; 12824 resolvedFile = null; 12825 } 12826 } 12827 } 12828 12829 static class MoveInfo { 12830 final int moveId; 12831 final String fromUuid; 12832 final String toUuid; 12833 final String packageName; 12834 final String dataAppName; 12835 final int appId; 12836 final String seinfo; 12837 final int targetSdkVersion; 12838 12839 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12840 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12841 this.moveId = moveId; 12842 this.fromUuid = fromUuid; 12843 this.toUuid = toUuid; 12844 this.packageName = packageName; 12845 this.dataAppName = dataAppName; 12846 this.appId = appId; 12847 this.seinfo = seinfo; 12848 this.targetSdkVersion = targetSdkVersion; 12849 } 12850 } 12851 12852 static class VerificationInfo { 12853 /** A constant used to indicate that a uid value is not present. */ 12854 public static final int NO_UID = -1; 12855 12856 /** URI referencing where the package was downloaded from. */ 12857 final Uri originatingUri; 12858 12859 /** HTTP referrer URI associated with the originatingURI. */ 12860 final Uri referrer; 12861 12862 /** UID of the application that the install request originated from. */ 12863 final int originatingUid; 12864 12865 /** UID of application requesting the install */ 12866 final int installerUid; 12867 12868 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12869 this.originatingUri = originatingUri; 12870 this.referrer = referrer; 12871 this.originatingUid = originatingUid; 12872 this.installerUid = installerUid; 12873 } 12874 } 12875 12876 class InstallParams extends HandlerParams { 12877 final OriginInfo origin; 12878 final MoveInfo move; 12879 final IPackageInstallObserver2 observer; 12880 int installFlags; 12881 final String installerPackageName; 12882 final String volumeUuid; 12883 private InstallArgs mArgs; 12884 private int mRet; 12885 final String packageAbiOverride; 12886 final String[] grantedRuntimePermissions; 12887 final VerificationInfo verificationInfo; 12888 final Certificate[][] certificates; 12889 12890 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12891 int installFlags, String installerPackageName, String volumeUuid, 12892 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12893 String[] grantedPermissions, Certificate[][] certificates) { 12894 super(user); 12895 this.origin = origin; 12896 this.move = move; 12897 this.observer = observer; 12898 this.installFlags = installFlags; 12899 this.installerPackageName = installerPackageName; 12900 this.volumeUuid = volumeUuid; 12901 this.verificationInfo = verificationInfo; 12902 this.packageAbiOverride = packageAbiOverride; 12903 this.grantedRuntimePermissions = grantedPermissions; 12904 this.certificates = certificates; 12905 } 12906 12907 @Override 12908 public String toString() { 12909 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12910 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12911 } 12912 12913 private int installLocationPolicy(PackageInfoLite pkgLite) { 12914 String packageName = pkgLite.packageName; 12915 int installLocation = pkgLite.installLocation; 12916 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12917 // reader 12918 synchronized (mPackages) { 12919 // Currently installed package which the new package is attempting to replace or 12920 // null if no such package is installed. 12921 PackageParser.Package installedPkg = mPackages.get(packageName); 12922 // Package which currently owns the data which the new package will own if installed. 12923 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12924 // will be null whereas dataOwnerPkg will contain information about the package 12925 // which was uninstalled while keeping its data. 12926 PackageParser.Package dataOwnerPkg = installedPkg; 12927 if (dataOwnerPkg == null) { 12928 PackageSetting ps = mSettings.mPackages.get(packageName); 12929 if (ps != null) { 12930 dataOwnerPkg = ps.pkg; 12931 } 12932 } 12933 12934 if (dataOwnerPkg != null) { 12935 // If installed, the package will get access to data left on the device by its 12936 // predecessor. As a security measure, this is permited only if this is not a 12937 // version downgrade or if the predecessor package is marked as debuggable and 12938 // a downgrade is explicitly requested. 12939 // 12940 // On debuggable platform builds, downgrades are permitted even for 12941 // non-debuggable packages to make testing easier. Debuggable platform builds do 12942 // not offer security guarantees and thus it's OK to disable some security 12943 // mechanisms to make debugging/testing easier on those builds. However, even on 12944 // debuggable builds downgrades of packages are permitted only if requested via 12945 // installFlags. This is because we aim to keep the behavior of debuggable 12946 // platform builds as close as possible to the behavior of non-debuggable 12947 // platform builds. 12948 final boolean downgradeRequested = 12949 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12950 final boolean packageDebuggable = 12951 (dataOwnerPkg.applicationInfo.flags 12952 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12953 final boolean downgradePermitted = 12954 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12955 if (!downgradePermitted) { 12956 try { 12957 checkDowngrade(dataOwnerPkg, pkgLite); 12958 } catch (PackageManagerException e) { 12959 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12960 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12961 } 12962 } 12963 } 12964 12965 if (installedPkg != null) { 12966 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12967 // Check for updated system application. 12968 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12969 if (onSd) { 12970 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12971 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12972 } 12973 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12974 } else { 12975 if (onSd) { 12976 // Install flag overrides everything. 12977 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12978 } 12979 // If current upgrade specifies particular preference 12980 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12981 // Application explicitly specified internal. 12982 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12983 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12984 // App explictly prefers external. Let policy decide 12985 } else { 12986 // Prefer previous location 12987 if (isExternal(installedPkg)) { 12988 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12989 } 12990 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12991 } 12992 } 12993 } else { 12994 // Invalid install. Return error code 12995 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12996 } 12997 } 12998 } 12999 // All the special cases have been taken care of. 13000 // Return result based on recommended install location. 13001 if (onSd) { 13002 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13003 } 13004 return pkgLite.recommendedInstallLocation; 13005 } 13006 13007 /* 13008 * Invoke remote method to get package information and install 13009 * location values. Override install location based on default 13010 * policy if needed and then create install arguments based 13011 * on the install location. 13012 */ 13013 public void handleStartCopy() throws RemoteException { 13014 int ret = PackageManager.INSTALL_SUCCEEDED; 13015 13016 // If we're already staged, we've firmly committed to an install location 13017 if (origin.staged) { 13018 if (origin.file != null) { 13019 installFlags |= PackageManager.INSTALL_INTERNAL; 13020 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13021 } else if (origin.cid != null) { 13022 installFlags |= PackageManager.INSTALL_EXTERNAL; 13023 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13024 } else { 13025 throw new IllegalStateException("Invalid stage location"); 13026 } 13027 } 13028 13029 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13030 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13031 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13032 PackageInfoLite pkgLite = null; 13033 13034 if (onInt && onSd) { 13035 // Check if both bits are set. 13036 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13037 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13038 } else if (onSd && ephemeral) { 13039 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13040 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13041 } else { 13042 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13043 packageAbiOverride); 13044 13045 if (DEBUG_EPHEMERAL && ephemeral) { 13046 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13047 } 13048 13049 /* 13050 * If we have too little free space, try to free cache 13051 * before giving up. 13052 */ 13053 if (!origin.staged && pkgLite.recommendedInstallLocation 13054 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13055 // TODO: focus freeing disk space on the target device 13056 final StorageManager storage = StorageManager.from(mContext); 13057 final long lowThreshold = storage.getStorageLowBytes( 13058 Environment.getDataDirectory()); 13059 13060 final long sizeBytes = mContainerService.calculateInstalledSize( 13061 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13062 13063 try { 13064 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 13065 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13066 installFlags, packageAbiOverride); 13067 } catch (InstallerException e) { 13068 Slog.w(TAG, "Failed to free cache", e); 13069 } 13070 13071 /* 13072 * The cache free must have deleted the file we 13073 * downloaded to install. 13074 * 13075 * TODO: fix the "freeCache" call to not delete 13076 * the file we care about. 13077 */ 13078 if (pkgLite.recommendedInstallLocation 13079 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13080 pkgLite.recommendedInstallLocation 13081 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13082 } 13083 } 13084 } 13085 13086 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13087 int loc = pkgLite.recommendedInstallLocation; 13088 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13089 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13090 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13091 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13092 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13093 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13094 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13095 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13096 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13097 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13098 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13099 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13100 } else { 13101 // Override with defaults if needed. 13102 loc = installLocationPolicy(pkgLite); 13103 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13104 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13105 } else if (!onSd && !onInt) { 13106 // Override install location with flags 13107 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13108 // Set the flag to install on external media. 13109 installFlags |= PackageManager.INSTALL_EXTERNAL; 13110 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13111 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13112 if (DEBUG_EPHEMERAL) { 13113 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13114 } 13115 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13116 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13117 |PackageManager.INSTALL_INTERNAL); 13118 } else { 13119 // Make sure the flag for installing on external 13120 // media is unset 13121 installFlags |= PackageManager.INSTALL_INTERNAL; 13122 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13123 } 13124 } 13125 } 13126 } 13127 13128 final InstallArgs args = createInstallArgs(this); 13129 mArgs = args; 13130 13131 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13132 // TODO: http://b/22976637 13133 // Apps installed for "all" users use the device owner to verify the app 13134 UserHandle verifierUser = getUser(); 13135 if (verifierUser == UserHandle.ALL) { 13136 verifierUser = UserHandle.SYSTEM; 13137 } 13138 13139 /* 13140 * Determine if we have any installed package verifiers. If we 13141 * do, then we'll defer to them to verify the packages. 13142 */ 13143 final int requiredUid = mRequiredVerifierPackage == null ? -1 13144 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13145 verifierUser.getIdentifier()); 13146 if (!origin.existing && requiredUid != -1 13147 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13148 final Intent verification = new Intent( 13149 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13150 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13151 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13152 PACKAGE_MIME_TYPE); 13153 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13154 13155 // Query all live verifiers based on current user state 13156 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13157 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13158 13159 if (DEBUG_VERIFY) { 13160 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13161 + verification.toString() + " with " + pkgLite.verifiers.length 13162 + " optional verifiers"); 13163 } 13164 13165 final int verificationId = mPendingVerificationToken++; 13166 13167 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13168 13169 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13170 installerPackageName); 13171 13172 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13173 installFlags); 13174 13175 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13176 pkgLite.packageName); 13177 13178 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13179 pkgLite.versionCode); 13180 13181 if (verificationInfo != null) { 13182 if (verificationInfo.originatingUri != null) { 13183 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13184 verificationInfo.originatingUri); 13185 } 13186 if (verificationInfo.referrer != null) { 13187 verification.putExtra(Intent.EXTRA_REFERRER, 13188 verificationInfo.referrer); 13189 } 13190 if (verificationInfo.originatingUid >= 0) { 13191 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13192 verificationInfo.originatingUid); 13193 } 13194 if (verificationInfo.installerUid >= 0) { 13195 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13196 verificationInfo.installerUid); 13197 } 13198 } 13199 13200 final PackageVerificationState verificationState = new PackageVerificationState( 13201 requiredUid, args); 13202 13203 mPendingVerification.append(verificationId, verificationState); 13204 13205 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13206 receivers, verificationState); 13207 13208 /* 13209 * If any sufficient verifiers were listed in the package 13210 * manifest, attempt to ask them. 13211 */ 13212 if (sufficientVerifiers != null) { 13213 final int N = sufficientVerifiers.size(); 13214 if (N == 0) { 13215 Slog.i(TAG, "Additional verifiers required, but none installed."); 13216 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13217 } else { 13218 for (int i = 0; i < N; i++) { 13219 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13220 13221 final Intent sufficientIntent = new Intent(verification); 13222 sufficientIntent.setComponent(verifierComponent); 13223 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13224 } 13225 } 13226 } 13227 13228 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13229 mRequiredVerifierPackage, receivers); 13230 if (ret == PackageManager.INSTALL_SUCCEEDED 13231 && mRequiredVerifierPackage != null) { 13232 Trace.asyncTraceBegin( 13233 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13234 /* 13235 * Send the intent to the required verification agent, 13236 * but only start the verification timeout after the 13237 * target BroadcastReceivers have run. 13238 */ 13239 verification.setComponent(requiredVerifierComponent); 13240 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13241 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13242 new BroadcastReceiver() { 13243 @Override 13244 public void onReceive(Context context, Intent intent) { 13245 final Message msg = mHandler 13246 .obtainMessage(CHECK_PENDING_VERIFICATION); 13247 msg.arg1 = verificationId; 13248 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13249 } 13250 }, null, 0, null, null); 13251 13252 /* 13253 * We don't want the copy to proceed until verification 13254 * succeeds, so null out this field. 13255 */ 13256 mArgs = null; 13257 } 13258 } else { 13259 /* 13260 * No package verification is enabled, so immediately start 13261 * the remote call to initiate copy using temporary file. 13262 */ 13263 ret = args.copyApk(mContainerService, true); 13264 } 13265 } 13266 13267 mRet = ret; 13268 } 13269 13270 @Override 13271 void handleReturnCode() { 13272 // If mArgs is null, then MCS couldn't be reached. When it 13273 // reconnects, it will try again to install. At that point, this 13274 // will succeed. 13275 if (mArgs != null) { 13276 processPendingInstall(mArgs, mRet); 13277 } 13278 } 13279 13280 @Override 13281 void handleServiceError() { 13282 mArgs = createInstallArgs(this); 13283 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13284 } 13285 13286 public boolean isForwardLocked() { 13287 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13288 } 13289 } 13290 13291 /** 13292 * Used during creation of InstallArgs 13293 * 13294 * @param installFlags package installation flags 13295 * @return true if should be installed on external storage 13296 */ 13297 private static boolean installOnExternalAsec(int installFlags) { 13298 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13299 return false; 13300 } 13301 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13302 return true; 13303 } 13304 return false; 13305 } 13306 13307 /** 13308 * Used during creation of InstallArgs 13309 * 13310 * @param installFlags package installation flags 13311 * @return true if should be installed as forward locked 13312 */ 13313 private static boolean installForwardLocked(int installFlags) { 13314 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13315 } 13316 13317 private InstallArgs createInstallArgs(InstallParams params) { 13318 if (params.move != null) { 13319 return new MoveInstallArgs(params); 13320 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13321 return new AsecInstallArgs(params); 13322 } else { 13323 return new FileInstallArgs(params); 13324 } 13325 } 13326 13327 /** 13328 * Create args that describe an existing installed package. Typically used 13329 * when cleaning up old installs, or used as a move source. 13330 */ 13331 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13332 String resourcePath, String[] instructionSets) { 13333 final boolean isInAsec; 13334 if (installOnExternalAsec(installFlags)) { 13335 /* Apps on SD card are always in ASEC containers. */ 13336 isInAsec = true; 13337 } else if (installForwardLocked(installFlags) 13338 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13339 /* 13340 * Forward-locked apps are only in ASEC containers if they're the 13341 * new style 13342 */ 13343 isInAsec = true; 13344 } else { 13345 isInAsec = false; 13346 } 13347 13348 if (isInAsec) { 13349 return new AsecInstallArgs(codePath, instructionSets, 13350 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13351 } else { 13352 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13353 } 13354 } 13355 13356 static abstract class InstallArgs { 13357 /** @see InstallParams#origin */ 13358 final OriginInfo origin; 13359 /** @see InstallParams#move */ 13360 final MoveInfo move; 13361 13362 final IPackageInstallObserver2 observer; 13363 // Always refers to PackageManager flags only 13364 final int installFlags; 13365 final String installerPackageName; 13366 final String volumeUuid; 13367 final UserHandle user; 13368 final String abiOverride; 13369 final String[] installGrantPermissions; 13370 /** If non-null, drop an async trace when the install completes */ 13371 final String traceMethod; 13372 final int traceCookie; 13373 final Certificate[][] certificates; 13374 13375 // The list of instruction sets supported by this app. This is currently 13376 // only used during the rmdex() phase to clean up resources. We can get rid of this 13377 // if we move dex files under the common app path. 13378 /* nullable */ String[] instructionSets; 13379 13380 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13381 int installFlags, String installerPackageName, String volumeUuid, 13382 UserHandle user, String[] instructionSets, 13383 String abiOverride, String[] installGrantPermissions, 13384 String traceMethod, int traceCookie, Certificate[][] certificates) { 13385 this.origin = origin; 13386 this.move = move; 13387 this.installFlags = installFlags; 13388 this.observer = observer; 13389 this.installerPackageName = installerPackageName; 13390 this.volumeUuid = volumeUuid; 13391 this.user = user; 13392 this.instructionSets = instructionSets; 13393 this.abiOverride = abiOverride; 13394 this.installGrantPermissions = installGrantPermissions; 13395 this.traceMethod = traceMethod; 13396 this.traceCookie = traceCookie; 13397 this.certificates = certificates; 13398 } 13399 13400 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13401 abstract int doPreInstall(int status); 13402 13403 /** 13404 * Rename package into final resting place. All paths on the given 13405 * scanned package should be updated to reflect the rename. 13406 */ 13407 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13408 abstract int doPostInstall(int status, int uid); 13409 13410 /** @see PackageSettingBase#codePathString */ 13411 abstract String getCodePath(); 13412 /** @see PackageSettingBase#resourcePathString */ 13413 abstract String getResourcePath(); 13414 13415 // Need installer lock especially for dex file removal. 13416 abstract void cleanUpResourcesLI(); 13417 abstract boolean doPostDeleteLI(boolean delete); 13418 13419 /** 13420 * Called before the source arguments are copied. This is used mostly 13421 * for MoveParams when it needs to read the source file to put it in the 13422 * destination. 13423 */ 13424 int doPreCopy() { 13425 return PackageManager.INSTALL_SUCCEEDED; 13426 } 13427 13428 /** 13429 * Called after the source arguments are copied. This is used mostly for 13430 * MoveParams when it needs to read the source file to put it in the 13431 * destination. 13432 */ 13433 int doPostCopy(int uid) { 13434 return PackageManager.INSTALL_SUCCEEDED; 13435 } 13436 13437 protected boolean isFwdLocked() { 13438 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13439 } 13440 13441 protected boolean isExternalAsec() { 13442 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13443 } 13444 13445 protected boolean isEphemeral() { 13446 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13447 } 13448 13449 UserHandle getUser() { 13450 return user; 13451 } 13452 } 13453 13454 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13455 if (!allCodePaths.isEmpty()) { 13456 if (instructionSets == null) { 13457 throw new IllegalStateException("instructionSet == null"); 13458 } 13459 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13460 for (String codePath : allCodePaths) { 13461 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13462 try { 13463 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13464 } catch (InstallerException ignored) { 13465 } 13466 } 13467 } 13468 } 13469 } 13470 13471 /** 13472 * Logic to handle installation of non-ASEC applications, including copying 13473 * and renaming logic. 13474 */ 13475 class FileInstallArgs extends InstallArgs { 13476 private File codeFile; 13477 private File resourceFile; 13478 13479 // Example topology: 13480 // /data/app/com.example/base.apk 13481 // /data/app/com.example/split_foo.apk 13482 // /data/app/com.example/lib/arm/libfoo.so 13483 // /data/app/com.example/lib/arm64/libfoo.so 13484 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13485 13486 /** New install */ 13487 FileInstallArgs(InstallParams params) { 13488 super(params.origin, params.move, params.observer, params.installFlags, 13489 params.installerPackageName, params.volumeUuid, 13490 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13491 params.grantedRuntimePermissions, 13492 params.traceMethod, params.traceCookie, params.certificates); 13493 if (isFwdLocked()) { 13494 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13495 } 13496 } 13497 13498 /** Existing install */ 13499 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13500 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13501 null, null, null, 0, null /*certificates*/); 13502 this.codeFile = (codePath != null) ? new File(codePath) : null; 13503 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13504 } 13505 13506 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13508 try { 13509 return doCopyApk(imcs, temp); 13510 } finally { 13511 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13512 } 13513 } 13514 13515 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13516 if (origin.staged) { 13517 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13518 codeFile = origin.file; 13519 resourceFile = origin.file; 13520 return PackageManager.INSTALL_SUCCEEDED; 13521 } 13522 13523 try { 13524 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13525 final File tempDir = 13526 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13527 codeFile = tempDir; 13528 resourceFile = tempDir; 13529 } catch (IOException e) { 13530 Slog.w(TAG, "Failed to create copy file: " + e); 13531 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13532 } 13533 13534 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13535 @Override 13536 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13537 if (!FileUtils.isValidExtFilename(name)) { 13538 throw new IllegalArgumentException("Invalid filename: " + name); 13539 } 13540 try { 13541 final File file = new File(codeFile, name); 13542 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13543 O_RDWR | O_CREAT, 0644); 13544 Os.chmod(file.getAbsolutePath(), 0644); 13545 return new ParcelFileDescriptor(fd); 13546 } catch (ErrnoException e) { 13547 throw new RemoteException("Failed to open: " + e.getMessage()); 13548 } 13549 } 13550 }; 13551 13552 int ret = PackageManager.INSTALL_SUCCEEDED; 13553 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13554 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13555 Slog.e(TAG, "Failed to copy package"); 13556 return ret; 13557 } 13558 13559 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13560 NativeLibraryHelper.Handle handle = null; 13561 try { 13562 handle = NativeLibraryHelper.Handle.create(codeFile); 13563 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13564 abiOverride); 13565 } catch (IOException e) { 13566 Slog.e(TAG, "Copying native libraries failed", e); 13567 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13568 } finally { 13569 IoUtils.closeQuietly(handle); 13570 } 13571 13572 return ret; 13573 } 13574 13575 int doPreInstall(int status) { 13576 if (status != PackageManager.INSTALL_SUCCEEDED) { 13577 cleanUp(); 13578 } 13579 return status; 13580 } 13581 13582 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13583 if (status != PackageManager.INSTALL_SUCCEEDED) { 13584 cleanUp(); 13585 return false; 13586 } 13587 13588 final File targetDir = codeFile.getParentFile(); 13589 final File beforeCodeFile = codeFile; 13590 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13591 13592 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13593 try { 13594 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13595 } catch (ErrnoException e) { 13596 Slog.w(TAG, "Failed to rename", e); 13597 return false; 13598 } 13599 13600 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13601 Slog.w(TAG, "Failed to restorecon"); 13602 return false; 13603 } 13604 13605 // Reflect the rename internally 13606 codeFile = afterCodeFile; 13607 resourceFile = afterCodeFile; 13608 13609 // Reflect the rename in scanned details 13610 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13611 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13612 afterCodeFile, pkg.baseCodePath)); 13613 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13614 afterCodeFile, pkg.splitCodePaths)); 13615 13616 // Reflect the rename in app info 13617 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13618 pkg.setApplicationInfoCodePath(pkg.codePath); 13619 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13620 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13621 pkg.setApplicationInfoResourcePath(pkg.codePath); 13622 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13623 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13624 13625 return true; 13626 } 13627 13628 int doPostInstall(int status, int uid) { 13629 if (status != PackageManager.INSTALL_SUCCEEDED) { 13630 cleanUp(); 13631 } 13632 return status; 13633 } 13634 13635 @Override 13636 String getCodePath() { 13637 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13638 } 13639 13640 @Override 13641 String getResourcePath() { 13642 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13643 } 13644 13645 private boolean cleanUp() { 13646 if (codeFile == null || !codeFile.exists()) { 13647 return false; 13648 } 13649 13650 removeCodePathLI(codeFile); 13651 13652 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13653 resourceFile.delete(); 13654 } 13655 13656 return true; 13657 } 13658 13659 void cleanUpResourcesLI() { 13660 // Try enumerating all code paths before deleting 13661 List<String> allCodePaths = Collections.EMPTY_LIST; 13662 if (codeFile != null && codeFile.exists()) { 13663 try { 13664 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13665 allCodePaths = pkg.getAllCodePaths(); 13666 } catch (PackageParserException e) { 13667 // Ignored; we tried our best 13668 } 13669 } 13670 13671 cleanUp(); 13672 removeDexFiles(allCodePaths, instructionSets); 13673 } 13674 13675 boolean doPostDeleteLI(boolean delete) { 13676 // XXX err, shouldn't we respect the delete flag? 13677 cleanUpResourcesLI(); 13678 return true; 13679 } 13680 } 13681 13682 private boolean isAsecExternal(String cid) { 13683 final String asecPath = PackageHelper.getSdFilesystem(cid); 13684 return !asecPath.startsWith(mAsecInternalPath); 13685 } 13686 13687 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13688 PackageManagerException { 13689 if (copyRet < 0) { 13690 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13691 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13692 throw new PackageManagerException(copyRet, message); 13693 } 13694 } 13695 } 13696 13697 /** 13698 * Extract the MountService "container ID" from the full code path of an 13699 * .apk. 13700 */ 13701 static String cidFromCodePath(String fullCodePath) { 13702 int eidx = fullCodePath.lastIndexOf("/"); 13703 String subStr1 = fullCodePath.substring(0, eidx); 13704 int sidx = subStr1.lastIndexOf("/"); 13705 return subStr1.substring(sidx+1, eidx); 13706 } 13707 13708 /** 13709 * Logic to handle installation of ASEC applications, including copying and 13710 * renaming logic. 13711 */ 13712 class AsecInstallArgs extends InstallArgs { 13713 static final String RES_FILE_NAME = "pkg.apk"; 13714 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13715 13716 String cid; 13717 String packagePath; 13718 String resourcePath; 13719 13720 /** New install */ 13721 AsecInstallArgs(InstallParams params) { 13722 super(params.origin, params.move, params.observer, params.installFlags, 13723 params.installerPackageName, params.volumeUuid, 13724 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13725 params.grantedRuntimePermissions, 13726 params.traceMethod, params.traceCookie, params.certificates); 13727 } 13728 13729 /** Existing install */ 13730 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13731 boolean isExternal, boolean isForwardLocked) { 13732 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13733 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13734 instructionSets, null, null, null, 0, null /*certificates*/); 13735 // Hackily pretend we're still looking at a full code path 13736 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13737 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13738 } 13739 13740 // Extract cid from fullCodePath 13741 int eidx = fullCodePath.lastIndexOf("/"); 13742 String subStr1 = fullCodePath.substring(0, eidx); 13743 int sidx = subStr1.lastIndexOf("/"); 13744 cid = subStr1.substring(sidx+1, eidx); 13745 setMountPath(subStr1); 13746 } 13747 13748 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13749 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13750 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13751 instructionSets, null, null, null, 0, null /*certificates*/); 13752 this.cid = cid; 13753 setMountPath(PackageHelper.getSdDir(cid)); 13754 } 13755 13756 void createCopyFile() { 13757 cid = mInstallerService.allocateExternalStageCidLegacy(); 13758 } 13759 13760 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13761 if (origin.staged && origin.cid != null) { 13762 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13763 cid = origin.cid; 13764 setMountPath(PackageHelper.getSdDir(cid)); 13765 return PackageManager.INSTALL_SUCCEEDED; 13766 } 13767 13768 if (temp) { 13769 createCopyFile(); 13770 } else { 13771 /* 13772 * Pre-emptively destroy the container since it's destroyed if 13773 * copying fails due to it existing anyway. 13774 */ 13775 PackageHelper.destroySdDir(cid); 13776 } 13777 13778 final String newMountPath = imcs.copyPackageToContainer( 13779 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13780 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13781 13782 if (newMountPath != null) { 13783 setMountPath(newMountPath); 13784 return PackageManager.INSTALL_SUCCEEDED; 13785 } else { 13786 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13787 } 13788 } 13789 13790 @Override 13791 String getCodePath() { 13792 return packagePath; 13793 } 13794 13795 @Override 13796 String getResourcePath() { 13797 return resourcePath; 13798 } 13799 13800 int doPreInstall(int status) { 13801 if (status != PackageManager.INSTALL_SUCCEEDED) { 13802 // Destroy container 13803 PackageHelper.destroySdDir(cid); 13804 } else { 13805 boolean mounted = PackageHelper.isContainerMounted(cid); 13806 if (!mounted) { 13807 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13808 Process.SYSTEM_UID); 13809 if (newMountPath != null) { 13810 setMountPath(newMountPath); 13811 } else { 13812 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13813 } 13814 } 13815 } 13816 return status; 13817 } 13818 13819 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13820 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13821 String newMountPath = null; 13822 if (PackageHelper.isContainerMounted(cid)) { 13823 // Unmount the container 13824 if (!PackageHelper.unMountSdDir(cid)) { 13825 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13826 return false; 13827 } 13828 } 13829 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13830 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13831 " which might be stale. Will try to clean up."); 13832 // Clean up the stale container and proceed to recreate. 13833 if (!PackageHelper.destroySdDir(newCacheId)) { 13834 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13835 return false; 13836 } 13837 // Successfully cleaned up stale container. Try to rename again. 13838 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13839 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13840 + " inspite of cleaning it up."); 13841 return false; 13842 } 13843 } 13844 if (!PackageHelper.isContainerMounted(newCacheId)) { 13845 Slog.w(TAG, "Mounting container " + newCacheId); 13846 newMountPath = PackageHelper.mountSdDir(newCacheId, 13847 getEncryptKey(), Process.SYSTEM_UID); 13848 } else { 13849 newMountPath = PackageHelper.getSdDir(newCacheId); 13850 } 13851 if (newMountPath == null) { 13852 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13853 return false; 13854 } 13855 Log.i(TAG, "Succesfully renamed " + cid + 13856 " to " + newCacheId + 13857 " at new path: " + newMountPath); 13858 cid = newCacheId; 13859 13860 final File beforeCodeFile = new File(packagePath); 13861 setMountPath(newMountPath); 13862 final File afterCodeFile = new File(packagePath); 13863 13864 // Reflect the rename in scanned details 13865 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13866 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13867 afterCodeFile, pkg.baseCodePath)); 13868 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13869 afterCodeFile, pkg.splitCodePaths)); 13870 13871 // Reflect the rename in app info 13872 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13873 pkg.setApplicationInfoCodePath(pkg.codePath); 13874 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13875 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13876 pkg.setApplicationInfoResourcePath(pkg.codePath); 13877 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13878 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13879 13880 return true; 13881 } 13882 13883 private void setMountPath(String mountPath) { 13884 final File mountFile = new File(mountPath); 13885 13886 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13887 if (monolithicFile.exists()) { 13888 packagePath = monolithicFile.getAbsolutePath(); 13889 if (isFwdLocked()) { 13890 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13891 } else { 13892 resourcePath = packagePath; 13893 } 13894 } else { 13895 packagePath = mountFile.getAbsolutePath(); 13896 resourcePath = packagePath; 13897 } 13898 } 13899 13900 int doPostInstall(int status, int uid) { 13901 if (status != PackageManager.INSTALL_SUCCEEDED) { 13902 cleanUp(); 13903 } else { 13904 final int groupOwner; 13905 final String protectedFile; 13906 if (isFwdLocked()) { 13907 groupOwner = UserHandle.getSharedAppGid(uid); 13908 protectedFile = RES_FILE_NAME; 13909 } else { 13910 groupOwner = -1; 13911 protectedFile = null; 13912 } 13913 13914 if (uid < Process.FIRST_APPLICATION_UID 13915 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13916 Slog.e(TAG, "Failed to finalize " + cid); 13917 PackageHelper.destroySdDir(cid); 13918 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13919 } 13920 13921 boolean mounted = PackageHelper.isContainerMounted(cid); 13922 if (!mounted) { 13923 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13924 } 13925 } 13926 return status; 13927 } 13928 13929 private void cleanUp() { 13930 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13931 13932 // Destroy secure container 13933 PackageHelper.destroySdDir(cid); 13934 } 13935 13936 private List<String> getAllCodePaths() { 13937 final File codeFile = new File(getCodePath()); 13938 if (codeFile != null && codeFile.exists()) { 13939 try { 13940 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13941 return pkg.getAllCodePaths(); 13942 } catch (PackageParserException e) { 13943 // Ignored; we tried our best 13944 } 13945 } 13946 return Collections.EMPTY_LIST; 13947 } 13948 13949 void cleanUpResourcesLI() { 13950 // Enumerate all code paths before deleting 13951 cleanUpResourcesLI(getAllCodePaths()); 13952 } 13953 13954 private void cleanUpResourcesLI(List<String> allCodePaths) { 13955 cleanUp(); 13956 removeDexFiles(allCodePaths, instructionSets); 13957 } 13958 13959 String getPackageName() { 13960 return getAsecPackageName(cid); 13961 } 13962 13963 boolean doPostDeleteLI(boolean delete) { 13964 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13965 final List<String> allCodePaths = getAllCodePaths(); 13966 boolean mounted = PackageHelper.isContainerMounted(cid); 13967 if (mounted) { 13968 // Unmount first 13969 if (PackageHelper.unMountSdDir(cid)) { 13970 mounted = false; 13971 } 13972 } 13973 if (!mounted && delete) { 13974 cleanUpResourcesLI(allCodePaths); 13975 } 13976 return !mounted; 13977 } 13978 13979 @Override 13980 int doPreCopy() { 13981 if (isFwdLocked()) { 13982 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13983 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13984 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13985 } 13986 } 13987 13988 return PackageManager.INSTALL_SUCCEEDED; 13989 } 13990 13991 @Override 13992 int doPostCopy(int uid) { 13993 if (isFwdLocked()) { 13994 if (uid < Process.FIRST_APPLICATION_UID 13995 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13996 RES_FILE_NAME)) { 13997 Slog.e(TAG, "Failed to finalize " + cid); 13998 PackageHelper.destroySdDir(cid); 13999 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14000 } 14001 } 14002 14003 return PackageManager.INSTALL_SUCCEEDED; 14004 } 14005 } 14006 14007 /** 14008 * Logic to handle movement of existing installed applications. 14009 */ 14010 class MoveInstallArgs extends InstallArgs { 14011 private File codeFile; 14012 private File resourceFile; 14013 14014 /** New install */ 14015 MoveInstallArgs(InstallParams params) { 14016 super(params.origin, params.move, params.observer, params.installFlags, 14017 params.installerPackageName, params.volumeUuid, 14018 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14019 params.grantedRuntimePermissions, 14020 params.traceMethod, params.traceCookie, params.certificates); 14021 } 14022 14023 int copyApk(IMediaContainerService imcs, boolean temp) { 14024 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14025 + move.fromUuid + " to " + move.toUuid); 14026 synchronized (mInstaller) { 14027 try { 14028 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14029 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14030 } catch (InstallerException e) { 14031 Slog.w(TAG, "Failed to move app", e); 14032 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14033 } 14034 } 14035 14036 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14037 resourceFile = codeFile; 14038 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14039 14040 return PackageManager.INSTALL_SUCCEEDED; 14041 } 14042 14043 int doPreInstall(int status) { 14044 if (status != PackageManager.INSTALL_SUCCEEDED) { 14045 cleanUp(move.toUuid); 14046 } 14047 return status; 14048 } 14049 14050 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14051 if (status != PackageManager.INSTALL_SUCCEEDED) { 14052 cleanUp(move.toUuid); 14053 return false; 14054 } 14055 14056 // Reflect the move in app info 14057 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14058 pkg.setApplicationInfoCodePath(pkg.codePath); 14059 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14060 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14061 pkg.setApplicationInfoResourcePath(pkg.codePath); 14062 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14063 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14064 14065 return true; 14066 } 14067 14068 int doPostInstall(int status, int uid) { 14069 if (status == PackageManager.INSTALL_SUCCEEDED) { 14070 cleanUp(move.fromUuid); 14071 } else { 14072 cleanUp(move.toUuid); 14073 } 14074 return status; 14075 } 14076 14077 @Override 14078 String getCodePath() { 14079 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14080 } 14081 14082 @Override 14083 String getResourcePath() { 14084 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14085 } 14086 14087 private boolean cleanUp(String volumeUuid) { 14088 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14089 move.dataAppName); 14090 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14091 final int[] userIds = sUserManager.getUserIds(); 14092 synchronized (mInstallLock) { 14093 // Clean up both app data and code 14094 // All package moves are frozen until finished 14095 for (int userId : userIds) { 14096 try { 14097 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14098 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14099 } catch (InstallerException e) { 14100 Slog.w(TAG, String.valueOf(e)); 14101 } 14102 } 14103 removeCodePathLI(codeFile); 14104 } 14105 return true; 14106 } 14107 14108 void cleanUpResourcesLI() { 14109 throw new UnsupportedOperationException(); 14110 } 14111 14112 boolean doPostDeleteLI(boolean delete) { 14113 throw new UnsupportedOperationException(); 14114 } 14115 } 14116 14117 static String getAsecPackageName(String packageCid) { 14118 int idx = packageCid.lastIndexOf("-"); 14119 if (idx == -1) { 14120 return packageCid; 14121 } 14122 return packageCid.substring(0, idx); 14123 } 14124 14125 // Utility method used to create code paths based on package name and available index. 14126 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14127 String idxStr = ""; 14128 int idx = 1; 14129 // Fall back to default value of idx=1 if prefix is not 14130 // part of oldCodePath 14131 if (oldCodePath != null) { 14132 String subStr = oldCodePath; 14133 // Drop the suffix right away 14134 if (suffix != null && subStr.endsWith(suffix)) { 14135 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14136 } 14137 // If oldCodePath already contains prefix find out the 14138 // ending index to either increment or decrement. 14139 int sidx = subStr.lastIndexOf(prefix); 14140 if (sidx != -1) { 14141 subStr = subStr.substring(sidx + prefix.length()); 14142 if (subStr != null) { 14143 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14144 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14145 } 14146 try { 14147 idx = Integer.parseInt(subStr); 14148 if (idx <= 1) { 14149 idx++; 14150 } else { 14151 idx--; 14152 } 14153 } catch(NumberFormatException e) { 14154 } 14155 } 14156 } 14157 } 14158 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14159 return prefix + idxStr; 14160 } 14161 14162 private File getNextCodePath(File targetDir, String packageName) { 14163 int suffix = 1; 14164 File result; 14165 do { 14166 result = new File(targetDir, packageName + "-" + suffix); 14167 suffix++; 14168 } while (result.exists()); 14169 return result; 14170 } 14171 14172 // Utility method that returns the relative package path with respect 14173 // to the installation directory. Like say for /data/data/com.test-1.apk 14174 // string com.test-1 is returned. 14175 static String deriveCodePathName(String codePath) { 14176 if (codePath == null) { 14177 return null; 14178 } 14179 final File codeFile = new File(codePath); 14180 final String name = codeFile.getName(); 14181 if (codeFile.isDirectory()) { 14182 return name; 14183 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14184 final int lastDot = name.lastIndexOf('.'); 14185 return name.substring(0, lastDot); 14186 } else { 14187 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14188 return null; 14189 } 14190 } 14191 14192 static class PackageInstalledInfo { 14193 String name; 14194 int uid; 14195 // The set of users that originally had this package installed. 14196 int[] origUsers; 14197 // The set of users that now have this package installed. 14198 int[] newUsers; 14199 PackageParser.Package pkg; 14200 int returnCode; 14201 String returnMsg; 14202 PackageRemovedInfo removedInfo; 14203 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14204 14205 public void setError(int code, String msg) { 14206 setReturnCode(code); 14207 setReturnMessage(msg); 14208 Slog.w(TAG, msg); 14209 } 14210 14211 public void setError(String msg, PackageParserException e) { 14212 setReturnCode(e.error); 14213 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14214 Slog.w(TAG, msg, e); 14215 } 14216 14217 public void setError(String msg, PackageManagerException e) { 14218 returnCode = e.error; 14219 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14220 Slog.w(TAG, msg, e); 14221 } 14222 14223 public void setReturnCode(int returnCode) { 14224 this.returnCode = returnCode; 14225 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14226 for (int i = 0; i < childCount; i++) { 14227 addedChildPackages.valueAt(i).returnCode = returnCode; 14228 } 14229 } 14230 14231 private void setReturnMessage(String returnMsg) { 14232 this.returnMsg = returnMsg; 14233 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14234 for (int i = 0; i < childCount; i++) { 14235 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14236 } 14237 } 14238 14239 // In some error cases we want to convey more info back to the observer 14240 String origPackage; 14241 String origPermission; 14242 } 14243 14244 /* 14245 * Install a non-existing package. 14246 */ 14247 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14248 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14249 PackageInstalledInfo res) { 14250 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14251 14252 // Remember this for later, in case we need to rollback this install 14253 String pkgName = pkg.packageName; 14254 14255 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14256 14257 synchronized(mPackages) { 14258 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14259 // A package with the same name is already installed, though 14260 // it has been renamed to an older name. The package we 14261 // are trying to install should be installed as an update to 14262 // the existing one, but that has not been requested, so bail. 14263 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14264 + " without first uninstalling package running as " 14265 + mSettings.mRenamedPackages.get(pkgName)); 14266 return; 14267 } 14268 if (mPackages.containsKey(pkgName)) { 14269 // Don't allow installation over an existing package with the same name. 14270 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14271 + " without first uninstalling."); 14272 return; 14273 } 14274 } 14275 14276 try { 14277 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14278 System.currentTimeMillis(), user); 14279 14280 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14281 14282 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14283 prepareAppDataAfterInstallLIF(newPackage); 14284 14285 } else { 14286 // Remove package from internal structures, but keep around any 14287 // data that might have already existed 14288 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14289 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14290 } 14291 } catch (PackageManagerException e) { 14292 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14293 } 14294 14295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14296 } 14297 14298 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14299 // Can't rotate keys during boot or if sharedUser. 14300 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14301 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14302 return false; 14303 } 14304 // app is using upgradeKeySets; make sure all are valid 14305 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14306 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14307 for (int i = 0; i < upgradeKeySets.length; i++) { 14308 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14309 Slog.wtf(TAG, "Package " 14310 + (oldPs.name != null ? oldPs.name : "<null>") 14311 + " contains upgrade-key-set reference to unknown key-set: " 14312 + upgradeKeySets[i] 14313 + " reverting to signatures check."); 14314 return false; 14315 } 14316 } 14317 return true; 14318 } 14319 14320 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14321 // Upgrade keysets are being used. Determine if new package has a superset of the 14322 // required keys. 14323 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14324 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14325 for (int i = 0; i < upgradeKeySets.length; i++) { 14326 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14327 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14328 return true; 14329 } 14330 } 14331 return false; 14332 } 14333 14334 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14335 try (DigestInputStream digestStream = 14336 new DigestInputStream(new FileInputStream(file), digest)) { 14337 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14338 } 14339 } 14340 14341 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14342 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14343 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14344 14345 final PackageParser.Package oldPackage; 14346 final String pkgName = pkg.packageName; 14347 final int[] allUsers; 14348 final int[] installedUsers; 14349 14350 synchronized(mPackages) { 14351 oldPackage = mPackages.get(pkgName); 14352 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14353 14354 // don't allow upgrade to target a release SDK from a pre-release SDK 14355 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14356 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14357 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14358 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14359 if (oldTargetsPreRelease 14360 && !newTargetsPreRelease 14361 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14362 Slog.w(TAG, "Can't install package targeting released sdk"); 14363 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14364 return; 14365 } 14366 14367 // don't allow an upgrade from full to ephemeral 14368 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14369 if (isEphemeral && !oldIsEphemeral) { 14370 // can't downgrade from full to ephemeral 14371 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14372 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14373 return; 14374 } 14375 14376 // verify signatures are valid 14377 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14378 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14379 if (!checkUpgradeKeySetLP(ps, pkg)) { 14380 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14381 "New package not signed by keys specified by upgrade-keysets: " 14382 + pkgName); 14383 return; 14384 } 14385 } else { 14386 // default to original signature matching 14387 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14388 != PackageManager.SIGNATURE_MATCH) { 14389 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14390 "New package has a different signature: " + pkgName); 14391 return; 14392 } 14393 } 14394 14395 // don't allow a system upgrade unless the upgrade hash matches 14396 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14397 byte[] digestBytes = null; 14398 try { 14399 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14400 updateDigest(digest, new File(pkg.baseCodePath)); 14401 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14402 for (String path : pkg.splitCodePaths) { 14403 updateDigest(digest, new File(path)); 14404 } 14405 } 14406 digestBytes = digest.digest(); 14407 } catch (NoSuchAlgorithmException | IOException e) { 14408 res.setError(INSTALL_FAILED_INVALID_APK, 14409 "Could not compute hash: " + pkgName); 14410 return; 14411 } 14412 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14413 res.setError(INSTALL_FAILED_INVALID_APK, 14414 "New package fails restrict-update check: " + pkgName); 14415 return; 14416 } 14417 // retain upgrade restriction 14418 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14419 } 14420 14421 // Check for shared user id changes 14422 String invalidPackageName = 14423 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14424 if (invalidPackageName != null) { 14425 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14426 "Package " + invalidPackageName + " tried to change user " 14427 + oldPackage.mSharedUserId); 14428 return; 14429 } 14430 14431 // In case of rollback, remember per-user/profile install state 14432 allUsers = sUserManager.getUserIds(); 14433 installedUsers = ps.queryInstalledUsers(allUsers, true); 14434 } 14435 14436 // Update what is removed 14437 res.removedInfo = new PackageRemovedInfo(); 14438 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14439 res.removedInfo.removedPackage = oldPackage.packageName; 14440 res.removedInfo.isUpdate = true; 14441 res.removedInfo.origUsers = installedUsers; 14442 final int childCount = (oldPackage.childPackages != null) 14443 ? oldPackage.childPackages.size() : 0; 14444 for (int i = 0; i < childCount; i++) { 14445 boolean childPackageUpdated = false; 14446 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14447 if (res.addedChildPackages != null) { 14448 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14449 if (childRes != null) { 14450 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14451 childRes.removedInfo.removedPackage = childPkg.packageName; 14452 childRes.removedInfo.isUpdate = true; 14453 childPackageUpdated = true; 14454 } 14455 } 14456 if (!childPackageUpdated) { 14457 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14458 childRemovedRes.removedPackage = childPkg.packageName; 14459 childRemovedRes.isUpdate = false; 14460 childRemovedRes.dataRemoved = true; 14461 synchronized (mPackages) { 14462 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14463 if (childPs != null) { 14464 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14465 } 14466 } 14467 if (res.removedInfo.removedChildPackages == null) { 14468 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14469 } 14470 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14471 } 14472 } 14473 14474 boolean sysPkg = (isSystemApp(oldPackage)); 14475 if (sysPkg) { 14476 // Set the system/privileged flags as needed 14477 final boolean privileged = 14478 (oldPackage.applicationInfo.privateFlags 14479 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14480 final int systemPolicyFlags = policyFlags 14481 | PackageParser.PARSE_IS_SYSTEM 14482 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14483 14484 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14485 user, allUsers, installerPackageName, res); 14486 } else { 14487 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14488 user, allUsers, installerPackageName, res); 14489 } 14490 } 14491 14492 public List<String> getPreviousCodePaths(String packageName) { 14493 final PackageSetting ps = mSettings.mPackages.get(packageName); 14494 final List<String> result = new ArrayList<String>(); 14495 if (ps != null && ps.oldCodePaths != null) { 14496 result.addAll(ps.oldCodePaths); 14497 } 14498 return result; 14499 } 14500 14501 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14502 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14503 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14504 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14505 + deletedPackage); 14506 14507 String pkgName = deletedPackage.packageName; 14508 boolean deletedPkg = true; 14509 boolean addedPkg = false; 14510 boolean updatedSettings = false; 14511 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14512 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14513 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14514 14515 final long origUpdateTime = (pkg.mExtras != null) 14516 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14517 14518 // First delete the existing package while retaining the data directory 14519 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14520 res.removedInfo, true, pkg)) { 14521 // If the existing package wasn't successfully deleted 14522 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14523 deletedPkg = false; 14524 } else { 14525 // Successfully deleted the old package; proceed with replace. 14526 14527 // If deleted package lived in a container, give users a chance to 14528 // relinquish resources before killing. 14529 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14530 if (DEBUG_INSTALL) { 14531 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14532 } 14533 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14534 final ArrayList<String> pkgList = new ArrayList<String>(1); 14535 pkgList.add(deletedPackage.applicationInfo.packageName); 14536 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14537 } 14538 14539 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14540 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14541 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14542 14543 try { 14544 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14545 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14546 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14547 14548 // Update the in-memory copy of the previous code paths. 14549 PackageSetting ps = mSettings.mPackages.get(pkgName); 14550 if (!killApp) { 14551 if (ps.oldCodePaths == null) { 14552 ps.oldCodePaths = new ArraySet<>(); 14553 } 14554 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14555 if (deletedPackage.splitCodePaths != null) { 14556 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14557 } 14558 } else { 14559 ps.oldCodePaths = null; 14560 } 14561 if (ps.childPackageNames != null) { 14562 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14563 final String childPkgName = ps.childPackageNames.get(i); 14564 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14565 childPs.oldCodePaths = ps.oldCodePaths; 14566 } 14567 } 14568 prepareAppDataAfterInstallLIF(newPackage); 14569 addedPkg = true; 14570 } catch (PackageManagerException e) { 14571 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14572 } 14573 } 14574 14575 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14576 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14577 14578 // Revert all internal state mutations and added folders for the failed install 14579 if (addedPkg) { 14580 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14581 res.removedInfo, true, null); 14582 } 14583 14584 // Restore the old package 14585 if (deletedPkg) { 14586 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14587 File restoreFile = new File(deletedPackage.codePath); 14588 // Parse old package 14589 boolean oldExternal = isExternal(deletedPackage); 14590 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14591 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14592 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14593 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14594 try { 14595 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14596 null); 14597 } catch (PackageManagerException e) { 14598 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14599 + e.getMessage()); 14600 return; 14601 } 14602 14603 synchronized (mPackages) { 14604 // Ensure the installer package name up to date 14605 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14606 14607 // Update permissions for restored package 14608 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14609 14610 mSettings.writeLPr(); 14611 } 14612 14613 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14614 } 14615 } else { 14616 synchronized (mPackages) { 14617 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14618 if (ps != null) { 14619 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14620 if (res.removedInfo.removedChildPackages != null) { 14621 final int childCount = res.removedInfo.removedChildPackages.size(); 14622 // Iterate in reverse as we may modify the collection 14623 for (int i = childCount - 1; i >= 0; i--) { 14624 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14625 if (res.addedChildPackages.containsKey(childPackageName)) { 14626 res.removedInfo.removedChildPackages.removeAt(i); 14627 } else { 14628 PackageRemovedInfo childInfo = res.removedInfo 14629 .removedChildPackages.valueAt(i); 14630 childInfo.removedForAllUsers = mPackages.get( 14631 childInfo.removedPackage) == null; 14632 } 14633 } 14634 } 14635 } 14636 } 14637 } 14638 } 14639 14640 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14641 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14642 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14643 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14644 + ", old=" + deletedPackage); 14645 14646 final boolean disabledSystem; 14647 14648 // Remove existing system package 14649 removePackageLI(deletedPackage, true); 14650 14651 synchronized (mPackages) { 14652 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14653 } 14654 if (!disabledSystem) { 14655 // We didn't need to disable the .apk as a current system package, 14656 // which means we are replacing another update that is already 14657 // installed. We need to make sure to delete the older one's .apk. 14658 res.removedInfo.args = createInstallArgsForExisting(0, 14659 deletedPackage.applicationInfo.getCodePath(), 14660 deletedPackage.applicationInfo.getResourcePath(), 14661 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14662 } else { 14663 res.removedInfo.args = null; 14664 } 14665 14666 // Successfully disabled the old package. Now proceed with re-installation 14667 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14668 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14669 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14670 14671 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14672 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14673 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14674 14675 PackageParser.Package newPackage = null; 14676 try { 14677 // Add the package to the internal data structures 14678 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14679 14680 // Set the update and install times 14681 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14682 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14683 System.currentTimeMillis()); 14684 14685 // Update the package dynamic state if succeeded 14686 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14687 // Now that the install succeeded make sure we remove data 14688 // directories for any child package the update removed. 14689 final int deletedChildCount = (deletedPackage.childPackages != null) 14690 ? deletedPackage.childPackages.size() : 0; 14691 final int newChildCount = (newPackage.childPackages != null) 14692 ? newPackage.childPackages.size() : 0; 14693 for (int i = 0; i < deletedChildCount; i++) { 14694 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14695 boolean childPackageDeleted = true; 14696 for (int j = 0; j < newChildCount; j++) { 14697 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14698 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14699 childPackageDeleted = false; 14700 break; 14701 } 14702 } 14703 if (childPackageDeleted) { 14704 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14705 deletedChildPkg.packageName); 14706 if (ps != null && res.removedInfo.removedChildPackages != null) { 14707 PackageRemovedInfo removedChildRes = res.removedInfo 14708 .removedChildPackages.get(deletedChildPkg.packageName); 14709 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14710 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14711 } 14712 } 14713 } 14714 14715 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14716 prepareAppDataAfterInstallLIF(newPackage); 14717 } 14718 } catch (PackageManagerException e) { 14719 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14720 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14721 } 14722 14723 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14724 // Re installation failed. Restore old information 14725 // Remove new pkg information 14726 if (newPackage != null) { 14727 removeInstalledPackageLI(newPackage, true); 14728 } 14729 // Add back the old system package 14730 try { 14731 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14732 } catch (PackageManagerException e) { 14733 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14734 } 14735 14736 synchronized (mPackages) { 14737 if (disabledSystem) { 14738 enableSystemPackageLPw(deletedPackage); 14739 } 14740 14741 // Ensure the installer package name up to date 14742 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14743 14744 // Update permissions for restored package 14745 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14746 14747 mSettings.writeLPr(); 14748 } 14749 14750 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14751 + " after failed upgrade"); 14752 } 14753 } 14754 14755 /** 14756 * Checks whether the parent or any of the child packages have a change shared 14757 * user. For a package to be a valid update the shred users of the parent and 14758 * the children should match. We may later support changing child shared users. 14759 * @param oldPkg The updated package. 14760 * @param newPkg The update package. 14761 * @return The shared user that change between the versions. 14762 */ 14763 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14764 PackageParser.Package newPkg) { 14765 // Check parent shared user 14766 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14767 return newPkg.packageName; 14768 } 14769 // Check child shared users 14770 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14771 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14772 for (int i = 0; i < newChildCount; i++) { 14773 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14774 // If this child was present, did it have the same shared user? 14775 for (int j = 0; j < oldChildCount; j++) { 14776 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14777 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14778 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14779 return newChildPkg.packageName; 14780 } 14781 } 14782 } 14783 return null; 14784 } 14785 14786 private void removeNativeBinariesLI(PackageSetting ps) { 14787 // Remove the lib path for the parent package 14788 if (ps != null) { 14789 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14790 // Remove the lib path for the child packages 14791 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14792 for (int i = 0; i < childCount; i++) { 14793 PackageSetting childPs = null; 14794 synchronized (mPackages) { 14795 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14796 } 14797 if (childPs != null) { 14798 NativeLibraryHelper.removeNativeBinariesLI(childPs 14799 .legacyNativeLibraryPathString); 14800 } 14801 } 14802 } 14803 } 14804 14805 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14806 // Enable the parent package 14807 mSettings.enableSystemPackageLPw(pkg.packageName); 14808 // Enable the child packages 14809 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14810 for (int i = 0; i < childCount; i++) { 14811 PackageParser.Package childPkg = pkg.childPackages.get(i); 14812 mSettings.enableSystemPackageLPw(childPkg.packageName); 14813 } 14814 } 14815 14816 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14817 PackageParser.Package newPkg) { 14818 // Disable the parent package (parent always replaced) 14819 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14820 // Disable the child packages 14821 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14822 for (int i = 0; i < childCount; i++) { 14823 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14824 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14825 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14826 } 14827 return disabled; 14828 } 14829 14830 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14831 String installerPackageName) { 14832 // Enable the parent package 14833 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14834 // Enable the child packages 14835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14836 for (int i = 0; i < childCount; i++) { 14837 PackageParser.Package childPkg = pkg.childPackages.get(i); 14838 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14839 } 14840 } 14841 14842 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14843 // Collect all used permissions in the UID 14844 ArraySet<String> usedPermissions = new ArraySet<>(); 14845 final int packageCount = su.packages.size(); 14846 for (int i = 0; i < packageCount; i++) { 14847 PackageSetting ps = su.packages.valueAt(i); 14848 if (ps.pkg == null) { 14849 continue; 14850 } 14851 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14852 for (int j = 0; j < requestedPermCount; j++) { 14853 String permission = ps.pkg.requestedPermissions.get(j); 14854 BasePermission bp = mSettings.mPermissions.get(permission); 14855 if (bp != null) { 14856 usedPermissions.add(permission); 14857 } 14858 } 14859 } 14860 14861 PermissionsState permissionsState = su.getPermissionsState(); 14862 // Prune install permissions 14863 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14864 final int installPermCount = installPermStates.size(); 14865 for (int i = installPermCount - 1; i >= 0; i--) { 14866 PermissionState permissionState = installPermStates.get(i); 14867 if (!usedPermissions.contains(permissionState.getName())) { 14868 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14869 if (bp != null) { 14870 permissionsState.revokeInstallPermission(bp); 14871 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14872 PackageManager.MASK_PERMISSION_FLAGS, 0); 14873 } 14874 } 14875 } 14876 14877 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14878 14879 // Prune runtime permissions 14880 for (int userId : allUserIds) { 14881 List<PermissionState> runtimePermStates = permissionsState 14882 .getRuntimePermissionStates(userId); 14883 final int runtimePermCount = runtimePermStates.size(); 14884 for (int i = runtimePermCount - 1; i >= 0; i--) { 14885 PermissionState permissionState = runtimePermStates.get(i); 14886 if (!usedPermissions.contains(permissionState.getName())) { 14887 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14888 if (bp != null) { 14889 permissionsState.revokeRuntimePermission(bp, userId); 14890 permissionsState.updatePermissionFlags(bp, userId, 14891 PackageManager.MASK_PERMISSION_FLAGS, 0); 14892 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14893 runtimePermissionChangedUserIds, userId); 14894 } 14895 } 14896 } 14897 } 14898 14899 return runtimePermissionChangedUserIds; 14900 } 14901 14902 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14903 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14904 // Update the parent package setting 14905 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14906 res, user); 14907 // Update the child packages setting 14908 final int childCount = (newPackage.childPackages != null) 14909 ? newPackage.childPackages.size() : 0; 14910 for (int i = 0; i < childCount; i++) { 14911 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14912 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14913 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14914 childRes.origUsers, childRes, user); 14915 } 14916 } 14917 14918 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14919 String installerPackageName, int[] allUsers, int[] installedForUsers, 14920 PackageInstalledInfo res, UserHandle user) { 14921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14922 14923 String pkgName = newPackage.packageName; 14924 synchronized (mPackages) { 14925 //write settings. the installStatus will be incomplete at this stage. 14926 //note that the new package setting would have already been 14927 //added to mPackages. It hasn't been persisted yet. 14928 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14929 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14930 mSettings.writeLPr(); 14931 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14932 } 14933 14934 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14935 synchronized (mPackages) { 14936 updatePermissionsLPw(newPackage.packageName, newPackage, 14937 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14938 ? UPDATE_PERMISSIONS_ALL : 0)); 14939 // For system-bundled packages, we assume that installing an upgraded version 14940 // of the package implies that the user actually wants to run that new code, 14941 // so we enable the package. 14942 PackageSetting ps = mSettings.mPackages.get(pkgName); 14943 final int userId = user.getIdentifier(); 14944 if (ps != null) { 14945 if (isSystemApp(newPackage)) { 14946 if (DEBUG_INSTALL) { 14947 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14948 } 14949 // Enable system package for requested users 14950 if (res.origUsers != null) { 14951 for (int origUserId : res.origUsers) { 14952 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14953 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14954 origUserId, installerPackageName); 14955 } 14956 } 14957 } 14958 // Also convey the prior install/uninstall state 14959 if (allUsers != null && installedForUsers != null) { 14960 for (int currentUserId : allUsers) { 14961 final boolean installed = ArrayUtils.contains( 14962 installedForUsers, currentUserId); 14963 if (DEBUG_INSTALL) { 14964 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14965 } 14966 ps.setInstalled(installed, currentUserId); 14967 } 14968 // these install state changes will be persisted in the 14969 // upcoming call to mSettings.writeLPr(). 14970 } 14971 } 14972 // It's implied that when a user requests installation, they want the app to be 14973 // installed and enabled. 14974 if (userId != UserHandle.USER_ALL) { 14975 ps.setInstalled(true, userId); 14976 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14977 } 14978 } 14979 res.name = pkgName; 14980 res.uid = newPackage.applicationInfo.uid; 14981 res.pkg = newPackage; 14982 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14983 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14984 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14985 //to update install status 14986 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14987 mSettings.writeLPr(); 14988 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14989 } 14990 14991 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14992 } 14993 14994 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14995 try { 14996 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14997 installPackageLI(args, res); 14998 } finally { 14999 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15000 } 15001 } 15002 15003 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15004 final int installFlags = args.installFlags; 15005 final String installerPackageName = args.installerPackageName; 15006 final String volumeUuid = args.volumeUuid; 15007 final File tmpPackageFile = new File(args.getCodePath()); 15008 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15009 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15010 || (args.volumeUuid != null)); 15011 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15012 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15013 boolean replace = false; 15014 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15015 if (args.move != null) { 15016 // moving a complete application; perform an initial scan on the new install location 15017 scanFlags |= SCAN_INITIAL; 15018 } 15019 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15020 scanFlags |= SCAN_DONT_KILL_APP; 15021 } 15022 15023 // Result object to be returned 15024 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15025 15026 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15027 15028 // Sanity check 15029 if (ephemeral && (forwardLocked || onExternal)) { 15030 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15031 + " external=" + onExternal); 15032 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15033 return; 15034 } 15035 15036 // Retrieve PackageSettings and parse package 15037 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15038 | PackageParser.PARSE_ENFORCE_CODE 15039 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15040 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15041 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15042 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15043 PackageParser pp = new PackageParser(); 15044 pp.setSeparateProcesses(mSeparateProcesses); 15045 pp.setDisplayMetrics(mMetrics); 15046 15047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15048 final PackageParser.Package pkg; 15049 try { 15050 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15051 } catch (PackageParserException e) { 15052 res.setError("Failed parse during installPackageLI", e); 15053 return; 15054 } finally { 15055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15056 } 15057 15058 // If we are installing a clustered package add results for the children 15059 if (pkg.childPackages != null) { 15060 synchronized (mPackages) { 15061 final int childCount = pkg.childPackages.size(); 15062 for (int i = 0; i < childCount; i++) { 15063 PackageParser.Package childPkg = pkg.childPackages.get(i); 15064 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15065 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15066 childRes.pkg = childPkg; 15067 childRes.name = childPkg.packageName; 15068 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15069 if (childPs != null) { 15070 childRes.origUsers = childPs.queryInstalledUsers( 15071 sUserManager.getUserIds(), true); 15072 } 15073 if ((mPackages.containsKey(childPkg.packageName))) { 15074 childRes.removedInfo = new PackageRemovedInfo(); 15075 childRes.removedInfo.removedPackage = childPkg.packageName; 15076 } 15077 if (res.addedChildPackages == null) { 15078 res.addedChildPackages = new ArrayMap<>(); 15079 } 15080 res.addedChildPackages.put(childPkg.packageName, childRes); 15081 } 15082 } 15083 } 15084 15085 // If package doesn't declare API override, mark that we have an install 15086 // time CPU ABI override. 15087 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15088 pkg.cpuAbiOverride = args.abiOverride; 15089 } 15090 15091 String pkgName = res.name = pkg.packageName; 15092 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15093 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15094 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15095 return; 15096 } 15097 } 15098 15099 try { 15100 // either use what we've been given or parse directly from the APK 15101 if (args.certificates != null) { 15102 try { 15103 PackageParser.populateCertificates(pkg, args.certificates); 15104 } catch (PackageParserException e) { 15105 // there was something wrong with the certificates we were given; 15106 // try to pull them from the APK 15107 PackageParser.collectCertificates(pkg, parseFlags); 15108 } 15109 } else { 15110 PackageParser.collectCertificates(pkg, parseFlags); 15111 } 15112 } catch (PackageParserException e) { 15113 res.setError("Failed collect during installPackageLI", e); 15114 return; 15115 } 15116 15117 // Get rid of all references to package scan path via parser. 15118 pp = null; 15119 String oldCodePath = null; 15120 boolean systemApp = false; 15121 synchronized (mPackages) { 15122 // Check if installing already existing package 15123 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15124 String oldName = mSettings.mRenamedPackages.get(pkgName); 15125 if (pkg.mOriginalPackages != null 15126 && pkg.mOriginalPackages.contains(oldName) 15127 && mPackages.containsKey(oldName)) { 15128 // This package is derived from an original package, 15129 // and this device has been updating from that original 15130 // name. We must continue using the original name, so 15131 // rename the new package here. 15132 pkg.setPackageName(oldName); 15133 pkgName = pkg.packageName; 15134 replace = true; 15135 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15136 + oldName + " pkgName=" + pkgName); 15137 } else if (mPackages.containsKey(pkgName)) { 15138 // This package, under its official name, already exists 15139 // on the device; we should replace it. 15140 replace = true; 15141 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15142 } 15143 15144 // Child packages are installed through the parent package 15145 if (pkg.parentPackage != null) { 15146 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15147 "Package " + pkg.packageName + " is child of package " 15148 + pkg.parentPackage.parentPackage + ". Child packages " 15149 + "can be updated only through the parent package."); 15150 return; 15151 } 15152 15153 if (replace) { 15154 // Prevent apps opting out from runtime permissions 15155 PackageParser.Package oldPackage = mPackages.get(pkgName); 15156 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15157 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15158 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15159 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15160 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15161 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15162 + " doesn't support runtime permissions but the old" 15163 + " target SDK " + oldTargetSdk + " does."); 15164 return; 15165 } 15166 15167 // Prevent installing of child packages 15168 if (oldPackage.parentPackage != null) { 15169 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15170 "Package " + pkg.packageName + " is child of package " 15171 + oldPackage.parentPackage + ". Child packages " 15172 + "can be updated only through the parent package."); 15173 return; 15174 } 15175 } 15176 } 15177 15178 PackageSetting ps = mSettings.mPackages.get(pkgName); 15179 if (ps != null) { 15180 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15181 15182 // Quick sanity check that we're signed correctly if updating; 15183 // we'll check this again later when scanning, but we want to 15184 // bail early here before tripping over redefined permissions. 15185 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15186 if (!checkUpgradeKeySetLP(ps, pkg)) { 15187 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15188 + pkg.packageName + " upgrade keys do not match the " 15189 + "previously installed version"); 15190 return; 15191 } 15192 } else { 15193 try { 15194 verifySignaturesLP(ps, pkg); 15195 } catch (PackageManagerException e) { 15196 res.setError(e.error, e.getMessage()); 15197 return; 15198 } 15199 } 15200 15201 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15202 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15203 systemApp = (ps.pkg.applicationInfo.flags & 15204 ApplicationInfo.FLAG_SYSTEM) != 0; 15205 } 15206 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15207 } 15208 15209 // Check whether the newly-scanned package wants to define an already-defined perm 15210 int N = pkg.permissions.size(); 15211 for (int i = N-1; i >= 0; i--) { 15212 PackageParser.Permission perm = pkg.permissions.get(i); 15213 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15214 if (bp != null) { 15215 // If the defining package is signed with our cert, it's okay. This 15216 // also includes the "updating the same package" case, of course. 15217 // "updating same package" could also involve key-rotation. 15218 final boolean sigsOk; 15219 if (bp.sourcePackage.equals(pkg.packageName) 15220 && (bp.packageSetting instanceof PackageSetting) 15221 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15222 scanFlags))) { 15223 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15224 } else { 15225 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15226 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15227 } 15228 if (!sigsOk) { 15229 // If the owning package is the system itself, we log but allow 15230 // install to proceed; we fail the install on all other permission 15231 // redefinitions. 15232 if (!bp.sourcePackage.equals("android")) { 15233 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15234 + pkg.packageName + " attempting to redeclare permission " 15235 + perm.info.name + " already owned by " + bp.sourcePackage); 15236 res.origPermission = perm.info.name; 15237 res.origPackage = bp.sourcePackage; 15238 return; 15239 } else { 15240 Slog.w(TAG, "Package " + pkg.packageName 15241 + " attempting to redeclare system permission " 15242 + perm.info.name + "; ignoring new declaration"); 15243 pkg.permissions.remove(i); 15244 } 15245 } 15246 } 15247 } 15248 } 15249 15250 if (systemApp) { 15251 if (onExternal) { 15252 // Abort update; system app can't be replaced with app on sdcard 15253 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15254 "Cannot install updates to system apps on sdcard"); 15255 return; 15256 } else if (ephemeral) { 15257 // Abort update; system app can't be replaced with an ephemeral app 15258 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15259 "Cannot update a system app with an ephemeral app"); 15260 return; 15261 } 15262 } 15263 15264 if (args.move != null) { 15265 // We did an in-place move, so dex is ready to roll 15266 scanFlags |= SCAN_NO_DEX; 15267 scanFlags |= SCAN_MOVE; 15268 15269 synchronized (mPackages) { 15270 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15271 if (ps == null) { 15272 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15273 "Missing settings for moved package " + pkgName); 15274 } 15275 15276 // We moved the entire application as-is, so bring over the 15277 // previously derived ABI information. 15278 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15279 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15280 } 15281 15282 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15283 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15284 scanFlags |= SCAN_NO_DEX; 15285 15286 try { 15287 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15288 args.abiOverride : pkg.cpuAbiOverride); 15289 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15290 true /* extract libs */); 15291 } catch (PackageManagerException pme) { 15292 Slog.e(TAG, "Error deriving application ABI", pme); 15293 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15294 return; 15295 } 15296 15297 // Shared libraries for the package need to be updated. 15298 synchronized (mPackages) { 15299 try { 15300 updateSharedLibrariesLPw(pkg, null); 15301 } catch (PackageManagerException e) { 15302 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15303 } 15304 } 15305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15306 // Do not run PackageDexOptimizer through the local performDexOpt 15307 // method because `pkg` may not be in `mPackages` yet. 15308 // 15309 // Also, don't fail application installs if the dexopt step fails. 15310 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15311 null /* instructionSets */, false /* checkProfiles */, 15312 getCompilerFilterForReason(REASON_INSTALL), 15313 getOrCreateCompilerPackageStats(pkg)); 15314 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15315 15316 // Notify BackgroundDexOptService that the package has been changed. 15317 // If this is an update of a package which used to fail to compile, 15318 // BDOS will remove it from its blacklist. 15319 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15320 } 15321 15322 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15323 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15324 return; 15325 } 15326 15327 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15328 15329 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15330 "installPackageLI")) { 15331 if (replace) { 15332 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15333 installerPackageName, res); 15334 } else { 15335 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15336 args.user, installerPackageName, volumeUuid, res); 15337 } 15338 } 15339 synchronized (mPackages) { 15340 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15341 if (ps != null) { 15342 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15343 } 15344 15345 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15346 for (int i = 0; i < childCount; i++) { 15347 PackageParser.Package childPkg = pkg.childPackages.get(i); 15348 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15349 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15350 if (childPs != null) { 15351 childRes.newUsers = childPs.queryInstalledUsers( 15352 sUserManager.getUserIds(), true); 15353 } 15354 } 15355 } 15356 } 15357 15358 private void startIntentFilterVerifications(int userId, boolean replacing, 15359 PackageParser.Package pkg) { 15360 if (mIntentFilterVerifierComponent == null) { 15361 Slog.w(TAG, "No IntentFilter verification will not be done as " 15362 + "there is no IntentFilterVerifier available!"); 15363 return; 15364 } 15365 15366 final int verifierUid = getPackageUid( 15367 mIntentFilterVerifierComponent.getPackageName(), 15368 MATCH_DEBUG_TRIAGED_MISSING, 15369 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15370 15371 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15372 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15373 mHandler.sendMessage(msg); 15374 15375 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15376 for (int i = 0; i < childCount; i++) { 15377 PackageParser.Package childPkg = pkg.childPackages.get(i); 15378 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15379 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15380 mHandler.sendMessage(msg); 15381 } 15382 } 15383 15384 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15385 PackageParser.Package pkg) { 15386 int size = pkg.activities.size(); 15387 if (size == 0) { 15388 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15389 "No activity, so no need to verify any IntentFilter!"); 15390 return; 15391 } 15392 15393 final boolean hasDomainURLs = hasDomainURLs(pkg); 15394 if (!hasDomainURLs) { 15395 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15396 "No domain URLs, so no need to verify any IntentFilter!"); 15397 return; 15398 } 15399 15400 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15401 + " if any IntentFilter from the " + size 15402 + " Activities needs verification ..."); 15403 15404 int count = 0; 15405 final String packageName = pkg.packageName; 15406 15407 synchronized (mPackages) { 15408 // If this is a new install and we see that we've already run verification for this 15409 // package, we have nothing to do: it means the state was restored from backup. 15410 if (!replacing) { 15411 IntentFilterVerificationInfo ivi = 15412 mSettings.getIntentFilterVerificationLPr(packageName); 15413 if (ivi != null) { 15414 if (DEBUG_DOMAIN_VERIFICATION) { 15415 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15416 + ivi.getStatusString()); 15417 } 15418 return; 15419 } 15420 } 15421 15422 // If any filters need to be verified, then all need to be. 15423 boolean needToVerify = false; 15424 for (PackageParser.Activity a : pkg.activities) { 15425 for (ActivityIntentInfo filter : a.intents) { 15426 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15427 if (DEBUG_DOMAIN_VERIFICATION) { 15428 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15429 } 15430 needToVerify = true; 15431 break; 15432 } 15433 } 15434 } 15435 15436 if (needToVerify) { 15437 final int verificationId = mIntentFilterVerificationToken++; 15438 for (PackageParser.Activity a : pkg.activities) { 15439 for (ActivityIntentInfo filter : a.intents) { 15440 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15441 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15442 "Verification needed for IntentFilter:" + filter.toString()); 15443 mIntentFilterVerifier.addOneIntentFilterVerification( 15444 verifierUid, userId, verificationId, filter, packageName); 15445 count++; 15446 } 15447 } 15448 } 15449 } 15450 } 15451 15452 if (count > 0) { 15453 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15454 + " IntentFilter verification" + (count > 1 ? "s" : "") 15455 + " for userId:" + userId); 15456 mIntentFilterVerifier.startVerifications(userId); 15457 } else { 15458 if (DEBUG_DOMAIN_VERIFICATION) { 15459 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15460 } 15461 } 15462 } 15463 15464 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15465 final ComponentName cn = filter.activity.getComponentName(); 15466 final String packageName = cn.getPackageName(); 15467 15468 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15469 packageName); 15470 if (ivi == null) { 15471 return true; 15472 } 15473 int status = ivi.getStatus(); 15474 switch (status) { 15475 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15476 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15477 return true; 15478 15479 default: 15480 // Nothing to do 15481 return false; 15482 } 15483 } 15484 15485 private static boolean isMultiArch(ApplicationInfo info) { 15486 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15487 } 15488 15489 private static boolean isExternal(PackageParser.Package pkg) { 15490 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15491 } 15492 15493 private static boolean isExternal(PackageSetting ps) { 15494 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15495 } 15496 15497 private static boolean isEphemeral(PackageParser.Package pkg) { 15498 return pkg.applicationInfo.isEphemeralApp(); 15499 } 15500 15501 private static boolean isEphemeral(PackageSetting ps) { 15502 return ps.pkg != null && isEphemeral(ps.pkg); 15503 } 15504 15505 private static boolean isSystemApp(PackageParser.Package pkg) { 15506 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15507 } 15508 15509 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15510 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15511 } 15512 15513 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15514 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15515 } 15516 15517 private static boolean isSystemApp(PackageSetting ps) { 15518 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15519 } 15520 15521 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15522 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15523 } 15524 15525 private int packageFlagsToInstallFlags(PackageSetting ps) { 15526 int installFlags = 0; 15527 if (isEphemeral(ps)) { 15528 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15529 } 15530 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15531 // This existing package was an external ASEC install when we have 15532 // the external flag without a UUID 15533 installFlags |= PackageManager.INSTALL_EXTERNAL; 15534 } 15535 if (ps.isForwardLocked()) { 15536 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15537 } 15538 return installFlags; 15539 } 15540 15541 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15542 if (isExternal(pkg)) { 15543 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15544 return StorageManager.UUID_PRIMARY_PHYSICAL; 15545 } else { 15546 return pkg.volumeUuid; 15547 } 15548 } else { 15549 return StorageManager.UUID_PRIVATE_INTERNAL; 15550 } 15551 } 15552 15553 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15554 if (isExternal(pkg)) { 15555 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15556 return mSettings.getExternalVersion(); 15557 } else { 15558 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15559 } 15560 } else { 15561 return mSettings.getInternalVersion(); 15562 } 15563 } 15564 15565 private void deleteTempPackageFiles() { 15566 final FilenameFilter filter = new FilenameFilter() { 15567 public boolean accept(File dir, String name) { 15568 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15569 } 15570 }; 15571 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15572 file.delete(); 15573 } 15574 } 15575 15576 @Override 15577 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15578 int flags) { 15579 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15580 flags); 15581 } 15582 15583 @Override 15584 public void deletePackage(final String packageName, 15585 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15586 mContext.enforceCallingOrSelfPermission( 15587 android.Manifest.permission.DELETE_PACKAGES, null); 15588 Preconditions.checkNotNull(packageName); 15589 Preconditions.checkNotNull(observer); 15590 final int uid = Binder.getCallingUid(); 15591 if (!isOrphaned(packageName) 15592 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15593 try { 15594 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15595 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15596 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15597 observer.onUserActionRequired(intent); 15598 } catch (RemoteException re) { 15599 } 15600 return; 15601 } 15602 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15603 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15604 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15605 mContext.enforceCallingOrSelfPermission( 15606 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15607 "deletePackage for user " + userId); 15608 } 15609 15610 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15611 try { 15612 observer.onPackageDeleted(packageName, 15613 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15614 } catch (RemoteException re) { 15615 } 15616 return; 15617 } 15618 15619 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15620 try { 15621 observer.onPackageDeleted(packageName, 15622 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15623 } catch (RemoteException re) { 15624 } 15625 return; 15626 } 15627 15628 if (DEBUG_REMOVE) { 15629 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15630 + " deleteAllUsers: " + deleteAllUsers ); 15631 } 15632 // Queue up an async operation since the package deletion may take a little while. 15633 mHandler.post(new Runnable() { 15634 public void run() { 15635 mHandler.removeCallbacks(this); 15636 int returnCode; 15637 if (!deleteAllUsers) { 15638 returnCode = deletePackageX(packageName, userId, deleteFlags); 15639 } else { 15640 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15641 // If nobody is blocking uninstall, proceed with delete for all users 15642 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15643 returnCode = deletePackageX(packageName, userId, deleteFlags); 15644 } else { 15645 // Otherwise uninstall individually for users with blockUninstalls=false 15646 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15647 for (int userId : users) { 15648 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15649 returnCode = deletePackageX(packageName, userId, userFlags); 15650 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15651 Slog.w(TAG, "Package delete failed for user " + userId 15652 + ", returnCode " + returnCode); 15653 } 15654 } 15655 } 15656 // The app has only been marked uninstalled for certain users. 15657 // We still need to report that delete was blocked 15658 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15659 } 15660 } 15661 try { 15662 observer.onPackageDeleted(packageName, returnCode, null); 15663 } catch (RemoteException e) { 15664 Log.i(TAG, "Observer no longer exists."); 15665 } //end catch 15666 } //end run 15667 }); 15668 } 15669 15670 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15671 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15672 || callingUid == Process.SYSTEM_UID) { 15673 return true; 15674 } 15675 final int callingUserId = UserHandle.getUserId(callingUid); 15676 // If the caller installed the pkgName, then allow it to silently uninstall. 15677 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15678 return true; 15679 } 15680 15681 // Allow package verifier to silently uninstall. 15682 if (mRequiredVerifierPackage != null && 15683 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15684 return true; 15685 } 15686 15687 // Allow package uninstaller to silently uninstall. 15688 if (mRequiredUninstallerPackage != null && 15689 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15690 return true; 15691 } 15692 15693 // Allow storage manager to silently uninstall. 15694 if (mStorageManagerPackage != null && 15695 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15696 return true; 15697 } 15698 return false; 15699 } 15700 15701 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15702 int[] result = EMPTY_INT_ARRAY; 15703 for (int userId : userIds) { 15704 if (getBlockUninstallForUser(packageName, userId)) { 15705 result = ArrayUtils.appendInt(result, userId); 15706 } 15707 } 15708 return result; 15709 } 15710 15711 @Override 15712 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15713 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15714 } 15715 15716 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15717 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15718 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15719 try { 15720 if (dpm != null) { 15721 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15722 /* callingUserOnly =*/ false); 15723 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15724 : deviceOwnerComponentName.getPackageName(); 15725 // Does the package contains the device owner? 15726 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15727 // this check is probably not needed, since DO should be registered as a device 15728 // admin on some user too. (Original bug for this: b/17657954) 15729 if (packageName.equals(deviceOwnerPackageName)) { 15730 return true; 15731 } 15732 // Does it contain a device admin for any user? 15733 int[] users; 15734 if (userId == UserHandle.USER_ALL) { 15735 users = sUserManager.getUserIds(); 15736 } else { 15737 users = new int[]{userId}; 15738 } 15739 for (int i = 0; i < users.length; ++i) { 15740 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15741 return true; 15742 } 15743 } 15744 } 15745 } catch (RemoteException e) { 15746 } 15747 return false; 15748 } 15749 15750 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15751 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15752 } 15753 15754 /** 15755 * This method is an internal method that could be get invoked either 15756 * to delete an installed package or to clean up a failed installation. 15757 * After deleting an installed package, a broadcast is sent to notify any 15758 * listeners that the package has been removed. For cleaning up a failed 15759 * installation, the broadcast is not necessary since the package's 15760 * installation wouldn't have sent the initial broadcast either 15761 * The key steps in deleting a package are 15762 * deleting the package information in internal structures like mPackages, 15763 * deleting the packages base directories through installd 15764 * updating mSettings to reflect current status 15765 * persisting settings for later use 15766 * sending a broadcast if necessary 15767 */ 15768 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15769 final PackageRemovedInfo info = new PackageRemovedInfo(); 15770 final boolean res; 15771 15772 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15773 ? UserHandle.USER_ALL : userId; 15774 15775 if (isPackageDeviceAdmin(packageName, removeUser)) { 15776 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15777 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15778 } 15779 15780 PackageSetting uninstalledPs = null; 15781 15782 // for the uninstall-updates case and restricted profiles, remember the per- 15783 // user handle installed state 15784 int[] allUsers; 15785 synchronized (mPackages) { 15786 uninstalledPs = mSettings.mPackages.get(packageName); 15787 if (uninstalledPs == null) { 15788 Slog.w(TAG, "Not removing non-existent package " + packageName); 15789 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15790 } 15791 allUsers = sUserManager.getUserIds(); 15792 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15793 } 15794 15795 final int freezeUser; 15796 if (isUpdatedSystemApp(uninstalledPs) 15797 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15798 // We're downgrading a system app, which will apply to all users, so 15799 // freeze them all during the downgrade 15800 freezeUser = UserHandle.USER_ALL; 15801 } else { 15802 freezeUser = removeUser; 15803 } 15804 15805 synchronized (mInstallLock) { 15806 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15807 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15808 deleteFlags, "deletePackageX")) { 15809 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15810 deleteFlags | REMOVE_CHATTY, info, true, null); 15811 } 15812 synchronized (mPackages) { 15813 if (res) { 15814 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15815 } 15816 } 15817 } 15818 15819 if (res) { 15820 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15821 info.sendPackageRemovedBroadcasts(killApp); 15822 info.sendSystemPackageUpdatedBroadcasts(); 15823 info.sendSystemPackageAppearedBroadcasts(); 15824 } 15825 // Force a gc here. 15826 Runtime.getRuntime().gc(); 15827 // Delete the resources here after sending the broadcast to let 15828 // other processes clean up before deleting resources. 15829 if (info.args != null) { 15830 synchronized (mInstallLock) { 15831 info.args.doPostDeleteLI(true); 15832 } 15833 } 15834 15835 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15836 } 15837 15838 class PackageRemovedInfo { 15839 String removedPackage; 15840 int uid = -1; 15841 int removedAppId = -1; 15842 int[] origUsers; 15843 int[] removedUsers = null; 15844 boolean isRemovedPackageSystemUpdate = false; 15845 boolean isUpdate; 15846 boolean dataRemoved; 15847 boolean removedForAllUsers; 15848 // Clean up resources deleted packages. 15849 InstallArgs args = null; 15850 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15851 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15852 15853 void sendPackageRemovedBroadcasts(boolean killApp) { 15854 sendPackageRemovedBroadcastInternal(killApp); 15855 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15856 for (int i = 0; i < childCount; i++) { 15857 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15858 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15859 } 15860 } 15861 15862 void sendSystemPackageUpdatedBroadcasts() { 15863 if (isRemovedPackageSystemUpdate) { 15864 sendSystemPackageUpdatedBroadcastsInternal(); 15865 final int childCount = (removedChildPackages != null) 15866 ? removedChildPackages.size() : 0; 15867 for (int i = 0; i < childCount; i++) { 15868 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15869 if (childInfo.isRemovedPackageSystemUpdate) { 15870 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15871 } 15872 } 15873 } 15874 } 15875 15876 void sendSystemPackageAppearedBroadcasts() { 15877 final int packageCount = (appearedChildPackages != null) 15878 ? appearedChildPackages.size() : 0; 15879 for (int i = 0; i < packageCount; i++) { 15880 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15881 for (int userId : installedInfo.newUsers) { 15882 sendPackageAddedForUser(installedInfo.name, true, 15883 UserHandle.getAppId(installedInfo.uid), userId); 15884 } 15885 } 15886 } 15887 15888 private void sendSystemPackageUpdatedBroadcastsInternal() { 15889 Bundle extras = new Bundle(2); 15890 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15891 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15892 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15893 extras, 0, null, null, null); 15894 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15895 extras, 0, null, null, null); 15896 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15897 null, 0, removedPackage, null, null); 15898 } 15899 15900 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15901 Bundle extras = new Bundle(2); 15902 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15903 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15904 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15905 if (isUpdate || isRemovedPackageSystemUpdate) { 15906 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15907 } 15908 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15909 if (removedPackage != null) { 15910 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15911 extras, 0, null, null, removedUsers); 15912 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15913 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15914 removedPackage, extras, 0, null, null, removedUsers); 15915 } 15916 } 15917 if (removedAppId >= 0) { 15918 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15919 removedUsers); 15920 } 15921 } 15922 } 15923 15924 /* 15925 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15926 * flag is not set, the data directory is removed as well. 15927 * make sure this flag is set for partially installed apps. If not its meaningless to 15928 * delete a partially installed application. 15929 */ 15930 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15931 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15932 String packageName = ps.name; 15933 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15934 // Retrieve object to delete permissions for shared user later on 15935 final PackageParser.Package deletedPkg; 15936 final PackageSetting deletedPs; 15937 // reader 15938 synchronized (mPackages) { 15939 deletedPkg = mPackages.get(packageName); 15940 deletedPs = mSettings.mPackages.get(packageName); 15941 if (outInfo != null) { 15942 outInfo.removedPackage = packageName; 15943 outInfo.removedUsers = deletedPs != null 15944 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15945 : null; 15946 } 15947 } 15948 15949 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15950 15951 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15952 final PackageParser.Package resolvedPkg; 15953 if (deletedPkg != null) { 15954 resolvedPkg = deletedPkg; 15955 } else { 15956 // We don't have a parsed package when it lives on an ejected 15957 // adopted storage device, so fake something together 15958 resolvedPkg = new PackageParser.Package(ps.name); 15959 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15960 } 15961 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15962 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15963 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15964 if (outInfo != null) { 15965 outInfo.dataRemoved = true; 15966 } 15967 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15968 } 15969 15970 // writer 15971 synchronized (mPackages) { 15972 if (deletedPs != null) { 15973 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15974 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15975 clearDefaultBrowserIfNeeded(packageName); 15976 if (outInfo != null) { 15977 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15978 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15979 } 15980 updatePermissionsLPw(deletedPs.name, null, 0); 15981 if (deletedPs.sharedUser != null) { 15982 // Remove permissions associated with package. Since runtime 15983 // permissions are per user we have to kill the removed package 15984 // or packages running under the shared user of the removed 15985 // package if revoking the permissions requested only by the removed 15986 // package is successful and this causes a change in gids. 15987 for (int userId : UserManagerService.getInstance().getUserIds()) { 15988 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15989 userId); 15990 if (userIdToKill == UserHandle.USER_ALL 15991 || userIdToKill >= UserHandle.USER_SYSTEM) { 15992 // If gids changed for this user, kill all affected packages. 15993 mHandler.post(new Runnable() { 15994 @Override 15995 public void run() { 15996 // This has to happen with no lock held. 15997 killApplication(deletedPs.name, deletedPs.appId, 15998 KILL_APP_REASON_GIDS_CHANGED); 15999 } 16000 }); 16001 break; 16002 } 16003 } 16004 } 16005 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16006 } 16007 // make sure to preserve per-user disabled state if this removal was just 16008 // a downgrade of a system app to the factory package 16009 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16010 if (DEBUG_REMOVE) { 16011 Slog.d(TAG, "Propagating install state across downgrade"); 16012 } 16013 for (int userId : allUserHandles) { 16014 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16015 if (DEBUG_REMOVE) { 16016 Slog.d(TAG, " user " + userId + " => " + installed); 16017 } 16018 ps.setInstalled(installed, userId); 16019 } 16020 } 16021 } 16022 // can downgrade to reader 16023 if (writeSettings) { 16024 // Save settings now 16025 mSettings.writeLPr(); 16026 } 16027 } 16028 if (outInfo != null) { 16029 // A user ID was deleted here. Go through all users and remove it 16030 // from KeyStore. 16031 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16032 } 16033 } 16034 16035 static boolean locationIsPrivileged(File path) { 16036 try { 16037 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16038 .getCanonicalPath(); 16039 return path.getCanonicalPath().startsWith(privilegedAppDir); 16040 } catch (IOException e) { 16041 Slog.e(TAG, "Unable to access code path " + path); 16042 } 16043 return false; 16044 } 16045 16046 /* 16047 * Tries to delete system package. 16048 */ 16049 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16050 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16051 boolean writeSettings) { 16052 if (deletedPs.parentPackageName != null) { 16053 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16054 return false; 16055 } 16056 16057 final boolean applyUserRestrictions 16058 = (allUserHandles != null) && (outInfo.origUsers != null); 16059 final PackageSetting disabledPs; 16060 // Confirm if the system package has been updated 16061 // An updated system app can be deleted. This will also have to restore 16062 // the system pkg from system partition 16063 // reader 16064 synchronized (mPackages) { 16065 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16066 } 16067 16068 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16069 + " disabledPs=" + disabledPs); 16070 16071 if (disabledPs == null) { 16072 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16073 return false; 16074 } else if (DEBUG_REMOVE) { 16075 Slog.d(TAG, "Deleting system pkg from data partition"); 16076 } 16077 16078 if (DEBUG_REMOVE) { 16079 if (applyUserRestrictions) { 16080 Slog.d(TAG, "Remembering install states:"); 16081 for (int userId : allUserHandles) { 16082 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16083 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16084 } 16085 } 16086 } 16087 16088 // Delete the updated package 16089 outInfo.isRemovedPackageSystemUpdate = true; 16090 if (outInfo.removedChildPackages != null) { 16091 final int childCount = (deletedPs.childPackageNames != null) 16092 ? deletedPs.childPackageNames.size() : 0; 16093 for (int i = 0; i < childCount; i++) { 16094 String childPackageName = deletedPs.childPackageNames.get(i); 16095 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16096 .contains(childPackageName)) { 16097 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16098 childPackageName); 16099 if (childInfo != null) { 16100 childInfo.isRemovedPackageSystemUpdate = true; 16101 } 16102 } 16103 } 16104 } 16105 16106 if (disabledPs.versionCode < deletedPs.versionCode) { 16107 // Delete data for downgrades 16108 flags &= ~PackageManager.DELETE_KEEP_DATA; 16109 } else { 16110 // Preserve data by setting flag 16111 flags |= PackageManager.DELETE_KEEP_DATA; 16112 } 16113 16114 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16115 outInfo, writeSettings, disabledPs.pkg); 16116 if (!ret) { 16117 return false; 16118 } 16119 16120 // writer 16121 synchronized (mPackages) { 16122 // Reinstate the old system package 16123 enableSystemPackageLPw(disabledPs.pkg); 16124 // Remove any native libraries from the upgraded package. 16125 removeNativeBinariesLI(deletedPs); 16126 } 16127 16128 // Install the system package 16129 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16130 int parseFlags = mDefParseFlags 16131 | PackageParser.PARSE_MUST_BE_APK 16132 | PackageParser.PARSE_IS_SYSTEM 16133 | PackageParser.PARSE_IS_SYSTEM_DIR; 16134 if (locationIsPrivileged(disabledPs.codePath)) { 16135 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16136 } 16137 16138 final PackageParser.Package newPkg; 16139 try { 16140 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16141 } catch (PackageManagerException e) { 16142 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16143 + e.getMessage()); 16144 return false; 16145 } 16146 try { 16147 // update shared libraries for the newly re-installed system package 16148 updateSharedLibrariesLPw(newPkg, null); 16149 } catch (PackageManagerException e) { 16150 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16151 } 16152 16153 prepareAppDataAfterInstallLIF(newPkg); 16154 16155 // writer 16156 synchronized (mPackages) { 16157 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16158 16159 // Propagate the permissions state as we do not want to drop on the floor 16160 // runtime permissions. The update permissions method below will take 16161 // care of removing obsolete permissions and grant install permissions. 16162 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16163 updatePermissionsLPw(newPkg.packageName, newPkg, 16164 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16165 16166 if (applyUserRestrictions) { 16167 if (DEBUG_REMOVE) { 16168 Slog.d(TAG, "Propagating install state across reinstall"); 16169 } 16170 for (int userId : allUserHandles) { 16171 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16172 if (DEBUG_REMOVE) { 16173 Slog.d(TAG, " user " + userId + " => " + installed); 16174 } 16175 ps.setInstalled(installed, userId); 16176 16177 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16178 } 16179 // Regardless of writeSettings we need to ensure that this restriction 16180 // state propagation is persisted 16181 mSettings.writeAllUsersPackageRestrictionsLPr(); 16182 } 16183 // can downgrade to reader here 16184 if (writeSettings) { 16185 mSettings.writeLPr(); 16186 } 16187 } 16188 return true; 16189 } 16190 16191 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16192 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16193 PackageRemovedInfo outInfo, boolean writeSettings, 16194 PackageParser.Package replacingPackage) { 16195 synchronized (mPackages) { 16196 if (outInfo != null) { 16197 outInfo.uid = ps.appId; 16198 } 16199 16200 if (outInfo != null && outInfo.removedChildPackages != null) { 16201 final int childCount = (ps.childPackageNames != null) 16202 ? ps.childPackageNames.size() : 0; 16203 for (int i = 0; i < childCount; i++) { 16204 String childPackageName = ps.childPackageNames.get(i); 16205 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16206 if (childPs == null) { 16207 return false; 16208 } 16209 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16210 childPackageName); 16211 if (childInfo != null) { 16212 childInfo.uid = childPs.appId; 16213 } 16214 } 16215 } 16216 } 16217 16218 // Delete package data from internal structures and also remove data if flag is set 16219 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16220 16221 // Delete the child packages data 16222 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16223 for (int i = 0; i < childCount; i++) { 16224 PackageSetting childPs; 16225 synchronized (mPackages) { 16226 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16227 } 16228 if (childPs != null) { 16229 PackageRemovedInfo childOutInfo = (outInfo != null 16230 && outInfo.removedChildPackages != null) 16231 ? outInfo.removedChildPackages.get(childPs.name) : null; 16232 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16233 && (replacingPackage != null 16234 && !replacingPackage.hasChildPackage(childPs.name)) 16235 ? flags & ~DELETE_KEEP_DATA : flags; 16236 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16237 deleteFlags, writeSettings); 16238 } 16239 } 16240 16241 // Delete application code and resources only for parent packages 16242 if (ps.parentPackageName == null) { 16243 if (deleteCodeAndResources && (outInfo != null)) { 16244 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16245 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16246 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16247 } 16248 } 16249 16250 return true; 16251 } 16252 16253 @Override 16254 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16255 int userId) { 16256 mContext.enforceCallingOrSelfPermission( 16257 android.Manifest.permission.DELETE_PACKAGES, null); 16258 synchronized (mPackages) { 16259 PackageSetting ps = mSettings.mPackages.get(packageName); 16260 if (ps == null) { 16261 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16262 return false; 16263 } 16264 if (!ps.getInstalled(userId)) { 16265 // Can't block uninstall for an app that is not installed or enabled. 16266 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16267 return false; 16268 } 16269 ps.setBlockUninstall(blockUninstall, userId); 16270 mSettings.writePackageRestrictionsLPr(userId); 16271 } 16272 return true; 16273 } 16274 16275 @Override 16276 public boolean getBlockUninstallForUser(String packageName, int userId) { 16277 synchronized (mPackages) { 16278 PackageSetting ps = mSettings.mPackages.get(packageName); 16279 if (ps == null) { 16280 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16281 return false; 16282 } 16283 return ps.getBlockUninstall(userId); 16284 } 16285 } 16286 16287 @Override 16288 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16289 int callingUid = Binder.getCallingUid(); 16290 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16291 throw new SecurityException( 16292 "setRequiredForSystemUser can only be run by the system or root"); 16293 } 16294 synchronized (mPackages) { 16295 PackageSetting ps = mSettings.mPackages.get(packageName); 16296 if (ps == null) { 16297 Log.w(TAG, "Package doesn't exist: " + packageName); 16298 return false; 16299 } 16300 if (systemUserApp) { 16301 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16302 } else { 16303 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16304 } 16305 mSettings.writeLPr(); 16306 } 16307 return true; 16308 } 16309 16310 /* 16311 * This method handles package deletion in general 16312 */ 16313 private boolean deletePackageLIF(String packageName, UserHandle user, 16314 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16315 PackageRemovedInfo outInfo, boolean writeSettings, 16316 PackageParser.Package replacingPackage) { 16317 if (packageName == null) { 16318 Slog.w(TAG, "Attempt to delete null packageName."); 16319 return false; 16320 } 16321 16322 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16323 16324 PackageSetting ps; 16325 16326 synchronized (mPackages) { 16327 ps = mSettings.mPackages.get(packageName); 16328 if (ps == null) { 16329 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16330 return false; 16331 } 16332 16333 if (ps.parentPackageName != null && (!isSystemApp(ps) 16334 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16335 if (DEBUG_REMOVE) { 16336 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16337 + ((user == null) ? UserHandle.USER_ALL : user)); 16338 } 16339 final int removedUserId = (user != null) ? user.getIdentifier() 16340 : UserHandle.USER_ALL; 16341 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16342 return false; 16343 } 16344 markPackageUninstalledForUserLPw(ps, user); 16345 scheduleWritePackageRestrictionsLocked(user); 16346 return true; 16347 } 16348 } 16349 16350 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16351 && user.getIdentifier() != UserHandle.USER_ALL)) { 16352 // The caller is asking that the package only be deleted for a single 16353 // user. To do this, we just mark its uninstalled state and delete 16354 // its data. If this is a system app, we only allow this to happen if 16355 // they have set the special DELETE_SYSTEM_APP which requests different 16356 // semantics than normal for uninstalling system apps. 16357 markPackageUninstalledForUserLPw(ps, user); 16358 16359 if (!isSystemApp(ps)) { 16360 // Do not uninstall the APK if an app should be cached 16361 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16362 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16363 // Other user still have this package installed, so all 16364 // we need to do is clear this user's data and save that 16365 // it is uninstalled. 16366 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16367 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16368 return false; 16369 } 16370 scheduleWritePackageRestrictionsLocked(user); 16371 return true; 16372 } else { 16373 // We need to set it back to 'installed' so the uninstall 16374 // broadcasts will be sent correctly. 16375 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16376 ps.setInstalled(true, user.getIdentifier()); 16377 } 16378 } else { 16379 // This is a system app, so we assume that the 16380 // other users still have this package installed, so all 16381 // we need to do is clear this user's data and save that 16382 // it is uninstalled. 16383 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16384 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16385 return false; 16386 } 16387 scheduleWritePackageRestrictionsLocked(user); 16388 return true; 16389 } 16390 } 16391 16392 // If we are deleting a composite package for all users, keep track 16393 // of result for each child. 16394 if (ps.childPackageNames != null && outInfo != null) { 16395 synchronized (mPackages) { 16396 final int childCount = ps.childPackageNames.size(); 16397 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16398 for (int i = 0; i < childCount; i++) { 16399 String childPackageName = ps.childPackageNames.get(i); 16400 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16401 childInfo.removedPackage = childPackageName; 16402 outInfo.removedChildPackages.put(childPackageName, childInfo); 16403 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16404 if (childPs != null) { 16405 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16406 } 16407 } 16408 } 16409 } 16410 16411 boolean ret = false; 16412 if (isSystemApp(ps)) { 16413 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16414 // When an updated system application is deleted we delete the existing resources 16415 // as well and fall back to existing code in system partition 16416 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16417 } else { 16418 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16419 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16420 outInfo, writeSettings, replacingPackage); 16421 } 16422 16423 // Take a note whether we deleted the package for all users 16424 if (outInfo != null) { 16425 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16426 if (outInfo.removedChildPackages != null) { 16427 synchronized (mPackages) { 16428 final int childCount = outInfo.removedChildPackages.size(); 16429 for (int i = 0; i < childCount; i++) { 16430 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16431 if (childInfo != null) { 16432 childInfo.removedForAllUsers = mPackages.get( 16433 childInfo.removedPackage) == null; 16434 } 16435 } 16436 } 16437 } 16438 // If we uninstalled an update to a system app there may be some 16439 // child packages that appeared as they are declared in the system 16440 // app but were not declared in the update. 16441 if (isSystemApp(ps)) { 16442 synchronized (mPackages) { 16443 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16444 final int childCount = (updatedPs.childPackageNames != null) 16445 ? updatedPs.childPackageNames.size() : 0; 16446 for (int i = 0; i < childCount; i++) { 16447 String childPackageName = updatedPs.childPackageNames.get(i); 16448 if (outInfo.removedChildPackages == null 16449 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16450 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16451 if (childPs == null) { 16452 continue; 16453 } 16454 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16455 installRes.name = childPackageName; 16456 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16457 installRes.pkg = mPackages.get(childPackageName); 16458 installRes.uid = childPs.pkg.applicationInfo.uid; 16459 if (outInfo.appearedChildPackages == null) { 16460 outInfo.appearedChildPackages = new ArrayMap<>(); 16461 } 16462 outInfo.appearedChildPackages.put(childPackageName, installRes); 16463 } 16464 } 16465 } 16466 } 16467 } 16468 16469 return ret; 16470 } 16471 16472 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16473 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16474 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16475 for (int nextUserId : userIds) { 16476 if (DEBUG_REMOVE) { 16477 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16478 } 16479 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16480 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16481 false /*hidden*/, false /*suspended*/, null, null, null, 16482 false /*blockUninstall*/, 16483 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16484 } 16485 } 16486 16487 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16488 PackageRemovedInfo outInfo) { 16489 final PackageParser.Package pkg; 16490 synchronized (mPackages) { 16491 pkg = mPackages.get(ps.name); 16492 } 16493 16494 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16495 : new int[] {userId}; 16496 for (int nextUserId : userIds) { 16497 if (DEBUG_REMOVE) { 16498 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16499 + nextUserId); 16500 } 16501 16502 destroyAppDataLIF(pkg, userId, 16503 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16504 destroyAppProfilesLIF(pkg, userId); 16505 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16506 schedulePackageCleaning(ps.name, nextUserId, false); 16507 synchronized (mPackages) { 16508 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16509 scheduleWritePackageRestrictionsLocked(nextUserId); 16510 } 16511 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16512 } 16513 } 16514 16515 if (outInfo != null) { 16516 outInfo.removedPackage = ps.name; 16517 outInfo.removedAppId = ps.appId; 16518 outInfo.removedUsers = userIds; 16519 } 16520 16521 return true; 16522 } 16523 16524 private final class ClearStorageConnection implements ServiceConnection { 16525 IMediaContainerService mContainerService; 16526 16527 @Override 16528 public void onServiceConnected(ComponentName name, IBinder service) { 16529 synchronized (this) { 16530 mContainerService = IMediaContainerService.Stub.asInterface(service); 16531 notifyAll(); 16532 } 16533 } 16534 16535 @Override 16536 public void onServiceDisconnected(ComponentName name) { 16537 } 16538 } 16539 16540 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16541 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16542 16543 final boolean mounted; 16544 if (Environment.isExternalStorageEmulated()) { 16545 mounted = true; 16546 } else { 16547 final String status = Environment.getExternalStorageState(); 16548 16549 mounted = status.equals(Environment.MEDIA_MOUNTED) 16550 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16551 } 16552 16553 if (!mounted) { 16554 return; 16555 } 16556 16557 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16558 int[] users; 16559 if (userId == UserHandle.USER_ALL) { 16560 users = sUserManager.getUserIds(); 16561 } else { 16562 users = new int[] { userId }; 16563 } 16564 final ClearStorageConnection conn = new ClearStorageConnection(); 16565 if (mContext.bindServiceAsUser( 16566 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16567 try { 16568 for (int curUser : users) { 16569 long timeout = SystemClock.uptimeMillis() + 5000; 16570 synchronized (conn) { 16571 long now; 16572 while (conn.mContainerService == null && 16573 (now = SystemClock.uptimeMillis()) < timeout) { 16574 try { 16575 conn.wait(timeout - now); 16576 } catch (InterruptedException e) { 16577 } 16578 } 16579 } 16580 if (conn.mContainerService == null) { 16581 return; 16582 } 16583 16584 final UserEnvironment userEnv = new UserEnvironment(curUser); 16585 clearDirectory(conn.mContainerService, 16586 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16587 if (allData) { 16588 clearDirectory(conn.mContainerService, 16589 userEnv.buildExternalStorageAppDataDirs(packageName)); 16590 clearDirectory(conn.mContainerService, 16591 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16592 } 16593 } 16594 } finally { 16595 mContext.unbindService(conn); 16596 } 16597 } 16598 } 16599 16600 @Override 16601 public void clearApplicationProfileData(String packageName) { 16602 enforceSystemOrRoot("Only the system can clear all profile data"); 16603 16604 final PackageParser.Package pkg; 16605 synchronized (mPackages) { 16606 pkg = mPackages.get(packageName); 16607 } 16608 16609 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16610 synchronized (mInstallLock) { 16611 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16612 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16613 true /* removeBaseMarker */); 16614 } 16615 } 16616 } 16617 16618 @Override 16619 public void clearApplicationUserData(final String packageName, 16620 final IPackageDataObserver observer, final int userId) { 16621 mContext.enforceCallingOrSelfPermission( 16622 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16623 16624 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16625 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16626 16627 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16628 throw new SecurityException("Cannot clear data for a protected package: " 16629 + packageName); 16630 } 16631 // Queue up an async operation since the package deletion may take a little while. 16632 mHandler.post(new Runnable() { 16633 public void run() { 16634 mHandler.removeCallbacks(this); 16635 final boolean succeeded; 16636 try (PackageFreezer freezer = freezePackage(packageName, 16637 "clearApplicationUserData")) { 16638 synchronized (mInstallLock) { 16639 succeeded = clearApplicationUserDataLIF(packageName, userId); 16640 } 16641 clearExternalStorageDataSync(packageName, userId, true); 16642 } 16643 if (succeeded) { 16644 // invoke DeviceStorageMonitor's update method to clear any notifications 16645 DeviceStorageMonitorInternal dsm = LocalServices 16646 .getService(DeviceStorageMonitorInternal.class); 16647 if (dsm != null) { 16648 dsm.checkMemory(); 16649 } 16650 } 16651 if(observer != null) { 16652 try { 16653 observer.onRemoveCompleted(packageName, succeeded); 16654 } catch (RemoteException e) { 16655 Log.i(TAG, "Observer no longer exists."); 16656 } 16657 } //end if observer 16658 } //end run 16659 }); 16660 } 16661 16662 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16663 if (packageName == null) { 16664 Slog.w(TAG, "Attempt to delete null packageName."); 16665 return false; 16666 } 16667 16668 // Try finding details about the requested package 16669 PackageParser.Package pkg; 16670 synchronized (mPackages) { 16671 pkg = mPackages.get(packageName); 16672 if (pkg == null) { 16673 final PackageSetting ps = mSettings.mPackages.get(packageName); 16674 if (ps != null) { 16675 pkg = ps.pkg; 16676 } 16677 } 16678 16679 if (pkg == null) { 16680 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16681 return false; 16682 } 16683 16684 PackageSetting ps = (PackageSetting) pkg.mExtras; 16685 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16686 } 16687 16688 clearAppDataLIF(pkg, userId, 16689 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16690 16691 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16692 removeKeystoreDataIfNeeded(userId, appId); 16693 16694 UserManagerInternal umInternal = getUserManagerInternal(); 16695 final int flags; 16696 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16697 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16698 } else if (umInternal.isUserRunning(userId)) { 16699 flags = StorageManager.FLAG_STORAGE_DE; 16700 } else { 16701 flags = 0; 16702 } 16703 prepareAppDataContentsLIF(pkg, userId, flags); 16704 16705 return true; 16706 } 16707 16708 /** 16709 * Reverts user permission state changes (permissions and flags) in 16710 * all packages for a given user. 16711 * 16712 * @param userId The device user for which to do a reset. 16713 */ 16714 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16715 final int packageCount = mPackages.size(); 16716 for (int i = 0; i < packageCount; i++) { 16717 PackageParser.Package pkg = mPackages.valueAt(i); 16718 PackageSetting ps = (PackageSetting) pkg.mExtras; 16719 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16720 } 16721 } 16722 16723 private void resetNetworkPolicies(int userId) { 16724 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16725 } 16726 16727 /** 16728 * Reverts user permission state changes (permissions and flags). 16729 * 16730 * @param ps The package for which to reset. 16731 * @param userId The device user for which to do a reset. 16732 */ 16733 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16734 final PackageSetting ps, final int userId) { 16735 if (ps.pkg == null) { 16736 return; 16737 } 16738 16739 // These are flags that can change base on user actions. 16740 final int userSettableMask = FLAG_PERMISSION_USER_SET 16741 | FLAG_PERMISSION_USER_FIXED 16742 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16743 | FLAG_PERMISSION_REVIEW_REQUIRED; 16744 16745 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16746 | FLAG_PERMISSION_POLICY_FIXED; 16747 16748 boolean writeInstallPermissions = false; 16749 boolean writeRuntimePermissions = false; 16750 16751 final int permissionCount = ps.pkg.requestedPermissions.size(); 16752 for (int i = 0; i < permissionCount; i++) { 16753 String permission = ps.pkg.requestedPermissions.get(i); 16754 16755 BasePermission bp = mSettings.mPermissions.get(permission); 16756 if (bp == null) { 16757 continue; 16758 } 16759 16760 // If shared user we just reset the state to which only this app contributed. 16761 if (ps.sharedUser != null) { 16762 boolean used = false; 16763 final int packageCount = ps.sharedUser.packages.size(); 16764 for (int j = 0; j < packageCount; j++) { 16765 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16766 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16767 && pkg.pkg.requestedPermissions.contains(permission)) { 16768 used = true; 16769 break; 16770 } 16771 } 16772 if (used) { 16773 continue; 16774 } 16775 } 16776 16777 PermissionsState permissionsState = ps.getPermissionsState(); 16778 16779 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16780 16781 // Always clear the user settable flags. 16782 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16783 bp.name) != null; 16784 // If permission review is enabled and this is a legacy app, mark the 16785 // permission as requiring a review as this is the initial state. 16786 int flags = 0; 16787 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 16788 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16789 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16790 } 16791 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16792 if (hasInstallState) { 16793 writeInstallPermissions = true; 16794 } else { 16795 writeRuntimePermissions = true; 16796 } 16797 } 16798 16799 // Below is only runtime permission handling. 16800 if (!bp.isRuntime()) { 16801 continue; 16802 } 16803 16804 // Never clobber system or policy. 16805 if ((oldFlags & policyOrSystemFlags) != 0) { 16806 continue; 16807 } 16808 16809 // If this permission was granted by default, make sure it is. 16810 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16811 if (permissionsState.grantRuntimePermission(bp, userId) 16812 != PERMISSION_OPERATION_FAILURE) { 16813 writeRuntimePermissions = true; 16814 } 16815 // If permission review is enabled the permissions for a legacy apps 16816 // are represented as constantly granted runtime ones, so don't revoke. 16817 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16818 // Otherwise, reset the permission. 16819 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16820 switch (revokeResult) { 16821 case PERMISSION_OPERATION_SUCCESS: 16822 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16823 writeRuntimePermissions = true; 16824 final int appId = ps.appId; 16825 mHandler.post(new Runnable() { 16826 @Override 16827 public void run() { 16828 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16829 } 16830 }); 16831 } break; 16832 } 16833 } 16834 } 16835 16836 // Synchronously write as we are taking permissions away. 16837 if (writeRuntimePermissions) { 16838 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16839 } 16840 16841 // Synchronously write as we are taking permissions away. 16842 if (writeInstallPermissions) { 16843 mSettings.writeLPr(); 16844 } 16845 } 16846 16847 /** 16848 * Remove entries from the keystore daemon. Will only remove it if the 16849 * {@code appId} is valid. 16850 */ 16851 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16852 if (appId < 0) { 16853 return; 16854 } 16855 16856 final KeyStore keyStore = KeyStore.getInstance(); 16857 if (keyStore != null) { 16858 if (userId == UserHandle.USER_ALL) { 16859 for (final int individual : sUserManager.getUserIds()) { 16860 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16861 } 16862 } else { 16863 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16864 } 16865 } else { 16866 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16867 } 16868 } 16869 16870 @Override 16871 public void deleteApplicationCacheFiles(final String packageName, 16872 final IPackageDataObserver observer) { 16873 final int userId = UserHandle.getCallingUserId(); 16874 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16875 } 16876 16877 @Override 16878 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16879 final IPackageDataObserver observer) { 16880 mContext.enforceCallingOrSelfPermission( 16881 android.Manifest.permission.DELETE_CACHE_FILES, null); 16882 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16883 /* requireFullPermission= */ true, /* checkShell= */ false, 16884 "delete application cache files"); 16885 16886 final PackageParser.Package pkg; 16887 synchronized (mPackages) { 16888 pkg = mPackages.get(packageName); 16889 } 16890 16891 // Queue up an async operation since the package deletion may take a little while. 16892 mHandler.post(new Runnable() { 16893 public void run() { 16894 synchronized (mInstallLock) { 16895 final int flags = StorageManager.FLAG_STORAGE_DE 16896 | StorageManager.FLAG_STORAGE_CE; 16897 // We're only clearing cache files, so we don't care if the 16898 // app is unfrozen and still able to run 16899 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16900 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16901 } 16902 clearExternalStorageDataSync(packageName, userId, false); 16903 if (observer != null) { 16904 try { 16905 observer.onRemoveCompleted(packageName, true); 16906 } catch (RemoteException e) { 16907 Log.i(TAG, "Observer no longer exists."); 16908 } 16909 } 16910 } 16911 }); 16912 } 16913 16914 @Override 16915 public void getPackageSizeInfo(final String packageName, int userHandle, 16916 final IPackageStatsObserver observer) { 16917 mContext.enforceCallingOrSelfPermission( 16918 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16919 if (packageName == null) { 16920 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16921 } 16922 16923 PackageStats stats = new PackageStats(packageName, userHandle); 16924 16925 /* 16926 * Queue up an async operation since the package measurement may take a 16927 * little while. 16928 */ 16929 Message msg = mHandler.obtainMessage(INIT_COPY); 16930 msg.obj = new MeasureParams(stats, observer); 16931 mHandler.sendMessage(msg); 16932 } 16933 16934 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16935 final PackageSetting ps; 16936 synchronized (mPackages) { 16937 ps = mSettings.mPackages.get(packageName); 16938 if (ps == null) { 16939 Slog.w(TAG, "Failed to find settings for " + packageName); 16940 return false; 16941 } 16942 } 16943 16944 final String[] packageNames = { packageName }; 16945 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 16946 final String[] codePaths = { ps.codePathString }; 16947 16948 try { 16949 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 16950 ps.appId, ceDataInodes, codePaths, stats); 16951 16952 // For now, ignore code size of packages on system partition 16953 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16954 stats.codeSize = 0; 16955 } 16956 16957 // External clients expect these to be tracked separately 16958 stats.dataSize -= stats.cacheSize; 16959 16960 } catch (InstallerException e) { 16961 Slog.w(TAG, String.valueOf(e)); 16962 return false; 16963 } 16964 16965 return true; 16966 } 16967 16968 private int getUidTargetSdkVersionLockedLPr(int uid) { 16969 Object obj = mSettings.getUserIdLPr(uid); 16970 if (obj instanceof SharedUserSetting) { 16971 final SharedUserSetting sus = (SharedUserSetting) obj; 16972 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16973 final Iterator<PackageSetting> it = sus.packages.iterator(); 16974 while (it.hasNext()) { 16975 final PackageSetting ps = it.next(); 16976 if (ps.pkg != null) { 16977 int v = ps.pkg.applicationInfo.targetSdkVersion; 16978 if (v < vers) vers = v; 16979 } 16980 } 16981 return vers; 16982 } else if (obj instanceof PackageSetting) { 16983 final PackageSetting ps = (PackageSetting) obj; 16984 if (ps.pkg != null) { 16985 return ps.pkg.applicationInfo.targetSdkVersion; 16986 } 16987 } 16988 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16989 } 16990 16991 @Override 16992 public void addPreferredActivity(IntentFilter filter, int match, 16993 ComponentName[] set, ComponentName activity, int userId) { 16994 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16995 "Adding preferred"); 16996 } 16997 16998 private void addPreferredActivityInternal(IntentFilter filter, int match, 16999 ComponentName[] set, ComponentName activity, boolean always, int userId, 17000 String opname) { 17001 // writer 17002 int callingUid = Binder.getCallingUid(); 17003 enforceCrossUserPermission(callingUid, userId, 17004 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17005 if (filter.countActions() == 0) { 17006 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17007 return; 17008 } 17009 synchronized (mPackages) { 17010 if (mContext.checkCallingOrSelfPermission( 17011 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17012 != PackageManager.PERMISSION_GRANTED) { 17013 if (getUidTargetSdkVersionLockedLPr(callingUid) 17014 < Build.VERSION_CODES.FROYO) { 17015 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17016 + callingUid); 17017 return; 17018 } 17019 mContext.enforceCallingOrSelfPermission( 17020 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17021 } 17022 17023 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17024 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17025 + userId + ":"); 17026 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17027 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17028 scheduleWritePackageRestrictionsLocked(userId); 17029 postPreferredActivityChangedBroadcast(userId); 17030 } 17031 } 17032 17033 private void postPreferredActivityChangedBroadcast(int userId) { 17034 mHandler.post(() -> { 17035 final IActivityManager am = ActivityManagerNative.getDefault(); 17036 if (am == null) { 17037 return; 17038 } 17039 17040 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17041 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17042 try { 17043 am.broadcastIntent(null, intent, null, null, 17044 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17045 null, false, false, userId); 17046 } catch (RemoteException e) { 17047 } 17048 }); 17049 } 17050 17051 @Override 17052 public void replacePreferredActivity(IntentFilter filter, int match, 17053 ComponentName[] set, ComponentName activity, int userId) { 17054 if (filter.countActions() != 1) { 17055 throw new IllegalArgumentException( 17056 "replacePreferredActivity expects filter to have only 1 action."); 17057 } 17058 if (filter.countDataAuthorities() != 0 17059 || filter.countDataPaths() != 0 17060 || filter.countDataSchemes() > 1 17061 || filter.countDataTypes() != 0) { 17062 throw new IllegalArgumentException( 17063 "replacePreferredActivity expects filter to have no data authorities, " + 17064 "paths, or types; and at most one scheme."); 17065 } 17066 17067 final int callingUid = Binder.getCallingUid(); 17068 enforceCrossUserPermission(callingUid, userId, 17069 true /* requireFullPermission */, false /* checkShell */, 17070 "replace preferred activity"); 17071 synchronized (mPackages) { 17072 if (mContext.checkCallingOrSelfPermission( 17073 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17074 != PackageManager.PERMISSION_GRANTED) { 17075 if (getUidTargetSdkVersionLockedLPr(callingUid) 17076 < Build.VERSION_CODES.FROYO) { 17077 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17078 + Binder.getCallingUid()); 17079 return; 17080 } 17081 mContext.enforceCallingOrSelfPermission( 17082 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17083 } 17084 17085 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17086 if (pir != null) { 17087 // Get all of the existing entries that exactly match this filter. 17088 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17089 if (existing != null && existing.size() == 1) { 17090 PreferredActivity cur = existing.get(0); 17091 if (DEBUG_PREFERRED) { 17092 Slog.i(TAG, "Checking replace of preferred:"); 17093 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17094 if (!cur.mPref.mAlways) { 17095 Slog.i(TAG, " -- CUR; not mAlways!"); 17096 } else { 17097 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17098 Slog.i(TAG, " -- CUR: mSet=" 17099 + Arrays.toString(cur.mPref.mSetComponents)); 17100 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17101 Slog.i(TAG, " -- NEW: mMatch=" 17102 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17103 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17104 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17105 } 17106 } 17107 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17108 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17109 && cur.mPref.sameSet(set)) { 17110 // Setting the preferred activity to what it happens to be already 17111 if (DEBUG_PREFERRED) { 17112 Slog.i(TAG, "Replacing with same preferred activity " 17113 + cur.mPref.mShortComponent + " for user " 17114 + userId + ":"); 17115 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17116 } 17117 return; 17118 } 17119 } 17120 17121 if (existing != null) { 17122 if (DEBUG_PREFERRED) { 17123 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17124 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17125 } 17126 for (int i = 0; i < existing.size(); i++) { 17127 PreferredActivity pa = existing.get(i); 17128 if (DEBUG_PREFERRED) { 17129 Slog.i(TAG, "Removing existing preferred activity " 17130 + pa.mPref.mComponent + ":"); 17131 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17132 } 17133 pir.removeFilter(pa); 17134 } 17135 } 17136 } 17137 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17138 "Replacing preferred"); 17139 } 17140 } 17141 17142 @Override 17143 public void clearPackagePreferredActivities(String packageName) { 17144 final int uid = Binder.getCallingUid(); 17145 // writer 17146 synchronized (mPackages) { 17147 PackageParser.Package pkg = mPackages.get(packageName); 17148 if (pkg == null || pkg.applicationInfo.uid != uid) { 17149 if (mContext.checkCallingOrSelfPermission( 17150 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17151 != PackageManager.PERMISSION_GRANTED) { 17152 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17153 < Build.VERSION_CODES.FROYO) { 17154 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17155 + Binder.getCallingUid()); 17156 return; 17157 } 17158 mContext.enforceCallingOrSelfPermission( 17159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17160 } 17161 } 17162 17163 int user = UserHandle.getCallingUserId(); 17164 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17165 scheduleWritePackageRestrictionsLocked(user); 17166 } 17167 } 17168 } 17169 17170 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17171 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17172 ArrayList<PreferredActivity> removed = null; 17173 boolean changed = false; 17174 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17175 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17176 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17177 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17178 continue; 17179 } 17180 Iterator<PreferredActivity> it = pir.filterIterator(); 17181 while (it.hasNext()) { 17182 PreferredActivity pa = it.next(); 17183 // Mark entry for removal only if it matches the package name 17184 // and the entry is of type "always". 17185 if (packageName == null || 17186 (pa.mPref.mComponent.getPackageName().equals(packageName) 17187 && pa.mPref.mAlways)) { 17188 if (removed == null) { 17189 removed = new ArrayList<PreferredActivity>(); 17190 } 17191 removed.add(pa); 17192 } 17193 } 17194 if (removed != null) { 17195 for (int j=0; j<removed.size(); j++) { 17196 PreferredActivity pa = removed.get(j); 17197 pir.removeFilter(pa); 17198 } 17199 changed = true; 17200 } 17201 } 17202 if (changed) { 17203 postPreferredActivityChangedBroadcast(userId); 17204 } 17205 return changed; 17206 } 17207 17208 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17209 private void clearIntentFilterVerificationsLPw(int userId) { 17210 final int packageCount = mPackages.size(); 17211 for (int i = 0; i < packageCount; i++) { 17212 PackageParser.Package pkg = mPackages.valueAt(i); 17213 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17214 } 17215 } 17216 17217 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17218 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17219 if (userId == UserHandle.USER_ALL) { 17220 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17221 sUserManager.getUserIds())) { 17222 for (int oneUserId : sUserManager.getUserIds()) { 17223 scheduleWritePackageRestrictionsLocked(oneUserId); 17224 } 17225 } 17226 } else { 17227 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17228 scheduleWritePackageRestrictionsLocked(userId); 17229 } 17230 } 17231 } 17232 17233 void clearDefaultBrowserIfNeeded(String packageName) { 17234 for (int oneUserId : sUserManager.getUserIds()) { 17235 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17236 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17237 if (packageName.equals(defaultBrowserPackageName)) { 17238 setDefaultBrowserPackageName(null, oneUserId); 17239 } 17240 } 17241 } 17242 17243 @Override 17244 public void resetApplicationPreferences(int userId) { 17245 mContext.enforceCallingOrSelfPermission( 17246 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17247 final long identity = Binder.clearCallingIdentity(); 17248 // writer 17249 try { 17250 synchronized (mPackages) { 17251 clearPackagePreferredActivitiesLPw(null, userId); 17252 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17253 // TODO: We have to reset the default SMS and Phone. This requires 17254 // significant refactoring to keep all default apps in the package 17255 // manager (cleaner but more work) or have the services provide 17256 // callbacks to the package manager to request a default app reset. 17257 applyFactoryDefaultBrowserLPw(userId); 17258 clearIntentFilterVerificationsLPw(userId); 17259 primeDomainVerificationsLPw(userId); 17260 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17261 scheduleWritePackageRestrictionsLocked(userId); 17262 } 17263 resetNetworkPolicies(userId); 17264 } finally { 17265 Binder.restoreCallingIdentity(identity); 17266 } 17267 } 17268 17269 @Override 17270 public int getPreferredActivities(List<IntentFilter> outFilters, 17271 List<ComponentName> outActivities, String packageName) { 17272 17273 int num = 0; 17274 final int userId = UserHandle.getCallingUserId(); 17275 // reader 17276 synchronized (mPackages) { 17277 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17278 if (pir != null) { 17279 final Iterator<PreferredActivity> it = pir.filterIterator(); 17280 while (it.hasNext()) { 17281 final PreferredActivity pa = it.next(); 17282 if (packageName == null 17283 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17284 && pa.mPref.mAlways)) { 17285 if (outFilters != null) { 17286 outFilters.add(new IntentFilter(pa)); 17287 } 17288 if (outActivities != null) { 17289 outActivities.add(pa.mPref.mComponent); 17290 } 17291 } 17292 } 17293 } 17294 } 17295 17296 return num; 17297 } 17298 17299 @Override 17300 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17301 int userId) { 17302 int callingUid = Binder.getCallingUid(); 17303 if (callingUid != Process.SYSTEM_UID) { 17304 throw new SecurityException( 17305 "addPersistentPreferredActivity can only be run by the system"); 17306 } 17307 if (filter.countActions() == 0) { 17308 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17309 return; 17310 } 17311 synchronized (mPackages) { 17312 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17313 ":"); 17314 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17315 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17316 new PersistentPreferredActivity(filter, activity)); 17317 scheduleWritePackageRestrictionsLocked(userId); 17318 postPreferredActivityChangedBroadcast(userId); 17319 } 17320 } 17321 17322 @Override 17323 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17324 int callingUid = Binder.getCallingUid(); 17325 if (callingUid != Process.SYSTEM_UID) { 17326 throw new SecurityException( 17327 "clearPackagePersistentPreferredActivities can only be run by the system"); 17328 } 17329 ArrayList<PersistentPreferredActivity> removed = null; 17330 boolean changed = false; 17331 synchronized (mPackages) { 17332 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17333 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17334 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17335 .valueAt(i); 17336 if (userId != thisUserId) { 17337 continue; 17338 } 17339 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17340 while (it.hasNext()) { 17341 PersistentPreferredActivity ppa = it.next(); 17342 // Mark entry for removal only if it matches the package name. 17343 if (ppa.mComponent.getPackageName().equals(packageName)) { 17344 if (removed == null) { 17345 removed = new ArrayList<PersistentPreferredActivity>(); 17346 } 17347 removed.add(ppa); 17348 } 17349 } 17350 if (removed != null) { 17351 for (int j=0; j<removed.size(); j++) { 17352 PersistentPreferredActivity ppa = removed.get(j); 17353 ppir.removeFilter(ppa); 17354 } 17355 changed = true; 17356 } 17357 } 17358 17359 if (changed) { 17360 scheduleWritePackageRestrictionsLocked(userId); 17361 postPreferredActivityChangedBroadcast(userId); 17362 } 17363 } 17364 } 17365 17366 /** 17367 * Common machinery for picking apart a restored XML blob and passing 17368 * it to a caller-supplied functor to be applied to the running system. 17369 */ 17370 private void restoreFromXml(XmlPullParser parser, int userId, 17371 String expectedStartTag, BlobXmlRestorer functor) 17372 throws IOException, XmlPullParserException { 17373 int type; 17374 while ((type = parser.next()) != XmlPullParser.START_TAG 17375 && type != XmlPullParser.END_DOCUMENT) { 17376 } 17377 if (type != XmlPullParser.START_TAG) { 17378 // oops didn't find a start tag?! 17379 if (DEBUG_BACKUP) { 17380 Slog.e(TAG, "Didn't find start tag during restore"); 17381 } 17382 return; 17383 } 17384Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17385 // this is supposed to be TAG_PREFERRED_BACKUP 17386 if (!expectedStartTag.equals(parser.getName())) { 17387 if (DEBUG_BACKUP) { 17388 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17389 } 17390 return; 17391 } 17392 17393 // skip interfering stuff, then we're aligned with the backing implementation 17394 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17395Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17396 functor.apply(parser, userId); 17397 } 17398 17399 private interface BlobXmlRestorer { 17400 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17401 } 17402 17403 /** 17404 * Non-Binder method, support for the backup/restore mechanism: write the 17405 * full set of preferred activities in its canonical XML format. Returns the 17406 * XML output as a byte array, or null if there is none. 17407 */ 17408 @Override 17409 public byte[] getPreferredActivityBackup(int userId) { 17410 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17411 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17412 } 17413 17414 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17415 try { 17416 final XmlSerializer serializer = new FastXmlSerializer(); 17417 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17418 serializer.startDocument(null, true); 17419 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17420 17421 synchronized (mPackages) { 17422 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17423 } 17424 17425 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17426 serializer.endDocument(); 17427 serializer.flush(); 17428 } catch (Exception e) { 17429 if (DEBUG_BACKUP) { 17430 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17431 } 17432 return null; 17433 } 17434 17435 return dataStream.toByteArray(); 17436 } 17437 17438 @Override 17439 public void restorePreferredActivities(byte[] backup, int userId) { 17440 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17441 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17442 } 17443 17444 try { 17445 final XmlPullParser parser = Xml.newPullParser(); 17446 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17447 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17448 new BlobXmlRestorer() { 17449 @Override 17450 public void apply(XmlPullParser parser, int userId) 17451 throws XmlPullParserException, IOException { 17452 synchronized (mPackages) { 17453 mSettings.readPreferredActivitiesLPw(parser, userId); 17454 } 17455 } 17456 } ); 17457 } catch (Exception e) { 17458 if (DEBUG_BACKUP) { 17459 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17460 } 17461 } 17462 } 17463 17464 /** 17465 * Non-Binder method, support for the backup/restore mechanism: write the 17466 * default browser (etc) settings in its canonical XML format. Returns the default 17467 * browser XML representation as a byte array, or null if there is none. 17468 */ 17469 @Override 17470 public byte[] getDefaultAppsBackup(int userId) { 17471 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17472 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17473 } 17474 17475 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17476 try { 17477 final XmlSerializer serializer = new FastXmlSerializer(); 17478 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17479 serializer.startDocument(null, true); 17480 serializer.startTag(null, TAG_DEFAULT_APPS); 17481 17482 synchronized (mPackages) { 17483 mSettings.writeDefaultAppsLPr(serializer, userId); 17484 } 17485 17486 serializer.endTag(null, TAG_DEFAULT_APPS); 17487 serializer.endDocument(); 17488 serializer.flush(); 17489 } catch (Exception e) { 17490 if (DEBUG_BACKUP) { 17491 Slog.e(TAG, "Unable to write default apps for backup", e); 17492 } 17493 return null; 17494 } 17495 17496 return dataStream.toByteArray(); 17497 } 17498 17499 @Override 17500 public void restoreDefaultApps(byte[] backup, int userId) { 17501 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17502 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17503 } 17504 17505 try { 17506 final XmlPullParser parser = Xml.newPullParser(); 17507 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17508 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17509 new BlobXmlRestorer() { 17510 @Override 17511 public void apply(XmlPullParser parser, int userId) 17512 throws XmlPullParserException, IOException { 17513 synchronized (mPackages) { 17514 mSettings.readDefaultAppsLPw(parser, userId); 17515 } 17516 } 17517 } ); 17518 } catch (Exception e) { 17519 if (DEBUG_BACKUP) { 17520 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17521 } 17522 } 17523 } 17524 17525 @Override 17526 public byte[] getIntentFilterVerificationBackup(int userId) { 17527 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17528 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17529 } 17530 17531 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17532 try { 17533 final XmlSerializer serializer = new FastXmlSerializer(); 17534 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17535 serializer.startDocument(null, true); 17536 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17537 17538 synchronized (mPackages) { 17539 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17540 } 17541 17542 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17543 serializer.endDocument(); 17544 serializer.flush(); 17545 } catch (Exception e) { 17546 if (DEBUG_BACKUP) { 17547 Slog.e(TAG, "Unable to write default apps for backup", e); 17548 } 17549 return null; 17550 } 17551 17552 return dataStream.toByteArray(); 17553 } 17554 17555 @Override 17556 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17557 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17558 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17559 } 17560 17561 try { 17562 final XmlPullParser parser = Xml.newPullParser(); 17563 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17564 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17565 new BlobXmlRestorer() { 17566 @Override 17567 public void apply(XmlPullParser parser, int userId) 17568 throws XmlPullParserException, IOException { 17569 synchronized (mPackages) { 17570 mSettings.readAllDomainVerificationsLPr(parser, userId); 17571 mSettings.writeLPr(); 17572 } 17573 } 17574 } ); 17575 } catch (Exception e) { 17576 if (DEBUG_BACKUP) { 17577 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17578 } 17579 } 17580 } 17581 17582 @Override 17583 public byte[] getPermissionGrantBackup(int userId) { 17584 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17585 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17586 } 17587 17588 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17589 try { 17590 final XmlSerializer serializer = new FastXmlSerializer(); 17591 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17592 serializer.startDocument(null, true); 17593 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17594 17595 synchronized (mPackages) { 17596 serializeRuntimePermissionGrantsLPr(serializer, userId); 17597 } 17598 17599 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17600 serializer.endDocument(); 17601 serializer.flush(); 17602 } catch (Exception e) { 17603 if (DEBUG_BACKUP) { 17604 Slog.e(TAG, "Unable to write default apps for backup", e); 17605 } 17606 return null; 17607 } 17608 17609 return dataStream.toByteArray(); 17610 } 17611 17612 @Override 17613 public void restorePermissionGrants(byte[] backup, int userId) { 17614 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17615 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17616 } 17617 17618 try { 17619 final XmlPullParser parser = Xml.newPullParser(); 17620 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17621 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17622 new BlobXmlRestorer() { 17623 @Override 17624 public void apply(XmlPullParser parser, int userId) 17625 throws XmlPullParserException, IOException { 17626 synchronized (mPackages) { 17627 processRestoredPermissionGrantsLPr(parser, userId); 17628 } 17629 } 17630 } ); 17631 } catch (Exception e) { 17632 if (DEBUG_BACKUP) { 17633 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17634 } 17635 } 17636 } 17637 17638 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17639 throws IOException { 17640 serializer.startTag(null, TAG_ALL_GRANTS); 17641 17642 final int N = mSettings.mPackages.size(); 17643 for (int i = 0; i < N; i++) { 17644 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17645 boolean pkgGrantsKnown = false; 17646 17647 PermissionsState packagePerms = ps.getPermissionsState(); 17648 17649 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17650 final int grantFlags = state.getFlags(); 17651 // only look at grants that are not system/policy fixed 17652 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17653 final boolean isGranted = state.isGranted(); 17654 // And only back up the user-twiddled state bits 17655 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17656 final String packageName = mSettings.mPackages.keyAt(i); 17657 if (!pkgGrantsKnown) { 17658 serializer.startTag(null, TAG_GRANT); 17659 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17660 pkgGrantsKnown = true; 17661 } 17662 17663 final boolean userSet = 17664 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17665 final boolean userFixed = 17666 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17667 final boolean revoke = 17668 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17669 17670 serializer.startTag(null, TAG_PERMISSION); 17671 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17672 if (isGranted) { 17673 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17674 } 17675 if (userSet) { 17676 serializer.attribute(null, ATTR_USER_SET, "true"); 17677 } 17678 if (userFixed) { 17679 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17680 } 17681 if (revoke) { 17682 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17683 } 17684 serializer.endTag(null, TAG_PERMISSION); 17685 } 17686 } 17687 } 17688 17689 if (pkgGrantsKnown) { 17690 serializer.endTag(null, TAG_GRANT); 17691 } 17692 } 17693 17694 serializer.endTag(null, TAG_ALL_GRANTS); 17695 } 17696 17697 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17698 throws XmlPullParserException, IOException { 17699 String pkgName = null; 17700 int outerDepth = parser.getDepth(); 17701 int type; 17702 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17703 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17704 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17705 continue; 17706 } 17707 17708 final String tagName = parser.getName(); 17709 if (tagName.equals(TAG_GRANT)) { 17710 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17711 if (DEBUG_BACKUP) { 17712 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17713 } 17714 } else if (tagName.equals(TAG_PERMISSION)) { 17715 17716 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17717 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17718 17719 int newFlagSet = 0; 17720 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17721 newFlagSet |= FLAG_PERMISSION_USER_SET; 17722 } 17723 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17724 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17725 } 17726 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17727 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17728 } 17729 if (DEBUG_BACKUP) { 17730 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17731 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17732 } 17733 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17734 if (ps != null) { 17735 // Already installed so we apply the grant immediately 17736 if (DEBUG_BACKUP) { 17737 Slog.v(TAG, " + already installed; applying"); 17738 } 17739 PermissionsState perms = ps.getPermissionsState(); 17740 BasePermission bp = mSettings.mPermissions.get(permName); 17741 if (bp != null) { 17742 if (isGranted) { 17743 perms.grantRuntimePermission(bp, userId); 17744 } 17745 if (newFlagSet != 0) { 17746 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17747 } 17748 } 17749 } else { 17750 // Need to wait for post-restore install to apply the grant 17751 if (DEBUG_BACKUP) { 17752 Slog.v(TAG, " - not yet installed; saving for later"); 17753 } 17754 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17755 isGranted, newFlagSet, userId); 17756 } 17757 } else { 17758 PackageManagerService.reportSettingsProblem(Log.WARN, 17759 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17760 XmlUtils.skipCurrentTag(parser); 17761 } 17762 } 17763 17764 scheduleWriteSettingsLocked(); 17765 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17766 } 17767 17768 @Override 17769 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17770 int sourceUserId, int targetUserId, int flags) { 17771 mContext.enforceCallingOrSelfPermission( 17772 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17773 int callingUid = Binder.getCallingUid(); 17774 enforceOwnerRights(ownerPackage, callingUid); 17775 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17776 if (intentFilter.countActions() == 0) { 17777 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17778 return; 17779 } 17780 synchronized (mPackages) { 17781 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17782 ownerPackage, targetUserId, flags); 17783 CrossProfileIntentResolver resolver = 17784 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17785 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17786 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17787 if (existing != null) { 17788 int size = existing.size(); 17789 for (int i = 0; i < size; i++) { 17790 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17791 return; 17792 } 17793 } 17794 } 17795 resolver.addFilter(newFilter); 17796 scheduleWritePackageRestrictionsLocked(sourceUserId); 17797 } 17798 } 17799 17800 @Override 17801 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17802 mContext.enforceCallingOrSelfPermission( 17803 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17804 int callingUid = Binder.getCallingUid(); 17805 enforceOwnerRights(ownerPackage, callingUid); 17806 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17807 synchronized (mPackages) { 17808 CrossProfileIntentResolver resolver = 17809 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17810 ArraySet<CrossProfileIntentFilter> set = 17811 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17812 for (CrossProfileIntentFilter filter : set) { 17813 if (filter.getOwnerPackage().equals(ownerPackage)) { 17814 resolver.removeFilter(filter); 17815 } 17816 } 17817 scheduleWritePackageRestrictionsLocked(sourceUserId); 17818 } 17819 } 17820 17821 // Enforcing that callingUid is owning pkg on userId 17822 private void enforceOwnerRights(String pkg, int callingUid) { 17823 // The system owns everything. 17824 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17825 return; 17826 } 17827 int callingUserId = UserHandle.getUserId(callingUid); 17828 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17829 if (pi == null) { 17830 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17831 + callingUserId); 17832 } 17833 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17834 throw new SecurityException("Calling uid " + callingUid 17835 + " does not own package " + pkg); 17836 } 17837 } 17838 17839 @Override 17840 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17841 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17842 } 17843 17844 private Intent getHomeIntent() { 17845 Intent intent = new Intent(Intent.ACTION_MAIN); 17846 intent.addCategory(Intent.CATEGORY_HOME); 17847 intent.addCategory(Intent.CATEGORY_DEFAULT); 17848 return intent; 17849 } 17850 17851 private IntentFilter getHomeFilter() { 17852 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17853 filter.addCategory(Intent.CATEGORY_HOME); 17854 filter.addCategory(Intent.CATEGORY_DEFAULT); 17855 return filter; 17856 } 17857 17858 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17859 int userId) { 17860 Intent intent = getHomeIntent(); 17861 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17862 PackageManager.GET_META_DATA, userId); 17863 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17864 true, false, false, userId); 17865 17866 allHomeCandidates.clear(); 17867 if (list != null) { 17868 for (ResolveInfo ri : list) { 17869 allHomeCandidates.add(ri); 17870 } 17871 } 17872 return (preferred == null || preferred.activityInfo == null) 17873 ? null 17874 : new ComponentName(preferred.activityInfo.packageName, 17875 preferred.activityInfo.name); 17876 } 17877 17878 @Override 17879 public void setHomeActivity(ComponentName comp, int userId) { 17880 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17881 getHomeActivitiesAsUser(homeActivities, userId); 17882 17883 boolean found = false; 17884 17885 final int size = homeActivities.size(); 17886 final ComponentName[] set = new ComponentName[size]; 17887 for (int i = 0; i < size; i++) { 17888 final ResolveInfo candidate = homeActivities.get(i); 17889 final ActivityInfo info = candidate.activityInfo; 17890 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17891 set[i] = activityName; 17892 if (!found && activityName.equals(comp)) { 17893 found = true; 17894 } 17895 } 17896 if (!found) { 17897 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17898 + userId); 17899 } 17900 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17901 set, comp, userId); 17902 } 17903 17904 private @Nullable String getSetupWizardPackageName() { 17905 final Intent intent = new Intent(Intent.ACTION_MAIN); 17906 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17907 17908 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17909 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17910 | MATCH_DISABLED_COMPONENTS, 17911 UserHandle.myUserId()); 17912 if (matches.size() == 1) { 17913 return matches.get(0).getComponentInfo().packageName; 17914 } else { 17915 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17916 + ": matches=" + matches); 17917 return null; 17918 } 17919 } 17920 17921 private @Nullable String getStorageManagerPackageName() { 17922 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17923 17924 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17925 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17926 | MATCH_DISABLED_COMPONENTS, 17927 UserHandle.myUserId()); 17928 if (matches.size() == 1) { 17929 return matches.get(0).getComponentInfo().packageName; 17930 } else { 17931 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17932 + matches.size() + ": matches=" + matches); 17933 return null; 17934 } 17935 } 17936 17937 @Override 17938 public void setApplicationEnabledSetting(String appPackageName, 17939 int newState, int flags, int userId, String callingPackage) { 17940 if (!sUserManager.exists(userId)) return; 17941 if (callingPackage == null) { 17942 callingPackage = Integer.toString(Binder.getCallingUid()); 17943 } 17944 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17945 } 17946 17947 @Override 17948 public void setComponentEnabledSetting(ComponentName componentName, 17949 int newState, int flags, int userId) { 17950 if (!sUserManager.exists(userId)) return; 17951 setEnabledSetting(componentName.getPackageName(), 17952 componentName.getClassName(), newState, flags, userId, null); 17953 } 17954 17955 private void setEnabledSetting(final String packageName, String className, int newState, 17956 final int flags, int userId, String callingPackage) { 17957 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17958 || newState == COMPONENT_ENABLED_STATE_ENABLED 17959 || newState == COMPONENT_ENABLED_STATE_DISABLED 17960 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17961 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17962 throw new IllegalArgumentException("Invalid new component state: " 17963 + newState); 17964 } 17965 PackageSetting pkgSetting; 17966 final int uid = Binder.getCallingUid(); 17967 final int permission; 17968 if (uid == Process.SYSTEM_UID) { 17969 permission = PackageManager.PERMISSION_GRANTED; 17970 } else { 17971 permission = mContext.checkCallingOrSelfPermission( 17972 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17973 } 17974 enforceCrossUserPermission(uid, userId, 17975 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17976 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17977 boolean sendNow = false; 17978 boolean isApp = (className == null); 17979 String componentName = isApp ? packageName : className; 17980 int packageUid = -1; 17981 ArrayList<String> components; 17982 17983 // writer 17984 synchronized (mPackages) { 17985 pkgSetting = mSettings.mPackages.get(packageName); 17986 if (pkgSetting == null) { 17987 if (className == null) { 17988 throw new IllegalArgumentException("Unknown package: " + packageName); 17989 } 17990 throw new IllegalArgumentException( 17991 "Unknown component: " + packageName + "/" + className); 17992 } 17993 } 17994 17995 // Limit who can change which apps 17996 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17997 // Don't allow apps that don't have permission to modify other apps 17998 if (!allowedByPermission) { 17999 throw new SecurityException( 18000 "Permission Denial: attempt to change component state from pid=" 18001 + Binder.getCallingPid() 18002 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18003 } 18004 // Don't allow changing protected packages. 18005 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18006 throw new SecurityException("Cannot disable a protected package: " + packageName); 18007 } 18008 } 18009 18010 synchronized (mPackages) { 18011 if (uid == Process.SHELL_UID) { 18012 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18013 int oldState = pkgSetting.getEnabled(userId); 18014 if (className == null 18015 && 18016 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18017 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18018 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18019 && 18020 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18021 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18022 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18023 // ok 18024 } else { 18025 throw new SecurityException( 18026 "Shell cannot change component state for " + packageName + "/" 18027 + className + " to " + newState); 18028 } 18029 } 18030 if (className == null) { 18031 // We're dealing with an application/package level state change 18032 if (pkgSetting.getEnabled(userId) == newState) { 18033 // Nothing to do 18034 return; 18035 } 18036 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18037 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18038 // Don't care about who enables an app. 18039 callingPackage = null; 18040 } 18041 pkgSetting.setEnabled(newState, userId, callingPackage); 18042 // pkgSetting.pkg.mSetEnabled = newState; 18043 } else { 18044 // We're dealing with a component level state change 18045 // First, verify that this is a valid class name. 18046 PackageParser.Package pkg = pkgSetting.pkg; 18047 if (pkg == null || !pkg.hasComponentClassName(className)) { 18048 if (pkg != null && 18049 pkg.applicationInfo.targetSdkVersion >= 18050 Build.VERSION_CODES.JELLY_BEAN) { 18051 throw new IllegalArgumentException("Component class " + className 18052 + " does not exist in " + packageName); 18053 } else { 18054 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18055 + className + " does not exist in " + packageName); 18056 } 18057 } 18058 switch (newState) { 18059 case COMPONENT_ENABLED_STATE_ENABLED: 18060 if (!pkgSetting.enableComponentLPw(className, userId)) { 18061 return; 18062 } 18063 break; 18064 case COMPONENT_ENABLED_STATE_DISABLED: 18065 if (!pkgSetting.disableComponentLPw(className, userId)) { 18066 return; 18067 } 18068 break; 18069 case COMPONENT_ENABLED_STATE_DEFAULT: 18070 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18071 return; 18072 } 18073 break; 18074 default: 18075 Slog.e(TAG, "Invalid new component state: " + newState); 18076 return; 18077 } 18078 } 18079 scheduleWritePackageRestrictionsLocked(userId); 18080 components = mPendingBroadcasts.get(userId, packageName); 18081 final boolean newPackage = components == null; 18082 if (newPackage) { 18083 components = new ArrayList<String>(); 18084 } 18085 if (!components.contains(componentName)) { 18086 components.add(componentName); 18087 } 18088 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18089 sendNow = true; 18090 // Purge entry from pending broadcast list if another one exists already 18091 // since we are sending one right away. 18092 mPendingBroadcasts.remove(userId, packageName); 18093 } else { 18094 if (newPackage) { 18095 mPendingBroadcasts.put(userId, packageName, components); 18096 } 18097 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18098 // Schedule a message 18099 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18100 } 18101 } 18102 } 18103 18104 long callingId = Binder.clearCallingIdentity(); 18105 try { 18106 if (sendNow) { 18107 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18108 sendPackageChangedBroadcast(packageName, 18109 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18110 } 18111 } finally { 18112 Binder.restoreCallingIdentity(callingId); 18113 } 18114 } 18115 18116 @Override 18117 public void flushPackageRestrictionsAsUser(int userId) { 18118 if (!sUserManager.exists(userId)) { 18119 return; 18120 } 18121 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18122 false /* checkShell */, "flushPackageRestrictions"); 18123 synchronized (mPackages) { 18124 mSettings.writePackageRestrictionsLPr(userId); 18125 mDirtyUsers.remove(userId); 18126 if (mDirtyUsers.isEmpty()) { 18127 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18128 } 18129 } 18130 } 18131 18132 private void sendPackageChangedBroadcast(String packageName, 18133 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18134 if (DEBUG_INSTALL) 18135 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18136 + componentNames); 18137 Bundle extras = new Bundle(4); 18138 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18139 String nameList[] = new String[componentNames.size()]; 18140 componentNames.toArray(nameList); 18141 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18142 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18143 extras.putInt(Intent.EXTRA_UID, packageUid); 18144 // If this is not reporting a change of the overall package, then only send it 18145 // to registered receivers. We don't want to launch a swath of apps for every 18146 // little component state change. 18147 final int flags = !componentNames.contains(packageName) 18148 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18149 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18150 new int[] {UserHandle.getUserId(packageUid)}); 18151 } 18152 18153 @Override 18154 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18155 if (!sUserManager.exists(userId)) return; 18156 final int uid = Binder.getCallingUid(); 18157 final int permission = mContext.checkCallingOrSelfPermission( 18158 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18159 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18160 enforceCrossUserPermission(uid, userId, 18161 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18162 // writer 18163 synchronized (mPackages) { 18164 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18165 allowedByPermission, uid, userId)) { 18166 scheduleWritePackageRestrictionsLocked(userId); 18167 } 18168 } 18169 } 18170 18171 @Override 18172 public String getInstallerPackageName(String packageName) { 18173 // reader 18174 synchronized (mPackages) { 18175 return mSettings.getInstallerPackageNameLPr(packageName); 18176 } 18177 } 18178 18179 public boolean isOrphaned(String packageName) { 18180 // reader 18181 synchronized (mPackages) { 18182 return mSettings.isOrphaned(packageName); 18183 } 18184 } 18185 18186 @Override 18187 public int getApplicationEnabledSetting(String packageName, int userId) { 18188 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18189 int uid = Binder.getCallingUid(); 18190 enforceCrossUserPermission(uid, userId, 18191 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18192 // reader 18193 synchronized (mPackages) { 18194 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18195 } 18196 } 18197 18198 @Override 18199 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18200 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18201 int uid = Binder.getCallingUid(); 18202 enforceCrossUserPermission(uid, userId, 18203 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18204 // reader 18205 synchronized (mPackages) { 18206 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18207 } 18208 } 18209 18210 @Override 18211 public void enterSafeMode() { 18212 enforceSystemOrRoot("Only the system can request entering safe mode"); 18213 18214 if (!mSystemReady) { 18215 mSafeMode = true; 18216 } 18217 } 18218 18219 @Override 18220 public void systemReady() { 18221 mSystemReady = true; 18222 18223 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18224 // disabled after already being started. 18225 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18226 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18227 18228 // Read the compatibilty setting when the system is ready. 18229 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18230 mContext.getContentResolver(), 18231 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18232 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18233 if (DEBUG_SETTINGS) { 18234 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18235 } 18236 18237 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18238 18239 synchronized (mPackages) { 18240 // Verify that all of the preferred activity components actually 18241 // exist. It is possible for applications to be updated and at 18242 // that point remove a previously declared activity component that 18243 // had been set as a preferred activity. We try to clean this up 18244 // the next time we encounter that preferred activity, but it is 18245 // possible for the user flow to never be able to return to that 18246 // situation so here we do a sanity check to make sure we haven't 18247 // left any junk around. 18248 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18249 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18250 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18251 removed.clear(); 18252 for (PreferredActivity pa : pir.filterSet()) { 18253 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18254 removed.add(pa); 18255 } 18256 } 18257 if (removed.size() > 0) { 18258 for (int r=0; r<removed.size(); r++) { 18259 PreferredActivity pa = removed.get(r); 18260 Slog.w(TAG, "Removing dangling preferred activity: " 18261 + pa.mPref.mComponent); 18262 pir.removeFilter(pa); 18263 } 18264 mSettings.writePackageRestrictionsLPr( 18265 mSettings.mPreferredActivities.keyAt(i)); 18266 } 18267 } 18268 18269 for (int userId : UserManagerService.getInstance().getUserIds()) { 18270 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18271 grantPermissionsUserIds = ArrayUtils.appendInt( 18272 grantPermissionsUserIds, userId); 18273 } 18274 } 18275 } 18276 sUserManager.systemReady(); 18277 18278 // If we upgraded grant all default permissions before kicking off. 18279 for (int userId : grantPermissionsUserIds) { 18280 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18281 } 18282 18283 // If we did not grant default permissions, we preload from this the 18284 // default permission exceptions lazily to ensure we don't hit the 18285 // disk on a new user creation. 18286 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18287 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18288 } 18289 18290 // Kick off any messages waiting for system ready 18291 if (mPostSystemReadyMessages != null) { 18292 for (Message msg : mPostSystemReadyMessages) { 18293 msg.sendToTarget(); 18294 } 18295 mPostSystemReadyMessages = null; 18296 } 18297 18298 // Watch for external volumes that come and go over time 18299 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18300 storage.registerListener(mStorageListener); 18301 18302 mInstallerService.systemReady(); 18303 mPackageDexOptimizer.systemReady(); 18304 18305 MountServiceInternal mountServiceInternal = LocalServices.getService( 18306 MountServiceInternal.class); 18307 mountServiceInternal.addExternalStoragePolicy( 18308 new MountServiceInternal.ExternalStorageMountPolicy() { 18309 @Override 18310 public int getMountMode(int uid, String packageName) { 18311 if (Process.isIsolated(uid)) { 18312 return Zygote.MOUNT_EXTERNAL_NONE; 18313 } 18314 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18315 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18316 } 18317 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18318 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18319 } 18320 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18321 return Zygote.MOUNT_EXTERNAL_READ; 18322 } 18323 return Zygote.MOUNT_EXTERNAL_WRITE; 18324 } 18325 18326 @Override 18327 public boolean hasExternalStorage(int uid, String packageName) { 18328 return true; 18329 } 18330 }); 18331 18332 // Now that we're mostly running, clean up stale users and apps 18333 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18334 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18335 } 18336 18337 @Override 18338 public boolean isSafeMode() { 18339 return mSafeMode; 18340 } 18341 18342 @Override 18343 public boolean hasSystemUidErrors() { 18344 return mHasSystemUidErrors; 18345 } 18346 18347 static String arrayToString(int[] array) { 18348 StringBuffer buf = new StringBuffer(128); 18349 buf.append('['); 18350 if (array != null) { 18351 for (int i=0; i<array.length; i++) { 18352 if (i > 0) buf.append(", "); 18353 buf.append(array[i]); 18354 } 18355 } 18356 buf.append(']'); 18357 return buf.toString(); 18358 } 18359 18360 static class DumpState { 18361 public static final int DUMP_LIBS = 1 << 0; 18362 public static final int DUMP_FEATURES = 1 << 1; 18363 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18364 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18365 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18366 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18367 public static final int DUMP_PERMISSIONS = 1 << 6; 18368 public static final int DUMP_PACKAGES = 1 << 7; 18369 public static final int DUMP_SHARED_USERS = 1 << 8; 18370 public static final int DUMP_MESSAGES = 1 << 9; 18371 public static final int DUMP_PROVIDERS = 1 << 10; 18372 public static final int DUMP_VERIFIERS = 1 << 11; 18373 public static final int DUMP_PREFERRED = 1 << 12; 18374 public static final int DUMP_PREFERRED_XML = 1 << 13; 18375 public static final int DUMP_KEYSETS = 1 << 14; 18376 public static final int DUMP_VERSION = 1 << 15; 18377 public static final int DUMP_INSTALLS = 1 << 16; 18378 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18379 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18380 public static final int DUMP_FROZEN = 1 << 19; 18381 public static final int DUMP_DEXOPT = 1 << 20; 18382 public static final int DUMP_COMPILER_STATS = 1 << 21; 18383 18384 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18385 18386 private int mTypes; 18387 18388 private int mOptions; 18389 18390 private boolean mTitlePrinted; 18391 18392 private SharedUserSetting mSharedUser; 18393 18394 public boolean isDumping(int type) { 18395 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18396 return true; 18397 } 18398 18399 return (mTypes & type) != 0; 18400 } 18401 18402 public void setDump(int type) { 18403 mTypes |= type; 18404 } 18405 18406 public boolean isOptionEnabled(int option) { 18407 return (mOptions & option) != 0; 18408 } 18409 18410 public void setOptionEnabled(int option) { 18411 mOptions |= option; 18412 } 18413 18414 public boolean onTitlePrinted() { 18415 final boolean printed = mTitlePrinted; 18416 mTitlePrinted = true; 18417 return printed; 18418 } 18419 18420 public boolean getTitlePrinted() { 18421 return mTitlePrinted; 18422 } 18423 18424 public void setTitlePrinted(boolean enabled) { 18425 mTitlePrinted = enabled; 18426 } 18427 18428 public SharedUserSetting getSharedUser() { 18429 return mSharedUser; 18430 } 18431 18432 public void setSharedUser(SharedUserSetting user) { 18433 mSharedUser = user; 18434 } 18435 } 18436 18437 @Override 18438 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18439 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18440 (new PackageManagerShellCommand(this)).exec( 18441 this, in, out, err, args, resultReceiver); 18442 } 18443 18444 @Override 18445 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18446 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18447 != PackageManager.PERMISSION_GRANTED) { 18448 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18449 + Binder.getCallingPid() 18450 + ", uid=" + Binder.getCallingUid() 18451 + " without permission " 18452 + android.Manifest.permission.DUMP); 18453 return; 18454 } 18455 18456 DumpState dumpState = new DumpState(); 18457 boolean fullPreferred = false; 18458 boolean checkin = false; 18459 18460 String packageName = null; 18461 ArraySet<String> permissionNames = null; 18462 18463 int opti = 0; 18464 while (opti < args.length) { 18465 String opt = args[opti]; 18466 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18467 break; 18468 } 18469 opti++; 18470 18471 if ("-a".equals(opt)) { 18472 // Right now we only know how to print all. 18473 } else if ("-h".equals(opt)) { 18474 pw.println("Package manager dump options:"); 18475 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18476 pw.println(" --checkin: dump for a checkin"); 18477 pw.println(" -f: print details of intent filters"); 18478 pw.println(" -h: print this help"); 18479 pw.println(" cmd may be one of:"); 18480 pw.println(" l[ibraries]: list known shared libraries"); 18481 pw.println(" f[eatures]: list device features"); 18482 pw.println(" k[eysets]: print known keysets"); 18483 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18484 pw.println(" perm[issions]: dump permissions"); 18485 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18486 pw.println(" pref[erred]: print preferred package settings"); 18487 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18488 pw.println(" prov[iders]: dump content providers"); 18489 pw.println(" p[ackages]: dump installed packages"); 18490 pw.println(" s[hared-users]: dump shared user IDs"); 18491 pw.println(" m[essages]: print collected runtime messages"); 18492 pw.println(" v[erifiers]: print package verifier info"); 18493 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18494 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18495 pw.println(" version: print database version info"); 18496 pw.println(" write: write current settings now"); 18497 pw.println(" installs: details about install sessions"); 18498 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18499 pw.println(" dexopt: dump dexopt state"); 18500 pw.println(" compiler-stats: dump compiler statistics"); 18501 pw.println(" <package.name>: info about given package"); 18502 return; 18503 } else if ("--checkin".equals(opt)) { 18504 checkin = true; 18505 } else if ("-f".equals(opt)) { 18506 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18507 } else { 18508 pw.println("Unknown argument: " + opt + "; use -h for help"); 18509 } 18510 } 18511 18512 // Is the caller requesting to dump a particular piece of data? 18513 if (opti < args.length) { 18514 String cmd = args[opti]; 18515 opti++; 18516 // Is this a package name? 18517 if ("android".equals(cmd) || cmd.contains(".")) { 18518 packageName = cmd; 18519 // When dumping a single package, we always dump all of its 18520 // filter information since the amount of data will be reasonable. 18521 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18522 } else if ("check-permission".equals(cmd)) { 18523 if (opti >= args.length) { 18524 pw.println("Error: check-permission missing permission argument"); 18525 return; 18526 } 18527 String perm = args[opti]; 18528 opti++; 18529 if (opti >= args.length) { 18530 pw.println("Error: check-permission missing package argument"); 18531 return; 18532 } 18533 String pkg = args[opti]; 18534 opti++; 18535 int user = UserHandle.getUserId(Binder.getCallingUid()); 18536 if (opti < args.length) { 18537 try { 18538 user = Integer.parseInt(args[opti]); 18539 } catch (NumberFormatException e) { 18540 pw.println("Error: check-permission user argument is not a number: " 18541 + args[opti]); 18542 return; 18543 } 18544 } 18545 pw.println(checkPermission(perm, pkg, user)); 18546 return; 18547 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18548 dumpState.setDump(DumpState.DUMP_LIBS); 18549 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18550 dumpState.setDump(DumpState.DUMP_FEATURES); 18551 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18552 if (opti >= args.length) { 18553 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18554 | DumpState.DUMP_SERVICE_RESOLVERS 18555 | DumpState.DUMP_RECEIVER_RESOLVERS 18556 | DumpState.DUMP_CONTENT_RESOLVERS); 18557 } else { 18558 while (opti < args.length) { 18559 String name = args[opti]; 18560 if ("a".equals(name) || "activity".equals(name)) { 18561 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18562 } else if ("s".equals(name) || "service".equals(name)) { 18563 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18564 } else if ("r".equals(name) || "receiver".equals(name)) { 18565 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18566 } else if ("c".equals(name) || "content".equals(name)) { 18567 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18568 } else { 18569 pw.println("Error: unknown resolver table type: " + name); 18570 return; 18571 } 18572 opti++; 18573 } 18574 } 18575 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18576 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18577 } else if ("permission".equals(cmd)) { 18578 if (opti >= args.length) { 18579 pw.println("Error: permission requires permission name"); 18580 return; 18581 } 18582 permissionNames = new ArraySet<>(); 18583 while (opti < args.length) { 18584 permissionNames.add(args[opti]); 18585 opti++; 18586 } 18587 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18588 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18589 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18590 dumpState.setDump(DumpState.DUMP_PREFERRED); 18591 } else if ("preferred-xml".equals(cmd)) { 18592 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18593 if (opti < args.length && "--full".equals(args[opti])) { 18594 fullPreferred = true; 18595 opti++; 18596 } 18597 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18598 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18599 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18600 dumpState.setDump(DumpState.DUMP_PACKAGES); 18601 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18602 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18603 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18604 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18605 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18606 dumpState.setDump(DumpState.DUMP_MESSAGES); 18607 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18608 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18609 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18610 || "intent-filter-verifiers".equals(cmd)) { 18611 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18612 } else if ("version".equals(cmd)) { 18613 dumpState.setDump(DumpState.DUMP_VERSION); 18614 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18615 dumpState.setDump(DumpState.DUMP_KEYSETS); 18616 } else if ("installs".equals(cmd)) { 18617 dumpState.setDump(DumpState.DUMP_INSTALLS); 18618 } else if ("frozen".equals(cmd)) { 18619 dumpState.setDump(DumpState.DUMP_FROZEN); 18620 } else if ("dexopt".equals(cmd)) { 18621 dumpState.setDump(DumpState.DUMP_DEXOPT); 18622 } else if ("compiler-stats".equals(cmd)) { 18623 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18624 } else if ("write".equals(cmd)) { 18625 synchronized (mPackages) { 18626 mSettings.writeLPr(); 18627 pw.println("Settings written."); 18628 return; 18629 } 18630 } 18631 } 18632 18633 if (checkin) { 18634 pw.println("vers,1"); 18635 } 18636 18637 // reader 18638 synchronized (mPackages) { 18639 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18640 if (!checkin) { 18641 if (dumpState.onTitlePrinted()) 18642 pw.println(); 18643 pw.println("Database versions:"); 18644 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18645 } 18646 } 18647 18648 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18649 if (!checkin) { 18650 if (dumpState.onTitlePrinted()) 18651 pw.println(); 18652 pw.println("Verifiers:"); 18653 pw.print(" Required: "); 18654 pw.print(mRequiredVerifierPackage); 18655 pw.print(" (uid="); 18656 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18657 UserHandle.USER_SYSTEM)); 18658 pw.println(")"); 18659 } else if (mRequiredVerifierPackage != null) { 18660 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18661 pw.print(","); 18662 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18663 UserHandle.USER_SYSTEM)); 18664 } 18665 } 18666 18667 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18668 packageName == null) { 18669 if (mIntentFilterVerifierComponent != null) { 18670 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18671 if (!checkin) { 18672 if (dumpState.onTitlePrinted()) 18673 pw.println(); 18674 pw.println("Intent Filter Verifier:"); 18675 pw.print(" Using: "); 18676 pw.print(verifierPackageName); 18677 pw.print(" (uid="); 18678 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18679 UserHandle.USER_SYSTEM)); 18680 pw.println(")"); 18681 } else if (verifierPackageName != null) { 18682 pw.print("ifv,"); pw.print(verifierPackageName); 18683 pw.print(","); 18684 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18685 UserHandle.USER_SYSTEM)); 18686 } 18687 } else { 18688 pw.println(); 18689 pw.println("No Intent Filter Verifier available!"); 18690 } 18691 } 18692 18693 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18694 boolean printedHeader = false; 18695 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18696 while (it.hasNext()) { 18697 String name = it.next(); 18698 SharedLibraryEntry ent = mSharedLibraries.get(name); 18699 if (!checkin) { 18700 if (!printedHeader) { 18701 if (dumpState.onTitlePrinted()) 18702 pw.println(); 18703 pw.println("Libraries:"); 18704 printedHeader = true; 18705 } 18706 pw.print(" "); 18707 } else { 18708 pw.print("lib,"); 18709 } 18710 pw.print(name); 18711 if (!checkin) { 18712 pw.print(" -> "); 18713 } 18714 if (ent.path != null) { 18715 if (!checkin) { 18716 pw.print("(jar) "); 18717 pw.print(ent.path); 18718 } else { 18719 pw.print(",jar,"); 18720 pw.print(ent.path); 18721 } 18722 } else { 18723 if (!checkin) { 18724 pw.print("(apk) "); 18725 pw.print(ent.apk); 18726 } else { 18727 pw.print(",apk,"); 18728 pw.print(ent.apk); 18729 } 18730 } 18731 pw.println(); 18732 } 18733 } 18734 18735 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18736 if (dumpState.onTitlePrinted()) 18737 pw.println(); 18738 if (!checkin) { 18739 pw.println("Features:"); 18740 } 18741 18742 for (FeatureInfo feat : mAvailableFeatures.values()) { 18743 if (checkin) { 18744 pw.print("feat,"); 18745 pw.print(feat.name); 18746 pw.print(","); 18747 pw.println(feat.version); 18748 } else { 18749 pw.print(" "); 18750 pw.print(feat.name); 18751 if (feat.version > 0) { 18752 pw.print(" version="); 18753 pw.print(feat.version); 18754 } 18755 pw.println(); 18756 } 18757 } 18758 } 18759 18760 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18761 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18762 : "Activity Resolver Table:", " ", packageName, 18763 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18764 dumpState.setTitlePrinted(true); 18765 } 18766 } 18767 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18768 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18769 : "Receiver Resolver Table:", " ", packageName, 18770 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18771 dumpState.setTitlePrinted(true); 18772 } 18773 } 18774 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18775 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18776 : "Service Resolver Table:", " ", packageName, 18777 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18778 dumpState.setTitlePrinted(true); 18779 } 18780 } 18781 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18782 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18783 : "Provider Resolver Table:", " ", packageName, 18784 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18785 dumpState.setTitlePrinted(true); 18786 } 18787 } 18788 18789 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18790 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18791 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18792 int user = mSettings.mPreferredActivities.keyAt(i); 18793 if (pir.dump(pw, 18794 dumpState.getTitlePrinted() 18795 ? "\nPreferred Activities User " + user + ":" 18796 : "Preferred Activities User " + user + ":", " ", 18797 packageName, true, false)) { 18798 dumpState.setTitlePrinted(true); 18799 } 18800 } 18801 } 18802 18803 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18804 pw.flush(); 18805 FileOutputStream fout = new FileOutputStream(fd); 18806 BufferedOutputStream str = new BufferedOutputStream(fout); 18807 XmlSerializer serializer = new FastXmlSerializer(); 18808 try { 18809 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18810 serializer.startDocument(null, true); 18811 serializer.setFeature( 18812 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18813 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18814 serializer.endDocument(); 18815 serializer.flush(); 18816 } catch (IllegalArgumentException e) { 18817 pw.println("Failed writing: " + e); 18818 } catch (IllegalStateException e) { 18819 pw.println("Failed writing: " + e); 18820 } catch (IOException e) { 18821 pw.println("Failed writing: " + e); 18822 } 18823 } 18824 18825 if (!checkin 18826 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18827 && packageName == null) { 18828 pw.println(); 18829 int count = mSettings.mPackages.size(); 18830 if (count == 0) { 18831 pw.println("No applications!"); 18832 pw.println(); 18833 } else { 18834 final String prefix = " "; 18835 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18836 if (allPackageSettings.size() == 0) { 18837 pw.println("No domain preferred apps!"); 18838 pw.println(); 18839 } else { 18840 pw.println("App verification status:"); 18841 pw.println(); 18842 count = 0; 18843 for (PackageSetting ps : allPackageSettings) { 18844 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18845 if (ivi == null || ivi.getPackageName() == null) continue; 18846 pw.println(prefix + "Package: " + ivi.getPackageName()); 18847 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18848 pw.println(prefix + "Status: " + ivi.getStatusString()); 18849 pw.println(); 18850 count++; 18851 } 18852 if (count == 0) { 18853 pw.println(prefix + "No app verification established."); 18854 pw.println(); 18855 } 18856 for (int userId : sUserManager.getUserIds()) { 18857 pw.println("App linkages for user " + userId + ":"); 18858 pw.println(); 18859 count = 0; 18860 for (PackageSetting ps : allPackageSettings) { 18861 final long status = ps.getDomainVerificationStatusForUser(userId); 18862 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18863 continue; 18864 } 18865 pw.println(prefix + "Package: " + ps.name); 18866 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18867 String statusStr = IntentFilterVerificationInfo. 18868 getStatusStringFromValue(status); 18869 pw.println(prefix + "Status: " + statusStr); 18870 pw.println(); 18871 count++; 18872 } 18873 if (count == 0) { 18874 pw.println(prefix + "No configured app linkages."); 18875 pw.println(); 18876 } 18877 } 18878 } 18879 } 18880 } 18881 18882 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18883 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18884 if (packageName == null && permissionNames == null) { 18885 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18886 if (iperm == 0) { 18887 if (dumpState.onTitlePrinted()) 18888 pw.println(); 18889 pw.println("AppOp Permissions:"); 18890 } 18891 pw.print(" AppOp Permission "); 18892 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18893 pw.println(":"); 18894 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18895 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18896 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18897 } 18898 } 18899 } 18900 } 18901 18902 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18903 boolean printedSomething = false; 18904 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18905 if (packageName != null && !packageName.equals(p.info.packageName)) { 18906 continue; 18907 } 18908 if (!printedSomething) { 18909 if (dumpState.onTitlePrinted()) 18910 pw.println(); 18911 pw.println("Registered ContentProviders:"); 18912 printedSomething = true; 18913 } 18914 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18915 pw.print(" "); pw.println(p.toString()); 18916 } 18917 printedSomething = false; 18918 for (Map.Entry<String, PackageParser.Provider> entry : 18919 mProvidersByAuthority.entrySet()) { 18920 PackageParser.Provider p = entry.getValue(); 18921 if (packageName != null && !packageName.equals(p.info.packageName)) { 18922 continue; 18923 } 18924 if (!printedSomething) { 18925 if (dumpState.onTitlePrinted()) 18926 pw.println(); 18927 pw.println("ContentProvider Authorities:"); 18928 printedSomething = true; 18929 } 18930 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18931 pw.print(" "); pw.println(p.toString()); 18932 if (p.info != null && p.info.applicationInfo != null) { 18933 final String appInfo = p.info.applicationInfo.toString(); 18934 pw.print(" applicationInfo="); pw.println(appInfo); 18935 } 18936 } 18937 } 18938 18939 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18940 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18941 } 18942 18943 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18944 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18945 } 18946 18947 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18948 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18949 } 18950 18951 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18952 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18953 } 18954 18955 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18956 // XXX should handle packageName != null by dumping only install data that 18957 // the given package is involved with. 18958 if (dumpState.onTitlePrinted()) pw.println(); 18959 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18960 } 18961 18962 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18963 // XXX should handle packageName != null by dumping only install data that 18964 // the given package is involved with. 18965 if (dumpState.onTitlePrinted()) pw.println(); 18966 18967 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18968 ipw.println(); 18969 ipw.println("Frozen packages:"); 18970 ipw.increaseIndent(); 18971 if (mFrozenPackages.size() == 0) { 18972 ipw.println("(none)"); 18973 } else { 18974 for (int i = 0; i < mFrozenPackages.size(); i++) { 18975 ipw.println(mFrozenPackages.valueAt(i)); 18976 } 18977 } 18978 ipw.decreaseIndent(); 18979 } 18980 18981 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18982 if (dumpState.onTitlePrinted()) pw.println(); 18983 dumpDexoptStateLPr(pw, packageName); 18984 } 18985 18986 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18987 if (dumpState.onTitlePrinted()) pw.println(); 18988 dumpCompilerStatsLPr(pw, packageName); 18989 } 18990 18991 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18992 if (dumpState.onTitlePrinted()) pw.println(); 18993 mSettings.dumpReadMessagesLPr(pw, dumpState); 18994 18995 pw.println(); 18996 pw.println("Package warning messages:"); 18997 BufferedReader in = null; 18998 String line = null; 18999 try { 19000 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19001 while ((line = in.readLine()) != null) { 19002 if (line.contains("ignored: updated version")) continue; 19003 pw.println(line); 19004 } 19005 } catch (IOException ignored) { 19006 } finally { 19007 IoUtils.closeQuietly(in); 19008 } 19009 } 19010 19011 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19012 BufferedReader in = null; 19013 String line = null; 19014 try { 19015 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19016 while ((line = in.readLine()) != null) { 19017 if (line.contains("ignored: updated version")) continue; 19018 pw.print("msg,"); 19019 pw.println(line); 19020 } 19021 } catch (IOException ignored) { 19022 } finally { 19023 IoUtils.closeQuietly(in); 19024 } 19025 } 19026 } 19027 } 19028 19029 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19030 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19031 ipw.println(); 19032 ipw.println("Dexopt state:"); 19033 ipw.increaseIndent(); 19034 Collection<PackageParser.Package> packages = null; 19035 if (packageName != null) { 19036 PackageParser.Package targetPackage = mPackages.get(packageName); 19037 if (targetPackage != null) { 19038 packages = Collections.singletonList(targetPackage); 19039 } else { 19040 ipw.println("Unable to find package: " + packageName); 19041 return; 19042 } 19043 } else { 19044 packages = mPackages.values(); 19045 } 19046 19047 for (PackageParser.Package pkg : packages) { 19048 ipw.println("[" + pkg.packageName + "]"); 19049 ipw.increaseIndent(); 19050 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19051 ipw.decreaseIndent(); 19052 } 19053 } 19054 19055 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19056 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19057 ipw.println(); 19058 ipw.println("Compiler stats:"); 19059 ipw.increaseIndent(); 19060 Collection<PackageParser.Package> packages = null; 19061 if (packageName != null) { 19062 PackageParser.Package targetPackage = mPackages.get(packageName); 19063 if (targetPackage != null) { 19064 packages = Collections.singletonList(targetPackage); 19065 } else { 19066 ipw.println("Unable to find package: " + packageName); 19067 return; 19068 } 19069 } else { 19070 packages = mPackages.values(); 19071 } 19072 19073 for (PackageParser.Package pkg : packages) { 19074 ipw.println("[" + pkg.packageName + "]"); 19075 ipw.increaseIndent(); 19076 19077 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19078 if (stats == null) { 19079 ipw.println("(No recorded stats)"); 19080 } else { 19081 stats.dump(ipw); 19082 } 19083 ipw.decreaseIndent(); 19084 } 19085 } 19086 19087 private String dumpDomainString(String packageName) { 19088 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19089 .getList(); 19090 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19091 19092 ArraySet<String> result = new ArraySet<>(); 19093 if (iviList.size() > 0) { 19094 for (IntentFilterVerificationInfo ivi : iviList) { 19095 for (String host : ivi.getDomains()) { 19096 result.add(host); 19097 } 19098 } 19099 } 19100 if (filters != null && filters.size() > 0) { 19101 for (IntentFilter filter : filters) { 19102 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19103 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19104 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19105 result.addAll(filter.getHostsList()); 19106 } 19107 } 19108 } 19109 19110 StringBuilder sb = new StringBuilder(result.size() * 16); 19111 for (String domain : result) { 19112 if (sb.length() > 0) sb.append(" "); 19113 sb.append(domain); 19114 } 19115 return sb.toString(); 19116 } 19117 19118 // ------- apps on sdcard specific code ------- 19119 static final boolean DEBUG_SD_INSTALL = false; 19120 19121 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19122 19123 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19124 19125 private boolean mMediaMounted = false; 19126 19127 static String getEncryptKey() { 19128 try { 19129 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19130 SD_ENCRYPTION_KEYSTORE_NAME); 19131 if (sdEncKey == null) { 19132 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19133 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19134 if (sdEncKey == null) { 19135 Slog.e(TAG, "Failed to create encryption keys"); 19136 return null; 19137 } 19138 } 19139 return sdEncKey; 19140 } catch (NoSuchAlgorithmException nsae) { 19141 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19142 return null; 19143 } catch (IOException ioe) { 19144 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19145 return null; 19146 } 19147 } 19148 19149 /* 19150 * Update media status on PackageManager. 19151 */ 19152 @Override 19153 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19154 int callingUid = Binder.getCallingUid(); 19155 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19156 throw new SecurityException("Media status can only be updated by the system"); 19157 } 19158 // reader; this apparently protects mMediaMounted, but should probably 19159 // be a different lock in that case. 19160 synchronized (mPackages) { 19161 Log.i(TAG, "Updating external media status from " 19162 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19163 + (mediaStatus ? "mounted" : "unmounted")); 19164 if (DEBUG_SD_INSTALL) 19165 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19166 + ", mMediaMounted=" + mMediaMounted); 19167 if (mediaStatus == mMediaMounted) { 19168 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19169 : 0, -1); 19170 mHandler.sendMessage(msg); 19171 return; 19172 } 19173 mMediaMounted = mediaStatus; 19174 } 19175 // Queue up an async operation since the package installation may take a 19176 // little while. 19177 mHandler.post(new Runnable() { 19178 public void run() { 19179 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19180 } 19181 }); 19182 } 19183 19184 /** 19185 * Called by MountService when the initial ASECs to scan are available. 19186 * Should block until all the ASEC containers are finished being scanned. 19187 */ 19188 public void scanAvailableAsecs() { 19189 updateExternalMediaStatusInner(true, false, false); 19190 } 19191 19192 /* 19193 * Collect information of applications on external media, map them against 19194 * existing containers and update information based on current mount status. 19195 * Please note that we always have to report status if reportStatus has been 19196 * set to true especially when unloading packages. 19197 */ 19198 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19199 boolean externalStorage) { 19200 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19201 int[] uidArr = EmptyArray.INT; 19202 19203 final String[] list = PackageHelper.getSecureContainerList(); 19204 if (ArrayUtils.isEmpty(list)) { 19205 Log.i(TAG, "No secure containers found"); 19206 } else { 19207 // Process list of secure containers and categorize them 19208 // as active or stale based on their package internal state. 19209 19210 // reader 19211 synchronized (mPackages) { 19212 for (String cid : list) { 19213 // Leave stages untouched for now; installer service owns them 19214 if (PackageInstallerService.isStageName(cid)) continue; 19215 19216 if (DEBUG_SD_INSTALL) 19217 Log.i(TAG, "Processing container " + cid); 19218 String pkgName = getAsecPackageName(cid); 19219 if (pkgName == null) { 19220 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19221 continue; 19222 } 19223 if (DEBUG_SD_INSTALL) 19224 Log.i(TAG, "Looking for pkg : " + pkgName); 19225 19226 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19227 if (ps == null) { 19228 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19229 continue; 19230 } 19231 19232 /* 19233 * Skip packages that are not external if we're unmounting 19234 * external storage. 19235 */ 19236 if (externalStorage && !isMounted && !isExternal(ps)) { 19237 continue; 19238 } 19239 19240 final AsecInstallArgs args = new AsecInstallArgs(cid, 19241 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19242 // The package status is changed only if the code path 19243 // matches between settings and the container id. 19244 if (ps.codePathString != null 19245 && ps.codePathString.startsWith(args.getCodePath())) { 19246 if (DEBUG_SD_INSTALL) { 19247 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19248 + " at code path: " + ps.codePathString); 19249 } 19250 19251 // We do have a valid package installed on sdcard 19252 processCids.put(args, ps.codePathString); 19253 final int uid = ps.appId; 19254 if (uid != -1) { 19255 uidArr = ArrayUtils.appendInt(uidArr, uid); 19256 } 19257 } else { 19258 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19259 + ps.codePathString); 19260 } 19261 } 19262 } 19263 19264 Arrays.sort(uidArr); 19265 } 19266 19267 // Process packages with valid entries. 19268 if (isMounted) { 19269 if (DEBUG_SD_INSTALL) 19270 Log.i(TAG, "Loading packages"); 19271 loadMediaPackages(processCids, uidArr, externalStorage); 19272 startCleaningPackages(); 19273 mInstallerService.onSecureContainersAvailable(); 19274 } else { 19275 if (DEBUG_SD_INSTALL) 19276 Log.i(TAG, "Unloading packages"); 19277 unloadMediaPackages(processCids, uidArr, reportStatus); 19278 } 19279 } 19280 19281 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19282 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19283 final int size = infos.size(); 19284 final String[] packageNames = new String[size]; 19285 final int[] packageUids = new int[size]; 19286 for (int i = 0; i < size; i++) { 19287 final ApplicationInfo info = infos.get(i); 19288 packageNames[i] = info.packageName; 19289 packageUids[i] = info.uid; 19290 } 19291 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19292 finishedReceiver); 19293 } 19294 19295 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19296 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19297 sendResourcesChangedBroadcast(mediaStatus, replacing, 19298 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19299 } 19300 19301 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19302 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19303 int size = pkgList.length; 19304 if (size > 0) { 19305 // Send broadcasts here 19306 Bundle extras = new Bundle(); 19307 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19308 if (uidArr != null) { 19309 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19310 } 19311 if (replacing) { 19312 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19313 } 19314 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19315 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19316 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19317 } 19318 } 19319 19320 /* 19321 * Look at potentially valid container ids from processCids If package 19322 * information doesn't match the one on record or package scanning fails, 19323 * the cid is added to list of removeCids. We currently don't delete stale 19324 * containers. 19325 */ 19326 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19327 boolean externalStorage) { 19328 ArrayList<String> pkgList = new ArrayList<String>(); 19329 Set<AsecInstallArgs> keys = processCids.keySet(); 19330 19331 for (AsecInstallArgs args : keys) { 19332 String codePath = processCids.get(args); 19333 if (DEBUG_SD_INSTALL) 19334 Log.i(TAG, "Loading container : " + args.cid); 19335 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19336 try { 19337 // Make sure there are no container errors first. 19338 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19339 Slog.e(TAG, "Failed to mount cid : " + args.cid 19340 + " when installing from sdcard"); 19341 continue; 19342 } 19343 // Check code path here. 19344 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19345 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19346 + " does not match one in settings " + codePath); 19347 continue; 19348 } 19349 // Parse package 19350 int parseFlags = mDefParseFlags; 19351 if (args.isExternalAsec()) { 19352 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19353 } 19354 if (args.isFwdLocked()) { 19355 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19356 } 19357 19358 synchronized (mInstallLock) { 19359 PackageParser.Package pkg = null; 19360 try { 19361 // Sadly we don't know the package name yet to freeze it 19362 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19363 SCAN_IGNORE_FROZEN, 0, null); 19364 } catch (PackageManagerException e) { 19365 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19366 } 19367 // Scan the package 19368 if (pkg != null) { 19369 /* 19370 * TODO why is the lock being held? doPostInstall is 19371 * called in other places without the lock. This needs 19372 * to be straightened out. 19373 */ 19374 // writer 19375 synchronized (mPackages) { 19376 retCode = PackageManager.INSTALL_SUCCEEDED; 19377 pkgList.add(pkg.packageName); 19378 // Post process args 19379 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19380 pkg.applicationInfo.uid); 19381 } 19382 } else { 19383 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19384 } 19385 } 19386 19387 } finally { 19388 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19389 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19390 } 19391 } 19392 } 19393 // writer 19394 synchronized (mPackages) { 19395 // If the platform SDK has changed since the last time we booted, 19396 // we need to re-grant app permission to catch any new ones that 19397 // appear. This is really a hack, and means that apps can in some 19398 // cases get permissions that the user didn't initially explicitly 19399 // allow... it would be nice to have some better way to handle 19400 // this situation. 19401 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19402 : mSettings.getInternalVersion(); 19403 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19404 : StorageManager.UUID_PRIVATE_INTERNAL; 19405 19406 int updateFlags = UPDATE_PERMISSIONS_ALL; 19407 if (ver.sdkVersion != mSdkVersion) { 19408 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19409 + mSdkVersion + "; regranting permissions for external"); 19410 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19411 } 19412 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19413 19414 // Yay, everything is now upgraded 19415 ver.forceCurrent(); 19416 19417 // can downgrade to reader 19418 // Persist settings 19419 mSettings.writeLPr(); 19420 } 19421 // Send a broadcast to let everyone know we are done processing 19422 if (pkgList.size() > 0) { 19423 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19424 } 19425 } 19426 19427 /* 19428 * Utility method to unload a list of specified containers 19429 */ 19430 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19431 // Just unmount all valid containers. 19432 for (AsecInstallArgs arg : cidArgs) { 19433 synchronized (mInstallLock) { 19434 arg.doPostDeleteLI(false); 19435 } 19436 } 19437 } 19438 19439 /* 19440 * Unload packages mounted on external media. This involves deleting package 19441 * data from internal structures, sending broadcasts about disabled packages, 19442 * gc'ing to free up references, unmounting all secure containers 19443 * corresponding to packages on external media, and posting a 19444 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19445 * that we always have to post this message if status has been requested no 19446 * matter what. 19447 */ 19448 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19449 final boolean reportStatus) { 19450 if (DEBUG_SD_INSTALL) 19451 Log.i(TAG, "unloading media packages"); 19452 ArrayList<String> pkgList = new ArrayList<String>(); 19453 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19454 final Set<AsecInstallArgs> keys = processCids.keySet(); 19455 for (AsecInstallArgs args : keys) { 19456 String pkgName = args.getPackageName(); 19457 if (DEBUG_SD_INSTALL) 19458 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19459 // Delete package internally 19460 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19461 synchronized (mInstallLock) { 19462 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19463 final boolean res; 19464 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19465 "unloadMediaPackages")) { 19466 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19467 null); 19468 } 19469 if (res) { 19470 pkgList.add(pkgName); 19471 } else { 19472 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19473 failedList.add(args); 19474 } 19475 } 19476 } 19477 19478 // reader 19479 synchronized (mPackages) { 19480 // We didn't update the settings after removing each package; 19481 // write them now for all packages. 19482 mSettings.writeLPr(); 19483 } 19484 19485 // We have to absolutely send UPDATED_MEDIA_STATUS only 19486 // after confirming that all the receivers processed the ordered 19487 // broadcast when packages get disabled, force a gc to clean things up. 19488 // and unload all the containers. 19489 if (pkgList.size() > 0) { 19490 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19491 new IIntentReceiver.Stub() { 19492 public void performReceive(Intent intent, int resultCode, String data, 19493 Bundle extras, boolean ordered, boolean sticky, 19494 int sendingUser) throws RemoteException { 19495 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19496 reportStatus ? 1 : 0, 1, keys); 19497 mHandler.sendMessage(msg); 19498 } 19499 }); 19500 } else { 19501 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19502 keys); 19503 mHandler.sendMessage(msg); 19504 } 19505 } 19506 19507 private void loadPrivatePackages(final VolumeInfo vol) { 19508 mHandler.post(new Runnable() { 19509 @Override 19510 public void run() { 19511 loadPrivatePackagesInner(vol); 19512 } 19513 }); 19514 } 19515 19516 private void loadPrivatePackagesInner(VolumeInfo vol) { 19517 final String volumeUuid = vol.fsUuid; 19518 if (TextUtils.isEmpty(volumeUuid)) { 19519 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19520 return; 19521 } 19522 19523 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19524 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19525 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19526 19527 final VersionInfo ver; 19528 final List<PackageSetting> packages; 19529 synchronized (mPackages) { 19530 ver = mSettings.findOrCreateVersion(volumeUuid); 19531 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19532 } 19533 19534 for (PackageSetting ps : packages) { 19535 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19536 synchronized (mInstallLock) { 19537 final PackageParser.Package pkg; 19538 try { 19539 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19540 loaded.add(pkg.applicationInfo); 19541 19542 } catch (PackageManagerException e) { 19543 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19544 } 19545 19546 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19547 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19548 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19549 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19550 } 19551 } 19552 } 19553 19554 // Reconcile app data for all started/unlocked users 19555 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19556 final UserManager um = mContext.getSystemService(UserManager.class); 19557 UserManagerInternal umInternal = getUserManagerInternal(); 19558 for (UserInfo user : um.getUsers()) { 19559 final int flags; 19560 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19561 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19562 } else if (umInternal.isUserRunning(user.id)) { 19563 flags = StorageManager.FLAG_STORAGE_DE; 19564 } else { 19565 continue; 19566 } 19567 19568 try { 19569 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19570 synchronized (mInstallLock) { 19571 reconcileAppsDataLI(volumeUuid, user.id, flags); 19572 } 19573 } catch (IllegalStateException e) { 19574 // Device was probably ejected, and we'll process that event momentarily 19575 Slog.w(TAG, "Failed to prepare storage: " + e); 19576 } 19577 } 19578 19579 synchronized (mPackages) { 19580 int updateFlags = UPDATE_PERMISSIONS_ALL; 19581 if (ver.sdkVersion != mSdkVersion) { 19582 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19583 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19584 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19585 } 19586 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19587 19588 // Yay, everything is now upgraded 19589 ver.forceCurrent(); 19590 19591 mSettings.writeLPr(); 19592 } 19593 19594 for (PackageFreezer freezer : freezers) { 19595 freezer.close(); 19596 } 19597 19598 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19599 sendResourcesChangedBroadcast(true, false, loaded, null); 19600 } 19601 19602 private void unloadPrivatePackages(final VolumeInfo vol) { 19603 mHandler.post(new Runnable() { 19604 @Override 19605 public void run() { 19606 unloadPrivatePackagesInner(vol); 19607 } 19608 }); 19609 } 19610 19611 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19612 final String volumeUuid = vol.fsUuid; 19613 if (TextUtils.isEmpty(volumeUuid)) { 19614 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19615 return; 19616 } 19617 19618 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19619 synchronized (mInstallLock) { 19620 synchronized (mPackages) { 19621 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19622 for (PackageSetting ps : packages) { 19623 if (ps.pkg == null) continue; 19624 19625 final ApplicationInfo info = ps.pkg.applicationInfo; 19626 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19627 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19628 19629 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19630 "unloadPrivatePackagesInner")) { 19631 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19632 false, null)) { 19633 unloaded.add(info); 19634 } else { 19635 Slog.w(TAG, "Failed to unload " + ps.codePath); 19636 } 19637 } 19638 19639 // Try very hard to release any references to this package 19640 // so we don't risk the system server being killed due to 19641 // open FDs 19642 AttributeCache.instance().removePackage(ps.name); 19643 } 19644 19645 mSettings.writeLPr(); 19646 } 19647 } 19648 19649 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19650 sendResourcesChangedBroadcast(false, false, unloaded, null); 19651 19652 // Try very hard to release any references to this path so we don't risk 19653 // the system server being killed due to open FDs 19654 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19655 19656 for (int i = 0; i < 3; i++) { 19657 System.gc(); 19658 System.runFinalization(); 19659 } 19660 } 19661 19662 /** 19663 * Prepare storage areas for given user on all mounted devices. 19664 */ 19665 void prepareUserData(int userId, int userSerial, int flags) { 19666 synchronized (mInstallLock) { 19667 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19668 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19669 final String volumeUuid = vol.getFsUuid(); 19670 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19671 } 19672 } 19673 } 19674 19675 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19676 boolean allowRecover) { 19677 // Prepare storage and verify that serial numbers are consistent; if 19678 // there's a mismatch we need to destroy to avoid leaking data 19679 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19680 try { 19681 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19682 19683 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19684 UserManagerService.enforceSerialNumber( 19685 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19686 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19687 UserManagerService.enforceSerialNumber( 19688 Environment.getDataSystemDeDirectory(userId), userSerial); 19689 } 19690 } 19691 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19692 UserManagerService.enforceSerialNumber( 19693 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19694 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19695 UserManagerService.enforceSerialNumber( 19696 Environment.getDataSystemCeDirectory(userId), userSerial); 19697 } 19698 } 19699 19700 synchronized (mInstallLock) { 19701 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19702 } 19703 } catch (Exception e) { 19704 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19705 + " because we failed to prepare: " + e); 19706 destroyUserDataLI(volumeUuid, userId, 19707 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19708 19709 if (allowRecover) { 19710 // Try one last time; if we fail again we're really in trouble 19711 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19712 } 19713 } 19714 } 19715 19716 /** 19717 * Destroy storage areas for given user on all mounted devices. 19718 */ 19719 void destroyUserData(int userId, int flags) { 19720 synchronized (mInstallLock) { 19721 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19722 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19723 final String volumeUuid = vol.getFsUuid(); 19724 destroyUserDataLI(volumeUuid, userId, flags); 19725 } 19726 } 19727 } 19728 19729 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19730 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19731 try { 19732 // Clean up app data, profile data, and media data 19733 mInstaller.destroyUserData(volumeUuid, userId, flags); 19734 19735 // Clean up system data 19736 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19737 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19738 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19739 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19740 } 19741 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19742 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19743 } 19744 } 19745 19746 // Data with special labels is now gone, so finish the job 19747 storage.destroyUserStorage(volumeUuid, userId, flags); 19748 19749 } catch (Exception e) { 19750 logCriticalInfo(Log.WARN, 19751 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19752 } 19753 } 19754 19755 /** 19756 * Examine all users present on given mounted volume, and destroy data 19757 * belonging to users that are no longer valid, or whose user ID has been 19758 * recycled. 19759 */ 19760 private void reconcileUsers(String volumeUuid) { 19761 final List<File> files = new ArrayList<>(); 19762 Collections.addAll(files, FileUtils 19763 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19764 Collections.addAll(files, FileUtils 19765 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19766 Collections.addAll(files, FileUtils 19767 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19768 Collections.addAll(files, FileUtils 19769 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19770 for (File file : files) { 19771 if (!file.isDirectory()) continue; 19772 19773 final int userId; 19774 final UserInfo info; 19775 try { 19776 userId = Integer.parseInt(file.getName()); 19777 info = sUserManager.getUserInfo(userId); 19778 } catch (NumberFormatException e) { 19779 Slog.w(TAG, "Invalid user directory " + file); 19780 continue; 19781 } 19782 19783 boolean destroyUser = false; 19784 if (info == null) { 19785 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19786 + " because no matching user was found"); 19787 destroyUser = true; 19788 } else if (!mOnlyCore) { 19789 try { 19790 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19791 } catch (IOException e) { 19792 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19793 + " because we failed to enforce serial number: " + e); 19794 destroyUser = true; 19795 } 19796 } 19797 19798 if (destroyUser) { 19799 synchronized (mInstallLock) { 19800 destroyUserDataLI(volumeUuid, userId, 19801 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19802 } 19803 } 19804 } 19805 } 19806 19807 private void assertPackageKnown(String volumeUuid, String packageName) 19808 throws PackageManagerException { 19809 synchronized (mPackages) { 19810 final PackageSetting ps = mSettings.mPackages.get(packageName); 19811 if (ps == null) { 19812 throw new PackageManagerException("Package " + packageName + " is unknown"); 19813 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19814 throw new PackageManagerException( 19815 "Package " + packageName + " found on unknown volume " + volumeUuid 19816 + "; expected volume " + ps.volumeUuid); 19817 } 19818 } 19819 } 19820 19821 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19822 throws PackageManagerException { 19823 synchronized (mPackages) { 19824 final PackageSetting ps = mSettings.mPackages.get(packageName); 19825 if (ps == null) { 19826 throw new PackageManagerException("Package " + packageName + " is unknown"); 19827 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19828 throw new PackageManagerException( 19829 "Package " + packageName + " found on unknown volume " + volumeUuid 19830 + "; expected volume " + ps.volumeUuid); 19831 } else if (!ps.getInstalled(userId)) { 19832 throw new PackageManagerException( 19833 "Package " + packageName + " not installed for user " + userId); 19834 } 19835 } 19836 } 19837 19838 /** 19839 * Examine all apps present on given mounted volume, and destroy apps that 19840 * aren't expected, either due to uninstallation or reinstallation on 19841 * another volume. 19842 */ 19843 private void reconcileApps(String volumeUuid) { 19844 final File[] files = FileUtils 19845 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19846 for (File file : files) { 19847 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19848 && !PackageInstallerService.isStageName(file.getName()); 19849 if (!isPackage) { 19850 // Ignore entries which are not packages 19851 continue; 19852 } 19853 19854 try { 19855 final PackageLite pkg = PackageParser.parsePackageLite(file, 19856 PackageParser.PARSE_MUST_BE_APK); 19857 assertPackageKnown(volumeUuid, pkg.packageName); 19858 19859 } catch (PackageParserException | PackageManagerException e) { 19860 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19861 synchronized (mInstallLock) { 19862 removeCodePathLI(file); 19863 } 19864 } 19865 } 19866 } 19867 19868 /** 19869 * Reconcile all app data for the given user. 19870 * <p> 19871 * Verifies that directories exist and that ownership and labeling is 19872 * correct for all installed apps on all mounted volumes. 19873 */ 19874 void reconcileAppsData(int userId, int flags) { 19875 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19876 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19877 final String volumeUuid = vol.getFsUuid(); 19878 synchronized (mInstallLock) { 19879 reconcileAppsDataLI(volumeUuid, userId, flags); 19880 } 19881 } 19882 } 19883 19884 /** 19885 * Reconcile all app data on given mounted volume. 19886 * <p> 19887 * Destroys app data that isn't expected, either due to uninstallation or 19888 * reinstallation on another volume. 19889 * <p> 19890 * Verifies that directories exist and that ownership and labeling is 19891 * correct for all installed apps. 19892 */ 19893 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19894 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19895 + Integer.toHexString(flags)); 19896 19897 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19898 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19899 19900 // First look for stale data that doesn't belong, and check if things 19901 // have changed since we did our last restorecon 19902 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19903 if (StorageManager.isFileEncryptedNativeOrEmulated() 19904 && !StorageManager.isUserKeyUnlocked(userId)) { 19905 throw new RuntimeException( 19906 "Yikes, someone asked us to reconcile CE storage while " + userId 19907 + " was still locked; this would have caused massive data loss!"); 19908 } 19909 19910 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19911 for (File file : files) { 19912 final String packageName = file.getName(); 19913 try { 19914 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19915 } catch (PackageManagerException e) { 19916 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19917 try { 19918 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19919 StorageManager.FLAG_STORAGE_CE, 0); 19920 } catch (InstallerException e2) { 19921 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19922 } 19923 } 19924 } 19925 } 19926 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19927 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19928 for (File file : files) { 19929 final String packageName = file.getName(); 19930 try { 19931 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19932 } catch (PackageManagerException e) { 19933 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19934 try { 19935 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19936 StorageManager.FLAG_STORAGE_DE, 0); 19937 } catch (InstallerException e2) { 19938 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19939 } 19940 } 19941 } 19942 } 19943 19944 // Ensure that data directories are ready to roll for all packages 19945 // installed for this volume and user 19946 final List<PackageSetting> packages; 19947 synchronized (mPackages) { 19948 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19949 } 19950 int preparedCount = 0; 19951 for (PackageSetting ps : packages) { 19952 final String packageName = ps.name; 19953 if (ps.pkg == null) { 19954 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19955 // TODO: might be due to legacy ASEC apps; we should circle back 19956 // and reconcile again once they're scanned 19957 continue; 19958 } 19959 19960 if (ps.getInstalled(userId)) { 19961 prepareAppDataLIF(ps.pkg, userId, flags); 19962 19963 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19964 // We may have just shuffled around app data directories, so 19965 // prepare them one more time 19966 prepareAppDataLIF(ps.pkg, userId, flags); 19967 } 19968 19969 preparedCount++; 19970 } 19971 } 19972 19973 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19974 } 19975 19976 /** 19977 * Prepare app data for the given app just after it was installed or 19978 * upgraded. This method carefully only touches users that it's installed 19979 * for, and it forces a restorecon to handle any seinfo changes. 19980 * <p> 19981 * Verifies that directories exist and that ownership and labeling is 19982 * correct for all installed apps. If there is an ownership mismatch, it 19983 * will try recovering system apps by wiping data; third-party app data is 19984 * left intact. 19985 * <p> 19986 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19987 */ 19988 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19989 final PackageSetting ps; 19990 synchronized (mPackages) { 19991 ps = mSettings.mPackages.get(pkg.packageName); 19992 mSettings.writeKernelMappingLPr(ps); 19993 } 19994 19995 final UserManager um = mContext.getSystemService(UserManager.class); 19996 UserManagerInternal umInternal = getUserManagerInternal(); 19997 for (UserInfo user : um.getUsers()) { 19998 final int flags; 19999 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20000 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20001 } else if (umInternal.isUserRunning(user.id)) { 20002 flags = StorageManager.FLAG_STORAGE_DE; 20003 } else { 20004 continue; 20005 } 20006 20007 if (ps.getInstalled(user.id)) { 20008 // TODO: when user data is locked, mark that we're still dirty 20009 prepareAppDataLIF(pkg, user.id, flags); 20010 } 20011 } 20012 } 20013 20014 /** 20015 * Prepare app data for the given app. 20016 * <p> 20017 * Verifies that directories exist and that ownership and labeling is 20018 * correct for all installed apps. If there is an ownership mismatch, this 20019 * will try recovering system apps by wiping data; third-party app data is 20020 * left intact. 20021 */ 20022 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20023 if (pkg == null) { 20024 Slog.wtf(TAG, "Package was null!", new Throwable()); 20025 return; 20026 } 20027 prepareAppDataLeafLIF(pkg, userId, flags); 20028 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20029 for (int i = 0; i < childCount; i++) { 20030 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20031 } 20032 } 20033 20034 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20035 if (DEBUG_APP_DATA) { 20036 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20037 + Integer.toHexString(flags)); 20038 } 20039 20040 final String volumeUuid = pkg.volumeUuid; 20041 final String packageName = pkg.packageName; 20042 final ApplicationInfo app = pkg.applicationInfo; 20043 final int appId = UserHandle.getAppId(app.uid); 20044 20045 Preconditions.checkNotNull(app.seinfo); 20046 20047 long ceDataInode = -1; 20048 try { 20049 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20050 appId, app.seinfo, app.targetSdkVersion); 20051 } catch (InstallerException e) { 20052 if (app.isSystemApp()) { 20053 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20054 + ", but trying to recover: " + e); 20055 destroyAppDataLeafLIF(pkg, userId, flags); 20056 try { 20057 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20058 appId, app.seinfo, app.targetSdkVersion); 20059 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20060 } catch (InstallerException e2) { 20061 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20062 } 20063 } else { 20064 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20065 } 20066 } 20067 20068 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20069 // TODO: mark this structure as dirty so we persist it! 20070 synchronized (mPackages) { 20071 final PackageSetting ps = mSettings.mPackages.get(packageName); 20072 if (ps != null) { 20073 ps.setCeDataInode(ceDataInode, userId); 20074 } 20075 } 20076 } 20077 20078 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20079 } 20080 20081 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20082 if (pkg == null) { 20083 Slog.wtf(TAG, "Package was null!", new Throwable()); 20084 return; 20085 } 20086 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20087 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20088 for (int i = 0; i < childCount; i++) { 20089 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20090 } 20091 } 20092 20093 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20094 final String volumeUuid = pkg.volumeUuid; 20095 final String packageName = pkg.packageName; 20096 final ApplicationInfo app = pkg.applicationInfo; 20097 20098 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20099 // Create a native library symlink only if we have native libraries 20100 // and if the native libraries are 32 bit libraries. We do not provide 20101 // this symlink for 64 bit libraries. 20102 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20103 final String nativeLibPath = app.nativeLibraryDir; 20104 try { 20105 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20106 nativeLibPath, userId); 20107 } catch (InstallerException e) { 20108 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20109 } 20110 } 20111 } 20112 } 20113 20114 /** 20115 * For system apps on non-FBE devices, this method migrates any existing 20116 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20117 * requested by the app. 20118 */ 20119 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20120 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20121 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20122 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20123 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20124 try { 20125 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20126 storageTarget); 20127 } catch (InstallerException e) { 20128 logCriticalInfo(Log.WARN, 20129 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20130 } 20131 return true; 20132 } else { 20133 return false; 20134 } 20135 } 20136 20137 public PackageFreezer freezePackage(String packageName, String killReason) { 20138 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20139 } 20140 20141 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20142 return new PackageFreezer(packageName, userId, killReason); 20143 } 20144 20145 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20146 String killReason) { 20147 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20148 } 20149 20150 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20151 String killReason) { 20152 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20153 return new PackageFreezer(); 20154 } else { 20155 return freezePackage(packageName, userId, killReason); 20156 } 20157 } 20158 20159 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20160 String killReason) { 20161 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20162 } 20163 20164 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20165 String killReason) { 20166 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20167 return new PackageFreezer(); 20168 } else { 20169 return freezePackage(packageName, userId, killReason); 20170 } 20171 } 20172 20173 /** 20174 * Class that freezes and kills the given package upon creation, and 20175 * unfreezes it upon closing. This is typically used when doing surgery on 20176 * app code/data to prevent the app from running while you're working. 20177 */ 20178 private class PackageFreezer implements AutoCloseable { 20179 private final String mPackageName; 20180 private final PackageFreezer[] mChildren; 20181 20182 private final boolean mWeFroze; 20183 20184 private final AtomicBoolean mClosed = new AtomicBoolean(); 20185 private final CloseGuard mCloseGuard = CloseGuard.get(); 20186 20187 /** 20188 * Create and return a stub freezer that doesn't actually do anything, 20189 * typically used when someone requested 20190 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20191 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20192 */ 20193 public PackageFreezer() { 20194 mPackageName = null; 20195 mChildren = null; 20196 mWeFroze = false; 20197 mCloseGuard.open("close"); 20198 } 20199 20200 public PackageFreezer(String packageName, int userId, String killReason) { 20201 synchronized (mPackages) { 20202 mPackageName = packageName; 20203 mWeFroze = mFrozenPackages.add(mPackageName); 20204 20205 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20206 if (ps != null) { 20207 killApplication(ps.name, ps.appId, userId, killReason); 20208 } 20209 20210 final PackageParser.Package p = mPackages.get(packageName); 20211 if (p != null && p.childPackages != null) { 20212 final int N = p.childPackages.size(); 20213 mChildren = new PackageFreezer[N]; 20214 for (int i = 0; i < N; i++) { 20215 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20216 userId, killReason); 20217 } 20218 } else { 20219 mChildren = null; 20220 } 20221 } 20222 mCloseGuard.open("close"); 20223 } 20224 20225 @Override 20226 protected void finalize() throws Throwable { 20227 try { 20228 mCloseGuard.warnIfOpen(); 20229 close(); 20230 } finally { 20231 super.finalize(); 20232 } 20233 } 20234 20235 @Override 20236 public void close() { 20237 mCloseGuard.close(); 20238 if (mClosed.compareAndSet(false, true)) { 20239 synchronized (mPackages) { 20240 if (mWeFroze) { 20241 mFrozenPackages.remove(mPackageName); 20242 } 20243 20244 if (mChildren != null) { 20245 for (PackageFreezer freezer : mChildren) { 20246 freezer.close(); 20247 } 20248 } 20249 } 20250 } 20251 } 20252 } 20253 20254 /** 20255 * Verify that given package is currently frozen. 20256 */ 20257 private void checkPackageFrozen(String packageName) { 20258 synchronized (mPackages) { 20259 if (!mFrozenPackages.contains(packageName)) { 20260 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20261 } 20262 } 20263 } 20264 20265 @Override 20266 public int movePackage(final String packageName, final String volumeUuid) { 20267 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20268 20269 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20270 final int moveId = mNextMoveId.getAndIncrement(); 20271 mHandler.post(new Runnable() { 20272 @Override 20273 public void run() { 20274 try { 20275 movePackageInternal(packageName, volumeUuid, moveId, user); 20276 } catch (PackageManagerException e) { 20277 Slog.w(TAG, "Failed to move " + packageName, e); 20278 mMoveCallbacks.notifyStatusChanged(moveId, 20279 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20280 } 20281 } 20282 }); 20283 return moveId; 20284 } 20285 20286 private void movePackageInternal(final String packageName, final String volumeUuid, 20287 final int moveId, UserHandle user) throws PackageManagerException { 20288 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20289 final PackageManager pm = mContext.getPackageManager(); 20290 20291 final boolean currentAsec; 20292 final String currentVolumeUuid; 20293 final File codeFile; 20294 final String installerPackageName; 20295 final String packageAbiOverride; 20296 final int appId; 20297 final String seinfo; 20298 final String label; 20299 final int targetSdkVersion; 20300 final PackageFreezer freezer; 20301 final int[] installedUserIds; 20302 20303 // reader 20304 synchronized (mPackages) { 20305 final PackageParser.Package pkg = mPackages.get(packageName); 20306 final PackageSetting ps = mSettings.mPackages.get(packageName); 20307 if (pkg == null || ps == null) { 20308 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20309 } 20310 20311 if (pkg.applicationInfo.isSystemApp()) { 20312 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20313 "Cannot move system application"); 20314 } 20315 20316 if (pkg.applicationInfo.isExternalAsec()) { 20317 currentAsec = true; 20318 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20319 } else if (pkg.applicationInfo.isForwardLocked()) { 20320 currentAsec = true; 20321 currentVolumeUuid = "forward_locked"; 20322 } else { 20323 currentAsec = false; 20324 currentVolumeUuid = ps.volumeUuid; 20325 20326 final File probe = new File(pkg.codePath); 20327 final File probeOat = new File(probe, "oat"); 20328 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20329 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20330 "Move only supported for modern cluster style installs"); 20331 } 20332 } 20333 20334 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20335 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20336 "Package already moved to " + volumeUuid); 20337 } 20338 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20339 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20340 "Device admin cannot be moved"); 20341 } 20342 20343 if (mFrozenPackages.contains(packageName)) { 20344 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20345 "Failed to move already frozen package"); 20346 } 20347 20348 codeFile = new File(pkg.codePath); 20349 installerPackageName = ps.installerPackageName; 20350 packageAbiOverride = ps.cpuAbiOverrideString; 20351 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20352 seinfo = pkg.applicationInfo.seinfo; 20353 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20354 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20355 freezer = freezePackage(packageName, "movePackageInternal"); 20356 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20357 } 20358 20359 final Bundle extras = new Bundle(); 20360 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20361 extras.putString(Intent.EXTRA_TITLE, label); 20362 mMoveCallbacks.notifyCreated(moveId, extras); 20363 20364 int installFlags; 20365 final boolean moveCompleteApp; 20366 final File measurePath; 20367 20368 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20369 installFlags = INSTALL_INTERNAL; 20370 moveCompleteApp = !currentAsec; 20371 measurePath = Environment.getDataAppDirectory(volumeUuid); 20372 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20373 installFlags = INSTALL_EXTERNAL; 20374 moveCompleteApp = false; 20375 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20376 } else { 20377 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20378 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20379 || !volume.isMountedWritable()) { 20380 freezer.close(); 20381 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20382 "Move location not mounted private volume"); 20383 } 20384 20385 Preconditions.checkState(!currentAsec); 20386 20387 installFlags = INSTALL_INTERNAL; 20388 moveCompleteApp = true; 20389 measurePath = Environment.getDataAppDirectory(volumeUuid); 20390 } 20391 20392 final PackageStats stats = new PackageStats(null, -1); 20393 synchronized (mInstaller) { 20394 for (int userId : installedUserIds) { 20395 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20396 freezer.close(); 20397 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20398 "Failed to measure package size"); 20399 } 20400 } 20401 } 20402 20403 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20404 + stats.dataSize); 20405 20406 final long startFreeBytes = measurePath.getFreeSpace(); 20407 final long sizeBytes; 20408 if (moveCompleteApp) { 20409 sizeBytes = stats.codeSize + stats.dataSize; 20410 } else { 20411 sizeBytes = stats.codeSize; 20412 } 20413 20414 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20415 freezer.close(); 20416 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20417 "Not enough free space to move"); 20418 } 20419 20420 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20421 20422 final CountDownLatch installedLatch = new CountDownLatch(1); 20423 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20424 @Override 20425 public void onUserActionRequired(Intent intent) throws RemoteException { 20426 throw new IllegalStateException(); 20427 } 20428 20429 @Override 20430 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20431 Bundle extras) throws RemoteException { 20432 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20433 + PackageManager.installStatusToString(returnCode, msg)); 20434 20435 installedLatch.countDown(); 20436 freezer.close(); 20437 20438 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20439 switch (status) { 20440 case PackageInstaller.STATUS_SUCCESS: 20441 mMoveCallbacks.notifyStatusChanged(moveId, 20442 PackageManager.MOVE_SUCCEEDED); 20443 break; 20444 case PackageInstaller.STATUS_FAILURE_STORAGE: 20445 mMoveCallbacks.notifyStatusChanged(moveId, 20446 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20447 break; 20448 default: 20449 mMoveCallbacks.notifyStatusChanged(moveId, 20450 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20451 break; 20452 } 20453 } 20454 }; 20455 20456 final MoveInfo move; 20457 if (moveCompleteApp) { 20458 // Kick off a thread to report progress estimates 20459 new Thread() { 20460 @Override 20461 public void run() { 20462 while (true) { 20463 try { 20464 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20465 break; 20466 } 20467 } catch (InterruptedException ignored) { 20468 } 20469 20470 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20471 final int progress = 10 + (int) MathUtils.constrain( 20472 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20473 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20474 } 20475 } 20476 }.start(); 20477 20478 final String dataAppName = codeFile.getName(); 20479 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20480 dataAppName, appId, seinfo, targetSdkVersion); 20481 } else { 20482 move = null; 20483 } 20484 20485 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20486 20487 final Message msg = mHandler.obtainMessage(INIT_COPY); 20488 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20489 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20490 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20491 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20492 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20493 msg.obj = params; 20494 20495 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20496 System.identityHashCode(msg.obj)); 20497 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20498 System.identityHashCode(msg.obj)); 20499 20500 mHandler.sendMessage(msg); 20501 } 20502 20503 @Override 20504 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20505 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20506 20507 final int realMoveId = mNextMoveId.getAndIncrement(); 20508 final Bundle extras = new Bundle(); 20509 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20510 mMoveCallbacks.notifyCreated(realMoveId, extras); 20511 20512 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20513 @Override 20514 public void onCreated(int moveId, Bundle extras) { 20515 // Ignored 20516 } 20517 20518 @Override 20519 public void onStatusChanged(int moveId, int status, long estMillis) { 20520 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20521 } 20522 }; 20523 20524 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20525 storage.setPrimaryStorageUuid(volumeUuid, callback); 20526 return realMoveId; 20527 } 20528 20529 @Override 20530 public int getMoveStatus(int moveId) { 20531 mContext.enforceCallingOrSelfPermission( 20532 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20533 return mMoveCallbacks.mLastStatus.get(moveId); 20534 } 20535 20536 @Override 20537 public void registerMoveCallback(IPackageMoveObserver callback) { 20538 mContext.enforceCallingOrSelfPermission( 20539 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20540 mMoveCallbacks.register(callback); 20541 } 20542 20543 @Override 20544 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20545 mContext.enforceCallingOrSelfPermission( 20546 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20547 mMoveCallbacks.unregister(callback); 20548 } 20549 20550 @Override 20551 public boolean setInstallLocation(int loc) { 20552 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20553 null); 20554 if (getInstallLocation() == loc) { 20555 return true; 20556 } 20557 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20558 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20559 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20560 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20561 return true; 20562 } 20563 return false; 20564 } 20565 20566 @Override 20567 public int getInstallLocation() { 20568 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20569 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20570 PackageHelper.APP_INSTALL_AUTO); 20571 } 20572 20573 /** Called by UserManagerService */ 20574 void cleanUpUser(UserManagerService userManager, int userHandle) { 20575 synchronized (mPackages) { 20576 mDirtyUsers.remove(userHandle); 20577 mUserNeedsBadging.delete(userHandle); 20578 mSettings.removeUserLPw(userHandle); 20579 mPendingBroadcasts.remove(userHandle); 20580 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20581 removeUnusedPackagesLPw(userManager, userHandle); 20582 } 20583 } 20584 20585 /** 20586 * We're removing userHandle and would like to remove any downloaded packages 20587 * that are no longer in use by any other user. 20588 * @param userHandle the user being removed 20589 */ 20590 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20591 final boolean DEBUG_CLEAN_APKS = false; 20592 int [] users = userManager.getUserIds(); 20593 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20594 while (psit.hasNext()) { 20595 PackageSetting ps = psit.next(); 20596 if (ps.pkg == null) { 20597 continue; 20598 } 20599 final String packageName = ps.pkg.packageName; 20600 // Skip over if system app 20601 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20602 continue; 20603 } 20604 if (DEBUG_CLEAN_APKS) { 20605 Slog.i(TAG, "Checking package " + packageName); 20606 } 20607 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20608 if (keep) { 20609 if (DEBUG_CLEAN_APKS) { 20610 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20611 } 20612 } else { 20613 for (int i = 0; i < users.length; i++) { 20614 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20615 keep = true; 20616 if (DEBUG_CLEAN_APKS) { 20617 Slog.i(TAG, " Keeping package " + packageName + " for user " 20618 + users[i]); 20619 } 20620 break; 20621 } 20622 } 20623 } 20624 if (!keep) { 20625 if (DEBUG_CLEAN_APKS) { 20626 Slog.i(TAG, " Removing package " + packageName); 20627 } 20628 mHandler.post(new Runnable() { 20629 public void run() { 20630 deletePackageX(packageName, userHandle, 0); 20631 } //end run 20632 }); 20633 } 20634 } 20635 } 20636 20637 /** Called by UserManagerService */ 20638 void createNewUser(int userId) { 20639 synchronized (mInstallLock) { 20640 mSettings.createNewUserLI(this, mInstaller, userId); 20641 } 20642 synchronized (mPackages) { 20643 scheduleWritePackageRestrictionsLocked(userId); 20644 scheduleWritePackageListLocked(userId); 20645 applyFactoryDefaultBrowserLPw(userId); 20646 primeDomainVerificationsLPw(userId); 20647 } 20648 } 20649 20650 void onNewUserCreated(final int userId) { 20651 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20652 // If permission review for legacy apps is required, we represent 20653 // dagerous permissions for such apps as always granted runtime 20654 // permissions to keep per user flag state whether review is needed. 20655 // Hence, if a new user is added we have to propagate dangerous 20656 // permission grants for these legacy apps. 20657 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) { 20658 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20659 | UPDATE_PERMISSIONS_REPLACE_ALL); 20660 } 20661 } 20662 20663 @Override 20664 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20665 mContext.enforceCallingOrSelfPermission( 20666 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20667 "Only package verification agents can read the verifier device identity"); 20668 20669 synchronized (mPackages) { 20670 return mSettings.getVerifierDeviceIdentityLPw(); 20671 } 20672 } 20673 20674 @Override 20675 public void setPermissionEnforced(String permission, boolean enforced) { 20676 // TODO: Now that we no longer change GID for storage, this should to away. 20677 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20678 "setPermissionEnforced"); 20679 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20680 synchronized (mPackages) { 20681 if (mSettings.mReadExternalStorageEnforced == null 20682 || mSettings.mReadExternalStorageEnforced != enforced) { 20683 mSettings.mReadExternalStorageEnforced = enforced; 20684 mSettings.writeLPr(); 20685 } 20686 } 20687 // kill any non-foreground processes so we restart them and 20688 // grant/revoke the GID. 20689 final IActivityManager am = ActivityManagerNative.getDefault(); 20690 if (am != null) { 20691 final long token = Binder.clearCallingIdentity(); 20692 try { 20693 am.killProcessesBelowForeground("setPermissionEnforcement"); 20694 } catch (RemoteException e) { 20695 } finally { 20696 Binder.restoreCallingIdentity(token); 20697 } 20698 } 20699 } else { 20700 throw new IllegalArgumentException("No selective enforcement for " + permission); 20701 } 20702 } 20703 20704 @Override 20705 @Deprecated 20706 public boolean isPermissionEnforced(String permission) { 20707 return true; 20708 } 20709 20710 @Override 20711 public boolean isStorageLow() { 20712 final long token = Binder.clearCallingIdentity(); 20713 try { 20714 final DeviceStorageMonitorInternal 20715 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20716 if (dsm != null) { 20717 return dsm.isMemoryLow(); 20718 } else { 20719 return false; 20720 } 20721 } finally { 20722 Binder.restoreCallingIdentity(token); 20723 } 20724 } 20725 20726 @Override 20727 public IPackageInstaller getPackageInstaller() { 20728 return mInstallerService; 20729 } 20730 20731 private boolean userNeedsBadging(int userId) { 20732 int index = mUserNeedsBadging.indexOfKey(userId); 20733 if (index < 0) { 20734 final UserInfo userInfo; 20735 final long token = Binder.clearCallingIdentity(); 20736 try { 20737 userInfo = sUserManager.getUserInfo(userId); 20738 } finally { 20739 Binder.restoreCallingIdentity(token); 20740 } 20741 final boolean b; 20742 if (userInfo != null && userInfo.isManagedProfile()) { 20743 b = true; 20744 } else { 20745 b = false; 20746 } 20747 mUserNeedsBadging.put(userId, b); 20748 return b; 20749 } 20750 return mUserNeedsBadging.valueAt(index); 20751 } 20752 20753 @Override 20754 public KeySet getKeySetByAlias(String packageName, String alias) { 20755 if (packageName == null || alias == null) { 20756 return null; 20757 } 20758 synchronized(mPackages) { 20759 final PackageParser.Package pkg = mPackages.get(packageName); 20760 if (pkg == null) { 20761 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20762 throw new IllegalArgumentException("Unknown package: " + packageName); 20763 } 20764 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20765 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20766 } 20767 } 20768 20769 @Override 20770 public KeySet getSigningKeySet(String packageName) { 20771 if (packageName == null) { 20772 return null; 20773 } 20774 synchronized(mPackages) { 20775 final PackageParser.Package pkg = mPackages.get(packageName); 20776 if (pkg == null) { 20777 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20778 throw new IllegalArgumentException("Unknown package: " + packageName); 20779 } 20780 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20781 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20782 throw new SecurityException("May not access signing KeySet of other apps."); 20783 } 20784 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20785 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20786 } 20787 } 20788 20789 @Override 20790 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20791 if (packageName == null || ks == null) { 20792 return false; 20793 } 20794 synchronized(mPackages) { 20795 final PackageParser.Package pkg = mPackages.get(packageName); 20796 if (pkg == null) { 20797 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20798 throw new IllegalArgumentException("Unknown package: " + packageName); 20799 } 20800 IBinder ksh = ks.getToken(); 20801 if (ksh instanceof KeySetHandle) { 20802 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20803 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20804 } 20805 return false; 20806 } 20807 } 20808 20809 @Override 20810 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20811 if (packageName == null || ks == null) { 20812 return false; 20813 } 20814 synchronized(mPackages) { 20815 final PackageParser.Package pkg = mPackages.get(packageName); 20816 if (pkg == null) { 20817 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20818 throw new IllegalArgumentException("Unknown package: " + packageName); 20819 } 20820 IBinder ksh = ks.getToken(); 20821 if (ksh instanceof KeySetHandle) { 20822 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20823 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20824 } 20825 return false; 20826 } 20827 } 20828 20829 private void deletePackageIfUnusedLPr(final String packageName) { 20830 PackageSetting ps = mSettings.mPackages.get(packageName); 20831 if (ps == null) { 20832 return; 20833 } 20834 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20835 // TODO Implement atomic delete if package is unused 20836 // It is currently possible that the package will be deleted even if it is installed 20837 // after this method returns. 20838 mHandler.post(new Runnable() { 20839 public void run() { 20840 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20841 } 20842 }); 20843 } 20844 } 20845 20846 /** 20847 * Check and throw if the given before/after packages would be considered a 20848 * downgrade. 20849 */ 20850 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20851 throws PackageManagerException { 20852 if (after.versionCode < before.mVersionCode) { 20853 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20854 "Update version code " + after.versionCode + " is older than current " 20855 + before.mVersionCode); 20856 } else if (after.versionCode == before.mVersionCode) { 20857 if (after.baseRevisionCode < before.baseRevisionCode) { 20858 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20859 "Update base revision code " + after.baseRevisionCode 20860 + " is older than current " + before.baseRevisionCode); 20861 } 20862 20863 if (!ArrayUtils.isEmpty(after.splitNames)) { 20864 for (int i = 0; i < after.splitNames.length; i++) { 20865 final String splitName = after.splitNames[i]; 20866 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20867 if (j != -1) { 20868 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20869 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20870 "Update split " + splitName + " revision code " 20871 + after.splitRevisionCodes[i] + " is older than current " 20872 + before.splitRevisionCodes[j]); 20873 } 20874 } 20875 } 20876 } 20877 } 20878 } 20879 20880 private static class MoveCallbacks extends Handler { 20881 private static final int MSG_CREATED = 1; 20882 private static final int MSG_STATUS_CHANGED = 2; 20883 20884 private final RemoteCallbackList<IPackageMoveObserver> 20885 mCallbacks = new RemoteCallbackList<>(); 20886 20887 private final SparseIntArray mLastStatus = new SparseIntArray(); 20888 20889 public MoveCallbacks(Looper looper) { 20890 super(looper); 20891 } 20892 20893 public void register(IPackageMoveObserver callback) { 20894 mCallbacks.register(callback); 20895 } 20896 20897 public void unregister(IPackageMoveObserver callback) { 20898 mCallbacks.unregister(callback); 20899 } 20900 20901 @Override 20902 public void handleMessage(Message msg) { 20903 final SomeArgs args = (SomeArgs) msg.obj; 20904 final int n = mCallbacks.beginBroadcast(); 20905 for (int i = 0; i < n; i++) { 20906 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20907 try { 20908 invokeCallback(callback, msg.what, args); 20909 } catch (RemoteException ignored) { 20910 } 20911 } 20912 mCallbacks.finishBroadcast(); 20913 args.recycle(); 20914 } 20915 20916 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20917 throws RemoteException { 20918 switch (what) { 20919 case MSG_CREATED: { 20920 callback.onCreated(args.argi1, (Bundle) args.arg2); 20921 break; 20922 } 20923 case MSG_STATUS_CHANGED: { 20924 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20925 break; 20926 } 20927 } 20928 } 20929 20930 private void notifyCreated(int moveId, Bundle extras) { 20931 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20932 20933 final SomeArgs args = SomeArgs.obtain(); 20934 args.argi1 = moveId; 20935 args.arg2 = extras; 20936 obtainMessage(MSG_CREATED, args).sendToTarget(); 20937 } 20938 20939 private void notifyStatusChanged(int moveId, int status) { 20940 notifyStatusChanged(moveId, status, -1); 20941 } 20942 20943 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20944 Slog.v(TAG, "Move " + moveId + " status " + status); 20945 20946 final SomeArgs args = SomeArgs.obtain(); 20947 args.argi1 = moveId; 20948 args.argi2 = status; 20949 args.arg3 = estMillis; 20950 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20951 20952 synchronized (mLastStatus) { 20953 mLastStatus.put(moveId, status); 20954 } 20955 } 20956 } 20957 20958 private final static class OnPermissionChangeListeners extends Handler { 20959 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20960 20961 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20962 new RemoteCallbackList<>(); 20963 20964 public OnPermissionChangeListeners(Looper looper) { 20965 super(looper); 20966 } 20967 20968 @Override 20969 public void handleMessage(Message msg) { 20970 switch (msg.what) { 20971 case MSG_ON_PERMISSIONS_CHANGED: { 20972 final int uid = msg.arg1; 20973 handleOnPermissionsChanged(uid); 20974 } break; 20975 } 20976 } 20977 20978 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20979 mPermissionListeners.register(listener); 20980 20981 } 20982 20983 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20984 mPermissionListeners.unregister(listener); 20985 } 20986 20987 public void onPermissionsChanged(int uid) { 20988 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20989 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20990 } 20991 } 20992 20993 private void handleOnPermissionsChanged(int uid) { 20994 final int count = mPermissionListeners.beginBroadcast(); 20995 try { 20996 for (int i = 0; i < count; i++) { 20997 IOnPermissionsChangeListener callback = mPermissionListeners 20998 .getBroadcastItem(i); 20999 try { 21000 callback.onPermissionsChanged(uid); 21001 } catch (RemoteException e) { 21002 Log.e(TAG, "Permission listener is dead", e); 21003 } 21004 } 21005 } finally { 21006 mPermissionListeners.finishBroadcast(); 21007 } 21008 } 21009 } 21010 21011 private class PackageManagerInternalImpl extends PackageManagerInternal { 21012 @Override 21013 public void setLocationPackagesProvider(PackagesProvider provider) { 21014 synchronized (mPackages) { 21015 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21016 } 21017 } 21018 21019 @Override 21020 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21021 synchronized (mPackages) { 21022 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21023 } 21024 } 21025 21026 @Override 21027 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21028 synchronized (mPackages) { 21029 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21030 } 21031 } 21032 21033 @Override 21034 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21035 synchronized (mPackages) { 21036 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21037 } 21038 } 21039 21040 @Override 21041 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21042 synchronized (mPackages) { 21043 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21044 } 21045 } 21046 21047 @Override 21048 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21049 synchronized (mPackages) { 21050 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21051 } 21052 } 21053 21054 @Override 21055 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21056 synchronized (mPackages) { 21057 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21058 packageName, userId); 21059 } 21060 } 21061 21062 @Override 21063 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21064 synchronized (mPackages) { 21065 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21066 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21067 packageName, userId); 21068 } 21069 } 21070 21071 @Override 21072 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21073 synchronized (mPackages) { 21074 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21075 packageName, userId); 21076 } 21077 } 21078 21079 @Override 21080 public void setKeepUninstalledPackages(final List<String> packageList) { 21081 Preconditions.checkNotNull(packageList); 21082 List<String> removedFromList = null; 21083 synchronized (mPackages) { 21084 if (mKeepUninstalledPackages != null) { 21085 final int packagesCount = mKeepUninstalledPackages.size(); 21086 for (int i = 0; i < packagesCount; i++) { 21087 String oldPackage = mKeepUninstalledPackages.get(i); 21088 if (packageList != null && packageList.contains(oldPackage)) { 21089 continue; 21090 } 21091 if (removedFromList == null) { 21092 removedFromList = new ArrayList<>(); 21093 } 21094 removedFromList.add(oldPackage); 21095 } 21096 } 21097 mKeepUninstalledPackages = new ArrayList<>(packageList); 21098 if (removedFromList != null) { 21099 final int removedCount = removedFromList.size(); 21100 for (int i = 0; i < removedCount; i++) { 21101 deletePackageIfUnusedLPr(removedFromList.get(i)); 21102 } 21103 } 21104 } 21105 } 21106 21107 @Override 21108 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21109 synchronized (mPackages) { 21110 // If we do not support permission review, done. 21111 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) { 21112 return false; 21113 } 21114 21115 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21116 if (packageSetting == null) { 21117 return false; 21118 } 21119 21120 // Permission review applies only to apps not supporting the new permission model. 21121 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21122 return false; 21123 } 21124 21125 // Legacy apps have the permission and get user consent on launch. 21126 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21127 return permissionsState.isPermissionReviewRequired(userId); 21128 } 21129 } 21130 21131 @Override 21132 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21133 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21134 } 21135 21136 @Override 21137 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21138 int userId) { 21139 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21140 } 21141 21142 @Override 21143 public void setDeviceAndProfileOwnerPackages( 21144 int deviceOwnerUserId, String deviceOwnerPackage, 21145 SparseArray<String> profileOwnerPackages) { 21146 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21147 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21148 } 21149 21150 @Override 21151 public boolean isPackageDataProtected(int userId, String packageName) { 21152 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21153 } 21154 21155 @Override 21156 public boolean wasPackageEverLaunched(String packageName, int userId) { 21157 synchronized (mPackages) { 21158 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21159 } 21160 } 21161 } 21162 21163 @Override 21164 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21165 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21166 synchronized (mPackages) { 21167 final long identity = Binder.clearCallingIdentity(); 21168 try { 21169 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21170 packageNames, userId); 21171 } finally { 21172 Binder.restoreCallingIdentity(identity); 21173 } 21174 } 21175 } 21176 21177 @Override 21178 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 21179 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 21180 synchronized (mPackages) { 21181 final long identity = Binder.clearCallingIdentity(); 21182 try { 21183 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 21184 packageNames, userId); 21185 } finally { 21186 Binder.restoreCallingIdentity(identity); 21187 } 21188 } 21189 } 21190 21191 private static void enforceSystemOrPhoneCaller(String tag) { 21192 int callingUid = Binder.getCallingUid(); 21193 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21194 throw new SecurityException( 21195 "Cannot call " + tag + " from UID " + callingUid); 21196 } 21197 } 21198 21199 boolean isHistoricalPackageUsageAvailable() { 21200 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21201 } 21202 21203 /** 21204 * Return a <b>copy</b> of the collection of packages known to the package manager. 21205 * @return A copy of the values of mPackages. 21206 */ 21207 Collection<PackageParser.Package> getPackages() { 21208 synchronized (mPackages) { 21209 return new ArrayList<>(mPackages.values()); 21210 } 21211 } 21212 21213 /** 21214 * Logs process start information (including base APK hash) to the security log. 21215 * @hide 21216 */ 21217 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21218 String apkFile, int pid) { 21219 if (!SecurityLog.isLoggingEnabled()) { 21220 return; 21221 } 21222 Bundle data = new Bundle(); 21223 data.putLong("startTimestamp", System.currentTimeMillis()); 21224 data.putString("processName", processName); 21225 data.putInt("uid", uid); 21226 data.putString("seinfo", seinfo); 21227 data.putString("apkFile", apkFile); 21228 data.putInt("pid", pid); 21229 Message msg = mProcessLoggingHandler.obtainMessage( 21230 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21231 msg.setData(data); 21232 mProcessLoggingHandler.sendMessage(msg); 21233 } 21234 21235 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21236 return mCompilerStats.getPackageStats(pkgName); 21237 } 21238 21239 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21240 return getOrCreateCompilerPackageStats(pkg.packageName); 21241 } 21242 21243 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21244 return mCompilerStats.getOrCreatePackageStats(pkgName); 21245 } 21246 21247 public void deleteCompilerPackageStats(String pkgName) { 21248 mCompilerStats.deletePackageStats(pkgName); 21249 } 21250} 21251