PackageManagerService.java revision 4460839e5ce43777e7f32841e4ab2e2ce0008257
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.storage.DeviceStorageMonitorInternal; 257 258import dalvik.system.CloseGuard; 259import dalvik.system.DexFile; 260import dalvik.system.VMRuntime; 261 262import libcore.io.IoUtils; 263import libcore.util.EmptyArray; 264 265import org.xmlpull.v1.XmlPullParser; 266import org.xmlpull.v1.XmlPullParserException; 267import org.xmlpull.v1.XmlSerializer; 268 269import java.io.BufferedOutputStream; 270import java.io.BufferedReader; 271import java.io.ByteArrayInputStream; 272import java.io.ByteArrayOutputStream; 273import java.io.File; 274import java.io.FileDescriptor; 275import java.io.FileInputStream; 276import java.io.FileNotFoundException; 277import java.io.FileOutputStream; 278import java.io.FileReader; 279import java.io.FilenameFilter; 280import java.io.IOException; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307 308/** 309 * Keep track of all those APKs everywhere. 310 * <p> 311 * Internally there are two important locks: 312 * <ul> 313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 314 * and other related state. It is a fine-grained lock that should only be held 315 * momentarily, as it's one of the most contended locks in the system. 316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 317 * operations typically involve heavy lifting of application data on disk. Since 318 * {@code installd} is single-threaded, and it's operations can often be slow, 319 * this lock should never be acquired while already holding {@link #mPackages}. 320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 321 * holding {@link #mInstallLock}. 322 * </ul> 323 * Many internal methods rely on the caller to hold the appropriate locks, and 324 * this contract is expressed through method name suffixes: 325 * <ul> 326 * <li>fooLI(): the caller must hold {@link #mInstallLock} 327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 328 * being modified must be frozen 329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 331 * </ul> 332 * <p> 333 * Because this class is very central to the platform's security; please run all 334 * CTS and unit tests whenever making modifications: 335 * 336 * <pre> 337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 339 * </pre> 340 */ 341public class PackageManagerService extends IPackageManager.Stub { 342 static final String TAG = "PackageManager"; 343 static final boolean DEBUG_SETTINGS = false; 344 static final boolean DEBUG_PREFERRED = false; 345 static final boolean DEBUG_UPGRADE = false; 346 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 347 private static final boolean DEBUG_BACKUP = false; 348 private static final boolean DEBUG_INSTALL = false; 349 private static final boolean DEBUG_REMOVE = false; 350 private static final boolean DEBUG_BROADCASTS = false; 351 private static final boolean DEBUG_SHOW_INFO = false; 352 private static final boolean DEBUG_PACKAGE_INFO = false; 353 private static final boolean DEBUG_INTENT_MATCHING = false; 354 private static final boolean DEBUG_PACKAGE_SCANNING = false; 355 private static final boolean DEBUG_VERIFY = false; 356 private static final boolean DEBUG_FILTERS = false; 357 358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 360 // user, but by default initialize to this. 361 static final boolean DEBUG_DEXOPT = false; 362 363 private static final boolean DEBUG_ABI_SELECTION = false; 364 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 365 private static final boolean DEBUG_TRIAGED_MISSING = false; 366 private static final boolean DEBUG_APP_DATA = false; 367 368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 369 370 private static final boolean DISABLE_EPHEMERAL_APPS = false; 371 private static final boolean HIDE_EPHEMERAL_APIS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String PACKAGE_SCHEME = "package"; 464 465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 466 /** 467 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 468 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 469 * VENDOR_OVERLAY_DIR. 470 */ 471 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 472 473 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 474 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 475 476 /** Permission grant: not grant the permission. */ 477 private static final int GRANT_DENIED = 1; 478 479 /** Permission grant: grant the permission as an install permission. */ 480 private static final int GRANT_INSTALL = 2; 481 482 /** Permission grant: grant the permission as a runtime one. */ 483 private static final int GRANT_RUNTIME = 3; 484 485 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 486 private static final int GRANT_UPGRADE = 4; 487 488 /** Canonical intent used to identify what counts as a "web browser" app */ 489 private static final Intent sBrowserIntent; 490 static { 491 sBrowserIntent = new Intent(); 492 sBrowserIntent.setAction(Intent.ACTION_VIEW); 493 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 494 sBrowserIntent.setData(Uri.parse("http:")); 495 } 496 497 /** 498 * The set of all protected actions [i.e. those actions for which a high priority 499 * intent filter is disallowed]. 500 */ 501 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 502 static { 503 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 504 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 505 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 506 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 507 } 508 509 // Compilation reasons. 510 public static final int REASON_FIRST_BOOT = 0; 511 public static final int REASON_BOOT = 1; 512 public static final int REASON_INSTALL = 2; 513 public static final int REASON_BACKGROUND_DEXOPT = 3; 514 public static final int REASON_AB_OTA = 4; 515 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 516 public static final int REASON_SHARED_APK = 6; 517 public static final int REASON_FORCED_DEXOPT = 7; 518 public static final int REASON_CORE_APP = 8; 519 520 public static final int REASON_LAST = REASON_CORE_APP; 521 522 /** Special library name that skips shared libraries check during compilation. */ 523 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 524 525 final ServiceThread mHandlerThread; 526 527 final PackageHandler mHandler; 528 529 private final ProcessLoggingHandler mProcessLoggingHandler; 530 531 /** 532 * Messages for {@link #mHandler} that need to wait for system ready before 533 * being dispatched. 534 */ 535 private ArrayList<Message> mPostSystemReadyMessages; 536 537 final int mSdkVersion = Build.VERSION.SDK_INT; 538 539 final Context mContext; 540 final boolean mFactoryTest; 541 final boolean mOnlyCore; 542 final DisplayMetrics mMetrics; 543 final int mDefParseFlags; 544 final String[] mSeparateProcesses; 545 final boolean mIsUpgrade; 546 final boolean mIsPreNUpgrade; 547 final boolean mIsPreNMR1Upgrade; 548 549 @GuardedBy("mPackages") 550 private boolean mDexOptDialogShown; 551 552 /** The location for ASEC container files on internal storage. */ 553 final String mAsecInternalPath; 554 555 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 556 // LOCK HELD. Can be called with mInstallLock held. 557 @GuardedBy("mInstallLock") 558 final Installer mInstaller; 559 560 /** Directory where installed third-party apps stored */ 561 final File mAppInstallDir; 562 final File mEphemeralInstallDir; 563 564 /** 565 * Directory to which applications installed internally have their 566 * 32 bit native libraries copied. 567 */ 568 private File mAppLib32InstallDir; 569 570 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 571 // apps. 572 final File mDrmAppPrivateInstallDir; 573 574 // ---------------------------------------------------------------- 575 576 // Lock for state used when installing and doing other long running 577 // operations. Methods that must be called with this lock held have 578 // the suffix "LI". 579 final Object mInstallLock = new Object(); 580 581 // ---------------------------------------------------------------- 582 583 // Keys are String (package name), values are Package. This also serves 584 // as the lock for the global state. Methods that must be called with 585 // this lock held have the prefix "LP". 586 @GuardedBy("mPackages") 587 final ArrayMap<String, PackageParser.Package> mPackages = 588 new ArrayMap<String, PackageParser.Package>(); 589 590 final ArrayMap<String, Set<String>> mKnownCodebase = 591 new ArrayMap<String, Set<String>>(); 592 593 // Tracks available target package names -> overlay package paths. 594 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 595 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 596 597 /** 598 * Tracks new system packages [received in an OTA] that we expect to 599 * find updated user-installed versions. Keys are package name, values 600 * are package location. 601 */ 602 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 603 /** 604 * Tracks high priority intent filters for protected actions. During boot, certain 605 * filter actions are protected and should never be allowed to have a high priority 606 * intent filter for them. However, there is one, and only one exception -- the 607 * setup wizard. It must be able to define a high priority intent filter for these 608 * actions to ensure there are no escapes from the wizard. We need to delay processing 609 * of these during boot as we need to look at all of the system packages in order 610 * to know which component is the setup wizard. 611 */ 612 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 613 /** 614 * Whether or not processing protected filters should be deferred. 615 */ 616 private boolean mDeferProtectedFilters = true; 617 618 /** 619 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 620 */ 621 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 622 /** 623 * Whether or not system app permissions should be promoted from install to runtime. 624 */ 625 boolean mPromoteSystemApps; 626 627 @GuardedBy("mPackages") 628 final Settings mSettings; 629 630 /** 631 * Set of package names that are currently "frozen", which means active 632 * surgery is being done on the code/data for that package. The platform 633 * will refuse to launch frozen packages to avoid race conditions. 634 * 635 * @see PackageFreezer 636 */ 637 @GuardedBy("mPackages") 638 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 639 640 final ProtectedPackages mProtectedPackages; 641 642 boolean mFirstBoot; 643 644 // System configuration read by SystemConfig. 645 final int[] mGlobalGids; 646 final SparseArray<ArraySet<String>> mSystemPermissions; 647 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 648 649 // If mac_permissions.xml was found for seinfo labeling. 650 boolean mFoundPolicyFile; 651 652 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 653 654 public static final class SharedLibraryEntry { 655 public final String path; 656 public final String apk; 657 658 SharedLibraryEntry(String _path, String _apk) { 659 path = _path; 660 apk = _apk; 661 } 662 } 663 664 // Currently known shared libraries. 665 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 666 new ArrayMap<String, SharedLibraryEntry>(); 667 668 // All available activities, for your resolving pleasure. 669 final ActivityIntentResolver mActivities = 670 new ActivityIntentResolver(); 671 672 // All available receivers, for your resolving pleasure. 673 final ActivityIntentResolver mReceivers = 674 new ActivityIntentResolver(); 675 676 // All available services, for your resolving pleasure. 677 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 678 679 // All available providers, for your resolving pleasure. 680 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 681 682 // Mapping from provider base names (first directory in content URI codePath) 683 // to the provider information. 684 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 685 new ArrayMap<String, PackageParser.Provider>(); 686 687 // Mapping from instrumentation class names to info about them. 688 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 689 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 690 691 // Mapping from permission names to info about them. 692 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 693 new ArrayMap<String, PackageParser.PermissionGroup>(); 694 695 // Packages whose data we have transfered into another package, thus 696 // should no longer exist. 697 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 698 699 // Broadcast actions that are only available to the system. 700 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 701 702 /** List of packages waiting for verification. */ 703 final SparseArray<PackageVerificationState> mPendingVerification 704 = new SparseArray<PackageVerificationState>(); 705 706 /** Set of packages associated with each app op permission. */ 707 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 708 709 final PackageInstallerService mInstallerService; 710 711 private final PackageDexOptimizer mPackageDexOptimizer; 712 713 private AtomicInteger mNextMoveId = new AtomicInteger(); 714 private final MoveCallbacks mMoveCallbacks; 715 716 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 717 718 // Cache of users who need badging. 719 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 720 721 /** Token for keys in mPendingVerification. */ 722 private int mPendingVerificationToken = 0; 723 724 volatile boolean mSystemReady; 725 volatile boolean mSafeMode; 726 volatile boolean mHasSystemUidErrors; 727 728 ApplicationInfo mAndroidApplication; 729 final ActivityInfo mResolveActivity = new ActivityInfo(); 730 final ResolveInfo mResolveInfo = new ResolveInfo(); 731 ComponentName mResolveComponentName; 732 PackageParser.Package mPlatformPackage; 733 ComponentName mCustomResolverComponentName; 734 735 boolean mResolverReplaced = false; 736 737 private final @Nullable ComponentName mIntentFilterVerifierComponent; 738 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 739 740 private int mIntentFilterVerificationToken = 0; 741 742 /** Component that knows whether or not an ephemeral application exists */ 743 final ComponentName mEphemeralResolverComponent; 744 /** The service connection to the ephemeral resolver */ 745 final EphemeralResolverConnection mEphemeralResolverConnection; 746 747 /** Component used to install ephemeral applications */ 748 final ComponentName mEphemeralInstallerComponent; 749 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 750 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 751 752 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 753 = new SparseArray<IntentFilterVerificationState>(); 754 755 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 756 757 // List of packages names to keep cached, even if they are uninstalled for all users 758 private List<String> mKeepUninstalledPackages; 759 760 private UserManagerInternal mUserManagerInternal; 761 762 private static class IFVerificationParams { 763 PackageParser.Package pkg; 764 boolean replacing; 765 int userId; 766 int verifierUid; 767 768 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 769 int _userId, int _verifierUid) { 770 pkg = _pkg; 771 replacing = _replacing; 772 userId = _userId; 773 replacing = _replacing; 774 verifierUid = _verifierUid; 775 } 776 } 777 778 private interface IntentFilterVerifier<T extends IntentFilter> { 779 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 780 T filter, String packageName); 781 void startVerifications(int userId); 782 void receiveVerificationResponse(int verificationId); 783 } 784 785 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 786 private Context mContext; 787 private ComponentName mIntentFilterVerifierComponent; 788 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 789 790 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 791 mContext = context; 792 mIntentFilterVerifierComponent = verifierComponent; 793 } 794 795 private String getDefaultScheme() { 796 return IntentFilter.SCHEME_HTTPS; 797 } 798 799 @Override 800 public void startVerifications(int userId) { 801 // Launch verifications requests 802 int count = mCurrentIntentFilterVerifications.size(); 803 for (int n=0; n<count; n++) { 804 int verificationId = mCurrentIntentFilterVerifications.get(n); 805 final IntentFilterVerificationState ivs = 806 mIntentFilterVerificationStates.get(verificationId); 807 808 String packageName = ivs.getPackageName(); 809 810 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 811 final int filterCount = filters.size(); 812 ArraySet<String> domainsSet = new ArraySet<>(); 813 for (int m=0; m<filterCount; m++) { 814 PackageParser.ActivityIntentInfo filter = filters.get(m); 815 domainsSet.addAll(filter.getHostsList()); 816 } 817 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 818 synchronized (mPackages) { 819 if (mSettings.createIntentFilterVerificationIfNeededLPw( 820 packageName, domainsList) != null) { 821 scheduleWriteSettingsLocked(); 822 } 823 } 824 sendVerificationRequest(userId, verificationId, ivs); 825 } 826 mCurrentIntentFilterVerifications.clear(); 827 } 828 829 private void sendVerificationRequest(int userId, int verificationId, 830 IntentFilterVerificationState ivs) { 831 832 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 833 verificationIntent.putExtra( 834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 835 verificationId); 836 verificationIntent.putExtra( 837 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 838 getDefaultScheme()); 839 verificationIntent.putExtra( 840 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 841 ivs.getHostsString()); 842 verificationIntent.putExtra( 843 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 844 ivs.getPackageName()); 845 verificationIntent.setComponent(mIntentFilterVerifierComponent); 846 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 847 848 UserHandle user = new UserHandle(userId); 849 mContext.sendBroadcastAsUser(verificationIntent, user); 850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 851 "Sending IntentFilter verification broadcast"); 852 } 853 854 public void receiveVerificationResponse(int verificationId) { 855 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 856 857 final boolean verified = ivs.isVerified(); 858 859 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 860 final int count = filters.size(); 861 if (DEBUG_DOMAIN_VERIFICATION) { 862 Slog.i(TAG, "Received verification response " + verificationId 863 + " for " + count + " filters, verified=" + verified); 864 } 865 for (int n=0; n<count; n++) { 866 PackageParser.ActivityIntentInfo filter = filters.get(n); 867 filter.setVerified(verified); 868 869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 870 + " verified with result:" + verified + " and hosts:" 871 + ivs.getHostsString()); 872 } 873 874 mIntentFilterVerificationStates.remove(verificationId); 875 876 final String packageName = ivs.getPackageName(); 877 IntentFilterVerificationInfo ivi = null; 878 879 synchronized (mPackages) { 880 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 881 } 882 if (ivi == null) { 883 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 884 + verificationId + " packageName:" + packageName); 885 return; 886 } 887 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 888 "Updating IntentFilterVerificationInfo for package " + packageName 889 +" verificationId:" + verificationId); 890 891 synchronized (mPackages) { 892 if (verified) { 893 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 894 } else { 895 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 896 } 897 scheduleWriteSettingsLocked(); 898 899 final int userId = ivs.getUserId(); 900 if (userId != UserHandle.USER_ALL) { 901 final int userStatus = 902 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 903 904 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 905 boolean needUpdate = false; 906 907 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 908 // already been set by the User thru the Disambiguation dialog 909 switch (userStatus) { 910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 911 if (verified) { 912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 913 } else { 914 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 915 } 916 needUpdate = true; 917 break; 918 919 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 920 if (verified) { 921 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 922 needUpdate = true; 923 } 924 break; 925 926 default: 927 // Nothing to do 928 } 929 930 if (needUpdate) { 931 mSettings.updateIntentFilterVerificationStatusLPw( 932 packageName, updatedStatus, userId); 933 scheduleWritePackageRestrictionsLocked(userId); 934 } 935 } 936 } 937 } 938 939 @Override 940 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 941 ActivityIntentInfo filter, String packageName) { 942 if (!hasValidDomains(filter)) { 943 return false; 944 } 945 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 946 if (ivs == null) { 947 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 948 packageName); 949 } 950 if (DEBUG_DOMAIN_VERIFICATION) { 951 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 952 } 953 ivs.addFilter(filter); 954 return true; 955 } 956 957 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 958 int userId, int verificationId, String packageName) { 959 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 960 verifierUid, userId, packageName); 961 ivs.setPendingState(); 962 synchronized (mPackages) { 963 mIntentFilterVerificationStates.append(verificationId, ivs); 964 mCurrentIntentFilterVerifications.add(verificationId); 965 } 966 return ivs; 967 } 968 } 969 970 private static boolean hasValidDomains(ActivityIntentInfo filter) { 971 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 972 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 973 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 974 } 975 976 // Set of pending broadcasts for aggregating enable/disable of components. 977 static class PendingPackageBroadcasts { 978 // for each user id, a map of <package name -> components within that package> 979 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 980 981 public PendingPackageBroadcasts() { 982 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 983 } 984 985 public ArrayList<String> get(int userId, String packageName) { 986 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 987 return packages.get(packageName); 988 } 989 990 public void put(int userId, String packageName, ArrayList<String> components) { 991 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 992 packages.put(packageName, components); 993 } 994 995 public void remove(int userId, String packageName) { 996 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 997 if (packages != null) { 998 packages.remove(packageName); 999 } 1000 } 1001 1002 public void remove(int userId) { 1003 mUidMap.remove(userId); 1004 } 1005 1006 public int userIdCount() { 1007 return mUidMap.size(); 1008 } 1009 1010 public int userIdAt(int n) { 1011 return mUidMap.keyAt(n); 1012 } 1013 1014 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1015 return mUidMap.get(userId); 1016 } 1017 1018 public int size() { 1019 // total number of pending broadcast entries across all userIds 1020 int num = 0; 1021 for (int i = 0; i< mUidMap.size(); i++) { 1022 num += mUidMap.valueAt(i).size(); 1023 } 1024 return num; 1025 } 1026 1027 public void clear() { 1028 mUidMap.clear(); 1029 } 1030 1031 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1032 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1033 if (map == null) { 1034 map = new ArrayMap<String, ArrayList<String>>(); 1035 mUidMap.put(userId, map); 1036 } 1037 return map; 1038 } 1039 } 1040 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1041 1042 // Service Connection to remote media container service to copy 1043 // package uri's from external media onto secure containers 1044 // or internal storage. 1045 private IMediaContainerService mContainerService = null; 1046 1047 static final int SEND_PENDING_BROADCAST = 1; 1048 static final int MCS_BOUND = 3; 1049 static final int END_COPY = 4; 1050 static final int INIT_COPY = 5; 1051 static final int MCS_UNBIND = 6; 1052 static final int START_CLEANING_PACKAGE = 7; 1053 static final int FIND_INSTALL_LOC = 8; 1054 static final int POST_INSTALL = 9; 1055 static final int MCS_RECONNECT = 10; 1056 static final int MCS_GIVE_UP = 11; 1057 static final int UPDATED_MEDIA_STATUS = 12; 1058 static final int WRITE_SETTINGS = 13; 1059 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1060 static final int PACKAGE_VERIFIED = 15; 1061 static final int CHECK_PENDING_VERIFICATION = 16; 1062 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1063 static final int INTENT_FILTER_VERIFIED = 18; 1064 static final int WRITE_PACKAGE_LIST = 19; 1065 1066 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1067 1068 // Delay time in millisecs 1069 static final int BROADCAST_DELAY = 10 * 1000; 1070 1071 static UserManagerService sUserManager; 1072 1073 // Stores a list of users whose package restrictions file needs to be updated 1074 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1075 1076 final private DefaultContainerConnection mDefContainerConn = 1077 new DefaultContainerConnection(); 1078 class DefaultContainerConnection implements ServiceConnection { 1079 public void onServiceConnected(ComponentName name, IBinder service) { 1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1081 IMediaContainerService imcs = 1082 IMediaContainerService.Stub.asInterface(service); 1083 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1084 } 1085 1086 public void onServiceDisconnected(ComponentName name) { 1087 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1088 } 1089 } 1090 1091 // Recordkeeping of restore-after-install operations that are currently in flight 1092 // between the Package Manager and the Backup Manager 1093 static class PostInstallData { 1094 public InstallArgs args; 1095 public PackageInstalledInfo res; 1096 1097 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1098 args = _a; 1099 res = _r; 1100 } 1101 } 1102 1103 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1104 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1105 1106 // XML tags for backup/restore of various bits of state 1107 private static final String TAG_PREFERRED_BACKUP = "pa"; 1108 private static final String TAG_DEFAULT_APPS = "da"; 1109 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1110 1111 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1112 private static final String TAG_ALL_GRANTS = "rt-grants"; 1113 private static final String TAG_GRANT = "grant"; 1114 private static final String ATTR_PACKAGE_NAME = "pkg"; 1115 1116 private static final String TAG_PERMISSION = "perm"; 1117 private static final String ATTR_PERMISSION_NAME = "name"; 1118 private static final String ATTR_IS_GRANTED = "g"; 1119 private static final String ATTR_USER_SET = "set"; 1120 private static final String ATTR_USER_FIXED = "fixed"; 1121 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1122 1123 // System/policy permission grants are not backed up 1124 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1125 FLAG_PERMISSION_POLICY_FIXED 1126 | FLAG_PERMISSION_SYSTEM_FIXED 1127 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1128 1129 // And we back up these user-adjusted states 1130 private static final int USER_RUNTIME_GRANT_MASK = 1131 FLAG_PERMISSION_USER_SET 1132 | FLAG_PERMISSION_USER_FIXED 1133 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1134 1135 final @Nullable String mRequiredVerifierPackage; 1136 final @NonNull String mRequiredInstallerPackage; 1137 final @NonNull String mRequiredUninstallerPackage; 1138 final @Nullable String mSetupWizardPackage; 1139 final @Nullable String mStorageManagerPackage; 1140 final @NonNull String mServicesSystemSharedLibraryPackageName; 1141 final @NonNull String mSharedSystemSharedLibraryPackageName; 1142 1143 final boolean mPermissionReviewRequired; 1144 1145 private final PackageUsage mPackageUsage = new PackageUsage(); 1146 private final CompilerStats mCompilerStats = new CompilerStats(); 1147 1148 class PackageHandler extends Handler { 1149 private boolean mBound = false; 1150 final ArrayList<HandlerParams> mPendingInstalls = 1151 new ArrayList<HandlerParams>(); 1152 1153 private boolean connectToService() { 1154 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1155 " DefaultContainerService"); 1156 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1157 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1158 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1159 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1160 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1161 mBound = true; 1162 return true; 1163 } 1164 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1165 return false; 1166 } 1167 1168 private void disconnectService() { 1169 mContainerService = null; 1170 mBound = false; 1171 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1172 mContext.unbindService(mDefContainerConn); 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1174 } 1175 1176 PackageHandler(Looper looper) { 1177 super(looper); 1178 } 1179 1180 public void handleMessage(Message msg) { 1181 try { 1182 doHandleMessage(msg); 1183 } finally { 1184 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1185 } 1186 } 1187 1188 void doHandleMessage(Message msg) { 1189 switch (msg.what) { 1190 case INIT_COPY: { 1191 HandlerParams params = (HandlerParams) msg.obj; 1192 int idx = mPendingInstalls.size(); 1193 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1194 // If a bind was already initiated we dont really 1195 // need to do anything. The pending install 1196 // will be processed later on. 1197 if (!mBound) { 1198 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1199 System.identityHashCode(mHandler)); 1200 // If this is the only one pending we might 1201 // have to bind to the service again. 1202 if (!connectToService()) { 1203 Slog.e(TAG, "Failed to bind to media container service"); 1204 params.serviceError(); 1205 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1206 System.identityHashCode(mHandler)); 1207 if (params.traceMethod != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1209 params.traceCookie); 1210 } 1211 return; 1212 } else { 1213 // Once we bind to the service, the first 1214 // pending request will be processed. 1215 mPendingInstalls.add(idx, params); 1216 } 1217 } else { 1218 mPendingInstalls.add(idx, params); 1219 // Already bound to the service. Just make 1220 // sure we trigger off processing the first request. 1221 if (idx == 0) { 1222 mHandler.sendEmptyMessage(MCS_BOUND); 1223 } 1224 } 1225 break; 1226 } 1227 case MCS_BOUND: { 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1229 if (msg.obj != null) { 1230 mContainerService = (IMediaContainerService) msg.obj; 1231 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1232 System.identityHashCode(mHandler)); 1233 } 1234 if (mContainerService == null) { 1235 if (!mBound) { 1236 // Something seriously wrong since we are not bound and we are not 1237 // waiting for connection. Bail out. 1238 Slog.e(TAG, "Cannot bind to media container service"); 1239 for (HandlerParams params : mPendingInstalls) { 1240 // Indicate service bind error 1241 params.serviceError(); 1242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1243 System.identityHashCode(params)); 1244 if (params.traceMethod != null) { 1245 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1246 params.traceMethod, params.traceCookie); 1247 } 1248 return; 1249 } 1250 mPendingInstalls.clear(); 1251 } else { 1252 Slog.w(TAG, "Waiting to connect to media container service"); 1253 } 1254 } else if (mPendingInstalls.size() > 0) { 1255 HandlerParams params = mPendingInstalls.get(0); 1256 if (params != null) { 1257 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1258 System.identityHashCode(params)); 1259 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1260 if (params.startCopy()) { 1261 // We are done... look for more work or to 1262 // go idle. 1263 if (DEBUG_SD_INSTALL) Log.i(TAG, 1264 "Checking for more work or unbind..."); 1265 // Delete pending install 1266 if (mPendingInstalls.size() > 0) { 1267 mPendingInstalls.remove(0); 1268 } 1269 if (mPendingInstalls.size() == 0) { 1270 if (mBound) { 1271 if (DEBUG_SD_INSTALL) Log.i(TAG, 1272 "Posting delayed MCS_UNBIND"); 1273 removeMessages(MCS_UNBIND); 1274 Message ubmsg = obtainMessage(MCS_UNBIND); 1275 // Unbind after a little delay, to avoid 1276 // continual thrashing. 1277 sendMessageDelayed(ubmsg, 10000); 1278 } 1279 } else { 1280 // There are more pending requests in queue. 1281 // Just post MCS_BOUND message to trigger processing 1282 // of next pending install. 1283 if (DEBUG_SD_INSTALL) Log.i(TAG, 1284 "Posting MCS_BOUND for next work"); 1285 mHandler.sendEmptyMessage(MCS_BOUND); 1286 } 1287 } 1288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1289 } 1290 } else { 1291 // Should never happen ideally. 1292 Slog.w(TAG, "Empty queue"); 1293 } 1294 break; 1295 } 1296 case MCS_RECONNECT: { 1297 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1298 if (mPendingInstalls.size() > 0) { 1299 if (mBound) { 1300 disconnectService(); 1301 } 1302 if (!connectToService()) { 1303 Slog.e(TAG, "Failed to bind to media container service"); 1304 for (HandlerParams params : mPendingInstalls) { 1305 // Indicate service bind error 1306 params.serviceError(); 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1308 System.identityHashCode(params)); 1309 } 1310 mPendingInstalls.clear(); 1311 } 1312 } 1313 break; 1314 } 1315 case MCS_UNBIND: { 1316 // If there is no actual work left, then time to unbind. 1317 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1318 1319 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1320 if (mBound) { 1321 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1322 1323 disconnectService(); 1324 } 1325 } else if (mPendingInstalls.size() > 0) { 1326 // There are more pending requests in queue. 1327 // Just post MCS_BOUND message to trigger processing 1328 // of next pending install. 1329 mHandler.sendEmptyMessage(MCS_BOUND); 1330 } 1331 1332 break; 1333 } 1334 case MCS_GIVE_UP: { 1335 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1336 HandlerParams params = mPendingInstalls.remove(0); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 break; 1340 } 1341 case SEND_PENDING_BROADCAST: { 1342 String packages[]; 1343 ArrayList<String> components[]; 1344 int size = 0; 1345 int uids[]; 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1347 synchronized (mPackages) { 1348 if (mPendingBroadcasts == null) { 1349 return; 1350 } 1351 size = mPendingBroadcasts.size(); 1352 if (size <= 0) { 1353 // Nothing to be done. Just return 1354 return; 1355 } 1356 packages = new String[size]; 1357 components = new ArrayList[size]; 1358 uids = new int[size]; 1359 int i = 0; // filling out the above arrays 1360 1361 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1362 int packageUserId = mPendingBroadcasts.userIdAt(n); 1363 Iterator<Map.Entry<String, ArrayList<String>>> it 1364 = mPendingBroadcasts.packagesForUserId(packageUserId) 1365 .entrySet().iterator(); 1366 while (it.hasNext() && i < size) { 1367 Map.Entry<String, ArrayList<String>> ent = it.next(); 1368 packages[i] = ent.getKey(); 1369 components[i] = ent.getValue(); 1370 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1371 uids[i] = (ps != null) 1372 ? UserHandle.getUid(packageUserId, ps.appId) 1373 : -1; 1374 i++; 1375 } 1376 } 1377 size = i; 1378 mPendingBroadcasts.clear(); 1379 } 1380 // Send broadcasts 1381 for (int i = 0; i < size; i++) { 1382 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1383 } 1384 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1385 break; 1386 } 1387 case START_CLEANING_PACKAGE: { 1388 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1389 final String packageName = (String)msg.obj; 1390 final int userId = msg.arg1; 1391 final boolean andCode = msg.arg2 != 0; 1392 synchronized (mPackages) { 1393 if (userId == UserHandle.USER_ALL) { 1394 int[] users = sUserManager.getUserIds(); 1395 for (int user : users) { 1396 mSettings.addPackageToCleanLPw( 1397 new PackageCleanItem(user, packageName, andCode)); 1398 } 1399 } else { 1400 mSettings.addPackageToCleanLPw( 1401 new PackageCleanItem(userId, packageName, andCode)); 1402 } 1403 } 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1405 startCleaningPackages(); 1406 } break; 1407 case POST_INSTALL: { 1408 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1409 1410 PostInstallData data = mRunningInstalls.get(msg.arg1); 1411 final boolean didRestore = (msg.arg2 != 0); 1412 mRunningInstalls.delete(msg.arg1); 1413 1414 if (data != null) { 1415 InstallArgs args = data.args; 1416 PackageInstalledInfo parentRes = data.res; 1417 1418 final boolean grantPermissions = (args.installFlags 1419 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1420 final boolean killApp = (args.installFlags 1421 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1422 final String[] grantedPermissions = args.installGrantPermissions; 1423 1424 // Handle the parent package 1425 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1426 grantedPermissions, didRestore, args.installerPackageName, 1427 args.observer); 1428 1429 // Handle the child packages 1430 final int childCount = (parentRes.addedChildPackages != null) 1431 ? parentRes.addedChildPackages.size() : 0; 1432 for (int i = 0; i < childCount; i++) { 1433 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1434 handlePackagePostInstall(childRes, grantPermissions, killApp, 1435 grantedPermissions, false, args.installerPackageName, 1436 args.observer); 1437 } 1438 1439 // Log tracing if needed 1440 if (args.traceMethod != null) { 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1442 args.traceCookie); 1443 } 1444 } else { 1445 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1446 } 1447 1448 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1449 } break; 1450 case UPDATED_MEDIA_STATUS: { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1452 boolean reportStatus = msg.arg1 == 1; 1453 boolean doGc = msg.arg2 == 1; 1454 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1455 if (doGc) { 1456 // Force a gc to clear up stale containers. 1457 Runtime.getRuntime().gc(); 1458 } 1459 if (msg.obj != null) { 1460 @SuppressWarnings("unchecked") 1461 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1463 // Unload containers 1464 unloadAllContainers(args); 1465 } 1466 if (reportStatus) { 1467 try { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1469 PackageHelper.getMountService().finishMediaUpdate(); 1470 } catch (RemoteException e) { 1471 Log.e(TAG, "MountService not running?"); 1472 } 1473 } 1474 } break; 1475 case WRITE_SETTINGS: { 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1477 synchronized (mPackages) { 1478 removeMessages(WRITE_SETTINGS); 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 mSettings.writeLPr(); 1481 mDirtyUsers.clear(); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 } break; 1485 case WRITE_PACKAGE_RESTRICTIONS: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 synchronized (mPackages) { 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 for (int userId : mDirtyUsers) { 1490 mSettings.writePackageRestrictionsLPr(userId); 1491 } 1492 mDirtyUsers.clear(); 1493 } 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1495 } break; 1496 case WRITE_PACKAGE_LIST: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 synchronized (mPackages) { 1499 removeMessages(WRITE_PACKAGE_LIST); 1500 mSettings.writePackageListLPr(msg.arg1); 1501 } 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1503 } break; 1504 case CHECK_PENDING_VERIFICATION: { 1505 final int verificationId = msg.arg1; 1506 final PackageVerificationState state = mPendingVerification.get(verificationId); 1507 1508 if ((state != null) && !state.timeoutExtended()) { 1509 final InstallArgs args = state.getInstallArgs(); 1510 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1511 1512 Slog.i(TAG, "Verification timed out for " + originUri); 1513 mPendingVerification.remove(verificationId); 1514 1515 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1516 1517 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1518 Slog.i(TAG, "Continuing with installation of " + originUri); 1519 state.setVerifierResponse(Binder.getCallingUid(), 1520 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1521 broadcastPackageVerified(verificationId, originUri, 1522 PackageManager.VERIFICATION_ALLOW, 1523 state.getInstallArgs().getUser()); 1524 try { 1525 ret = args.copyApk(mContainerService, true); 1526 } catch (RemoteException e) { 1527 Slog.e(TAG, "Could not contact the ContainerService"); 1528 } 1529 } else { 1530 broadcastPackageVerified(verificationId, originUri, 1531 PackageManager.VERIFICATION_REJECT, 1532 state.getInstallArgs().getUser()); 1533 } 1534 1535 Trace.asyncTraceEnd( 1536 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1537 1538 processPendingInstall(args, ret); 1539 mHandler.sendEmptyMessage(MCS_UNBIND); 1540 } 1541 break; 1542 } 1543 case PACKAGE_VERIFIED: { 1544 final int verificationId = msg.arg1; 1545 1546 final PackageVerificationState state = mPendingVerification.get(verificationId); 1547 if (state == null) { 1548 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1549 break; 1550 } 1551 1552 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1553 1554 state.setVerifierResponse(response.callerUid, response.code); 1555 1556 if (state.isVerificationComplete()) { 1557 mPendingVerification.remove(verificationId); 1558 1559 final InstallArgs args = state.getInstallArgs(); 1560 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1561 1562 int ret; 1563 if (state.isInstallAllowed()) { 1564 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1565 broadcastPackageVerified(verificationId, originUri, 1566 response.code, state.getInstallArgs().getUser()); 1567 try { 1568 ret = args.copyApk(mContainerService, true); 1569 } catch (RemoteException e) { 1570 Slog.e(TAG, "Could not contact the ContainerService"); 1571 } 1572 } else { 1573 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1574 } 1575 1576 Trace.asyncTraceEnd( 1577 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1578 1579 processPendingInstall(args, ret); 1580 mHandler.sendEmptyMessage(MCS_UNBIND); 1581 } 1582 1583 break; 1584 } 1585 case START_INTENT_FILTER_VERIFICATIONS: { 1586 IFVerificationParams params = (IFVerificationParams) msg.obj; 1587 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1588 params.replacing, params.pkg); 1589 break; 1590 } 1591 case INTENT_FILTER_VERIFIED: { 1592 final int verificationId = msg.arg1; 1593 1594 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1595 verificationId); 1596 if (state == null) { 1597 Slog.w(TAG, "Invalid IntentFilter verification token " 1598 + verificationId + " received"); 1599 break; 1600 } 1601 1602 final int userId = state.getUserId(); 1603 1604 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1605 "Processing IntentFilter verification with token:" 1606 + verificationId + " and userId:" + userId); 1607 1608 final IntentFilterVerificationResponse response = 1609 (IntentFilterVerificationResponse) msg.obj; 1610 1611 state.setVerifierResponse(response.callerUid, response.code); 1612 1613 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1614 "IntentFilter verification with token:" + verificationId 1615 + " and userId:" + userId 1616 + " is settings verifier response with response code:" 1617 + response.code); 1618 1619 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1621 + response.getFailedDomainsString()); 1622 } 1623 1624 if (state.isVerificationComplete()) { 1625 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1626 } else { 1627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1628 "IntentFilter verification with token:" + verificationId 1629 + " was not said to be complete"); 1630 } 1631 1632 break; 1633 } 1634 } 1635 } 1636 } 1637 1638 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1639 boolean killApp, String[] grantedPermissions, 1640 boolean launchedForRestore, String installerPackage, 1641 IPackageInstallObserver2 installObserver) { 1642 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1643 // Send the removed broadcasts 1644 if (res.removedInfo != null) { 1645 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1646 } 1647 1648 // Now that we successfully installed the package, grant runtime 1649 // permissions if requested before broadcasting the install. 1650 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1651 >= Build.VERSION_CODES.M) { 1652 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1653 } 1654 1655 final boolean update = res.removedInfo != null 1656 && res.removedInfo.removedPackage != null; 1657 1658 // If this is the first time we have child packages for a disabled privileged 1659 // app that had no children, we grant requested runtime permissions to the new 1660 // children if the parent on the system image had them already granted. 1661 if (res.pkg.parentPackage != null) { 1662 synchronized (mPackages) { 1663 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1664 } 1665 } 1666 1667 synchronized (mPackages) { 1668 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1669 } 1670 1671 final String packageName = res.pkg.applicationInfo.packageName; 1672 Bundle extras = new Bundle(1); 1673 extras.putInt(Intent.EXTRA_UID, res.uid); 1674 1675 // Determine the set of users who are adding this package for 1676 // the first time vs. those who are seeing an update. 1677 int[] firstUsers = EMPTY_INT_ARRAY; 1678 int[] updateUsers = EMPTY_INT_ARRAY; 1679 if (res.origUsers == null || res.origUsers.length == 0) { 1680 firstUsers = res.newUsers; 1681 } else { 1682 for (int newUser : res.newUsers) { 1683 boolean isNew = true; 1684 for (int origUser : res.origUsers) { 1685 if (origUser == newUser) { 1686 isNew = false; 1687 break; 1688 } 1689 } 1690 if (isNew) { 1691 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1692 } else { 1693 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1694 } 1695 } 1696 } 1697 1698 // Send installed broadcasts if the install/update is not ephemeral 1699 if (!isEphemeral(res.pkg)) { 1700 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1701 1702 // Send added for users that see the package for the first time 1703 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1704 extras, 0 /*flags*/, null /*targetPackage*/, 1705 null /*finishedReceiver*/, firstUsers); 1706 1707 // Send added for users that don't see the package for the first time 1708 if (update) { 1709 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1710 } 1711 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1712 extras, 0 /*flags*/, null /*targetPackage*/, 1713 null /*finishedReceiver*/, updateUsers); 1714 1715 // Send replaced for users that don't see the package for the first time 1716 if (update) { 1717 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1718 packageName, extras, 0 /*flags*/, 1719 null /*targetPackage*/, null /*finishedReceiver*/, 1720 updateUsers); 1721 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1722 null /*package*/, null /*extras*/, 0 /*flags*/, 1723 packageName /*targetPackage*/, 1724 null /*finishedReceiver*/, updateUsers); 1725 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1726 // First-install and we did a restore, so we're responsible for the 1727 // first-launch broadcast. 1728 if (DEBUG_BACKUP) { 1729 Slog.i(TAG, "Post-restore of " + packageName 1730 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1731 } 1732 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1733 } 1734 1735 // Send broadcast package appeared if forward locked/external for all users 1736 // treat asec-hosted packages like removable media on upgrade 1737 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1738 if (DEBUG_INSTALL) { 1739 Slog.i(TAG, "upgrading pkg " + res.pkg 1740 + " is ASEC-hosted -> AVAILABLE"); 1741 } 1742 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1743 ArrayList<String> pkgList = new ArrayList<>(1); 1744 pkgList.add(packageName); 1745 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1746 } 1747 } 1748 1749 // Work that needs to happen on first install within each user 1750 if (firstUsers != null && firstUsers.length > 0) { 1751 synchronized (mPackages) { 1752 for (int userId : firstUsers) { 1753 // If this app is a browser and it's newly-installed for some 1754 // users, clear any default-browser state in those users. The 1755 // app's nature doesn't depend on the user, so we can just check 1756 // its browser nature in any user and generalize. 1757 if (packageIsBrowser(packageName, userId)) { 1758 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1759 } 1760 1761 // We may also need to apply pending (restored) runtime 1762 // permission grants within these users. 1763 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1764 } 1765 } 1766 } 1767 1768 // Log current value of "unknown sources" setting 1769 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1770 getUnknownSourcesSettings()); 1771 1772 // Force a gc to clear up things 1773 Runtime.getRuntime().gc(); 1774 1775 // Remove the replaced package's older resources safely now 1776 // We delete after a gc for applications on sdcard. 1777 if (res.removedInfo != null && res.removedInfo.args != null) { 1778 synchronized (mInstallLock) { 1779 res.removedInfo.args.doPostDeleteLI(true); 1780 } 1781 } 1782 } 1783 1784 // If someone is watching installs - notify them 1785 if (installObserver != null) { 1786 try { 1787 Bundle extras = extrasForInstallResult(res); 1788 installObserver.onPackageInstalled(res.name, res.returnCode, 1789 res.returnMsg, extras); 1790 } catch (RemoteException e) { 1791 Slog.i(TAG, "Observer no longer exists."); 1792 } 1793 } 1794 } 1795 1796 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1797 PackageParser.Package pkg) { 1798 if (pkg.parentPackage == null) { 1799 return; 1800 } 1801 if (pkg.requestedPermissions == null) { 1802 return; 1803 } 1804 final PackageSetting disabledSysParentPs = mSettings 1805 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1806 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1807 || !disabledSysParentPs.isPrivileged() 1808 || (disabledSysParentPs.childPackageNames != null 1809 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1810 return; 1811 } 1812 final int[] allUserIds = sUserManager.getUserIds(); 1813 final int permCount = pkg.requestedPermissions.size(); 1814 for (int i = 0; i < permCount; i++) { 1815 String permission = pkg.requestedPermissions.get(i); 1816 BasePermission bp = mSettings.mPermissions.get(permission); 1817 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1818 continue; 1819 } 1820 for (int userId : allUserIds) { 1821 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1822 permission, userId)) { 1823 grantRuntimePermission(pkg.packageName, permission, userId); 1824 } 1825 } 1826 } 1827 } 1828 1829 private StorageEventListener mStorageListener = new StorageEventListener() { 1830 @Override 1831 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1832 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1833 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1834 final String volumeUuid = vol.getFsUuid(); 1835 1836 // Clean up any users or apps that were removed or recreated 1837 // while this volume was missing 1838 reconcileUsers(volumeUuid); 1839 reconcileApps(volumeUuid); 1840 1841 // Clean up any install sessions that expired or were 1842 // cancelled while this volume was missing 1843 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1844 1845 loadPrivatePackages(vol); 1846 1847 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1848 unloadPrivatePackages(vol); 1849 } 1850 } 1851 1852 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1853 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1854 updateExternalMediaStatus(true, false); 1855 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1856 updateExternalMediaStatus(false, false); 1857 } 1858 } 1859 } 1860 1861 @Override 1862 public void onVolumeForgotten(String fsUuid) { 1863 if (TextUtils.isEmpty(fsUuid)) { 1864 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1865 return; 1866 } 1867 1868 // Remove any apps installed on the forgotten volume 1869 synchronized (mPackages) { 1870 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1871 for (PackageSetting ps : packages) { 1872 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1873 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1874 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1875 } 1876 1877 mSettings.onVolumeForgotten(fsUuid); 1878 mSettings.writeLPr(); 1879 } 1880 } 1881 }; 1882 1883 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1884 String[] grantedPermissions) { 1885 for (int userId : userIds) { 1886 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1887 } 1888 1889 // We could have touched GID membership, so flush out packages.list 1890 synchronized (mPackages) { 1891 mSettings.writePackageListLPr(); 1892 } 1893 } 1894 1895 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1896 String[] grantedPermissions) { 1897 SettingBase sb = (SettingBase) pkg.mExtras; 1898 if (sb == null) { 1899 return; 1900 } 1901 1902 PermissionsState permissionsState = sb.getPermissionsState(); 1903 1904 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1905 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1906 1907 for (String permission : pkg.requestedPermissions) { 1908 final BasePermission bp; 1909 synchronized (mPackages) { 1910 bp = mSettings.mPermissions.get(permission); 1911 } 1912 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1913 && (grantedPermissions == null 1914 || ArrayUtils.contains(grantedPermissions, permission))) { 1915 final int flags = permissionsState.getPermissionFlags(permission, userId); 1916 // Installer cannot change immutable permissions. 1917 if ((flags & immutableFlags) == 0) { 1918 grantRuntimePermission(pkg.packageName, permission, userId); 1919 } 1920 } 1921 } 1922 } 1923 1924 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1925 Bundle extras = null; 1926 switch (res.returnCode) { 1927 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1928 extras = new Bundle(); 1929 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1930 res.origPermission); 1931 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1932 res.origPackage); 1933 break; 1934 } 1935 case PackageManager.INSTALL_SUCCEEDED: { 1936 extras = new Bundle(); 1937 extras.putBoolean(Intent.EXTRA_REPLACING, 1938 res.removedInfo != null && res.removedInfo.removedPackage != null); 1939 break; 1940 } 1941 } 1942 return extras; 1943 } 1944 1945 void scheduleWriteSettingsLocked() { 1946 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1947 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1948 } 1949 } 1950 1951 void scheduleWritePackageListLocked(int userId) { 1952 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1953 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1954 msg.arg1 = userId; 1955 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1956 } 1957 } 1958 1959 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1960 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1961 scheduleWritePackageRestrictionsLocked(userId); 1962 } 1963 1964 void scheduleWritePackageRestrictionsLocked(int userId) { 1965 final int[] userIds = (userId == UserHandle.USER_ALL) 1966 ? sUserManager.getUserIds() : new int[]{userId}; 1967 for (int nextUserId : userIds) { 1968 if (!sUserManager.exists(nextUserId)) return; 1969 mDirtyUsers.add(nextUserId); 1970 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1971 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1972 } 1973 } 1974 } 1975 1976 public static PackageManagerService main(Context context, Installer installer, 1977 boolean factoryTest, boolean onlyCore) { 1978 // Self-check for initial settings. 1979 PackageManagerServiceCompilerMapping.checkProperties(); 1980 1981 PackageManagerService m = new PackageManagerService(context, installer, 1982 factoryTest, onlyCore); 1983 m.enableSystemUserPackages(); 1984 ServiceManager.addService("package", m); 1985 return m; 1986 } 1987 1988 private void enableSystemUserPackages() { 1989 if (!UserManager.isSplitSystemUser()) { 1990 return; 1991 } 1992 // For system user, enable apps based on the following conditions: 1993 // - app is whitelisted or belong to one of these groups: 1994 // -- system app which has no launcher icons 1995 // -- system app which has INTERACT_ACROSS_USERS permission 1996 // -- system IME app 1997 // - app is not in the blacklist 1998 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1999 Set<String> enableApps = new ArraySet<>(); 2000 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2001 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2002 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2003 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2004 enableApps.addAll(wlApps); 2005 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2006 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2007 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2008 enableApps.removeAll(blApps); 2009 Log.i(TAG, "Applications installed for system user: " + enableApps); 2010 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2011 UserHandle.SYSTEM); 2012 final int allAppsSize = allAps.size(); 2013 synchronized (mPackages) { 2014 for (int i = 0; i < allAppsSize; i++) { 2015 String pName = allAps.get(i); 2016 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2017 // Should not happen, but we shouldn't be failing if it does 2018 if (pkgSetting == null) { 2019 continue; 2020 } 2021 boolean install = enableApps.contains(pName); 2022 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2023 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2024 + " for system user"); 2025 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2026 } 2027 } 2028 } 2029 } 2030 2031 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2032 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2033 Context.DISPLAY_SERVICE); 2034 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2035 } 2036 2037 /** 2038 * Requests that files preopted on a secondary system partition be copied to the data partition 2039 * if possible. Note that the actual copying of the files is accomplished by init for security 2040 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2041 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2042 */ 2043 private static void requestCopyPreoptedFiles() { 2044 final int WAIT_TIME_MS = 100; 2045 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2046 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2047 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2048 // We will wait for up to 100 seconds. 2049 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2050 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2051 try { 2052 Thread.sleep(WAIT_TIME_MS); 2053 } catch (InterruptedException e) { 2054 // Do nothing 2055 } 2056 if (SystemClock.uptimeMillis() > timeEnd) { 2057 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2058 Slog.wtf(TAG, "cppreopt did not finish!"); 2059 break; 2060 } 2061 } 2062 } 2063 } 2064 2065 public PackageManagerService(Context context, Installer installer, 2066 boolean factoryTest, boolean onlyCore) { 2067 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2068 SystemClock.uptimeMillis()); 2069 2070 if (mSdkVersion <= 0) { 2071 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2072 } 2073 2074 mContext = context; 2075 2076 mPermissionReviewRequired = context.getResources().getBoolean( 2077 R.bool.config_permissionReviewRequired); 2078 2079 mFactoryTest = factoryTest; 2080 mOnlyCore = onlyCore; 2081 mMetrics = new DisplayMetrics(); 2082 mSettings = new Settings(mPackages); 2083 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2084 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2085 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2086 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2087 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2088 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2089 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2090 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2091 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2092 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2093 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2094 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2095 2096 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2097 if (separateProcesses != null && separateProcesses.length() > 0) { 2098 if ("*".equals(separateProcesses)) { 2099 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2100 mSeparateProcesses = null; 2101 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2102 } else { 2103 mDefParseFlags = 0; 2104 mSeparateProcesses = separateProcesses.split(","); 2105 Slog.w(TAG, "Running with debug.separate_processes: " 2106 + separateProcesses); 2107 } 2108 } else { 2109 mDefParseFlags = 0; 2110 mSeparateProcesses = null; 2111 } 2112 2113 mInstaller = installer; 2114 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2115 "*dexopt*"); 2116 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2117 2118 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2119 FgThread.get().getLooper()); 2120 2121 getDefaultDisplayMetrics(context, mMetrics); 2122 2123 SystemConfig systemConfig = SystemConfig.getInstance(); 2124 mGlobalGids = systemConfig.getGlobalGids(); 2125 mSystemPermissions = systemConfig.getSystemPermissions(); 2126 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2127 2128 mProtectedPackages = new ProtectedPackages(mContext); 2129 2130 synchronized (mInstallLock) { 2131 // writer 2132 synchronized (mPackages) { 2133 mHandlerThread = new ServiceThread(TAG, 2134 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2135 mHandlerThread.start(); 2136 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2137 mProcessLoggingHandler = new ProcessLoggingHandler(); 2138 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2139 2140 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2141 2142 File dataDir = Environment.getDataDirectory(); 2143 mAppInstallDir = new File(dataDir, "app"); 2144 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2145 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2146 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2147 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2148 2149 sUserManager = new UserManagerService(context, this, mPackages); 2150 2151 // Propagate permission configuration in to package manager. 2152 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2153 = systemConfig.getPermissions(); 2154 for (int i=0; i<permConfig.size(); i++) { 2155 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2156 BasePermission bp = mSettings.mPermissions.get(perm.name); 2157 if (bp == null) { 2158 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2159 mSettings.mPermissions.put(perm.name, bp); 2160 } 2161 if (perm.gids != null) { 2162 bp.setGids(perm.gids, perm.perUser); 2163 } 2164 } 2165 2166 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2167 for (int i=0; i<libConfig.size(); i++) { 2168 mSharedLibraries.put(libConfig.keyAt(i), 2169 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2170 } 2171 2172 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2173 2174 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2175 2176 // Clean up orphaned packages for which the code path doesn't exist 2177 // and they are an update to a system app - caused by bug/32321269 2178 final int packageSettingCount = mSettings.mPackages.size(); 2179 for (int i = packageSettingCount - 1; i >= 0; i--) { 2180 PackageSetting ps = mSettings.mPackages.valueAt(i); 2181 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2182 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2183 mSettings.mPackages.removeAt(i); 2184 mSettings.enableSystemPackageLPw(ps.name); 2185 } 2186 } 2187 2188 if (mFirstBoot) { 2189 requestCopyPreoptedFiles(); 2190 } 2191 2192 String customResolverActivity = Resources.getSystem().getString( 2193 R.string.config_customResolverActivity); 2194 if (TextUtils.isEmpty(customResolverActivity)) { 2195 customResolverActivity = null; 2196 } else { 2197 mCustomResolverComponentName = ComponentName.unflattenFromString( 2198 customResolverActivity); 2199 } 2200 2201 long startTime = SystemClock.uptimeMillis(); 2202 2203 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2204 startTime); 2205 2206 // Set flag to monitor and not change apk file paths when 2207 // scanning install directories. 2208 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2209 2210 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2211 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2212 2213 if (bootClassPath == null) { 2214 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2215 } 2216 2217 if (systemServerClassPath == null) { 2218 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2219 } 2220 2221 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2222 final String[] dexCodeInstructionSets = 2223 getDexCodeInstructionSets( 2224 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2225 2226 /** 2227 * Ensure all external libraries have had dexopt run on them. 2228 */ 2229 if (mSharedLibraries.size() > 0) { 2230 // NOTE: For now, we're compiling these system "shared libraries" 2231 // (and framework jars) into all available architectures. It's possible 2232 // to compile them only when we come across an app that uses them (there's 2233 // already logic for that in scanPackageLI) but that adds some complexity. 2234 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2235 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2236 final String lib = libEntry.path; 2237 if (lib == null) { 2238 continue; 2239 } 2240 2241 try { 2242 // Shared libraries do not have profiles so we perform a full 2243 // AOT compilation (if needed). 2244 int dexoptNeeded = DexFile.getDexOptNeeded( 2245 lib, dexCodeInstructionSet, 2246 getCompilerFilterForReason(REASON_SHARED_APK), 2247 false /* newProfile */); 2248 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2249 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2250 dexCodeInstructionSet, dexoptNeeded, null, 2251 DEXOPT_PUBLIC, 2252 getCompilerFilterForReason(REASON_SHARED_APK), 2253 StorageManager.UUID_PRIVATE_INTERNAL, 2254 SKIP_SHARED_LIBRARY_CHECK); 2255 } 2256 } catch (FileNotFoundException e) { 2257 Slog.w(TAG, "Library not found: " + lib); 2258 } catch (IOException | InstallerException e) { 2259 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2260 + e.getMessage()); 2261 } 2262 } 2263 } 2264 } 2265 2266 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2267 2268 final VersionInfo ver = mSettings.getInternalVersion(); 2269 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2270 2271 // when upgrading from pre-M, promote system app permissions from install to runtime 2272 mPromoteSystemApps = 2273 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2274 2275 // When upgrading from pre-N, we need to handle package extraction like first boot, 2276 // as there is no profiling data available. 2277 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2278 2279 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2280 2281 // save off the names of pre-existing system packages prior to scanning; we don't 2282 // want to automatically grant runtime permissions for new system apps 2283 if (mPromoteSystemApps) { 2284 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2285 while (pkgSettingIter.hasNext()) { 2286 PackageSetting ps = pkgSettingIter.next(); 2287 if (isSystemApp(ps)) { 2288 mExistingSystemPackages.add(ps.name); 2289 } 2290 } 2291 } 2292 2293 // Collect vendor overlay packages. (Do this before scanning any apps.) 2294 // For security and version matching reason, only consider 2295 // overlay packages if they reside in the right directory. 2296 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2297 if (!overlayThemeDir.isEmpty()) { 2298 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2299 | PackageParser.PARSE_IS_SYSTEM 2300 | PackageParser.PARSE_IS_SYSTEM_DIR 2301 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2302 } 2303 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2304 | PackageParser.PARSE_IS_SYSTEM 2305 | PackageParser.PARSE_IS_SYSTEM_DIR 2306 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2307 2308 // Find base frameworks (resource packages without code). 2309 scanDirTracedLI(frameworkDir, mDefParseFlags 2310 | PackageParser.PARSE_IS_SYSTEM 2311 | PackageParser.PARSE_IS_SYSTEM_DIR 2312 | PackageParser.PARSE_IS_PRIVILEGED, 2313 scanFlags | SCAN_NO_DEX, 0); 2314 2315 // Collected privileged system packages. 2316 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2317 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2318 | PackageParser.PARSE_IS_SYSTEM 2319 | PackageParser.PARSE_IS_SYSTEM_DIR 2320 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2321 2322 // Collect ordinary system packages. 2323 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2324 scanDirTracedLI(systemAppDir, mDefParseFlags 2325 | PackageParser.PARSE_IS_SYSTEM 2326 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2327 2328 // Collect all vendor packages. 2329 File vendorAppDir = new File("/vendor/app"); 2330 try { 2331 vendorAppDir = vendorAppDir.getCanonicalFile(); 2332 } catch (IOException e) { 2333 // failed to look up canonical path, continue with original one 2334 } 2335 scanDirTracedLI(vendorAppDir, mDefParseFlags 2336 | PackageParser.PARSE_IS_SYSTEM 2337 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2338 2339 // Collect all OEM packages. 2340 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2341 scanDirTracedLI(oemAppDir, mDefParseFlags 2342 | PackageParser.PARSE_IS_SYSTEM 2343 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2344 2345 // Prune any system packages that no longer exist. 2346 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2347 if (!mOnlyCore) { 2348 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2349 while (psit.hasNext()) { 2350 PackageSetting ps = psit.next(); 2351 2352 /* 2353 * If this is not a system app, it can't be a 2354 * disable system app. 2355 */ 2356 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2357 continue; 2358 } 2359 2360 /* 2361 * If the package is scanned, it's not erased. 2362 */ 2363 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2364 if (scannedPkg != null) { 2365 /* 2366 * If the system app is both scanned and in the 2367 * disabled packages list, then it must have been 2368 * added via OTA. Remove it from the currently 2369 * scanned package so the previously user-installed 2370 * application can be scanned. 2371 */ 2372 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2373 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2374 + ps.name + "; removing system app. Last known codePath=" 2375 + ps.codePathString + ", installStatus=" + ps.installStatus 2376 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2377 + scannedPkg.mVersionCode); 2378 removePackageLI(scannedPkg, true); 2379 mExpectingBetter.put(ps.name, ps.codePath); 2380 } 2381 2382 continue; 2383 } 2384 2385 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2386 psit.remove(); 2387 logCriticalInfo(Log.WARN, "System package " + ps.name 2388 + " no longer exists; it's data will be wiped"); 2389 // Actual deletion of code and data will be handled by later 2390 // reconciliation step 2391 } else { 2392 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2393 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2394 possiblyDeletedUpdatedSystemApps.add(ps.name); 2395 } 2396 } 2397 } 2398 } 2399 2400 //look for any incomplete package installations 2401 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2402 for (int i = 0; i < deletePkgsList.size(); i++) { 2403 // Actual deletion of code and data will be handled by later 2404 // reconciliation step 2405 final String packageName = deletePkgsList.get(i).name; 2406 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2407 synchronized (mPackages) { 2408 mSettings.removePackageLPw(packageName); 2409 } 2410 } 2411 2412 //delete tmp files 2413 deleteTempPackageFiles(); 2414 2415 // Remove any shared userIDs that have no associated packages 2416 mSettings.pruneSharedUsersLPw(); 2417 2418 if (!mOnlyCore) { 2419 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2420 SystemClock.uptimeMillis()); 2421 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2422 2423 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2424 | PackageParser.PARSE_FORWARD_LOCK, 2425 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2426 2427 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2428 | PackageParser.PARSE_IS_EPHEMERAL, 2429 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2430 2431 /** 2432 * Remove disable package settings for any updated system 2433 * apps that were removed via an OTA. If they're not a 2434 * previously-updated app, remove them completely. 2435 * Otherwise, just revoke their system-level permissions. 2436 */ 2437 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2438 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2439 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2440 2441 String msg; 2442 if (deletedPkg == null) { 2443 msg = "Updated system package " + deletedAppName 2444 + " no longer exists; it's data will be wiped"; 2445 // Actual deletion of code and data will be handled by later 2446 // reconciliation step 2447 } else { 2448 msg = "Updated system app + " + deletedAppName 2449 + " no longer present; removing system privileges for " 2450 + deletedAppName; 2451 2452 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2453 2454 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2455 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2456 } 2457 logCriticalInfo(Log.WARN, msg); 2458 } 2459 2460 /** 2461 * Make sure all system apps that we expected to appear on 2462 * the userdata partition actually showed up. If they never 2463 * appeared, crawl back and revive the system version. 2464 */ 2465 for (int i = 0; i < mExpectingBetter.size(); i++) { 2466 final String packageName = mExpectingBetter.keyAt(i); 2467 if (!mPackages.containsKey(packageName)) { 2468 final File scanFile = mExpectingBetter.valueAt(i); 2469 2470 logCriticalInfo(Log.WARN, "Expected better " + packageName 2471 + " but never showed up; reverting to system"); 2472 2473 int reparseFlags = mDefParseFlags; 2474 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2475 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2476 | PackageParser.PARSE_IS_SYSTEM_DIR 2477 | PackageParser.PARSE_IS_PRIVILEGED; 2478 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2479 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2480 | PackageParser.PARSE_IS_SYSTEM_DIR; 2481 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2482 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2483 | PackageParser.PARSE_IS_SYSTEM_DIR; 2484 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2485 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2486 | PackageParser.PARSE_IS_SYSTEM_DIR; 2487 } else { 2488 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2489 continue; 2490 } 2491 2492 mSettings.enableSystemPackageLPw(packageName); 2493 2494 try { 2495 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2496 } catch (PackageManagerException e) { 2497 Slog.e(TAG, "Failed to parse original system package: " 2498 + e.getMessage()); 2499 } 2500 } 2501 } 2502 } 2503 mExpectingBetter.clear(); 2504 2505 // Resolve the storage manager. 2506 mStorageManagerPackage = getStorageManagerPackageName(); 2507 2508 // Resolve protected action filters. Only the setup wizard is allowed to 2509 // have a high priority filter for these actions. 2510 mSetupWizardPackage = getSetupWizardPackageName(); 2511 if (mProtectedFilters.size() > 0) { 2512 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2513 Slog.i(TAG, "No setup wizard;" 2514 + " All protected intents capped to priority 0"); 2515 } 2516 for (ActivityIntentInfo filter : mProtectedFilters) { 2517 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2518 if (DEBUG_FILTERS) { 2519 Slog.i(TAG, "Found setup wizard;" 2520 + " allow priority " + filter.getPriority() + ";" 2521 + " package: " + filter.activity.info.packageName 2522 + " activity: " + filter.activity.className 2523 + " priority: " + filter.getPriority()); 2524 } 2525 // skip setup wizard; allow it to keep the high priority filter 2526 continue; 2527 } 2528 Slog.w(TAG, "Protected action; cap priority to 0;" 2529 + " package: " + filter.activity.info.packageName 2530 + " activity: " + filter.activity.className 2531 + " origPrio: " + filter.getPriority()); 2532 filter.setPriority(0); 2533 } 2534 } 2535 mDeferProtectedFilters = false; 2536 mProtectedFilters.clear(); 2537 2538 // Now that we know all of the shared libraries, update all clients to have 2539 // the correct library paths. 2540 updateAllSharedLibrariesLPw(); 2541 2542 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2543 // NOTE: We ignore potential failures here during a system scan (like 2544 // the rest of the commands above) because there's precious little we 2545 // can do about it. A settings error is reported, though. 2546 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2547 false /* boot complete */); 2548 } 2549 2550 // Now that we know all the packages we are keeping, 2551 // read and update their last usage times. 2552 mPackageUsage.read(mPackages); 2553 mCompilerStats.read(); 2554 2555 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2556 SystemClock.uptimeMillis()); 2557 Slog.i(TAG, "Time to scan packages: " 2558 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2559 + " seconds"); 2560 2561 // If the platform SDK has changed since the last time we booted, 2562 // we need to re-grant app permission to catch any new ones that 2563 // appear. This is really a hack, and means that apps can in some 2564 // cases get permissions that the user didn't initially explicitly 2565 // allow... it would be nice to have some better way to handle 2566 // this situation. 2567 int updateFlags = UPDATE_PERMISSIONS_ALL; 2568 if (ver.sdkVersion != mSdkVersion) { 2569 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2570 + mSdkVersion + "; regranting permissions for internal storage"); 2571 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2572 } 2573 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2574 ver.sdkVersion = mSdkVersion; 2575 2576 // If this is the first boot or an update from pre-M, and it is a normal 2577 // boot, then we need to initialize the default preferred apps across 2578 // all defined users. 2579 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2580 for (UserInfo user : sUserManager.getUsers(true)) { 2581 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2582 applyFactoryDefaultBrowserLPw(user.id); 2583 primeDomainVerificationsLPw(user.id); 2584 } 2585 } 2586 2587 // Prepare storage for system user really early during boot, 2588 // since core system apps like SettingsProvider and SystemUI 2589 // can't wait for user to start 2590 final int storageFlags; 2591 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2592 storageFlags = StorageManager.FLAG_STORAGE_DE; 2593 } else { 2594 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2595 } 2596 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2597 storageFlags); 2598 2599 // If this is first boot after an OTA, and a normal boot, then 2600 // we need to clear code cache directories. 2601 // Note that we do *not* clear the application profiles. These remain valid 2602 // across OTAs and are used to drive profile verification (post OTA) and 2603 // profile compilation (without waiting to collect a fresh set of profiles). 2604 if (mIsUpgrade && !onlyCore) { 2605 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2606 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2607 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2608 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2609 // No apps are running this early, so no need to freeze 2610 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2611 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2612 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2613 } 2614 } 2615 ver.fingerprint = Build.FINGERPRINT; 2616 } 2617 2618 checkDefaultBrowser(); 2619 2620 // clear only after permissions and other defaults have been updated 2621 mExistingSystemPackages.clear(); 2622 mPromoteSystemApps = false; 2623 2624 // All the changes are done during package scanning. 2625 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2626 2627 // can downgrade to reader 2628 mSettings.writeLPr(); 2629 2630 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2631 // early on (before the package manager declares itself as early) because other 2632 // components in the system server might ask for package contexts for these apps. 2633 // 2634 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2635 // (i.e, that the data partition is unavailable). 2636 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2637 long start = System.nanoTime(); 2638 List<PackageParser.Package> coreApps = new ArrayList<>(); 2639 for (PackageParser.Package pkg : mPackages.values()) { 2640 if (pkg.coreApp) { 2641 coreApps.add(pkg); 2642 } 2643 } 2644 2645 int[] stats = performDexOptUpgrade(coreApps, false, 2646 getCompilerFilterForReason(REASON_CORE_APP)); 2647 2648 final int elapsedTimeSeconds = 2649 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2650 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2651 2652 if (DEBUG_DEXOPT) { 2653 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2654 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2655 } 2656 2657 2658 // TODO: Should we log these stats to tron too ? 2659 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2660 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2661 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2662 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2663 } 2664 2665 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2666 SystemClock.uptimeMillis()); 2667 2668 if (!mOnlyCore) { 2669 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2670 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2671 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2672 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2673 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2674 mIntentFilterVerifierComponent); 2675 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2676 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2677 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2678 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2679 } else { 2680 mRequiredVerifierPackage = null; 2681 mRequiredInstallerPackage = null; 2682 mRequiredUninstallerPackage = null; 2683 mIntentFilterVerifierComponent = null; 2684 mIntentFilterVerifier = null; 2685 mServicesSystemSharedLibraryPackageName = null; 2686 mSharedSystemSharedLibraryPackageName = null; 2687 } 2688 2689 mInstallerService = new PackageInstallerService(context, this); 2690 2691 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2692 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2693 // both the installer and resolver must be present to enable ephemeral 2694 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2695 if (DEBUG_EPHEMERAL) { 2696 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2697 + " installer:" + ephemeralInstallerComponent); 2698 } 2699 mEphemeralResolverComponent = ephemeralResolverComponent; 2700 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2701 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2702 mEphemeralResolverConnection = 2703 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2704 } else { 2705 if (DEBUG_EPHEMERAL) { 2706 final String missingComponent = 2707 (ephemeralResolverComponent == null) 2708 ? (ephemeralInstallerComponent == null) 2709 ? "resolver and installer" 2710 : "resolver" 2711 : "installer"; 2712 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2713 } 2714 mEphemeralResolverComponent = null; 2715 mEphemeralInstallerComponent = null; 2716 mEphemeralResolverConnection = null; 2717 } 2718 2719 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2720 } // synchronized (mPackages) 2721 } // synchronized (mInstallLock) 2722 2723 // Now after opening every single application zip, make sure they 2724 // are all flushed. Not really needed, but keeps things nice and 2725 // tidy. 2726 Runtime.getRuntime().gc(); 2727 2728 // The initial scanning above does many calls into installd while 2729 // holding the mPackages lock, but we're mostly interested in yelling 2730 // once we have a booted system. 2731 mInstaller.setWarnIfHeld(mPackages); 2732 2733 // Expose private service for system components to use. 2734 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2735 } 2736 2737 @Override 2738 public boolean isFirstBoot() { 2739 return mFirstBoot; 2740 } 2741 2742 @Override 2743 public boolean isOnlyCoreApps() { 2744 return mOnlyCore; 2745 } 2746 2747 @Override 2748 public boolean isUpgrade() { 2749 return mIsUpgrade; 2750 } 2751 2752 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2753 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2754 2755 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2756 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2757 UserHandle.USER_SYSTEM); 2758 if (matches.size() == 1) { 2759 return matches.get(0).getComponentInfo().packageName; 2760 } else if (matches.size() == 0) { 2761 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2762 return null; 2763 } 2764 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2765 } 2766 2767 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2768 synchronized (mPackages) { 2769 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2770 if (libraryEntry == null) { 2771 throw new IllegalStateException("Missing required shared library:" + libraryName); 2772 } 2773 return libraryEntry.apk; 2774 } 2775 } 2776 2777 private @NonNull String getRequiredInstallerLPr() { 2778 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2779 intent.addCategory(Intent.CATEGORY_DEFAULT); 2780 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2781 2782 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2783 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2784 UserHandle.USER_SYSTEM); 2785 if (matches.size() == 1) { 2786 ResolveInfo resolveInfo = matches.get(0); 2787 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2788 throw new RuntimeException("The installer must be a privileged app"); 2789 } 2790 return matches.get(0).getComponentInfo().packageName; 2791 } else { 2792 throw new RuntimeException("There must be exactly one installer; found " + matches); 2793 } 2794 } 2795 2796 private @NonNull String getRequiredUninstallerLPr() { 2797 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2798 intent.addCategory(Intent.CATEGORY_DEFAULT); 2799 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2800 2801 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2802 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2803 UserHandle.USER_SYSTEM); 2804 if (resolveInfo == null || 2805 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2806 throw new RuntimeException("There must be exactly one uninstaller; found " 2807 + resolveInfo); 2808 } 2809 return resolveInfo.getComponentInfo().packageName; 2810 } 2811 2812 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2813 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2814 2815 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2816 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2817 UserHandle.USER_SYSTEM); 2818 ResolveInfo best = null; 2819 final int N = matches.size(); 2820 for (int i = 0; i < N; i++) { 2821 final ResolveInfo cur = matches.get(i); 2822 final String packageName = cur.getComponentInfo().packageName; 2823 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2824 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2825 continue; 2826 } 2827 2828 if (best == null || cur.priority > best.priority) { 2829 best = cur; 2830 } 2831 } 2832 2833 if (best != null) { 2834 return best.getComponentInfo().getComponentName(); 2835 } else { 2836 throw new RuntimeException("There must be at least one intent filter verifier"); 2837 } 2838 } 2839 2840 private @Nullable ComponentName getEphemeralResolverLPr() { 2841 final String[] packageArray = 2842 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2843 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2844 if (DEBUG_EPHEMERAL) { 2845 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2846 } 2847 return null; 2848 } 2849 2850 final int resolveFlags = 2851 MATCH_DIRECT_BOOT_AWARE 2852 | MATCH_DIRECT_BOOT_UNAWARE 2853 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2854 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2855 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2856 resolveFlags, UserHandle.USER_SYSTEM); 2857 2858 final int N = resolvers.size(); 2859 if (N == 0) { 2860 if (DEBUG_EPHEMERAL) { 2861 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2862 } 2863 return null; 2864 } 2865 2866 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2867 for (int i = 0; i < N; i++) { 2868 final ResolveInfo info = resolvers.get(i); 2869 2870 if (info.serviceInfo == null) { 2871 continue; 2872 } 2873 2874 final String packageName = info.serviceInfo.packageName; 2875 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2876 if (DEBUG_EPHEMERAL) { 2877 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2878 + " pkg: " + packageName + ", info:" + info); 2879 } 2880 continue; 2881 } 2882 2883 if (DEBUG_EPHEMERAL) { 2884 Slog.v(TAG, "Ephemeral resolver found;" 2885 + " pkg: " + packageName + ", info:" + info); 2886 } 2887 return new ComponentName(packageName, info.serviceInfo.name); 2888 } 2889 if (DEBUG_EPHEMERAL) { 2890 Slog.v(TAG, "Ephemeral resolver NOT found"); 2891 } 2892 return null; 2893 } 2894 2895 private @Nullable ComponentName getEphemeralInstallerLPr() { 2896 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2897 intent.addCategory(Intent.CATEGORY_DEFAULT); 2898 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2899 2900 final int resolveFlags = 2901 MATCH_DIRECT_BOOT_AWARE 2902 | MATCH_DIRECT_BOOT_UNAWARE 2903 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2904 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2905 resolveFlags, UserHandle.USER_SYSTEM); 2906 if (matches.size() == 0) { 2907 return null; 2908 } else if (matches.size() == 1) { 2909 return matches.get(0).getComponentInfo().getComponentName(); 2910 } else { 2911 throw new RuntimeException( 2912 "There must be at most one ephemeral installer; found " + matches); 2913 } 2914 } 2915 2916 private void primeDomainVerificationsLPw(int userId) { 2917 if (DEBUG_DOMAIN_VERIFICATION) { 2918 Slog.d(TAG, "Priming domain verifications in user " + userId); 2919 } 2920 2921 SystemConfig systemConfig = SystemConfig.getInstance(); 2922 ArraySet<String> packages = systemConfig.getLinkedApps(); 2923 ArraySet<String> domains = new ArraySet<String>(); 2924 2925 for (String packageName : packages) { 2926 PackageParser.Package pkg = mPackages.get(packageName); 2927 if (pkg != null) { 2928 if (!pkg.isSystemApp()) { 2929 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2930 continue; 2931 } 2932 2933 domains.clear(); 2934 for (PackageParser.Activity a : pkg.activities) { 2935 for (ActivityIntentInfo filter : a.intents) { 2936 if (hasValidDomains(filter)) { 2937 domains.addAll(filter.getHostsList()); 2938 } 2939 } 2940 } 2941 2942 if (domains.size() > 0) { 2943 if (DEBUG_DOMAIN_VERIFICATION) { 2944 Slog.v(TAG, " + " + packageName); 2945 } 2946 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2947 // state w.r.t. the formal app-linkage "no verification attempted" state; 2948 // and then 'always' in the per-user state actually used for intent resolution. 2949 final IntentFilterVerificationInfo ivi; 2950 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2951 new ArrayList<String>(domains)); 2952 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2953 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2954 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2955 } else { 2956 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2957 + "' does not handle web links"); 2958 } 2959 } else { 2960 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2961 } 2962 } 2963 2964 scheduleWritePackageRestrictionsLocked(userId); 2965 scheduleWriteSettingsLocked(); 2966 } 2967 2968 private void applyFactoryDefaultBrowserLPw(int userId) { 2969 // The default browser app's package name is stored in a string resource, 2970 // with a product-specific overlay used for vendor customization. 2971 String browserPkg = mContext.getResources().getString( 2972 com.android.internal.R.string.default_browser); 2973 if (!TextUtils.isEmpty(browserPkg)) { 2974 // non-empty string => required to be a known package 2975 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2976 if (ps == null) { 2977 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2978 browserPkg = null; 2979 } else { 2980 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2981 } 2982 } 2983 2984 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2985 // default. If there's more than one, just leave everything alone. 2986 if (browserPkg == null) { 2987 calculateDefaultBrowserLPw(userId); 2988 } 2989 } 2990 2991 private void calculateDefaultBrowserLPw(int userId) { 2992 List<String> allBrowsers = resolveAllBrowserApps(userId); 2993 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2994 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2995 } 2996 2997 private List<String> resolveAllBrowserApps(int userId) { 2998 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2999 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3000 PackageManager.MATCH_ALL, userId); 3001 3002 final int count = list.size(); 3003 List<String> result = new ArrayList<String>(count); 3004 for (int i=0; i<count; i++) { 3005 ResolveInfo info = list.get(i); 3006 if (info.activityInfo == null 3007 || !info.handleAllWebDataURI 3008 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3009 || result.contains(info.activityInfo.packageName)) { 3010 continue; 3011 } 3012 result.add(info.activityInfo.packageName); 3013 } 3014 3015 return result; 3016 } 3017 3018 private boolean packageIsBrowser(String packageName, int userId) { 3019 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3020 PackageManager.MATCH_ALL, userId); 3021 final int N = list.size(); 3022 for (int i = 0; i < N; i++) { 3023 ResolveInfo info = list.get(i); 3024 if (packageName.equals(info.activityInfo.packageName)) { 3025 return true; 3026 } 3027 } 3028 return false; 3029 } 3030 3031 private void checkDefaultBrowser() { 3032 final int myUserId = UserHandle.myUserId(); 3033 final String packageName = getDefaultBrowserPackageName(myUserId); 3034 if (packageName != null) { 3035 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3036 if (info == null) { 3037 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3038 synchronized (mPackages) { 3039 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3040 } 3041 } 3042 } 3043 } 3044 3045 @Override 3046 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3047 throws RemoteException { 3048 try { 3049 return super.onTransact(code, data, reply, flags); 3050 } catch (RuntimeException e) { 3051 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3052 Slog.wtf(TAG, "Package Manager Crash", e); 3053 } 3054 throw e; 3055 } 3056 } 3057 3058 static int[] appendInts(int[] cur, int[] add) { 3059 if (add == null) return cur; 3060 if (cur == null) return add; 3061 final int N = add.length; 3062 for (int i=0; i<N; i++) { 3063 cur = appendInt(cur, add[i]); 3064 } 3065 return cur; 3066 } 3067 3068 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3069 if (!sUserManager.exists(userId)) return null; 3070 if (ps == null) { 3071 return null; 3072 } 3073 final PackageParser.Package p = ps.pkg; 3074 if (p == null) { 3075 return null; 3076 } 3077 3078 final PermissionsState permissionsState = ps.getPermissionsState(); 3079 3080 // Compute GIDs only if requested 3081 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3082 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3083 // Compute granted permissions only if package has requested permissions 3084 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3085 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3086 final PackageUserState state = ps.readUserState(userId); 3087 3088 return PackageParser.generatePackageInfo(p, gids, flags, 3089 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3090 } 3091 3092 @Override 3093 public void checkPackageStartable(String packageName, int userId) { 3094 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3095 3096 synchronized (mPackages) { 3097 final PackageSetting ps = mSettings.mPackages.get(packageName); 3098 if (ps == null) { 3099 throw new SecurityException("Package " + packageName + " was not found!"); 3100 } 3101 3102 if (!ps.getInstalled(userId)) { 3103 throw new SecurityException( 3104 "Package " + packageName + " was not installed for user " + userId + "!"); 3105 } 3106 3107 if (mSafeMode && !ps.isSystem()) { 3108 throw new SecurityException("Package " + packageName + " not a system app!"); 3109 } 3110 3111 if (mFrozenPackages.contains(packageName)) { 3112 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3113 } 3114 3115 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3116 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3117 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3118 } 3119 } 3120 } 3121 3122 @Override 3123 public boolean isPackageAvailable(String packageName, int userId) { 3124 if (!sUserManager.exists(userId)) return false; 3125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3126 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3127 synchronized (mPackages) { 3128 PackageParser.Package p = mPackages.get(packageName); 3129 if (p != null) { 3130 final PackageSetting ps = (PackageSetting) p.mExtras; 3131 if (ps != null) { 3132 final PackageUserState state = ps.readUserState(userId); 3133 if (state != null) { 3134 return PackageParser.isAvailable(state); 3135 } 3136 } 3137 } 3138 } 3139 return false; 3140 } 3141 3142 @Override 3143 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3144 if (!sUserManager.exists(userId)) return null; 3145 flags = updateFlagsForPackage(flags, userId, packageName); 3146 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3147 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3148 3149 // reader 3150 synchronized (mPackages) { 3151 // Normalize package name to hanlde renamed packages 3152 packageName = normalizePackageNameLPr(packageName); 3153 3154 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3155 PackageParser.Package p = null; 3156 if (matchFactoryOnly) { 3157 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3158 if (ps != null) { 3159 return generatePackageInfo(ps, flags, userId); 3160 } 3161 } 3162 if (p == null) { 3163 p = mPackages.get(packageName); 3164 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3165 return null; 3166 } 3167 } 3168 if (DEBUG_PACKAGE_INFO) 3169 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3170 if (p != null) { 3171 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3172 } 3173 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3174 final PackageSetting ps = mSettings.mPackages.get(packageName); 3175 return generatePackageInfo(ps, flags, userId); 3176 } 3177 } 3178 return null; 3179 } 3180 3181 @Override 3182 public String[] currentToCanonicalPackageNames(String[] names) { 3183 String[] out = new String[names.length]; 3184 // reader 3185 synchronized (mPackages) { 3186 for (int i=names.length-1; i>=0; i--) { 3187 PackageSetting ps = mSettings.mPackages.get(names[i]); 3188 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3189 } 3190 } 3191 return out; 3192 } 3193 3194 @Override 3195 public String[] canonicalToCurrentPackageNames(String[] names) { 3196 String[] out = new String[names.length]; 3197 // reader 3198 synchronized (mPackages) { 3199 for (int i=names.length-1; i>=0; i--) { 3200 String cur = mSettings.mRenamedPackages.get(names[i]); 3201 out[i] = cur != null ? cur : names[i]; 3202 } 3203 } 3204 return out; 3205 } 3206 3207 @Override 3208 public int getPackageUid(String packageName, int flags, int userId) { 3209 if (!sUserManager.exists(userId)) return -1; 3210 flags = updateFlagsForPackage(flags, userId, packageName); 3211 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3212 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3213 3214 // reader 3215 synchronized (mPackages) { 3216 final PackageParser.Package p = mPackages.get(packageName); 3217 if (p != null && p.isMatch(flags)) { 3218 return UserHandle.getUid(userId, p.applicationInfo.uid); 3219 } 3220 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3221 final PackageSetting ps = mSettings.mPackages.get(packageName); 3222 if (ps != null && ps.isMatch(flags)) { 3223 return UserHandle.getUid(userId, ps.appId); 3224 } 3225 } 3226 } 3227 3228 return -1; 3229 } 3230 3231 @Override 3232 public int[] getPackageGids(String packageName, int flags, int userId) { 3233 if (!sUserManager.exists(userId)) return null; 3234 flags = updateFlagsForPackage(flags, userId, packageName); 3235 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3236 false /* requireFullPermission */, false /* checkShell */, 3237 "getPackageGids"); 3238 3239 // reader 3240 synchronized (mPackages) { 3241 final PackageParser.Package p = mPackages.get(packageName); 3242 if (p != null && p.isMatch(flags)) { 3243 PackageSetting ps = (PackageSetting) p.mExtras; 3244 return ps.getPermissionsState().computeGids(userId); 3245 } 3246 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3247 final PackageSetting ps = mSettings.mPackages.get(packageName); 3248 if (ps != null && ps.isMatch(flags)) { 3249 return ps.getPermissionsState().computeGids(userId); 3250 } 3251 } 3252 } 3253 3254 return null; 3255 } 3256 3257 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3258 if (bp.perm != null) { 3259 return PackageParser.generatePermissionInfo(bp.perm, flags); 3260 } 3261 PermissionInfo pi = new PermissionInfo(); 3262 pi.name = bp.name; 3263 pi.packageName = bp.sourcePackage; 3264 pi.nonLocalizedLabel = bp.name; 3265 pi.protectionLevel = bp.protectionLevel; 3266 return pi; 3267 } 3268 3269 @Override 3270 public PermissionInfo getPermissionInfo(String name, int flags) { 3271 // reader 3272 synchronized (mPackages) { 3273 final BasePermission p = mSettings.mPermissions.get(name); 3274 if (p != null) { 3275 return generatePermissionInfo(p, flags); 3276 } 3277 return null; 3278 } 3279 } 3280 3281 @Override 3282 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3283 int flags) { 3284 // reader 3285 synchronized (mPackages) { 3286 if (group != null && !mPermissionGroups.containsKey(group)) { 3287 // This is thrown as NameNotFoundException 3288 return null; 3289 } 3290 3291 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3292 for (BasePermission p : mSettings.mPermissions.values()) { 3293 if (group == null) { 3294 if (p.perm == null || p.perm.info.group == null) { 3295 out.add(generatePermissionInfo(p, flags)); 3296 } 3297 } else { 3298 if (p.perm != null && group.equals(p.perm.info.group)) { 3299 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3300 } 3301 } 3302 } 3303 return new ParceledListSlice<>(out); 3304 } 3305 } 3306 3307 @Override 3308 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3309 // reader 3310 synchronized (mPackages) { 3311 return PackageParser.generatePermissionGroupInfo( 3312 mPermissionGroups.get(name), flags); 3313 } 3314 } 3315 3316 @Override 3317 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3318 // reader 3319 synchronized (mPackages) { 3320 final int N = mPermissionGroups.size(); 3321 ArrayList<PermissionGroupInfo> out 3322 = new ArrayList<PermissionGroupInfo>(N); 3323 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3324 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3325 } 3326 return new ParceledListSlice<>(out); 3327 } 3328 } 3329 3330 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3331 int userId) { 3332 if (!sUserManager.exists(userId)) return null; 3333 PackageSetting ps = mSettings.mPackages.get(packageName); 3334 if (ps != null) { 3335 if (ps.pkg == null) { 3336 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3337 if (pInfo != null) { 3338 return pInfo.applicationInfo; 3339 } 3340 return null; 3341 } 3342 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3343 ps.readUserState(userId), userId); 3344 } 3345 return null; 3346 } 3347 3348 @Override 3349 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3350 if (!sUserManager.exists(userId)) return null; 3351 flags = updateFlagsForApplication(flags, userId, packageName); 3352 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3353 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3354 3355 // writer 3356 synchronized (mPackages) { 3357 // Normalize package name to hanlde renamed packages 3358 packageName = normalizePackageNameLPr(packageName); 3359 3360 PackageParser.Package p = mPackages.get(packageName); 3361 if (DEBUG_PACKAGE_INFO) Log.v( 3362 TAG, "getApplicationInfo " + packageName 3363 + ": " + p); 3364 if (p != null) { 3365 PackageSetting ps = mSettings.mPackages.get(packageName); 3366 if (ps == null) return null; 3367 // Note: isEnabledLP() does not apply here - always return info 3368 return PackageParser.generateApplicationInfo( 3369 p, flags, ps.readUserState(userId), userId); 3370 } 3371 if ("android".equals(packageName)||"system".equals(packageName)) { 3372 return mAndroidApplication; 3373 } 3374 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3375 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3376 } 3377 } 3378 return null; 3379 } 3380 3381 private String normalizePackageNameLPr(String packageName) { 3382 String normalizedPackageName = mSettings.mRenamedPackages.get(packageName); 3383 return normalizedPackageName != null ? normalizedPackageName : packageName; 3384 } 3385 3386 @Override 3387 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3388 final IPackageDataObserver observer) { 3389 mContext.enforceCallingOrSelfPermission( 3390 android.Manifest.permission.CLEAR_APP_CACHE, null); 3391 // Queue up an async operation since clearing cache may take a little while. 3392 mHandler.post(new Runnable() { 3393 public void run() { 3394 mHandler.removeCallbacks(this); 3395 boolean success = true; 3396 synchronized (mInstallLock) { 3397 try { 3398 mInstaller.freeCache(volumeUuid, freeStorageSize); 3399 } catch (InstallerException e) { 3400 Slog.w(TAG, "Couldn't clear application caches: " + e); 3401 success = false; 3402 } 3403 } 3404 if (observer != null) { 3405 try { 3406 observer.onRemoveCompleted(null, success); 3407 } catch (RemoteException e) { 3408 Slog.w(TAG, "RemoveException when invoking call back"); 3409 } 3410 } 3411 } 3412 }); 3413 } 3414 3415 @Override 3416 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3417 final IntentSender pi) { 3418 mContext.enforceCallingOrSelfPermission( 3419 android.Manifest.permission.CLEAR_APP_CACHE, null); 3420 // Queue up an async operation since clearing cache may take a little while. 3421 mHandler.post(new Runnable() { 3422 public void run() { 3423 mHandler.removeCallbacks(this); 3424 boolean success = true; 3425 synchronized (mInstallLock) { 3426 try { 3427 mInstaller.freeCache(volumeUuid, freeStorageSize); 3428 } catch (InstallerException e) { 3429 Slog.w(TAG, "Couldn't clear application caches: " + e); 3430 success = false; 3431 } 3432 } 3433 if(pi != null) { 3434 try { 3435 // Callback via pending intent 3436 int code = success ? 1 : 0; 3437 pi.sendIntent(null, code, null, 3438 null, null); 3439 } catch (SendIntentException e1) { 3440 Slog.i(TAG, "Failed to send pending intent"); 3441 } 3442 } 3443 } 3444 }); 3445 } 3446 3447 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3448 synchronized (mInstallLock) { 3449 try { 3450 mInstaller.freeCache(volumeUuid, freeStorageSize); 3451 } catch (InstallerException e) { 3452 throw new IOException("Failed to free enough space", e); 3453 } 3454 } 3455 } 3456 3457 /** 3458 * Update given flags based on encryption status of current user. 3459 */ 3460 private int updateFlags(int flags, int userId) { 3461 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3462 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3463 // Caller expressed an explicit opinion about what encryption 3464 // aware/unaware components they want to see, so fall through and 3465 // give them what they want 3466 } else { 3467 // Caller expressed no opinion, so match based on user state 3468 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3469 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3470 } else { 3471 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3472 } 3473 } 3474 return flags; 3475 } 3476 3477 private UserManagerInternal getUserManagerInternal() { 3478 if (mUserManagerInternal == null) { 3479 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3480 } 3481 return mUserManagerInternal; 3482 } 3483 3484 /** 3485 * Update given flags when being used to request {@link PackageInfo}. 3486 */ 3487 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3488 boolean triaged = true; 3489 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3490 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3491 // Caller is asking for component details, so they'd better be 3492 // asking for specific encryption matching behavior, or be triaged 3493 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3494 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3495 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3496 triaged = false; 3497 } 3498 } 3499 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3500 | PackageManager.MATCH_SYSTEM_ONLY 3501 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3502 triaged = false; 3503 } 3504 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3505 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3506 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3507 } 3508 return updateFlags(flags, userId); 3509 } 3510 3511 /** 3512 * Update given flags when being used to request {@link ApplicationInfo}. 3513 */ 3514 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3515 return updateFlagsForPackage(flags, userId, cookie); 3516 } 3517 3518 /** 3519 * Update given flags when being used to request {@link ComponentInfo}. 3520 */ 3521 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3522 if (cookie instanceof Intent) { 3523 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3524 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3525 } 3526 } 3527 3528 boolean triaged = true; 3529 // Caller is asking for component details, so they'd better be 3530 // asking for specific encryption matching behavior, or be triaged 3531 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3532 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3533 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3534 triaged = false; 3535 } 3536 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3537 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3538 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3539 } 3540 3541 return updateFlags(flags, userId); 3542 } 3543 3544 /** 3545 * Update given flags when being used to request {@link ResolveInfo}. 3546 */ 3547 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3548 // Safe mode means we shouldn't match any third-party components 3549 if (mSafeMode) { 3550 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3551 } 3552 3553 return updateFlagsForComponent(flags, userId, cookie); 3554 } 3555 3556 @Override 3557 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3558 if (!sUserManager.exists(userId)) return null; 3559 flags = updateFlagsForComponent(flags, userId, component); 3560 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3561 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3562 synchronized (mPackages) { 3563 PackageParser.Activity a = mActivities.mActivities.get(component); 3564 3565 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3566 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3567 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3568 if (ps == null) return null; 3569 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3570 userId); 3571 } 3572 if (mResolveComponentName.equals(component)) { 3573 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3574 new PackageUserState(), userId); 3575 } 3576 } 3577 return null; 3578 } 3579 3580 @Override 3581 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3582 String resolvedType) { 3583 synchronized (mPackages) { 3584 if (component.equals(mResolveComponentName)) { 3585 // The resolver supports EVERYTHING! 3586 return true; 3587 } 3588 PackageParser.Activity a = mActivities.mActivities.get(component); 3589 if (a == null) { 3590 return false; 3591 } 3592 for (int i=0; i<a.intents.size(); i++) { 3593 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3594 intent.getData(), intent.getCategories(), TAG) >= 0) { 3595 return true; 3596 } 3597 } 3598 return false; 3599 } 3600 } 3601 3602 @Override 3603 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3604 if (!sUserManager.exists(userId)) return null; 3605 flags = updateFlagsForComponent(flags, userId, component); 3606 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3607 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3608 synchronized (mPackages) { 3609 PackageParser.Activity a = mReceivers.mActivities.get(component); 3610 if (DEBUG_PACKAGE_INFO) Log.v( 3611 TAG, "getReceiverInfo " + component + ": " + a); 3612 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3613 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3614 if (ps == null) return null; 3615 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3616 userId); 3617 } 3618 } 3619 return null; 3620 } 3621 3622 @Override 3623 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3624 if (!sUserManager.exists(userId)) return null; 3625 flags = updateFlagsForComponent(flags, userId, component); 3626 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3627 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3628 synchronized (mPackages) { 3629 PackageParser.Service s = mServices.mServices.get(component); 3630 if (DEBUG_PACKAGE_INFO) Log.v( 3631 TAG, "getServiceInfo " + component + ": " + s); 3632 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3633 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3634 if (ps == null) return null; 3635 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3636 userId); 3637 } 3638 } 3639 return null; 3640 } 3641 3642 @Override 3643 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3644 if (!sUserManager.exists(userId)) return null; 3645 flags = updateFlagsForComponent(flags, userId, component); 3646 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3647 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3648 synchronized (mPackages) { 3649 PackageParser.Provider p = mProviders.mProviders.get(component); 3650 if (DEBUG_PACKAGE_INFO) Log.v( 3651 TAG, "getProviderInfo " + component + ": " + p); 3652 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3653 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3654 if (ps == null) return null; 3655 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3656 userId); 3657 } 3658 } 3659 return null; 3660 } 3661 3662 @Override 3663 public String[] getSystemSharedLibraryNames() { 3664 Set<String> libSet; 3665 synchronized (mPackages) { 3666 libSet = mSharedLibraries.keySet(); 3667 int size = libSet.size(); 3668 if (size > 0) { 3669 String[] libs = new String[size]; 3670 libSet.toArray(libs); 3671 return libs; 3672 } 3673 } 3674 return null; 3675 } 3676 3677 @Override 3678 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3679 synchronized (mPackages) { 3680 return mServicesSystemSharedLibraryPackageName; 3681 } 3682 } 3683 3684 @Override 3685 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3686 synchronized (mPackages) { 3687 return mSharedSystemSharedLibraryPackageName; 3688 } 3689 } 3690 3691 @Override 3692 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3693 synchronized (mPackages) { 3694 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3695 3696 final FeatureInfo fi = new FeatureInfo(); 3697 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3698 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3699 res.add(fi); 3700 3701 return new ParceledListSlice<>(res); 3702 } 3703 } 3704 3705 @Override 3706 public boolean hasSystemFeature(String name, int version) { 3707 synchronized (mPackages) { 3708 final FeatureInfo feat = mAvailableFeatures.get(name); 3709 if (feat == null) { 3710 return false; 3711 } else { 3712 return feat.version >= version; 3713 } 3714 } 3715 } 3716 3717 @Override 3718 public int checkPermission(String permName, String pkgName, int userId) { 3719 if (!sUserManager.exists(userId)) { 3720 return PackageManager.PERMISSION_DENIED; 3721 } 3722 3723 synchronized (mPackages) { 3724 final PackageParser.Package p = mPackages.get(pkgName); 3725 if (p != null && p.mExtras != null) { 3726 final PackageSetting ps = (PackageSetting) p.mExtras; 3727 final PermissionsState permissionsState = ps.getPermissionsState(); 3728 if (permissionsState.hasPermission(permName, userId)) { 3729 return PackageManager.PERMISSION_GRANTED; 3730 } 3731 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3732 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3733 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3734 return PackageManager.PERMISSION_GRANTED; 3735 } 3736 } 3737 } 3738 3739 return PackageManager.PERMISSION_DENIED; 3740 } 3741 3742 @Override 3743 public int checkUidPermission(String permName, int uid) { 3744 final int userId = UserHandle.getUserId(uid); 3745 3746 if (!sUserManager.exists(userId)) { 3747 return PackageManager.PERMISSION_DENIED; 3748 } 3749 3750 synchronized (mPackages) { 3751 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3752 if (obj != null) { 3753 final SettingBase ps = (SettingBase) obj; 3754 final PermissionsState permissionsState = ps.getPermissionsState(); 3755 if (permissionsState.hasPermission(permName, userId)) { 3756 return PackageManager.PERMISSION_GRANTED; 3757 } 3758 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3759 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3760 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3761 return PackageManager.PERMISSION_GRANTED; 3762 } 3763 } else { 3764 ArraySet<String> perms = mSystemPermissions.get(uid); 3765 if (perms != null) { 3766 if (perms.contains(permName)) { 3767 return PackageManager.PERMISSION_GRANTED; 3768 } 3769 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3770 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3771 return PackageManager.PERMISSION_GRANTED; 3772 } 3773 } 3774 } 3775 } 3776 3777 return PackageManager.PERMISSION_DENIED; 3778 } 3779 3780 @Override 3781 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3782 if (UserHandle.getCallingUserId() != userId) { 3783 mContext.enforceCallingPermission( 3784 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3785 "isPermissionRevokedByPolicy for user " + userId); 3786 } 3787 3788 if (checkPermission(permission, packageName, userId) 3789 == PackageManager.PERMISSION_GRANTED) { 3790 return false; 3791 } 3792 3793 final long identity = Binder.clearCallingIdentity(); 3794 try { 3795 final int flags = getPermissionFlags(permission, packageName, userId); 3796 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3797 } finally { 3798 Binder.restoreCallingIdentity(identity); 3799 } 3800 } 3801 3802 @Override 3803 public String getPermissionControllerPackageName() { 3804 synchronized (mPackages) { 3805 return mRequiredInstallerPackage; 3806 } 3807 } 3808 3809 /** 3810 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3811 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3812 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3813 * @param message the message to log on security exception 3814 */ 3815 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3816 boolean checkShell, String message) { 3817 if (userId < 0) { 3818 throw new IllegalArgumentException("Invalid userId " + userId); 3819 } 3820 if (checkShell) { 3821 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3822 } 3823 if (userId == UserHandle.getUserId(callingUid)) return; 3824 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3825 if (requireFullPermission) { 3826 mContext.enforceCallingOrSelfPermission( 3827 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3828 } else { 3829 try { 3830 mContext.enforceCallingOrSelfPermission( 3831 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3832 } catch (SecurityException se) { 3833 mContext.enforceCallingOrSelfPermission( 3834 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3835 } 3836 } 3837 } 3838 } 3839 3840 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3841 if (callingUid == Process.SHELL_UID) { 3842 if (userHandle >= 0 3843 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3844 throw new SecurityException("Shell does not have permission to access user " 3845 + userHandle); 3846 } else if (userHandle < 0) { 3847 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3848 + Debug.getCallers(3)); 3849 } 3850 } 3851 } 3852 3853 private BasePermission findPermissionTreeLP(String permName) { 3854 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3855 if (permName.startsWith(bp.name) && 3856 permName.length() > bp.name.length() && 3857 permName.charAt(bp.name.length()) == '.') { 3858 return bp; 3859 } 3860 } 3861 return null; 3862 } 3863 3864 private BasePermission checkPermissionTreeLP(String permName) { 3865 if (permName != null) { 3866 BasePermission bp = findPermissionTreeLP(permName); 3867 if (bp != null) { 3868 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3869 return bp; 3870 } 3871 throw new SecurityException("Calling uid " 3872 + Binder.getCallingUid() 3873 + " is not allowed to add to permission tree " 3874 + bp.name + " owned by uid " + bp.uid); 3875 } 3876 } 3877 throw new SecurityException("No permission tree found for " + permName); 3878 } 3879 3880 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3881 if (s1 == null) { 3882 return s2 == null; 3883 } 3884 if (s2 == null) { 3885 return false; 3886 } 3887 if (s1.getClass() != s2.getClass()) { 3888 return false; 3889 } 3890 return s1.equals(s2); 3891 } 3892 3893 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3894 if (pi1.icon != pi2.icon) return false; 3895 if (pi1.logo != pi2.logo) return false; 3896 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3897 if (!compareStrings(pi1.name, pi2.name)) return false; 3898 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3899 // We'll take care of setting this one. 3900 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3901 // These are not currently stored in settings. 3902 //if (!compareStrings(pi1.group, pi2.group)) return false; 3903 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3904 //if (pi1.labelRes != pi2.labelRes) return false; 3905 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3906 return true; 3907 } 3908 3909 int permissionInfoFootprint(PermissionInfo info) { 3910 int size = info.name.length(); 3911 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3912 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3913 return size; 3914 } 3915 3916 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3917 int size = 0; 3918 for (BasePermission perm : mSettings.mPermissions.values()) { 3919 if (perm.uid == tree.uid) { 3920 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3921 } 3922 } 3923 return size; 3924 } 3925 3926 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3927 // We calculate the max size of permissions defined by this uid and throw 3928 // if that plus the size of 'info' would exceed our stated maximum. 3929 if (tree.uid != Process.SYSTEM_UID) { 3930 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3931 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3932 throw new SecurityException("Permission tree size cap exceeded"); 3933 } 3934 } 3935 } 3936 3937 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3938 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3939 throw new SecurityException("Label must be specified in permission"); 3940 } 3941 BasePermission tree = checkPermissionTreeLP(info.name); 3942 BasePermission bp = mSettings.mPermissions.get(info.name); 3943 boolean added = bp == null; 3944 boolean changed = true; 3945 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3946 if (added) { 3947 enforcePermissionCapLocked(info, tree); 3948 bp = new BasePermission(info.name, tree.sourcePackage, 3949 BasePermission.TYPE_DYNAMIC); 3950 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3951 throw new SecurityException( 3952 "Not allowed to modify non-dynamic permission " 3953 + info.name); 3954 } else { 3955 if (bp.protectionLevel == fixedLevel 3956 && bp.perm.owner.equals(tree.perm.owner) 3957 && bp.uid == tree.uid 3958 && comparePermissionInfos(bp.perm.info, info)) { 3959 changed = false; 3960 } 3961 } 3962 bp.protectionLevel = fixedLevel; 3963 info = new PermissionInfo(info); 3964 info.protectionLevel = fixedLevel; 3965 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3966 bp.perm.info.packageName = tree.perm.info.packageName; 3967 bp.uid = tree.uid; 3968 if (added) { 3969 mSettings.mPermissions.put(info.name, bp); 3970 } 3971 if (changed) { 3972 if (!async) { 3973 mSettings.writeLPr(); 3974 } else { 3975 scheduleWriteSettingsLocked(); 3976 } 3977 } 3978 return added; 3979 } 3980 3981 @Override 3982 public boolean addPermission(PermissionInfo info) { 3983 synchronized (mPackages) { 3984 return addPermissionLocked(info, false); 3985 } 3986 } 3987 3988 @Override 3989 public boolean addPermissionAsync(PermissionInfo info) { 3990 synchronized (mPackages) { 3991 return addPermissionLocked(info, true); 3992 } 3993 } 3994 3995 @Override 3996 public void removePermission(String name) { 3997 synchronized (mPackages) { 3998 checkPermissionTreeLP(name); 3999 BasePermission bp = mSettings.mPermissions.get(name); 4000 if (bp != null) { 4001 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4002 throw new SecurityException( 4003 "Not allowed to modify non-dynamic permission " 4004 + name); 4005 } 4006 mSettings.mPermissions.remove(name); 4007 mSettings.writeLPr(); 4008 } 4009 } 4010 } 4011 4012 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4013 BasePermission bp) { 4014 int index = pkg.requestedPermissions.indexOf(bp.name); 4015 if (index == -1) { 4016 throw new SecurityException("Package " + pkg.packageName 4017 + " has not requested permission " + bp.name); 4018 } 4019 if (!bp.isRuntime() && !bp.isDevelopment()) { 4020 throw new SecurityException("Permission " + bp.name 4021 + " is not a changeable permission type"); 4022 } 4023 } 4024 4025 @Override 4026 public void grantRuntimePermission(String packageName, String name, final int userId) { 4027 if (!sUserManager.exists(userId)) { 4028 Log.e(TAG, "No such user:" + userId); 4029 return; 4030 } 4031 4032 mContext.enforceCallingOrSelfPermission( 4033 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4034 "grantRuntimePermission"); 4035 4036 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4037 true /* requireFullPermission */, true /* checkShell */, 4038 "grantRuntimePermission"); 4039 4040 final int uid; 4041 final SettingBase sb; 4042 4043 synchronized (mPackages) { 4044 final PackageParser.Package pkg = mPackages.get(packageName); 4045 if (pkg == null) { 4046 throw new IllegalArgumentException("Unknown package: " + packageName); 4047 } 4048 4049 final BasePermission bp = mSettings.mPermissions.get(name); 4050 if (bp == null) { 4051 throw new IllegalArgumentException("Unknown permission: " + name); 4052 } 4053 4054 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4055 4056 // If a permission review is required for legacy apps we represent 4057 // their permissions as always granted runtime ones since we need 4058 // to keep the review required permission flag per user while an 4059 // install permission's state is shared across all users. 4060 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4061 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4062 && bp.isRuntime()) { 4063 return; 4064 } 4065 4066 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4067 sb = (SettingBase) pkg.mExtras; 4068 if (sb == null) { 4069 throw new IllegalArgumentException("Unknown package: " + packageName); 4070 } 4071 4072 final PermissionsState permissionsState = sb.getPermissionsState(); 4073 4074 final int flags = permissionsState.getPermissionFlags(name, userId); 4075 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4076 throw new SecurityException("Cannot grant system fixed permission " 4077 + name + " for package " + packageName); 4078 } 4079 4080 if (bp.isDevelopment()) { 4081 // Development permissions must be handled specially, since they are not 4082 // normal runtime permissions. For now they apply to all users. 4083 if (permissionsState.grantInstallPermission(bp) != 4084 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4085 scheduleWriteSettingsLocked(); 4086 } 4087 return; 4088 } 4089 4090 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4091 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4092 return; 4093 } 4094 4095 final int result = permissionsState.grantRuntimePermission(bp, userId); 4096 switch (result) { 4097 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4098 return; 4099 } 4100 4101 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4102 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4103 mHandler.post(new Runnable() { 4104 @Override 4105 public void run() { 4106 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4107 } 4108 }); 4109 } 4110 break; 4111 } 4112 4113 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4114 4115 // Not critical if that is lost - app has to request again. 4116 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4117 } 4118 4119 // Only need to do this if user is initialized. Otherwise it's a new user 4120 // and there are no processes running as the user yet and there's no need 4121 // to make an expensive call to remount processes for the changed permissions. 4122 if (READ_EXTERNAL_STORAGE.equals(name) 4123 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4124 final long token = Binder.clearCallingIdentity(); 4125 try { 4126 if (sUserManager.isInitialized(userId)) { 4127 MountServiceInternal mountServiceInternal = LocalServices.getService( 4128 MountServiceInternal.class); 4129 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4130 } 4131 } finally { 4132 Binder.restoreCallingIdentity(token); 4133 } 4134 } 4135 } 4136 4137 @Override 4138 public void revokeRuntimePermission(String packageName, String name, int userId) { 4139 if (!sUserManager.exists(userId)) { 4140 Log.e(TAG, "No such user:" + userId); 4141 return; 4142 } 4143 4144 mContext.enforceCallingOrSelfPermission( 4145 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4146 "revokeRuntimePermission"); 4147 4148 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4149 true /* requireFullPermission */, true /* checkShell */, 4150 "revokeRuntimePermission"); 4151 4152 final int appId; 4153 4154 synchronized (mPackages) { 4155 final PackageParser.Package pkg = mPackages.get(packageName); 4156 if (pkg == null) { 4157 throw new IllegalArgumentException("Unknown package: " + packageName); 4158 } 4159 4160 final BasePermission bp = mSettings.mPermissions.get(name); 4161 if (bp == null) { 4162 throw new IllegalArgumentException("Unknown permission: " + name); 4163 } 4164 4165 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4166 4167 // If a permission review is required for legacy apps we represent 4168 // their permissions as always granted runtime ones since we need 4169 // to keep the review required permission flag per user while an 4170 // install permission's state is shared across all users. 4171 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4172 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4173 && bp.isRuntime()) { 4174 return; 4175 } 4176 4177 SettingBase sb = (SettingBase) pkg.mExtras; 4178 if (sb == null) { 4179 throw new IllegalArgumentException("Unknown package: " + packageName); 4180 } 4181 4182 final PermissionsState permissionsState = sb.getPermissionsState(); 4183 4184 final int flags = permissionsState.getPermissionFlags(name, userId); 4185 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4186 throw new SecurityException("Cannot revoke system fixed permission " 4187 + name + " for package " + packageName); 4188 } 4189 4190 if (bp.isDevelopment()) { 4191 // Development permissions must be handled specially, since they are not 4192 // normal runtime permissions. For now they apply to all users. 4193 if (permissionsState.revokeInstallPermission(bp) != 4194 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4195 scheduleWriteSettingsLocked(); 4196 } 4197 return; 4198 } 4199 4200 if (permissionsState.revokeRuntimePermission(bp, userId) == 4201 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4202 return; 4203 } 4204 4205 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4206 4207 // Critical, after this call app should never have the permission. 4208 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4209 4210 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4211 } 4212 4213 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4214 } 4215 4216 @Override 4217 public void resetRuntimePermissions() { 4218 mContext.enforceCallingOrSelfPermission( 4219 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4220 "revokeRuntimePermission"); 4221 4222 int callingUid = Binder.getCallingUid(); 4223 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4224 mContext.enforceCallingOrSelfPermission( 4225 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4226 "resetRuntimePermissions"); 4227 } 4228 4229 synchronized (mPackages) { 4230 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4231 for (int userId : UserManagerService.getInstance().getUserIds()) { 4232 final int packageCount = mPackages.size(); 4233 for (int i = 0; i < packageCount; i++) { 4234 PackageParser.Package pkg = mPackages.valueAt(i); 4235 if (!(pkg.mExtras instanceof PackageSetting)) { 4236 continue; 4237 } 4238 PackageSetting ps = (PackageSetting) pkg.mExtras; 4239 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4240 } 4241 } 4242 } 4243 } 4244 4245 @Override 4246 public int getPermissionFlags(String name, String packageName, int userId) { 4247 if (!sUserManager.exists(userId)) { 4248 return 0; 4249 } 4250 4251 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4252 4253 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4254 true /* requireFullPermission */, false /* checkShell */, 4255 "getPermissionFlags"); 4256 4257 synchronized (mPackages) { 4258 final PackageParser.Package pkg = mPackages.get(packageName); 4259 if (pkg == null) { 4260 return 0; 4261 } 4262 4263 final BasePermission bp = mSettings.mPermissions.get(name); 4264 if (bp == null) { 4265 return 0; 4266 } 4267 4268 SettingBase sb = (SettingBase) pkg.mExtras; 4269 if (sb == null) { 4270 return 0; 4271 } 4272 4273 PermissionsState permissionsState = sb.getPermissionsState(); 4274 return permissionsState.getPermissionFlags(name, userId); 4275 } 4276 } 4277 4278 @Override 4279 public void updatePermissionFlags(String name, String packageName, int flagMask, 4280 int flagValues, int userId) { 4281 if (!sUserManager.exists(userId)) { 4282 return; 4283 } 4284 4285 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4286 4287 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4288 true /* requireFullPermission */, true /* checkShell */, 4289 "updatePermissionFlags"); 4290 4291 // Only the system can change these flags and nothing else. 4292 if (getCallingUid() != Process.SYSTEM_UID) { 4293 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4294 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4295 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4296 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4297 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4298 } 4299 4300 synchronized (mPackages) { 4301 final PackageParser.Package pkg = mPackages.get(packageName); 4302 if (pkg == null) { 4303 throw new IllegalArgumentException("Unknown package: " + packageName); 4304 } 4305 4306 final BasePermission bp = mSettings.mPermissions.get(name); 4307 if (bp == null) { 4308 throw new IllegalArgumentException("Unknown permission: " + name); 4309 } 4310 4311 SettingBase sb = (SettingBase) pkg.mExtras; 4312 if (sb == null) { 4313 throw new IllegalArgumentException("Unknown package: " + packageName); 4314 } 4315 4316 PermissionsState permissionsState = sb.getPermissionsState(); 4317 4318 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4319 4320 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4321 // Install and runtime permissions are stored in different places, 4322 // so figure out what permission changed and persist the change. 4323 if (permissionsState.getInstallPermissionState(name) != null) { 4324 scheduleWriteSettingsLocked(); 4325 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4326 || hadState) { 4327 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4328 } 4329 } 4330 } 4331 } 4332 4333 /** 4334 * Update the permission flags for all packages and runtime permissions of a user in order 4335 * to allow device or profile owner to remove POLICY_FIXED. 4336 */ 4337 @Override 4338 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4339 if (!sUserManager.exists(userId)) { 4340 return; 4341 } 4342 4343 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4344 4345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4346 true /* requireFullPermission */, true /* checkShell */, 4347 "updatePermissionFlagsForAllApps"); 4348 4349 // Only the system can change system fixed flags. 4350 if (getCallingUid() != Process.SYSTEM_UID) { 4351 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4352 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4353 } 4354 4355 synchronized (mPackages) { 4356 boolean changed = false; 4357 final int packageCount = mPackages.size(); 4358 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4359 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4360 SettingBase sb = (SettingBase) pkg.mExtras; 4361 if (sb == null) { 4362 continue; 4363 } 4364 PermissionsState permissionsState = sb.getPermissionsState(); 4365 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4366 userId, flagMask, flagValues); 4367 } 4368 if (changed) { 4369 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4370 } 4371 } 4372 } 4373 4374 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4375 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4376 != PackageManager.PERMISSION_GRANTED 4377 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4378 != PackageManager.PERMISSION_GRANTED) { 4379 throw new SecurityException(message + " requires " 4380 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4381 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4382 } 4383 } 4384 4385 @Override 4386 public boolean shouldShowRequestPermissionRationale(String permissionName, 4387 String packageName, int userId) { 4388 if (UserHandle.getCallingUserId() != userId) { 4389 mContext.enforceCallingPermission( 4390 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4391 "canShowRequestPermissionRationale for user " + userId); 4392 } 4393 4394 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4395 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4396 return false; 4397 } 4398 4399 if (checkPermission(permissionName, packageName, userId) 4400 == PackageManager.PERMISSION_GRANTED) { 4401 return false; 4402 } 4403 4404 final int flags; 4405 4406 final long identity = Binder.clearCallingIdentity(); 4407 try { 4408 flags = getPermissionFlags(permissionName, 4409 packageName, userId); 4410 } finally { 4411 Binder.restoreCallingIdentity(identity); 4412 } 4413 4414 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4415 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4416 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4417 4418 if ((flags & fixedFlags) != 0) { 4419 return false; 4420 } 4421 4422 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4423 } 4424 4425 @Override 4426 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4427 mContext.enforceCallingOrSelfPermission( 4428 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4429 "addOnPermissionsChangeListener"); 4430 4431 synchronized (mPackages) { 4432 mOnPermissionChangeListeners.addListenerLocked(listener); 4433 } 4434 } 4435 4436 @Override 4437 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4438 synchronized (mPackages) { 4439 mOnPermissionChangeListeners.removeListenerLocked(listener); 4440 } 4441 } 4442 4443 @Override 4444 public boolean isProtectedBroadcast(String actionName) { 4445 synchronized (mPackages) { 4446 if (mProtectedBroadcasts.contains(actionName)) { 4447 return true; 4448 } else if (actionName != null) { 4449 // TODO: remove these terrible hacks 4450 if (actionName.startsWith("android.net.netmon.lingerExpired") 4451 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4452 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4453 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4454 return true; 4455 } 4456 } 4457 } 4458 return false; 4459 } 4460 4461 @Override 4462 public int checkSignatures(String pkg1, String pkg2) { 4463 synchronized (mPackages) { 4464 final PackageParser.Package p1 = mPackages.get(pkg1); 4465 final PackageParser.Package p2 = mPackages.get(pkg2); 4466 if (p1 == null || p1.mExtras == null 4467 || p2 == null || p2.mExtras == null) { 4468 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4469 } 4470 return compareSignatures(p1.mSignatures, p2.mSignatures); 4471 } 4472 } 4473 4474 @Override 4475 public int checkUidSignatures(int uid1, int uid2) { 4476 // Map to base uids. 4477 uid1 = UserHandle.getAppId(uid1); 4478 uid2 = UserHandle.getAppId(uid2); 4479 // reader 4480 synchronized (mPackages) { 4481 Signature[] s1; 4482 Signature[] s2; 4483 Object obj = mSettings.getUserIdLPr(uid1); 4484 if (obj != null) { 4485 if (obj instanceof SharedUserSetting) { 4486 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4487 } else if (obj instanceof PackageSetting) { 4488 s1 = ((PackageSetting)obj).signatures.mSignatures; 4489 } else { 4490 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4491 } 4492 } else { 4493 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4494 } 4495 obj = mSettings.getUserIdLPr(uid2); 4496 if (obj != null) { 4497 if (obj instanceof SharedUserSetting) { 4498 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4499 } else if (obj instanceof PackageSetting) { 4500 s2 = ((PackageSetting)obj).signatures.mSignatures; 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 } else { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 return compareSignatures(s1, s2); 4508 } 4509 } 4510 4511 /** 4512 * This method should typically only be used when granting or revoking 4513 * permissions, since the app may immediately restart after this call. 4514 * <p> 4515 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4516 * guard your work against the app being relaunched. 4517 */ 4518 private void killUid(int appId, int userId, String reason) { 4519 final long identity = Binder.clearCallingIdentity(); 4520 try { 4521 IActivityManager am = ActivityManagerNative.getDefault(); 4522 if (am != null) { 4523 try { 4524 am.killUid(appId, userId, reason); 4525 } catch (RemoteException e) { 4526 /* ignore - same process */ 4527 } 4528 } 4529 } finally { 4530 Binder.restoreCallingIdentity(identity); 4531 } 4532 } 4533 4534 /** 4535 * Compares two sets of signatures. Returns: 4536 * <br /> 4537 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4538 * <br /> 4539 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4540 * <br /> 4541 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4542 * <br /> 4543 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4544 * <br /> 4545 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4546 */ 4547 static int compareSignatures(Signature[] s1, Signature[] s2) { 4548 if (s1 == null) { 4549 return s2 == null 4550 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4551 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4552 } 4553 4554 if (s2 == null) { 4555 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4556 } 4557 4558 if (s1.length != s2.length) { 4559 return PackageManager.SIGNATURE_NO_MATCH; 4560 } 4561 4562 // Since both signature sets are of size 1, we can compare without HashSets. 4563 if (s1.length == 1) { 4564 return s1[0].equals(s2[0]) ? 4565 PackageManager.SIGNATURE_MATCH : 4566 PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4570 for (Signature sig : s1) { 4571 set1.add(sig); 4572 } 4573 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4574 for (Signature sig : s2) { 4575 set2.add(sig); 4576 } 4577 // Make sure s2 contains all signatures in s1. 4578 if (set1.equals(set2)) { 4579 return PackageManager.SIGNATURE_MATCH; 4580 } 4581 return PackageManager.SIGNATURE_NO_MATCH; 4582 } 4583 4584 /** 4585 * If the database version for this type of package (internal storage or 4586 * external storage) is less than the version where package signatures 4587 * were updated, return true. 4588 */ 4589 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4590 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4591 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4592 } 4593 4594 /** 4595 * Used for backward compatibility to make sure any packages with 4596 * certificate chains get upgraded to the new style. {@code existingSigs} 4597 * will be in the old format (since they were stored on disk from before the 4598 * system upgrade) and {@code scannedSigs} will be in the newer format. 4599 */ 4600 private int compareSignaturesCompat(PackageSignatures existingSigs, 4601 PackageParser.Package scannedPkg) { 4602 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4603 return PackageManager.SIGNATURE_NO_MATCH; 4604 } 4605 4606 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4607 for (Signature sig : existingSigs.mSignatures) { 4608 existingSet.add(sig); 4609 } 4610 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4611 for (Signature sig : scannedPkg.mSignatures) { 4612 try { 4613 Signature[] chainSignatures = sig.getChainSignatures(); 4614 for (Signature chainSig : chainSignatures) { 4615 scannedCompatSet.add(chainSig); 4616 } 4617 } catch (CertificateEncodingException e) { 4618 scannedCompatSet.add(sig); 4619 } 4620 } 4621 /* 4622 * Make sure the expanded scanned set contains all signatures in the 4623 * existing one. 4624 */ 4625 if (scannedCompatSet.equals(existingSet)) { 4626 // Migrate the old signatures to the new scheme. 4627 existingSigs.assignSignatures(scannedPkg.mSignatures); 4628 // The new KeySets will be re-added later in the scanning process. 4629 synchronized (mPackages) { 4630 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4631 } 4632 return PackageManager.SIGNATURE_MATCH; 4633 } 4634 return PackageManager.SIGNATURE_NO_MATCH; 4635 } 4636 4637 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4638 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4639 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4640 } 4641 4642 private int compareSignaturesRecover(PackageSignatures existingSigs, 4643 PackageParser.Package scannedPkg) { 4644 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4645 return PackageManager.SIGNATURE_NO_MATCH; 4646 } 4647 4648 String msg = null; 4649 try { 4650 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4651 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4652 + scannedPkg.packageName); 4653 return PackageManager.SIGNATURE_MATCH; 4654 } 4655 } catch (CertificateException e) { 4656 msg = e.getMessage(); 4657 } 4658 4659 logCriticalInfo(Log.INFO, 4660 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4661 return PackageManager.SIGNATURE_NO_MATCH; 4662 } 4663 4664 @Override 4665 public List<String> getAllPackages() { 4666 synchronized (mPackages) { 4667 return new ArrayList<String>(mPackages.keySet()); 4668 } 4669 } 4670 4671 @Override 4672 public String[] getPackagesForUid(int uid) { 4673 final int userId = UserHandle.getUserId(uid); 4674 uid = UserHandle.getAppId(uid); 4675 // reader 4676 synchronized (mPackages) { 4677 Object obj = mSettings.getUserIdLPr(uid); 4678 if (obj instanceof SharedUserSetting) { 4679 final SharedUserSetting sus = (SharedUserSetting) obj; 4680 final int N = sus.packages.size(); 4681 String[] res = new String[N]; 4682 final Iterator<PackageSetting> it = sus.packages.iterator(); 4683 int i = 0; 4684 while (it.hasNext()) { 4685 PackageSetting ps = it.next(); 4686 if (ps.getInstalled(userId)) { 4687 res[i++] = ps.name; 4688 } else { 4689 res = ArrayUtils.removeElement(String.class, res, res[i]); 4690 } 4691 } 4692 return res; 4693 } else if (obj instanceof PackageSetting) { 4694 final PackageSetting ps = (PackageSetting) obj; 4695 return new String[] { ps.name }; 4696 } 4697 } 4698 return null; 4699 } 4700 4701 @Override 4702 public String getNameForUid(int uid) { 4703 // reader 4704 synchronized (mPackages) { 4705 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4706 if (obj instanceof SharedUserSetting) { 4707 final SharedUserSetting sus = (SharedUserSetting) obj; 4708 return sus.name + ":" + sus.userId; 4709 } else if (obj instanceof PackageSetting) { 4710 final PackageSetting ps = (PackageSetting) obj; 4711 return ps.name; 4712 } 4713 } 4714 return null; 4715 } 4716 4717 @Override 4718 public int getUidForSharedUser(String sharedUserName) { 4719 if(sharedUserName == null) { 4720 return -1; 4721 } 4722 // reader 4723 synchronized (mPackages) { 4724 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4725 if (suid == null) { 4726 return -1; 4727 } 4728 return suid.userId; 4729 } 4730 } 4731 4732 @Override 4733 public int getFlagsForUid(int uid) { 4734 synchronized (mPackages) { 4735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4736 if (obj instanceof SharedUserSetting) { 4737 final SharedUserSetting sus = (SharedUserSetting) obj; 4738 return sus.pkgFlags; 4739 } else if (obj instanceof PackageSetting) { 4740 final PackageSetting ps = (PackageSetting) obj; 4741 return ps.pkgFlags; 4742 } 4743 } 4744 return 0; 4745 } 4746 4747 @Override 4748 public int getPrivateFlagsForUid(int uid) { 4749 synchronized (mPackages) { 4750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4751 if (obj instanceof SharedUserSetting) { 4752 final SharedUserSetting sus = (SharedUserSetting) obj; 4753 return sus.pkgPrivateFlags; 4754 } else if (obj instanceof PackageSetting) { 4755 final PackageSetting ps = (PackageSetting) obj; 4756 return ps.pkgPrivateFlags; 4757 } 4758 } 4759 return 0; 4760 } 4761 4762 @Override 4763 public boolean isUidPrivileged(int uid) { 4764 uid = UserHandle.getAppId(uid); 4765 // reader 4766 synchronized (mPackages) { 4767 Object obj = mSettings.getUserIdLPr(uid); 4768 if (obj instanceof SharedUserSetting) { 4769 final SharedUserSetting sus = (SharedUserSetting) obj; 4770 final Iterator<PackageSetting> it = sus.packages.iterator(); 4771 while (it.hasNext()) { 4772 if (it.next().isPrivileged()) { 4773 return true; 4774 } 4775 } 4776 } else if (obj instanceof PackageSetting) { 4777 final PackageSetting ps = (PackageSetting) obj; 4778 return ps.isPrivileged(); 4779 } 4780 } 4781 return false; 4782 } 4783 4784 @Override 4785 public String[] getAppOpPermissionPackages(String permissionName) { 4786 synchronized (mPackages) { 4787 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4788 if (pkgs == null) { 4789 return null; 4790 } 4791 return pkgs.toArray(new String[pkgs.size()]); 4792 } 4793 } 4794 4795 @Override 4796 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4797 int flags, int userId) { 4798 try { 4799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4800 4801 if (!sUserManager.exists(userId)) return null; 4802 flags = updateFlagsForResolve(flags, userId, intent); 4803 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4804 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4805 4806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4807 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4808 flags, userId); 4809 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4810 4811 final ResolveInfo bestChoice = 4812 chooseBestActivity(intent, resolvedType, flags, query, userId); 4813 return bestChoice; 4814 } finally { 4815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4816 } 4817 } 4818 4819 @Override 4820 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4821 IntentFilter filter, int match, ComponentName activity) { 4822 final int userId = UserHandle.getCallingUserId(); 4823 if (DEBUG_PREFERRED) { 4824 Log.v(TAG, "setLastChosenActivity intent=" + intent 4825 + " resolvedType=" + resolvedType 4826 + " flags=" + flags 4827 + " filter=" + filter 4828 + " match=" + match 4829 + " activity=" + activity); 4830 filter.dump(new PrintStreamPrinter(System.out), " "); 4831 } 4832 intent.setComponent(null); 4833 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4834 userId); 4835 // Find any earlier preferred or last chosen entries and nuke them 4836 findPreferredActivity(intent, resolvedType, 4837 flags, query, 0, false, true, false, userId); 4838 // Add the new activity as the last chosen for this filter 4839 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4840 "Setting last chosen"); 4841 } 4842 4843 @Override 4844 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4845 final int userId = UserHandle.getCallingUserId(); 4846 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4847 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4848 userId); 4849 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4850 false, false, false, userId); 4851 } 4852 4853 private boolean isEphemeralDisabled() { 4854 // ephemeral apps have been disabled across the board 4855 if (DISABLE_EPHEMERAL_APPS) { 4856 return true; 4857 } 4858 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4859 if (!mSystemReady) { 4860 return true; 4861 } 4862 // we can't get a content resolver until the system is ready; these checks must happen last 4863 final ContentResolver resolver = mContext.getContentResolver(); 4864 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4865 return true; 4866 } 4867 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4868 } 4869 4870 private boolean isEphemeralAllowed( 4871 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4872 boolean skipPackageCheck) { 4873 // Short circuit and return early if possible. 4874 if (isEphemeralDisabled()) { 4875 return false; 4876 } 4877 final int callingUser = UserHandle.getCallingUserId(); 4878 if (callingUser != UserHandle.USER_SYSTEM) { 4879 return false; 4880 } 4881 if (mEphemeralResolverConnection == null) { 4882 return false; 4883 } 4884 if (intent.getComponent() != null) { 4885 return false; 4886 } 4887 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4888 return false; 4889 } 4890 if (!skipPackageCheck && intent.getPackage() != null) { 4891 return false; 4892 } 4893 final boolean isWebUri = hasWebURI(intent); 4894 if (!isWebUri || intent.getData().getHost() == null) { 4895 return false; 4896 } 4897 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4898 synchronized (mPackages) { 4899 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4900 for (int n = 0; n < count; n++) { 4901 ResolveInfo info = resolvedActivities.get(n); 4902 String packageName = info.activityInfo.packageName; 4903 PackageSetting ps = mSettings.mPackages.get(packageName); 4904 if (ps != null) { 4905 // Try to get the status from User settings first 4906 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4907 int status = (int) (packedStatus >> 32); 4908 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4909 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4910 if (DEBUG_EPHEMERAL) { 4911 Slog.v(TAG, "DENY ephemeral apps;" 4912 + " pkg: " + packageName + ", status: " + status); 4913 } 4914 return false; 4915 } 4916 } 4917 } 4918 } 4919 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4920 return true; 4921 } 4922 4923 private static EphemeralResolveInfo getEphemeralResolveInfo( 4924 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4925 String resolvedType, int userId, String packageName) { 4926 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4927 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4928 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4929 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4930 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4931 ephemeralPrefixCount); 4932 final int[] shaPrefix = digest.getDigestPrefix(); 4933 final byte[][] digestBytes = digest.getDigestBytes(); 4934 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4935 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4936 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4937 // No hash prefix match; there are no ephemeral apps for this domain. 4938 return null; 4939 } 4940 4941 // Go in reverse order so we match the narrowest scope first. 4942 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4943 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4944 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4945 continue; 4946 } 4947 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4948 // No filters; this should never happen. 4949 if (filters.isEmpty()) { 4950 continue; 4951 } 4952 if (packageName != null 4953 && !packageName.equals(ephemeralApplication.getPackageName())) { 4954 continue; 4955 } 4956 // We have a domain match; resolve the filters to see if anything matches. 4957 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4958 for (int j = filters.size() - 1; j >= 0; --j) { 4959 final EphemeralResolveIntentInfo intentInfo = 4960 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4961 ephemeralResolver.addFilter(intentInfo); 4962 } 4963 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4964 intent, resolvedType, false /*defaultOnly*/, userId); 4965 if (!matchedResolveInfoList.isEmpty()) { 4966 return matchedResolveInfoList.get(0); 4967 } 4968 } 4969 } 4970 // Hash or filter mis-match; no ephemeral apps for this domain. 4971 return null; 4972 } 4973 4974 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4975 int flags, List<ResolveInfo> query, int userId) { 4976 if (query != null) { 4977 final int N = query.size(); 4978 if (N == 1) { 4979 return query.get(0); 4980 } else if (N > 1) { 4981 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4982 // If there is more than one activity with the same priority, 4983 // then let the user decide between them. 4984 ResolveInfo r0 = query.get(0); 4985 ResolveInfo r1 = query.get(1); 4986 if (DEBUG_INTENT_MATCHING || debug) { 4987 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4988 + r1.activityInfo.name + "=" + r1.priority); 4989 } 4990 // If the first activity has a higher priority, or a different 4991 // default, then it is always desirable to pick it. 4992 if (r0.priority != r1.priority 4993 || r0.preferredOrder != r1.preferredOrder 4994 || r0.isDefault != r1.isDefault) { 4995 return query.get(0); 4996 } 4997 // If we have saved a preference for a preferred activity for 4998 // this Intent, use that. 4999 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5000 flags, query, r0.priority, true, false, debug, userId); 5001 if (ri != null) { 5002 return ri; 5003 } 5004 ri = new ResolveInfo(mResolveInfo); 5005 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5006 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5007 // If all of the options come from the same package, show the application's 5008 // label and icon instead of the generic resolver's. 5009 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5010 // and then throw away the ResolveInfo itself, meaning that the caller loses 5011 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5012 // a fallback for this case; we only set the target package's resources on 5013 // the ResolveInfo, not the ActivityInfo. 5014 final String intentPackage = intent.getPackage(); 5015 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5016 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5017 ri.resolvePackageName = intentPackage; 5018 if (userNeedsBadging(userId)) { 5019 ri.noResourceId = true; 5020 } else { 5021 ri.icon = appi.icon; 5022 } 5023 ri.iconResourceId = appi.icon; 5024 ri.labelRes = appi.labelRes; 5025 } 5026 ri.activityInfo.applicationInfo = new ApplicationInfo( 5027 ri.activityInfo.applicationInfo); 5028 if (userId != 0) { 5029 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5030 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5031 } 5032 // Make sure that the resolver is displayable in car mode 5033 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5034 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5035 return ri; 5036 } 5037 } 5038 return null; 5039 } 5040 5041 /** 5042 * Return true if the given list is not empty and all of its contents have 5043 * an activityInfo with the given package name. 5044 */ 5045 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5046 if (ArrayUtils.isEmpty(list)) { 5047 return false; 5048 } 5049 for (int i = 0, N = list.size(); i < N; i++) { 5050 final ResolveInfo ri = list.get(i); 5051 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5052 if (ai == null || !packageName.equals(ai.packageName)) { 5053 return false; 5054 } 5055 } 5056 return true; 5057 } 5058 5059 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5060 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5061 final int N = query.size(); 5062 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5063 .get(userId); 5064 // Get the list of persistent preferred activities that handle the intent 5065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5066 List<PersistentPreferredActivity> pprefs = ppir != null 5067 ? ppir.queryIntent(intent, resolvedType, 5068 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5069 : null; 5070 if (pprefs != null && pprefs.size() > 0) { 5071 final int M = pprefs.size(); 5072 for (int i=0; i<M; i++) { 5073 final PersistentPreferredActivity ppa = pprefs.get(i); 5074 if (DEBUG_PREFERRED || debug) { 5075 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5076 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5077 + "\n component=" + ppa.mComponent); 5078 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5079 } 5080 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5081 flags | MATCH_DISABLED_COMPONENTS, userId); 5082 if (DEBUG_PREFERRED || debug) { 5083 Slog.v(TAG, "Found persistent preferred activity:"); 5084 if (ai != null) { 5085 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5086 } else { 5087 Slog.v(TAG, " null"); 5088 } 5089 } 5090 if (ai == null) { 5091 // This previously registered persistent preferred activity 5092 // component is no longer known. Ignore it and do NOT remove it. 5093 continue; 5094 } 5095 for (int j=0; j<N; j++) { 5096 final ResolveInfo ri = query.get(j); 5097 if (!ri.activityInfo.applicationInfo.packageName 5098 .equals(ai.applicationInfo.packageName)) { 5099 continue; 5100 } 5101 if (!ri.activityInfo.name.equals(ai.name)) { 5102 continue; 5103 } 5104 // Found a persistent preference that can handle the intent. 5105 if (DEBUG_PREFERRED || debug) { 5106 Slog.v(TAG, "Returning persistent preferred activity: " + 5107 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5108 } 5109 return ri; 5110 } 5111 } 5112 } 5113 return null; 5114 } 5115 5116 // TODO: handle preferred activities missing while user has amnesia 5117 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5118 List<ResolveInfo> query, int priority, boolean always, 5119 boolean removeMatches, boolean debug, int userId) { 5120 if (!sUserManager.exists(userId)) return null; 5121 flags = updateFlagsForResolve(flags, userId, intent); 5122 // writer 5123 synchronized (mPackages) { 5124 if (intent.getSelector() != null) { 5125 intent = intent.getSelector(); 5126 } 5127 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5128 5129 // Try to find a matching persistent preferred activity. 5130 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5131 debug, userId); 5132 5133 // If a persistent preferred activity matched, use it. 5134 if (pri != null) { 5135 return pri; 5136 } 5137 5138 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5139 // Get the list of preferred activities that handle the intent 5140 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5141 List<PreferredActivity> prefs = pir != null 5142 ? pir.queryIntent(intent, resolvedType, 5143 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5144 : null; 5145 if (prefs != null && prefs.size() > 0) { 5146 boolean changed = false; 5147 try { 5148 // First figure out how good the original match set is. 5149 // We will only allow preferred activities that came 5150 // from the same match quality. 5151 int match = 0; 5152 5153 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5154 5155 final int N = query.size(); 5156 for (int j=0; j<N; j++) { 5157 final ResolveInfo ri = query.get(j); 5158 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5159 + ": 0x" + Integer.toHexString(match)); 5160 if (ri.match > match) { 5161 match = ri.match; 5162 } 5163 } 5164 5165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5166 + Integer.toHexString(match)); 5167 5168 match &= IntentFilter.MATCH_CATEGORY_MASK; 5169 final int M = prefs.size(); 5170 for (int i=0; i<M; i++) { 5171 final PreferredActivity pa = prefs.get(i); 5172 if (DEBUG_PREFERRED || debug) { 5173 Slog.v(TAG, "Checking PreferredActivity ds=" 5174 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5175 + "\n component=" + pa.mPref.mComponent); 5176 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5177 } 5178 if (pa.mPref.mMatch != match) { 5179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5180 + Integer.toHexString(pa.mPref.mMatch)); 5181 continue; 5182 } 5183 // If it's not an "always" type preferred activity and that's what we're 5184 // looking for, skip it. 5185 if (always && !pa.mPref.mAlways) { 5186 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5187 continue; 5188 } 5189 final ActivityInfo ai = getActivityInfo( 5190 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5191 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5192 userId); 5193 if (DEBUG_PREFERRED || debug) { 5194 Slog.v(TAG, "Found preferred activity:"); 5195 if (ai != null) { 5196 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5197 } else { 5198 Slog.v(TAG, " null"); 5199 } 5200 } 5201 if (ai == null) { 5202 // This previously registered preferred activity 5203 // component is no longer known. Most likely an update 5204 // to the app was installed and in the new version this 5205 // component no longer exists. Clean it up by removing 5206 // it from the preferred activities list, and skip it. 5207 Slog.w(TAG, "Removing dangling preferred activity: " 5208 + pa.mPref.mComponent); 5209 pir.removeFilter(pa); 5210 changed = true; 5211 continue; 5212 } 5213 for (int j=0; j<N; j++) { 5214 final ResolveInfo ri = query.get(j); 5215 if (!ri.activityInfo.applicationInfo.packageName 5216 .equals(ai.applicationInfo.packageName)) { 5217 continue; 5218 } 5219 if (!ri.activityInfo.name.equals(ai.name)) { 5220 continue; 5221 } 5222 5223 if (removeMatches) { 5224 pir.removeFilter(pa); 5225 changed = true; 5226 if (DEBUG_PREFERRED) { 5227 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5228 } 5229 break; 5230 } 5231 5232 // Okay we found a previously set preferred or last chosen app. 5233 // If the result set is different from when this 5234 // was created, we need to clear it and re-ask the 5235 // user their preference, if we're looking for an "always" type entry. 5236 if (always && !pa.mPref.sameSet(query)) { 5237 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5238 + intent + " type " + resolvedType); 5239 if (DEBUG_PREFERRED) { 5240 Slog.v(TAG, "Removing preferred activity since set changed " 5241 + pa.mPref.mComponent); 5242 } 5243 pir.removeFilter(pa); 5244 // Re-add the filter as a "last chosen" entry (!always) 5245 PreferredActivity lastChosen = new PreferredActivity( 5246 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5247 pir.addFilter(lastChosen); 5248 changed = true; 5249 return null; 5250 } 5251 5252 // Yay! Either the set matched or we're looking for the last chosen 5253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5254 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5255 return ri; 5256 } 5257 } 5258 } finally { 5259 if (changed) { 5260 if (DEBUG_PREFERRED) { 5261 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5262 } 5263 scheduleWritePackageRestrictionsLocked(userId); 5264 } 5265 } 5266 } 5267 } 5268 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5269 return null; 5270 } 5271 5272 /* 5273 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5274 */ 5275 @Override 5276 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5277 int targetUserId) { 5278 mContext.enforceCallingOrSelfPermission( 5279 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5280 List<CrossProfileIntentFilter> matches = 5281 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5282 if (matches != null) { 5283 int size = matches.size(); 5284 for (int i = 0; i < size; i++) { 5285 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5286 } 5287 } 5288 if (hasWebURI(intent)) { 5289 // cross-profile app linking works only towards the parent. 5290 final UserInfo parent = getProfileParent(sourceUserId); 5291 synchronized(mPackages) { 5292 int flags = updateFlagsForResolve(0, parent.id, intent); 5293 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5294 intent, resolvedType, flags, sourceUserId, parent.id); 5295 return xpDomainInfo != null; 5296 } 5297 } 5298 return false; 5299 } 5300 5301 private UserInfo getProfileParent(int userId) { 5302 final long identity = Binder.clearCallingIdentity(); 5303 try { 5304 return sUserManager.getProfileParent(userId); 5305 } finally { 5306 Binder.restoreCallingIdentity(identity); 5307 } 5308 } 5309 5310 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5311 String resolvedType, int userId) { 5312 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5313 if (resolver != null) { 5314 return resolver.queryIntent(intent, resolvedType, false, userId); 5315 } 5316 return null; 5317 } 5318 5319 @Override 5320 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5321 String resolvedType, int flags, int userId) { 5322 try { 5323 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5324 5325 return new ParceledListSlice<>( 5326 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5327 } finally { 5328 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5329 } 5330 } 5331 5332 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5333 String resolvedType, int flags, int userId) { 5334 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5335 flags = updateFlagsForResolve(flags, userId, intent); 5336 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5337 false /* requireFullPermission */, false /* checkShell */, 5338 "query intent activities"); 5339 ComponentName comp = intent.getComponent(); 5340 if (comp == null) { 5341 if (intent.getSelector() != null) { 5342 intent = intent.getSelector(); 5343 comp = intent.getComponent(); 5344 } 5345 } 5346 5347 if (comp != null) { 5348 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5349 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5350 if (ai != null) { 5351 final ResolveInfo ri = new ResolveInfo(); 5352 ri.activityInfo = ai; 5353 list.add(ri); 5354 } 5355 return list; 5356 } 5357 5358 // reader 5359 boolean sortResult = false; 5360 boolean addEphemeral = false; 5361 boolean matchEphemeralPackage = false; 5362 List<ResolveInfo> result; 5363 final String pkgName = intent.getPackage(); 5364 synchronized (mPackages) { 5365 if (pkgName == null) { 5366 List<CrossProfileIntentFilter> matchingFilters = 5367 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5368 // Check for results that need to skip the current profile. 5369 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5370 resolvedType, flags, userId); 5371 if (xpResolveInfo != null) { 5372 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5373 xpResult.add(xpResolveInfo); 5374 return filterIfNotSystemUser(xpResult, userId); 5375 } 5376 5377 // Check for results in the current profile. 5378 result = filterIfNotSystemUser(mActivities.queryIntent( 5379 intent, resolvedType, flags, userId), userId); 5380 addEphemeral = 5381 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5382 5383 // Check for cross profile results. 5384 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5385 xpResolveInfo = queryCrossProfileIntents( 5386 matchingFilters, intent, resolvedType, flags, userId, 5387 hasNonNegativePriorityResult); 5388 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5389 boolean isVisibleToUser = filterIfNotSystemUser( 5390 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5391 if (isVisibleToUser) { 5392 result.add(xpResolveInfo); 5393 sortResult = true; 5394 } 5395 } 5396 if (hasWebURI(intent)) { 5397 CrossProfileDomainInfo xpDomainInfo = null; 5398 final UserInfo parent = getProfileParent(userId); 5399 if (parent != null) { 5400 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5401 flags, userId, parent.id); 5402 } 5403 if (xpDomainInfo != null) { 5404 if (xpResolveInfo != null) { 5405 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5406 // in the result. 5407 result.remove(xpResolveInfo); 5408 } 5409 if (result.size() == 0 && !addEphemeral) { 5410 result.add(xpDomainInfo.resolveInfo); 5411 return result; 5412 } 5413 } 5414 if (result.size() > 1 || addEphemeral) { 5415 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5416 intent, flags, result, xpDomainInfo, userId); 5417 sortResult = true; 5418 } 5419 } 5420 } else { 5421 final PackageParser.Package pkg = mPackages.get(pkgName); 5422 if (pkg != null) { 5423 result = filterIfNotSystemUser( 5424 mActivities.queryIntentForPackage( 5425 intent, resolvedType, flags, pkg.activities, userId), 5426 userId); 5427 } else { 5428 // the caller wants to resolve for a particular package; however, there 5429 // were no installed results, so, try to find an ephemeral result 5430 addEphemeral = isEphemeralAllowed( 5431 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5432 matchEphemeralPackage = true; 5433 result = new ArrayList<ResolveInfo>(); 5434 } 5435 } 5436 } 5437 if (addEphemeral) { 5438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5439 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5440 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5441 matchEphemeralPackage ? pkgName : null); 5442 if (ai != null) { 5443 if (DEBUG_EPHEMERAL) { 5444 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5445 } 5446 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5447 ephemeralInstaller.ephemeralResolveInfo = ai; 5448 // make sure this resolver is the default 5449 ephemeralInstaller.isDefault = true; 5450 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5451 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5452 // add a non-generic filter 5453 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5454 ephemeralInstaller.filter.addDataPath( 5455 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5456 result.add(ephemeralInstaller); 5457 } 5458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5459 } 5460 if (sortResult) { 5461 Collections.sort(result, mResolvePrioritySorter); 5462 } 5463 return result; 5464 } 5465 5466 private static class CrossProfileDomainInfo { 5467 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5468 ResolveInfo resolveInfo; 5469 /* Best domain verification status of the activities found in the other profile */ 5470 int bestDomainVerificationStatus; 5471 } 5472 5473 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5474 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5475 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5476 sourceUserId)) { 5477 return null; 5478 } 5479 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5480 resolvedType, flags, parentUserId); 5481 5482 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5483 return null; 5484 } 5485 CrossProfileDomainInfo result = null; 5486 int size = resultTargetUser.size(); 5487 for (int i = 0; i < size; i++) { 5488 ResolveInfo riTargetUser = resultTargetUser.get(i); 5489 // Intent filter verification is only for filters that specify a host. So don't return 5490 // those that handle all web uris. 5491 if (riTargetUser.handleAllWebDataURI) { 5492 continue; 5493 } 5494 String packageName = riTargetUser.activityInfo.packageName; 5495 PackageSetting ps = mSettings.mPackages.get(packageName); 5496 if (ps == null) { 5497 continue; 5498 } 5499 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5500 int status = (int)(verificationState >> 32); 5501 if (result == null) { 5502 result = new CrossProfileDomainInfo(); 5503 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5504 sourceUserId, parentUserId); 5505 result.bestDomainVerificationStatus = status; 5506 } else { 5507 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5508 result.bestDomainVerificationStatus); 5509 } 5510 } 5511 // Don't consider matches with status NEVER across profiles. 5512 if (result != null && result.bestDomainVerificationStatus 5513 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5514 return null; 5515 } 5516 return result; 5517 } 5518 5519 /** 5520 * Verification statuses are ordered from the worse to the best, except for 5521 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5522 */ 5523 private int bestDomainVerificationStatus(int status1, int status2) { 5524 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5525 return status2; 5526 } 5527 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5528 return status1; 5529 } 5530 return (int) MathUtils.max(status1, status2); 5531 } 5532 5533 private boolean isUserEnabled(int userId) { 5534 long callingId = Binder.clearCallingIdentity(); 5535 try { 5536 UserInfo userInfo = sUserManager.getUserInfo(userId); 5537 return userInfo != null && userInfo.isEnabled(); 5538 } finally { 5539 Binder.restoreCallingIdentity(callingId); 5540 } 5541 } 5542 5543 /** 5544 * Filter out activities with systemUserOnly flag set, when current user is not System. 5545 * 5546 * @return filtered list 5547 */ 5548 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5549 if (userId == UserHandle.USER_SYSTEM) { 5550 return resolveInfos; 5551 } 5552 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5553 ResolveInfo info = resolveInfos.get(i); 5554 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5555 resolveInfos.remove(i); 5556 } 5557 } 5558 return resolveInfos; 5559 } 5560 5561 /** 5562 * @param resolveInfos list of resolve infos in descending priority order 5563 * @return if the list contains a resolve info with non-negative priority 5564 */ 5565 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5566 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5567 } 5568 5569 private static boolean hasWebURI(Intent intent) { 5570 if (intent.getData() == null) { 5571 return false; 5572 } 5573 final String scheme = intent.getScheme(); 5574 if (TextUtils.isEmpty(scheme)) { 5575 return false; 5576 } 5577 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5578 } 5579 5580 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5581 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5582 int userId) { 5583 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5584 5585 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5586 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5587 candidates.size()); 5588 } 5589 5590 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5591 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5592 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5593 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5594 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5595 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5596 5597 synchronized (mPackages) { 5598 final int count = candidates.size(); 5599 // First, try to use linked apps. Partition the candidates into four lists: 5600 // one for the final results, one for the "do not use ever", one for "undefined status" 5601 // and finally one for "browser app type". 5602 for (int n=0; n<count; n++) { 5603 ResolveInfo info = candidates.get(n); 5604 String packageName = info.activityInfo.packageName; 5605 PackageSetting ps = mSettings.mPackages.get(packageName); 5606 if (ps != null) { 5607 // Add to the special match all list (Browser use case) 5608 if (info.handleAllWebDataURI) { 5609 matchAllList.add(info); 5610 continue; 5611 } 5612 // Try to get the status from User settings first 5613 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5614 int status = (int)(packedStatus >> 32); 5615 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5616 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5617 if (DEBUG_DOMAIN_VERIFICATION) { 5618 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5619 + " : linkgen=" + linkGeneration); 5620 } 5621 // Use link-enabled generation as preferredOrder, i.e. 5622 // prefer newly-enabled over earlier-enabled. 5623 info.preferredOrder = linkGeneration; 5624 alwaysList.add(info); 5625 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5626 if (DEBUG_DOMAIN_VERIFICATION) { 5627 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5628 } 5629 neverList.add(info); 5630 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5631 if (DEBUG_DOMAIN_VERIFICATION) { 5632 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5633 } 5634 alwaysAskList.add(info); 5635 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5636 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5637 if (DEBUG_DOMAIN_VERIFICATION) { 5638 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5639 } 5640 undefinedList.add(info); 5641 } 5642 } 5643 } 5644 5645 // We'll want to include browser possibilities in a few cases 5646 boolean includeBrowser = false; 5647 5648 // First try to add the "always" resolution(s) for the current user, if any 5649 if (alwaysList.size() > 0) { 5650 result.addAll(alwaysList); 5651 } else { 5652 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5653 result.addAll(undefinedList); 5654 // Maybe add one for the other profile. 5655 if (xpDomainInfo != null && ( 5656 xpDomainInfo.bestDomainVerificationStatus 5657 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5658 result.add(xpDomainInfo.resolveInfo); 5659 } 5660 includeBrowser = true; 5661 } 5662 5663 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5664 // If there were 'always' entries their preferred order has been set, so we also 5665 // back that off to make the alternatives equivalent 5666 if (alwaysAskList.size() > 0) { 5667 for (ResolveInfo i : result) { 5668 i.preferredOrder = 0; 5669 } 5670 result.addAll(alwaysAskList); 5671 includeBrowser = true; 5672 } 5673 5674 if (includeBrowser) { 5675 // Also add browsers (all of them or only the default one) 5676 if (DEBUG_DOMAIN_VERIFICATION) { 5677 Slog.v(TAG, " ...including browsers in candidate set"); 5678 } 5679 if ((matchFlags & MATCH_ALL) != 0) { 5680 result.addAll(matchAllList); 5681 } else { 5682 // Browser/generic handling case. If there's a default browser, go straight 5683 // to that (but only if there is no other higher-priority match). 5684 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5685 int maxMatchPrio = 0; 5686 ResolveInfo defaultBrowserMatch = null; 5687 final int numCandidates = matchAllList.size(); 5688 for (int n = 0; n < numCandidates; n++) { 5689 ResolveInfo info = matchAllList.get(n); 5690 // track the highest overall match priority... 5691 if (info.priority > maxMatchPrio) { 5692 maxMatchPrio = info.priority; 5693 } 5694 // ...and the highest-priority default browser match 5695 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5696 if (defaultBrowserMatch == null 5697 || (defaultBrowserMatch.priority < info.priority)) { 5698 if (debug) { 5699 Slog.v(TAG, "Considering default browser match " + info); 5700 } 5701 defaultBrowserMatch = info; 5702 } 5703 } 5704 } 5705 if (defaultBrowserMatch != null 5706 && defaultBrowserMatch.priority >= maxMatchPrio 5707 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5708 { 5709 if (debug) { 5710 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5711 } 5712 result.add(defaultBrowserMatch); 5713 } else { 5714 result.addAll(matchAllList); 5715 } 5716 } 5717 5718 // If there is nothing selected, add all candidates and remove the ones that the user 5719 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5720 if (result.size() == 0) { 5721 result.addAll(candidates); 5722 result.removeAll(neverList); 5723 } 5724 } 5725 } 5726 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5727 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5728 result.size()); 5729 for (ResolveInfo info : result) { 5730 Slog.v(TAG, " + " + info.activityInfo); 5731 } 5732 } 5733 return result; 5734 } 5735 5736 // Returns a packed value as a long: 5737 // 5738 // high 'int'-sized word: link status: undefined/ask/never/always. 5739 // low 'int'-sized word: relative priority among 'always' results. 5740 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5741 long result = ps.getDomainVerificationStatusForUser(userId); 5742 // if none available, get the master status 5743 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5744 if (ps.getIntentFilterVerificationInfo() != null) { 5745 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5746 } 5747 } 5748 return result; 5749 } 5750 5751 private ResolveInfo querySkipCurrentProfileIntents( 5752 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5753 int flags, int sourceUserId) { 5754 if (matchingFilters != null) { 5755 int size = matchingFilters.size(); 5756 for (int i = 0; i < size; i ++) { 5757 CrossProfileIntentFilter filter = matchingFilters.get(i); 5758 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5759 // Checking if there are activities in the target user that can handle the 5760 // intent. 5761 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5762 resolvedType, flags, sourceUserId); 5763 if (resolveInfo != null) { 5764 return resolveInfo; 5765 } 5766 } 5767 } 5768 } 5769 return null; 5770 } 5771 5772 // Return matching ResolveInfo in target user if any. 5773 private ResolveInfo queryCrossProfileIntents( 5774 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5775 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5776 if (matchingFilters != null) { 5777 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5778 // match the same intent. For performance reasons, it is better not to 5779 // run queryIntent twice for the same userId 5780 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5781 int size = matchingFilters.size(); 5782 for (int i = 0; i < size; i++) { 5783 CrossProfileIntentFilter filter = matchingFilters.get(i); 5784 int targetUserId = filter.getTargetUserId(); 5785 boolean skipCurrentProfile = 5786 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5787 boolean skipCurrentProfileIfNoMatchFound = 5788 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5789 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5790 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5791 // Checking if there are activities in the target user that can handle the 5792 // intent. 5793 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5794 resolvedType, flags, sourceUserId); 5795 if (resolveInfo != null) return resolveInfo; 5796 alreadyTriedUserIds.put(targetUserId, true); 5797 } 5798 } 5799 } 5800 return null; 5801 } 5802 5803 /** 5804 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5805 * will forward the intent to the filter's target user. 5806 * Otherwise, returns null. 5807 */ 5808 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5809 String resolvedType, int flags, int sourceUserId) { 5810 int targetUserId = filter.getTargetUserId(); 5811 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5812 resolvedType, flags, targetUserId); 5813 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5814 // If all the matches in the target profile are suspended, return null. 5815 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5816 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5817 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5818 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5819 targetUserId); 5820 } 5821 } 5822 } 5823 return null; 5824 } 5825 5826 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5827 int sourceUserId, int targetUserId) { 5828 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5829 long ident = Binder.clearCallingIdentity(); 5830 boolean targetIsProfile; 5831 try { 5832 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5833 } finally { 5834 Binder.restoreCallingIdentity(ident); 5835 } 5836 String className; 5837 if (targetIsProfile) { 5838 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5839 } else { 5840 className = FORWARD_INTENT_TO_PARENT; 5841 } 5842 ComponentName forwardingActivityComponentName = new ComponentName( 5843 mAndroidApplication.packageName, className); 5844 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5845 sourceUserId); 5846 if (!targetIsProfile) { 5847 forwardingActivityInfo.showUserIcon = targetUserId; 5848 forwardingResolveInfo.noResourceId = true; 5849 } 5850 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5851 forwardingResolveInfo.priority = 0; 5852 forwardingResolveInfo.preferredOrder = 0; 5853 forwardingResolveInfo.match = 0; 5854 forwardingResolveInfo.isDefault = true; 5855 forwardingResolveInfo.filter = filter; 5856 forwardingResolveInfo.targetUserId = targetUserId; 5857 return forwardingResolveInfo; 5858 } 5859 5860 @Override 5861 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5862 Intent[] specifics, String[] specificTypes, Intent intent, 5863 String resolvedType, int flags, int userId) { 5864 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5865 specificTypes, intent, resolvedType, flags, userId)); 5866 } 5867 5868 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5869 Intent[] specifics, String[] specificTypes, Intent intent, 5870 String resolvedType, int flags, int userId) { 5871 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5872 flags = updateFlagsForResolve(flags, userId, intent); 5873 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5874 false /* requireFullPermission */, false /* checkShell */, 5875 "query intent activity options"); 5876 final String resultsAction = intent.getAction(); 5877 5878 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5879 | PackageManager.GET_RESOLVED_FILTER, userId); 5880 5881 if (DEBUG_INTENT_MATCHING) { 5882 Log.v(TAG, "Query " + intent + ": " + results); 5883 } 5884 5885 int specificsPos = 0; 5886 int N; 5887 5888 // todo: note that the algorithm used here is O(N^2). This 5889 // isn't a problem in our current environment, but if we start running 5890 // into situations where we have more than 5 or 10 matches then this 5891 // should probably be changed to something smarter... 5892 5893 // First we go through and resolve each of the specific items 5894 // that were supplied, taking care of removing any corresponding 5895 // duplicate items in the generic resolve list. 5896 if (specifics != null) { 5897 for (int i=0; i<specifics.length; i++) { 5898 final Intent sintent = specifics[i]; 5899 if (sintent == null) { 5900 continue; 5901 } 5902 5903 if (DEBUG_INTENT_MATCHING) { 5904 Log.v(TAG, "Specific #" + i + ": " + sintent); 5905 } 5906 5907 String action = sintent.getAction(); 5908 if (resultsAction != null && resultsAction.equals(action)) { 5909 // If this action was explicitly requested, then don't 5910 // remove things that have it. 5911 action = null; 5912 } 5913 5914 ResolveInfo ri = null; 5915 ActivityInfo ai = null; 5916 5917 ComponentName comp = sintent.getComponent(); 5918 if (comp == null) { 5919 ri = resolveIntent( 5920 sintent, 5921 specificTypes != null ? specificTypes[i] : null, 5922 flags, userId); 5923 if (ri == null) { 5924 continue; 5925 } 5926 if (ri == mResolveInfo) { 5927 // ACK! Must do something better with this. 5928 } 5929 ai = ri.activityInfo; 5930 comp = new ComponentName(ai.applicationInfo.packageName, 5931 ai.name); 5932 } else { 5933 ai = getActivityInfo(comp, flags, userId); 5934 if (ai == null) { 5935 continue; 5936 } 5937 } 5938 5939 // Look for any generic query activities that are duplicates 5940 // of this specific one, and remove them from the results. 5941 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5942 N = results.size(); 5943 int j; 5944 for (j=specificsPos; j<N; j++) { 5945 ResolveInfo sri = results.get(j); 5946 if ((sri.activityInfo.name.equals(comp.getClassName()) 5947 && sri.activityInfo.applicationInfo.packageName.equals( 5948 comp.getPackageName())) 5949 || (action != null && sri.filter.matchAction(action))) { 5950 results.remove(j); 5951 if (DEBUG_INTENT_MATCHING) Log.v( 5952 TAG, "Removing duplicate item from " + j 5953 + " due to specific " + specificsPos); 5954 if (ri == null) { 5955 ri = sri; 5956 } 5957 j--; 5958 N--; 5959 } 5960 } 5961 5962 // Add this specific item to its proper place. 5963 if (ri == null) { 5964 ri = new ResolveInfo(); 5965 ri.activityInfo = ai; 5966 } 5967 results.add(specificsPos, ri); 5968 ri.specificIndex = i; 5969 specificsPos++; 5970 } 5971 } 5972 5973 // Now we go through the remaining generic results and remove any 5974 // duplicate actions that are found here. 5975 N = results.size(); 5976 for (int i=specificsPos; i<N-1; i++) { 5977 final ResolveInfo rii = results.get(i); 5978 if (rii.filter == null) { 5979 continue; 5980 } 5981 5982 // Iterate over all of the actions of this result's intent 5983 // filter... typically this should be just one. 5984 final Iterator<String> it = rii.filter.actionsIterator(); 5985 if (it == null) { 5986 continue; 5987 } 5988 while (it.hasNext()) { 5989 final String action = it.next(); 5990 if (resultsAction != null && resultsAction.equals(action)) { 5991 // If this action was explicitly requested, then don't 5992 // remove things that have it. 5993 continue; 5994 } 5995 for (int j=i+1; j<N; j++) { 5996 final ResolveInfo rij = results.get(j); 5997 if (rij.filter != null && rij.filter.hasAction(action)) { 5998 results.remove(j); 5999 if (DEBUG_INTENT_MATCHING) Log.v( 6000 TAG, "Removing duplicate item from " + j 6001 + " due to action " + action + " at " + i); 6002 j--; 6003 N--; 6004 } 6005 } 6006 } 6007 6008 // If the caller didn't request filter information, drop it now 6009 // so we don't have to marshall/unmarshall it. 6010 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6011 rii.filter = null; 6012 } 6013 } 6014 6015 // Filter out the caller activity if so requested. 6016 if (caller != null) { 6017 N = results.size(); 6018 for (int i=0; i<N; i++) { 6019 ActivityInfo ainfo = results.get(i).activityInfo; 6020 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6021 && caller.getClassName().equals(ainfo.name)) { 6022 results.remove(i); 6023 break; 6024 } 6025 } 6026 } 6027 6028 // If the caller didn't request filter information, 6029 // drop them now so we don't have to 6030 // marshall/unmarshall it. 6031 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6032 N = results.size(); 6033 for (int i=0; i<N; i++) { 6034 results.get(i).filter = null; 6035 } 6036 } 6037 6038 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6039 return results; 6040 } 6041 6042 @Override 6043 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6044 String resolvedType, int flags, int userId) { 6045 return new ParceledListSlice<>( 6046 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6047 } 6048 6049 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6050 String resolvedType, int flags, int userId) { 6051 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6052 flags = updateFlagsForResolve(flags, userId, intent); 6053 ComponentName comp = intent.getComponent(); 6054 if (comp == null) { 6055 if (intent.getSelector() != null) { 6056 intent = intent.getSelector(); 6057 comp = intent.getComponent(); 6058 } 6059 } 6060 if (comp != null) { 6061 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6062 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6063 if (ai != null) { 6064 ResolveInfo ri = new ResolveInfo(); 6065 ri.activityInfo = ai; 6066 list.add(ri); 6067 } 6068 return list; 6069 } 6070 6071 // reader 6072 synchronized (mPackages) { 6073 String pkgName = intent.getPackage(); 6074 if (pkgName == null) { 6075 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6076 } 6077 final PackageParser.Package pkg = mPackages.get(pkgName); 6078 if (pkg != null) { 6079 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6080 userId); 6081 } 6082 return Collections.emptyList(); 6083 } 6084 } 6085 6086 @Override 6087 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6088 if (!sUserManager.exists(userId)) return null; 6089 flags = updateFlagsForResolve(flags, userId, intent); 6090 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6091 if (query != null) { 6092 if (query.size() >= 1) { 6093 // If there is more than one service with the same priority, 6094 // just arbitrarily pick the first one. 6095 return query.get(0); 6096 } 6097 } 6098 return null; 6099 } 6100 6101 @Override 6102 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6103 String resolvedType, int flags, int userId) { 6104 return new ParceledListSlice<>( 6105 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6106 } 6107 6108 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6109 String resolvedType, int flags, int userId) { 6110 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6111 flags = updateFlagsForResolve(flags, userId, intent); 6112 ComponentName comp = intent.getComponent(); 6113 if (comp == null) { 6114 if (intent.getSelector() != null) { 6115 intent = intent.getSelector(); 6116 comp = intent.getComponent(); 6117 } 6118 } 6119 if (comp != null) { 6120 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6121 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6122 if (si != null) { 6123 final ResolveInfo ri = new ResolveInfo(); 6124 ri.serviceInfo = si; 6125 list.add(ri); 6126 } 6127 return list; 6128 } 6129 6130 // reader 6131 synchronized (mPackages) { 6132 String pkgName = intent.getPackage(); 6133 if (pkgName == null) { 6134 return mServices.queryIntent(intent, resolvedType, flags, userId); 6135 } 6136 final PackageParser.Package pkg = mPackages.get(pkgName); 6137 if (pkg != null) { 6138 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6139 userId); 6140 } 6141 return Collections.emptyList(); 6142 } 6143 } 6144 6145 @Override 6146 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6147 String resolvedType, int flags, int userId) { 6148 return new ParceledListSlice<>( 6149 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6150 } 6151 6152 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6153 Intent intent, String resolvedType, int flags, int userId) { 6154 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6155 flags = updateFlagsForResolve(flags, userId, intent); 6156 ComponentName comp = intent.getComponent(); 6157 if (comp == null) { 6158 if (intent.getSelector() != null) { 6159 intent = intent.getSelector(); 6160 comp = intent.getComponent(); 6161 } 6162 } 6163 if (comp != null) { 6164 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6165 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6166 if (pi != null) { 6167 final ResolveInfo ri = new ResolveInfo(); 6168 ri.providerInfo = pi; 6169 list.add(ri); 6170 } 6171 return list; 6172 } 6173 6174 // reader 6175 synchronized (mPackages) { 6176 String pkgName = intent.getPackage(); 6177 if (pkgName == null) { 6178 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6179 } 6180 final PackageParser.Package pkg = mPackages.get(pkgName); 6181 if (pkg != null) { 6182 return mProviders.queryIntentForPackage( 6183 intent, resolvedType, flags, pkg.providers, userId); 6184 } 6185 return Collections.emptyList(); 6186 } 6187 } 6188 6189 @Override 6190 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6191 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6192 flags = updateFlagsForPackage(flags, userId, null); 6193 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6195 true /* requireFullPermission */, false /* checkShell */, 6196 "get installed packages"); 6197 6198 // writer 6199 synchronized (mPackages) { 6200 ArrayList<PackageInfo> list; 6201 if (listUninstalled) { 6202 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6203 for (PackageSetting ps : mSettings.mPackages.values()) { 6204 final PackageInfo pi; 6205 if (ps.pkg != null) { 6206 pi = generatePackageInfo(ps, flags, userId); 6207 } else { 6208 pi = generatePackageInfo(ps, flags, userId); 6209 } 6210 if (pi != null) { 6211 list.add(pi); 6212 } 6213 } 6214 } else { 6215 list = new ArrayList<PackageInfo>(mPackages.size()); 6216 for (PackageParser.Package p : mPackages.values()) { 6217 final PackageInfo pi = 6218 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6219 if (pi != null) { 6220 list.add(pi); 6221 } 6222 } 6223 } 6224 6225 return new ParceledListSlice<PackageInfo>(list); 6226 } 6227 } 6228 6229 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6230 String[] permissions, boolean[] tmp, int flags, int userId) { 6231 int numMatch = 0; 6232 final PermissionsState permissionsState = ps.getPermissionsState(); 6233 for (int i=0; i<permissions.length; i++) { 6234 final String permission = permissions[i]; 6235 if (permissionsState.hasPermission(permission, userId)) { 6236 tmp[i] = true; 6237 numMatch++; 6238 } else { 6239 tmp[i] = false; 6240 } 6241 } 6242 if (numMatch == 0) { 6243 return; 6244 } 6245 final PackageInfo pi; 6246 if (ps.pkg != null) { 6247 pi = generatePackageInfo(ps, flags, userId); 6248 } else { 6249 pi = generatePackageInfo(ps, flags, userId); 6250 } 6251 // The above might return null in cases of uninstalled apps or install-state 6252 // skew across users/profiles. 6253 if (pi != null) { 6254 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6255 if (numMatch == permissions.length) { 6256 pi.requestedPermissions = permissions; 6257 } else { 6258 pi.requestedPermissions = new String[numMatch]; 6259 numMatch = 0; 6260 for (int i=0; i<permissions.length; i++) { 6261 if (tmp[i]) { 6262 pi.requestedPermissions[numMatch] = permissions[i]; 6263 numMatch++; 6264 } 6265 } 6266 } 6267 } 6268 list.add(pi); 6269 } 6270 } 6271 6272 @Override 6273 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6274 String[] permissions, int flags, int userId) { 6275 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6276 flags = updateFlagsForPackage(flags, userId, permissions); 6277 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6278 6279 // writer 6280 synchronized (mPackages) { 6281 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6282 boolean[] tmpBools = new boolean[permissions.length]; 6283 if (listUninstalled) { 6284 for (PackageSetting ps : mSettings.mPackages.values()) { 6285 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6286 } 6287 } else { 6288 for (PackageParser.Package pkg : mPackages.values()) { 6289 PackageSetting ps = (PackageSetting)pkg.mExtras; 6290 if (ps != null) { 6291 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6292 userId); 6293 } 6294 } 6295 } 6296 6297 return new ParceledListSlice<PackageInfo>(list); 6298 } 6299 } 6300 6301 @Override 6302 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6303 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6304 flags = updateFlagsForApplication(flags, userId, null); 6305 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6306 6307 // writer 6308 synchronized (mPackages) { 6309 ArrayList<ApplicationInfo> list; 6310 if (listUninstalled) { 6311 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6312 for (PackageSetting ps : mSettings.mPackages.values()) { 6313 ApplicationInfo ai; 6314 if (ps.pkg != null) { 6315 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6316 ps.readUserState(userId), userId); 6317 } else { 6318 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6319 } 6320 if (ai != null) { 6321 list.add(ai); 6322 } 6323 } 6324 } else { 6325 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6326 for (PackageParser.Package p : mPackages.values()) { 6327 if (p.mExtras != null) { 6328 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6329 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6330 if (ai != null) { 6331 list.add(ai); 6332 } 6333 } 6334 } 6335 } 6336 6337 return new ParceledListSlice<ApplicationInfo>(list); 6338 } 6339 } 6340 6341 @Override 6342 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6343 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6344 return null; 6345 } 6346 6347 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6348 "getEphemeralApplications"); 6349 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6350 true /* requireFullPermission */, false /* checkShell */, 6351 "getEphemeralApplications"); 6352 synchronized (mPackages) { 6353 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6354 .getEphemeralApplicationsLPw(userId); 6355 if (ephemeralApps != null) { 6356 return new ParceledListSlice<>(ephemeralApps); 6357 } 6358 } 6359 return null; 6360 } 6361 6362 @Override 6363 public boolean isEphemeralApplication(String packageName, int userId) { 6364 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6365 true /* requireFullPermission */, false /* checkShell */, 6366 "isEphemeral"); 6367 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6368 return false; 6369 } 6370 6371 if (!isCallerSameApp(packageName)) { 6372 return false; 6373 } 6374 synchronized (mPackages) { 6375 PackageParser.Package pkg = mPackages.get(packageName); 6376 if (pkg != null) { 6377 return pkg.applicationInfo.isEphemeralApp(); 6378 } 6379 } 6380 return false; 6381 } 6382 6383 @Override 6384 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6385 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6386 return null; 6387 } 6388 6389 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6390 true /* requireFullPermission */, false /* checkShell */, 6391 "getCookie"); 6392 if (!isCallerSameApp(packageName)) { 6393 return null; 6394 } 6395 synchronized (mPackages) { 6396 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6397 packageName, userId); 6398 } 6399 } 6400 6401 @Override 6402 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6403 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6404 return true; 6405 } 6406 6407 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6408 true /* requireFullPermission */, true /* checkShell */, 6409 "setCookie"); 6410 if (!isCallerSameApp(packageName)) { 6411 return false; 6412 } 6413 synchronized (mPackages) { 6414 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6415 packageName, cookie, userId); 6416 } 6417 } 6418 6419 @Override 6420 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6421 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6422 return null; 6423 } 6424 6425 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6426 "getEphemeralApplicationIcon"); 6427 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6428 true /* requireFullPermission */, false /* checkShell */, 6429 "getEphemeralApplicationIcon"); 6430 synchronized (mPackages) { 6431 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6432 packageName, userId); 6433 } 6434 } 6435 6436 private boolean isCallerSameApp(String packageName) { 6437 PackageParser.Package pkg = mPackages.get(packageName); 6438 return pkg != null 6439 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6440 } 6441 6442 @Override 6443 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6444 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6445 } 6446 6447 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6448 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6449 6450 // reader 6451 synchronized (mPackages) { 6452 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6453 final int userId = UserHandle.getCallingUserId(); 6454 while (i.hasNext()) { 6455 final PackageParser.Package p = i.next(); 6456 if (p.applicationInfo == null) continue; 6457 6458 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6459 && !p.applicationInfo.isDirectBootAware(); 6460 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6461 && p.applicationInfo.isDirectBootAware(); 6462 6463 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6464 && (!mSafeMode || isSystemApp(p)) 6465 && (matchesUnaware || matchesAware)) { 6466 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6467 if (ps != null) { 6468 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6469 ps.readUserState(userId), userId); 6470 if (ai != null) { 6471 finalList.add(ai); 6472 } 6473 } 6474 } 6475 } 6476 } 6477 6478 return finalList; 6479 } 6480 6481 @Override 6482 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6483 if (!sUserManager.exists(userId)) return null; 6484 flags = updateFlagsForComponent(flags, userId, name); 6485 // reader 6486 synchronized (mPackages) { 6487 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6488 PackageSetting ps = provider != null 6489 ? mSettings.mPackages.get(provider.owner.packageName) 6490 : null; 6491 return ps != null 6492 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6493 ? PackageParser.generateProviderInfo(provider, flags, 6494 ps.readUserState(userId), userId) 6495 : null; 6496 } 6497 } 6498 6499 /** 6500 * @deprecated 6501 */ 6502 @Deprecated 6503 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6504 // reader 6505 synchronized (mPackages) { 6506 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6507 .entrySet().iterator(); 6508 final int userId = UserHandle.getCallingUserId(); 6509 while (i.hasNext()) { 6510 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6511 PackageParser.Provider p = entry.getValue(); 6512 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6513 6514 if (ps != null && p.syncable 6515 && (!mSafeMode || (p.info.applicationInfo.flags 6516 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6517 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6518 ps.readUserState(userId), userId); 6519 if (info != null) { 6520 outNames.add(entry.getKey()); 6521 outInfo.add(info); 6522 } 6523 } 6524 } 6525 } 6526 } 6527 6528 @Override 6529 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6530 int uid, int flags) { 6531 final int userId = processName != null ? UserHandle.getUserId(uid) 6532 : UserHandle.getCallingUserId(); 6533 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6534 flags = updateFlagsForComponent(flags, userId, processName); 6535 6536 ArrayList<ProviderInfo> finalList = null; 6537 // reader 6538 synchronized (mPackages) { 6539 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6540 while (i.hasNext()) { 6541 final PackageParser.Provider p = i.next(); 6542 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6543 if (ps != null && p.info.authority != null 6544 && (processName == null 6545 || (p.info.processName.equals(processName) 6546 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6547 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6548 if (finalList == null) { 6549 finalList = new ArrayList<ProviderInfo>(3); 6550 } 6551 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6552 ps.readUserState(userId), userId); 6553 if (info != null) { 6554 finalList.add(info); 6555 } 6556 } 6557 } 6558 } 6559 6560 if (finalList != null) { 6561 Collections.sort(finalList, mProviderInitOrderSorter); 6562 return new ParceledListSlice<ProviderInfo>(finalList); 6563 } 6564 6565 return ParceledListSlice.emptyList(); 6566 } 6567 6568 @Override 6569 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6570 // reader 6571 synchronized (mPackages) { 6572 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6573 return PackageParser.generateInstrumentationInfo(i, flags); 6574 } 6575 } 6576 6577 @Override 6578 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6579 String targetPackage, int flags) { 6580 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6581 } 6582 6583 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6584 int flags) { 6585 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6586 6587 // reader 6588 synchronized (mPackages) { 6589 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6590 while (i.hasNext()) { 6591 final PackageParser.Instrumentation p = i.next(); 6592 if (targetPackage == null 6593 || targetPackage.equals(p.info.targetPackage)) { 6594 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6595 flags); 6596 if (ii != null) { 6597 finalList.add(ii); 6598 } 6599 } 6600 } 6601 } 6602 6603 return finalList; 6604 } 6605 6606 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6607 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6608 if (overlays == null) { 6609 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6610 return; 6611 } 6612 for (PackageParser.Package opkg : overlays.values()) { 6613 // Not much to do if idmap fails: we already logged the error 6614 // and we certainly don't want to abort installation of pkg simply 6615 // because an overlay didn't fit properly. For these reasons, 6616 // ignore the return value of createIdmapForPackagePairLI. 6617 createIdmapForPackagePairLI(pkg, opkg); 6618 } 6619 } 6620 6621 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6622 PackageParser.Package opkg) { 6623 if (!opkg.mTrustedOverlay) { 6624 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6625 opkg.baseCodePath + ": overlay not trusted"); 6626 return false; 6627 } 6628 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6629 if (overlaySet == null) { 6630 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6631 opkg.baseCodePath + " but target package has no known overlays"); 6632 return false; 6633 } 6634 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6635 // TODO: generate idmap for split APKs 6636 try { 6637 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6638 } catch (InstallerException e) { 6639 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6640 + opkg.baseCodePath); 6641 return false; 6642 } 6643 PackageParser.Package[] overlayArray = 6644 overlaySet.values().toArray(new PackageParser.Package[0]); 6645 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6646 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6647 return p1.mOverlayPriority - p2.mOverlayPriority; 6648 } 6649 }; 6650 Arrays.sort(overlayArray, cmp); 6651 6652 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6653 int i = 0; 6654 for (PackageParser.Package p : overlayArray) { 6655 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6656 } 6657 return true; 6658 } 6659 6660 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6661 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6662 try { 6663 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6664 } finally { 6665 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6666 } 6667 } 6668 6669 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6670 final File[] files = dir.listFiles(); 6671 if (ArrayUtils.isEmpty(files)) { 6672 Log.d(TAG, "No files in app dir " + dir); 6673 return; 6674 } 6675 6676 if (DEBUG_PACKAGE_SCANNING) { 6677 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6678 + " flags=0x" + Integer.toHexString(parseFlags)); 6679 } 6680 6681 for (File file : files) { 6682 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6683 && !PackageInstallerService.isStageName(file.getName()); 6684 if (!isPackage) { 6685 // Ignore entries which are not packages 6686 continue; 6687 } 6688 try { 6689 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6690 scanFlags, currentTime, null); 6691 } catch (PackageManagerException e) { 6692 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6693 6694 // Delete invalid userdata apps 6695 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6696 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6697 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6698 removeCodePathLI(file); 6699 } 6700 } 6701 } 6702 } 6703 6704 private static File getSettingsProblemFile() { 6705 File dataDir = Environment.getDataDirectory(); 6706 File systemDir = new File(dataDir, "system"); 6707 File fname = new File(systemDir, "uiderrors.txt"); 6708 return fname; 6709 } 6710 6711 static void reportSettingsProblem(int priority, String msg) { 6712 logCriticalInfo(priority, msg); 6713 } 6714 6715 static void logCriticalInfo(int priority, String msg) { 6716 Slog.println(priority, TAG, msg); 6717 EventLogTags.writePmCriticalInfo(msg); 6718 try { 6719 File fname = getSettingsProblemFile(); 6720 FileOutputStream out = new FileOutputStream(fname, true); 6721 PrintWriter pw = new FastPrintWriter(out); 6722 SimpleDateFormat formatter = new SimpleDateFormat(); 6723 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6724 pw.println(dateString + ": " + msg); 6725 pw.close(); 6726 FileUtils.setPermissions( 6727 fname.toString(), 6728 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6729 -1, -1); 6730 } catch (java.io.IOException e) { 6731 } 6732 } 6733 6734 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6735 if (srcFile.isDirectory()) { 6736 final File baseFile = new File(pkg.baseCodePath); 6737 long maxModifiedTime = baseFile.lastModified(); 6738 if (pkg.splitCodePaths != null) { 6739 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6740 final File splitFile = new File(pkg.splitCodePaths[i]); 6741 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6742 } 6743 } 6744 return maxModifiedTime; 6745 } 6746 return srcFile.lastModified(); 6747 } 6748 6749 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6750 final int policyFlags) throws PackageManagerException { 6751 // When upgrading from pre-N MR1, verify the package time stamp using the package 6752 // directory and not the APK file. 6753 final long lastModifiedTime = mIsPreNMR1Upgrade 6754 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6755 if (ps != null 6756 && ps.codePath.equals(srcFile) 6757 && ps.timeStamp == lastModifiedTime 6758 && !isCompatSignatureUpdateNeeded(pkg) 6759 && !isRecoverSignatureUpdateNeeded(pkg)) { 6760 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6761 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6762 ArraySet<PublicKey> signingKs; 6763 synchronized (mPackages) { 6764 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6765 } 6766 if (ps.signatures.mSignatures != null 6767 && ps.signatures.mSignatures.length != 0 6768 && signingKs != null) { 6769 // Optimization: reuse the existing cached certificates 6770 // if the package appears to be unchanged. 6771 pkg.mSignatures = ps.signatures.mSignatures; 6772 pkg.mSigningKeys = signingKs; 6773 return; 6774 } 6775 6776 Slog.w(TAG, "PackageSetting for " + ps.name 6777 + " is missing signatures. Collecting certs again to recover them."); 6778 } else { 6779 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6780 } 6781 6782 try { 6783 PackageParser.collectCertificates(pkg, policyFlags); 6784 } catch (PackageParserException e) { 6785 throw PackageManagerException.from(e); 6786 } 6787 } 6788 6789 /** 6790 * Traces a package scan. 6791 * @see #scanPackageLI(File, int, int, long, UserHandle) 6792 */ 6793 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6794 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6795 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6796 try { 6797 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6798 } finally { 6799 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6800 } 6801 } 6802 6803 /** 6804 * Scans a package and returns the newly parsed package. 6805 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6806 */ 6807 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6808 long currentTime, UserHandle user) throws PackageManagerException { 6809 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6810 PackageParser pp = new PackageParser(); 6811 pp.setSeparateProcesses(mSeparateProcesses); 6812 pp.setOnlyCoreApps(mOnlyCore); 6813 pp.setDisplayMetrics(mMetrics); 6814 6815 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6816 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6817 } 6818 6819 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6820 final PackageParser.Package pkg; 6821 try { 6822 pkg = pp.parsePackage(scanFile, parseFlags); 6823 } catch (PackageParserException e) { 6824 throw PackageManagerException.from(e); 6825 } finally { 6826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6827 } 6828 6829 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6830 } 6831 6832 /** 6833 * Scans a package and returns the newly parsed package. 6834 * @throws PackageManagerException on a parse error. 6835 */ 6836 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6837 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6838 throws PackageManagerException { 6839 // If the package has children and this is the first dive in the function 6840 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6841 // packages (parent and children) would be successfully scanned before the 6842 // actual scan since scanning mutates internal state and we want to atomically 6843 // install the package and its children. 6844 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6845 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6846 scanFlags |= SCAN_CHECK_ONLY; 6847 } 6848 } else { 6849 scanFlags &= ~SCAN_CHECK_ONLY; 6850 } 6851 6852 // Scan the parent 6853 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6854 scanFlags, currentTime, user); 6855 6856 // Scan the children 6857 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6858 for (int i = 0; i < childCount; i++) { 6859 PackageParser.Package childPackage = pkg.childPackages.get(i); 6860 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6861 currentTime, user); 6862 } 6863 6864 6865 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6866 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6867 } 6868 6869 return scannedPkg; 6870 } 6871 6872 /** 6873 * Scans a package and returns the newly parsed package. 6874 * @throws PackageManagerException on a parse error. 6875 */ 6876 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6877 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6878 throws PackageManagerException { 6879 PackageSetting ps = null; 6880 PackageSetting updatedPkg; 6881 // reader 6882 synchronized (mPackages) { 6883 // Look to see if we already know about this package. 6884 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6885 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6886 // This package has been renamed to its original name. Let's 6887 // use that. 6888 ps = mSettings.peekPackageLPr(oldName); 6889 } 6890 // If there was no original package, see one for the real package name. 6891 if (ps == null) { 6892 ps = mSettings.peekPackageLPr(pkg.packageName); 6893 } 6894 // Check to see if this package could be hiding/updating a system 6895 // package. Must look for it either under the original or real 6896 // package name depending on our state. 6897 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6898 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6899 6900 // If this is a package we don't know about on the system partition, we 6901 // may need to remove disabled child packages on the system partition 6902 // or may need to not add child packages if the parent apk is updated 6903 // on the data partition and no longer defines this child package. 6904 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6905 // If this is a parent package for an updated system app and this system 6906 // app got an OTA update which no longer defines some of the child packages 6907 // we have to prune them from the disabled system packages. 6908 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6909 if (disabledPs != null) { 6910 final int scannedChildCount = (pkg.childPackages != null) 6911 ? pkg.childPackages.size() : 0; 6912 final int disabledChildCount = disabledPs.childPackageNames != null 6913 ? disabledPs.childPackageNames.size() : 0; 6914 for (int i = 0; i < disabledChildCount; i++) { 6915 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6916 boolean disabledPackageAvailable = false; 6917 for (int j = 0; j < scannedChildCount; j++) { 6918 PackageParser.Package childPkg = pkg.childPackages.get(j); 6919 if (childPkg.packageName.equals(disabledChildPackageName)) { 6920 disabledPackageAvailable = true; 6921 break; 6922 } 6923 } 6924 if (!disabledPackageAvailable) { 6925 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6926 } 6927 } 6928 } 6929 } 6930 } 6931 6932 boolean updatedPkgBetter = false; 6933 // First check if this is a system package that may involve an update 6934 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6935 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6936 // it needs to drop FLAG_PRIVILEGED. 6937 if (locationIsPrivileged(scanFile)) { 6938 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6939 } else { 6940 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6941 } 6942 6943 if (ps != null && !ps.codePath.equals(scanFile)) { 6944 // The path has changed from what was last scanned... check the 6945 // version of the new path against what we have stored to determine 6946 // what to do. 6947 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6948 if (pkg.mVersionCode <= ps.versionCode) { 6949 // The system package has been updated and the code path does not match 6950 // Ignore entry. Skip it. 6951 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6952 + " ignored: updated version " + ps.versionCode 6953 + " better than this " + pkg.mVersionCode); 6954 if (!updatedPkg.codePath.equals(scanFile)) { 6955 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6956 + ps.name + " changing from " + updatedPkg.codePathString 6957 + " to " + scanFile); 6958 updatedPkg.codePath = scanFile; 6959 updatedPkg.codePathString = scanFile.toString(); 6960 updatedPkg.resourcePath = scanFile; 6961 updatedPkg.resourcePathString = scanFile.toString(); 6962 } 6963 updatedPkg.pkg = pkg; 6964 updatedPkg.versionCode = pkg.mVersionCode; 6965 6966 // Update the disabled system child packages to point to the package too. 6967 final int childCount = updatedPkg.childPackageNames != null 6968 ? updatedPkg.childPackageNames.size() : 0; 6969 for (int i = 0; i < childCount; i++) { 6970 String childPackageName = updatedPkg.childPackageNames.get(i); 6971 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6972 childPackageName); 6973 if (updatedChildPkg != null) { 6974 updatedChildPkg.pkg = pkg; 6975 updatedChildPkg.versionCode = pkg.mVersionCode; 6976 } 6977 } 6978 6979 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6980 + scanFile + " ignored: updated version " + ps.versionCode 6981 + " better than this " + pkg.mVersionCode); 6982 } else { 6983 // The current app on the system partition is better than 6984 // what we have updated to on the data partition; switch 6985 // back to the system partition version. 6986 // At this point, its safely assumed that package installation for 6987 // apps in system partition will go through. If not there won't be a working 6988 // version of the app 6989 // writer 6990 synchronized (mPackages) { 6991 // Just remove the loaded entries from package lists. 6992 mPackages.remove(ps.name); 6993 } 6994 6995 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6996 + " reverting from " + ps.codePathString 6997 + ": new version " + pkg.mVersionCode 6998 + " better than installed " + ps.versionCode); 6999 7000 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7001 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7002 synchronized (mInstallLock) { 7003 args.cleanUpResourcesLI(); 7004 } 7005 synchronized (mPackages) { 7006 mSettings.enableSystemPackageLPw(ps.name); 7007 } 7008 updatedPkgBetter = true; 7009 } 7010 } 7011 } 7012 7013 if (updatedPkg != null) { 7014 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7015 // initially 7016 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7017 7018 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7019 // flag set initially 7020 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7021 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7022 } 7023 } 7024 7025 // Verify certificates against what was last scanned 7026 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7027 7028 /* 7029 * A new system app appeared, but we already had a non-system one of the 7030 * same name installed earlier. 7031 */ 7032 boolean shouldHideSystemApp = false; 7033 if (updatedPkg == null && ps != null 7034 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7035 /* 7036 * Check to make sure the signatures match first. If they don't, 7037 * wipe the installed application and its data. 7038 */ 7039 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7040 != PackageManager.SIGNATURE_MATCH) { 7041 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7042 + " signatures don't match existing userdata copy; removing"); 7043 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7044 "scanPackageInternalLI")) { 7045 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7046 } 7047 ps = null; 7048 } else { 7049 /* 7050 * If the newly-added system app is an older version than the 7051 * already installed version, hide it. It will be scanned later 7052 * and re-added like an update. 7053 */ 7054 if (pkg.mVersionCode <= ps.versionCode) { 7055 shouldHideSystemApp = true; 7056 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7057 + " but new version " + pkg.mVersionCode + " better than installed " 7058 + ps.versionCode + "; hiding system"); 7059 } else { 7060 /* 7061 * The newly found system app is a newer version that the 7062 * one previously installed. Simply remove the 7063 * already-installed application and replace it with our own 7064 * while keeping the application data. 7065 */ 7066 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7067 + " reverting from " + ps.codePathString + ": new version " 7068 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7069 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7070 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7071 synchronized (mInstallLock) { 7072 args.cleanUpResourcesLI(); 7073 } 7074 } 7075 } 7076 } 7077 7078 // The apk is forward locked (not public) if its code and resources 7079 // are kept in different files. (except for app in either system or 7080 // vendor path). 7081 // TODO grab this value from PackageSettings 7082 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7083 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7084 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7085 } 7086 } 7087 7088 // TODO: extend to support forward-locked splits 7089 String resourcePath = null; 7090 String baseResourcePath = null; 7091 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7092 if (ps != null && ps.resourcePathString != null) { 7093 resourcePath = ps.resourcePathString; 7094 baseResourcePath = ps.resourcePathString; 7095 } else { 7096 // Should not happen at all. Just log an error. 7097 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7098 } 7099 } else { 7100 resourcePath = pkg.codePath; 7101 baseResourcePath = pkg.baseCodePath; 7102 } 7103 7104 // Set application objects path explicitly. 7105 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7106 pkg.setApplicationInfoCodePath(pkg.codePath); 7107 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7108 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7109 pkg.setApplicationInfoResourcePath(resourcePath); 7110 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7111 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7112 7113 // Note that we invoke the following method only if we are about to unpack an application 7114 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7115 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7116 7117 /* 7118 * If the system app should be overridden by a previously installed 7119 * data, hide the system app now and let the /data/app scan pick it up 7120 * again. 7121 */ 7122 if (shouldHideSystemApp) { 7123 synchronized (mPackages) { 7124 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7125 } 7126 } 7127 7128 return scannedPkg; 7129 } 7130 7131 private static String fixProcessName(String defProcessName, 7132 String processName, int uid) { 7133 if (processName == null) { 7134 return defProcessName; 7135 } 7136 return processName; 7137 } 7138 7139 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7140 throws PackageManagerException { 7141 if (pkgSetting.signatures.mSignatures != null) { 7142 // Already existing package. Make sure signatures match 7143 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7144 == PackageManager.SIGNATURE_MATCH; 7145 if (!match) { 7146 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7147 == PackageManager.SIGNATURE_MATCH; 7148 } 7149 if (!match) { 7150 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7151 == PackageManager.SIGNATURE_MATCH; 7152 } 7153 if (!match) { 7154 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7155 + pkg.packageName + " signatures do not match the " 7156 + "previously installed version; ignoring!"); 7157 } 7158 } 7159 7160 // Check for shared user signatures 7161 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7162 // Already existing package. Make sure signatures match 7163 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7164 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7165 if (!match) { 7166 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7167 == PackageManager.SIGNATURE_MATCH; 7168 } 7169 if (!match) { 7170 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7171 == PackageManager.SIGNATURE_MATCH; 7172 } 7173 if (!match) { 7174 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7175 "Package " + pkg.packageName 7176 + " has no signatures that match those in shared user " 7177 + pkgSetting.sharedUser.name + "; ignoring!"); 7178 } 7179 } 7180 } 7181 7182 /** 7183 * Enforces that only the system UID or root's UID can call a method exposed 7184 * via Binder. 7185 * 7186 * @param message used as message if SecurityException is thrown 7187 * @throws SecurityException if the caller is not system or root 7188 */ 7189 private static final void enforceSystemOrRoot(String message) { 7190 final int uid = Binder.getCallingUid(); 7191 if (uid != Process.SYSTEM_UID && uid != 0) { 7192 throw new SecurityException(message); 7193 } 7194 } 7195 7196 @Override 7197 public void performFstrimIfNeeded() { 7198 enforceSystemOrRoot("Only the system can request fstrim"); 7199 7200 // Before everything else, see whether we need to fstrim. 7201 try { 7202 IMountService ms = PackageHelper.getMountService(); 7203 if (ms != null) { 7204 boolean doTrim = false; 7205 final long interval = android.provider.Settings.Global.getLong( 7206 mContext.getContentResolver(), 7207 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7208 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7209 if (interval > 0) { 7210 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7211 if (timeSinceLast > interval) { 7212 doTrim = true; 7213 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7214 + "; running immediately"); 7215 } 7216 } 7217 if (doTrim) { 7218 final boolean dexOptDialogShown; 7219 synchronized (mPackages) { 7220 dexOptDialogShown = mDexOptDialogShown; 7221 } 7222 if (!isFirstBoot() && dexOptDialogShown) { 7223 try { 7224 ActivityManagerNative.getDefault().showBootMessage( 7225 mContext.getResources().getString( 7226 R.string.android_upgrading_fstrim), true); 7227 } catch (RemoteException e) { 7228 } 7229 } 7230 ms.runMaintenance(); 7231 } 7232 } else { 7233 Slog.e(TAG, "Mount service unavailable!"); 7234 } 7235 } catch (RemoteException e) { 7236 // Can't happen; MountService is local 7237 } 7238 } 7239 7240 @Override 7241 public void updatePackagesIfNeeded() { 7242 enforceSystemOrRoot("Only the system can request package update"); 7243 7244 // We need to re-extract after an OTA. 7245 boolean causeUpgrade = isUpgrade(); 7246 7247 // First boot or factory reset. 7248 // Note: we also handle devices that are upgrading to N right now as if it is their 7249 // first boot, as they do not have profile data. 7250 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7251 7252 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7253 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7254 7255 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7256 return; 7257 } 7258 7259 List<PackageParser.Package> pkgs; 7260 synchronized (mPackages) { 7261 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7262 } 7263 7264 final long startTime = System.nanoTime(); 7265 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7266 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7267 7268 final int elapsedTimeSeconds = 7269 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7270 7271 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7272 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7273 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7274 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7275 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7276 } 7277 7278 /** 7279 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7280 * containing statistics about the invocation. The array consists of three elements, 7281 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7282 * and {@code numberOfPackagesFailed}. 7283 */ 7284 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7285 String compilerFilter) { 7286 7287 int numberOfPackagesVisited = 0; 7288 int numberOfPackagesOptimized = 0; 7289 int numberOfPackagesSkipped = 0; 7290 int numberOfPackagesFailed = 0; 7291 final int numberOfPackagesToDexopt = pkgs.size(); 7292 7293 for (PackageParser.Package pkg : pkgs) { 7294 numberOfPackagesVisited++; 7295 7296 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7297 if (DEBUG_DEXOPT) { 7298 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7299 } 7300 numberOfPackagesSkipped++; 7301 continue; 7302 } 7303 7304 if (DEBUG_DEXOPT) { 7305 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7306 numberOfPackagesToDexopt + ": " + pkg.packageName); 7307 } 7308 7309 if (showDialog) { 7310 try { 7311 ActivityManagerNative.getDefault().showBootMessage( 7312 mContext.getResources().getString(R.string.android_upgrading_apk, 7313 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7314 } catch (RemoteException e) { 7315 } 7316 synchronized (mPackages) { 7317 mDexOptDialogShown = true; 7318 } 7319 } 7320 7321 // If the OTA updates a system app which was previously preopted to a non-preopted state 7322 // the app might end up being verified at runtime. That's because by default the apps 7323 // are verify-profile but for preopted apps there's no profile. 7324 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7325 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7326 // filter (by default interpret-only). 7327 // Note that at this stage unused apps are already filtered. 7328 if (isSystemApp(pkg) && 7329 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7330 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7331 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7332 } 7333 7334 // If the OTA updates a system app which was previously preopted to a non-preopted state 7335 // the app might end up being verified at runtime. That's because by default the apps 7336 // are verify-profile but for preopted apps there's no profile. 7337 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7338 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7339 // filter (by default interpret-only). 7340 // Note that at this stage unused apps are already filtered. 7341 if (isSystemApp(pkg) && 7342 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7343 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7344 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7345 } 7346 7347 // checkProfiles is false to avoid merging profiles during boot which 7348 // might interfere with background compilation (b/28612421). 7349 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7350 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7351 // trade-off worth doing to save boot time work. 7352 int dexOptStatus = performDexOptTraced(pkg.packageName, 7353 false /* checkProfiles */, 7354 compilerFilter, 7355 false /* force */); 7356 switch (dexOptStatus) { 7357 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7358 numberOfPackagesOptimized++; 7359 break; 7360 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7361 numberOfPackagesSkipped++; 7362 break; 7363 case PackageDexOptimizer.DEX_OPT_FAILED: 7364 numberOfPackagesFailed++; 7365 break; 7366 default: 7367 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7368 break; 7369 } 7370 } 7371 7372 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7373 numberOfPackagesFailed }; 7374 } 7375 7376 @Override 7377 public void notifyPackageUse(String packageName, int reason) { 7378 synchronized (mPackages) { 7379 PackageParser.Package p = mPackages.get(packageName); 7380 if (p == null) { 7381 return; 7382 } 7383 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7384 } 7385 } 7386 7387 // TODO: this is not used nor needed. Delete it. 7388 @Override 7389 public boolean performDexOptIfNeeded(String packageName) { 7390 int dexOptStatus = performDexOptTraced(packageName, 7391 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7392 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7393 } 7394 7395 @Override 7396 public boolean performDexOpt(String packageName, 7397 boolean checkProfiles, int compileReason, boolean force) { 7398 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7399 getCompilerFilterForReason(compileReason), force); 7400 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7401 } 7402 7403 @Override 7404 public boolean performDexOptMode(String packageName, 7405 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7406 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7407 targetCompilerFilter, force); 7408 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7409 } 7410 7411 private int performDexOptTraced(String packageName, 7412 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7413 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7414 try { 7415 return performDexOptInternal(packageName, checkProfiles, 7416 targetCompilerFilter, force); 7417 } finally { 7418 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7419 } 7420 } 7421 7422 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7423 // if the package can now be considered up to date for the given filter. 7424 private int performDexOptInternal(String packageName, 7425 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7426 PackageParser.Package p; 7427 synchronized (mPackages) { 7428 p = mPackages.get(packageName); 7429 if (p == null) { 7430 // Package could not be found. Report failure. 7431 return PackageDexOptimizer.DEX_OPT_FAILED; 7432 } 7433 mPackageUsage.maybeWriteAsync(mPackages); 7434 mCompilerStats.maybeWriteAsync(); 7435 } 7436 long callingId = Binder.clearCallingIdentity(); 7437 try { 7438 synchronized (mInstallLock) { 7439 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7440 targetCompilerFilter, force); 7441 } 7442 } finally { 7443 Binder.restoreCallingIdentity(callingId); 7444 } 7445 } 7446 7447 public ArraySet<String> getOptimizablePackages() { 7448 ArraySet<String> pkgs = new ArraySet<String>(); 7449 synchronized (mPackages) { 7450 for (PackageParser.Package p : mPackages.values()) { 7451 if (PackageDexOptimizer.canOptimizePackage(p)) { 7452 pkgs.add(p.packageName); 7453 } 7454 } 7455 } 7456 return pkgs; 7457 } 7458 7459 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7460 boolean checkProfiles, String targetCompilerFilter, 7461 boolean force) { 7462 // Select the dex optimizer based on the force parameter. 7463 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7464 // allocate an object here. 7465 PackageDexOptimizer pdo = force 7466 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7467 : mPackageDexOptimizer; 7468 7469 // Optimize all dependencies first. Note: we ignore the return value and march on 7470 // on errors. 7471 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7472 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7473 if (!deps.isEmpty()) { 7474 for (PackageParser.Package depPackage : deps) { 7475 // TODO: Analyze and investigate if we (should) profile libraries. 7476 // Currently this will do a full compilation of the library by default. 7477 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7478 false /* checkProfiles */, 7479 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7480 getOrCreateCompilerPackageStats(depPackage)); 7481 } 7482 } 7483 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7484 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7485 } 7486 7487 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7488 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7489 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7490 Set<String> collectedNames = new HashSet<>(); 7491 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7492 7493 retValue.remove(p); 7494 7495 return retValue; 7496 } else { 7497 return Collections.emptyList(); 7498 } 7499 } 7500 7501 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7502 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7503 if (!collectedNames.contains(p.packageName)) { 7504 collectedNames.add(p.packageName); 7505 collected.add(p); 7506 7507 if (p.usesLibraries != null) { 7508 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7509 } 7510 if (p.usesOptionalLibraries != null) { 7511 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7512 collectedNames); 7513 } 7514 } 7515 } 7516 7517 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7518 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7519 for (String libName : libs) { 7520 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7521 if (libPkg != null) { 7522 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7523 } 7524 } 7525 } 7526 7527 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7528 synchronized (mPackages) { 7529 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7530 if (lib != null && lib.apk != null) { 7531 return mPackages.get(lib.apk); 7532 } 7533 } 7534 return null; 7535 } 7536 7537 public void shutdown() { 7538 mPackageUsage.writeNow(mPackages); 7539 mCompilerStats.writeNow(); 7540 } 7541 7542 @Override 7543 public void dumpProfiles(String packageName) { 7544 PackageParser.Package pkg; 7545 synchronized (mPackages) { 7546 pkg = mPackages.get(packageName); 7547 if (pkg == null) { 7548 throw new IllegalArgumentException("Unknown package: " + packageName); 7549 } 7550 } 7551 /* Only the shell, root, or the app user should be able to dump profiles. */ 7552 int callingUid = Binder.getCallingUid(); 7553 if (callingUid != Process.SHELL_UID && 7554 callingUid != Process.ROOT_UID && 7555 callingUid != pkg.applicationInfo.uid) { 7556 throw new SecurityException("dumpProfiles"); 7557 } 7558 7559 synchronized (mInstallLock) { 7560 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7561 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7562 try { 7563 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7564 String codePaths = TextUtils.join(";", allCodePaths); 7565 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7566 } catch (InstallerException e) { 7567 Slog.w(TAG, "Failed to dump profiles", e); 7568 } 7569 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7570 } 7571 } 7572 7573 @Override 7574 public void forceDexOpt(String packageName) { 7575 enforceSystemOrRoot("forceDexOpt"); 7576 7577 PackageParser.Package pkg; 7578 synchronized (mPackages) { 7579 pkg = mPackages.get(packageName); 7580 if (pkg == null) { 7581 throw new IllegalArgumentException("Unknown package: " + packageName); 7582 } 7583 } 7584 7585 synchronized (mInstallLock) { 7586 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7587 7588 // Whoever is calling forceDexOpt wants a fully compiled package. 7589 // Don't use profiles since that may cause compilation to be skipped. 7590 final int res = performDexOptInternalWithDependenciesLI(pkg, 7591 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7592 true /* force */); 7593 7594 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7595 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7596 throw new IllegalStateException("Failed to dexopt: " + res); 7597 } 7598 } 7599 } 7600 7601 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7602 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7603 Slog.w(TAG, "Unable to update from " + oldPkg.name 7604 + " to " + newPkg.packageName 7605 + ": old package not in system partition"); 7606 return false; 7607 } else if (mPackages.get(oldPkg.name) != null) { 7608 Slog.w(TAG, "Unable to update from " + oldPkg.name 7609 + " to " + newPkg.packageName 7610 + ": old package still exists"); 7611 return false; 7612 } 7613 return true; 7614 } 7615 7616 void removeCodePathLI(File codePath) { 7617 if (codePath.isDirectory()) { 7618 try { 7619 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7620 } catch (InstallerException e) { 7621 Slog.w(TAG, "Failed to remove code path", e); 7622 } 7623 } else { 7624 codePath.delete(); 7625 } 7626 } 7627 7628 private int[] resolveUserIds(int userId) { 7629 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7630 } 7631 7632 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7633 if (pkg == null) { 7634 Slog.wtf(TAG, "Package was null!", new Throwable()); 7635 return; 7636 } 7637 clearAppDataLeafLIF(pkg, userId, flags); 7638 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7639 for (int i = 0; i < childCount; i++) { 7640 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7641 } 7642 } 7643 7644 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7645 final PackageSetting ps; 7646 synchronized (mPackages) { 7647 ps = mSettings.mPackages.get(pkg.packageName); 7648 } 7649 for (int realUserId : resolveUserIds(userId)) { 7650 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7651 try { 7652 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7653 ceDataInode); 7654 } catch (InstallerException e) { 7655 Slog.w(TAG, String.valueOf(e)); 7656 } 7657 } 7658 } 7659 7660 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7661 if (pkg == null) { 7662 Slog.wtf(TAG, "Package was null!", new Throwable()); 7663 return; 7664 } 7665 destroyAppDataLeafLIF(pkg, userId, flags); 7666 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7667 for (int i = 0; i < childCount; i++) { 7668 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7669 } 7670 } 7671 7672 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7673 final PackageSetting ps; 7674 synchronized (mPackages) { 7675 ps = mSettings.mPackages.get(pkg.packageName); 7676 } 7677 for (int realUserId : resolveUserIds(userId)) { 7678 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7679 try { 7680 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7681 ceDataInode); 7682 } catch (InstallerException e) { 7683 Slog.w(TAG, String.valueOf(e)); 7684 } 7685 } 7686 } 7687 7688 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7689 if (pkg == null) { 7690 Slog.wtf(TAG, "Package was null!", new Throwable()); 7691 return; 7692 } 7693 destroyAppProfilesLeafLIF(pkg); 7694 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7695 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7696 for (int i = 0; i < childCount; i++) { 7697 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7698 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7699 true /* removeBaseMarker */); 7700 } 7701 } 7702 7703 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7704 boolean removeBaseMarker) { 7705 if (pkg.isForwardLocked()) { 7706 return; 7707 } 7708 7709 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7710 try { 7711 path = PackageManagerServiceUtils.realpath(new File(path)); 7712 } catch (IOException e) { 7713 // TODO: Should we return early here ? 7714 Slog.w(TAG, "Failed to get canonical path", e); 7715 continue; 7716 } 7717 7718 final String useMarker = path.replace('/', '@'); 7719 for (int realUserId : resolveUserIds(userId)) { 7720 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7721 if (removeBaseMarker) { 7722 File foreignUseMark = new File(profileDir, useMarker); 7723 if (foreignUseMark.exists()) { 7724 if (!foreignUseMark.delete()) { 7725 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7726 + pkg.packageName); 7727 } 7728 } 7729 } 7730 7731 File[] markers = profileDir.listFiles(); 7732 if (markers != null) { 7733 final String searchString = "@" + pkg.packageName + "@"; 7734 // We also delete all markers that contain the package name we're 7735 // uninstalling. These are associated with secondary dex-files belonging 7736 // to the package. Reconstructing the path of these dex files is messy 7737 // in general. 7738 for (File marker : markers) { 7739 if (marker.getName().indexOf(searchString) > 0) { 7740 if (!marker.delete()) { 7741 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7742 + pkg.packageName); 7743 } 7744 } 7745 } 7746 } 7747 } 7748 } 7749 } 7750 7751 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7752 try { 7753 mInstaller.destroyAppProfiles(pkg.packageName); 7754 } catch (InstallerException e) { 7755 Slog.w(TAG, String.valueOf(e)); 7756 } 7757 } 7758 7759 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7760 if (pkg == null) { 7761 Slog.wtf(TAG, "Package was null!", new Throwable()); 7762 return; 7763 } 7764 clearAppProfilesLeafLIF(pkg); 7765 // We don't remove the base foreign use marker when clearing profiles because 7766 // we will rename it when the app is updated. Unlike the actual profile contents, 7767 // the foreign use marker is good across installs. 7768 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7769 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7770 for (int i = 0; i < childCount; i++) { 7771 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7772 } 7773 } 7774 7775 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7776 try { 7777 mInstaller.clearAppProfiles(pkg.packageName); 7778 } catch (InstallerException e) { 7779 Slog.w(TAG, String.valueOf(e)); 7780 } 7781 } 7782 7783 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7784 long lastUpdateTime) { 7785 // Set parent install/update time 7786 PackageSetting ps = (PackageSetting) pkg.mExtras; 7787 if (ps != null) { 7788 ps.firstInstallTime = firstInstallTime; 7789 ps.lastUpdateTime = lastUpdateTime; 7790 } 7791 // Set children install/update time 7792 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7793 for (int i = 0; i < childCount; i++) { 7794 PackageParser.Package childPkg = pkg.childPackages.get(i); 7795 ps = (PackageSetting) childPkg.mExtras; 7796 if (ps != null) { 7797 ps.firstInstallTime = firstInstallTime; 7798 ps.lastUpdateTime = lastUpdateTime; 7799 } 7800 } 7801 } 7802 7803 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7804 PackageParser.Package changingLib) { 7805 if (file.path != null) { 7806 usesLibraryFiles.add(file.path); 7807 return; 7808 } 7809 PackageParser.Package p = mPackages.get(file.apk); 7810 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7811 // If we are doing this while in the middle of updating a library apk, 7812 // then we need to make sure to use that new apk for determining the 7813 // dependencies here. (We haven't yet finished committing the new apk 7814 // to the package manager state.) 7815 if (p == null || p.packageName.equals(changingLib.packageName)) { 7816 p = changingLib; 7817 } 7818 } 7819 if (p != null) { 7820 usesLibraryFiles.addAll(p.getAllCodePaths()); 7821 } 7822 } 7823 7824 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7825 PackageParser.Package changingLib) throws PackageManagerException { 7826 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7827 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7828 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7829 for (int i=0; i<N; i++) { 7830 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7831 if (file == null) { 7832 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7833 "Package " + pkg.packageName + " requires unavailable shared library " 7834 + pkg.usesLibraries.get(i) + "; failing!"); 7835 } 7836 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7837 } 7838 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7839 for (int i=0; i<N; i++) { 7840 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7841 if (file == null) { 7842 Slog.w(TAG, "Package " + pkg.packageName 7843 + " desires unavailable shared library " 7844 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7845 } else { 7846 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7847 } 7848 } 7849 N = usesLibraryFiles.size(); 7850 if (N > 0) { 7851 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7852 } else { 7853 pkg.usesLibraryFiles = null; 7854 } 7855 } 7856 } 7857 7858 private static boolean hasString(List<String> list, List<String> which) { 7859 if (list == null) { 7860 return false; 7861 } 7862 for (int i=list.size()-1; i>=0; i--) { 7863 for (int j=which.size()-1; j>=0; j--) { 7864 if (which.get(j).equals(list.get(i))) { 7865 return true; 7866 } 7867 } 7868 } 7869 return false; 7870 } 7871 7872 private void updateAllSharedLibrariesLPw() { 7873 for (PackageParser.Package pkg : mPackages.values()) { 7874 try { 7875 updateSharedLibrariesLPw(pkg, null); 7876 } catch (PackageManagerException e) { 7877 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7878 } 7879 } 7880 } 7881 7882 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7883 PackageParser.Package changingPkg) { 7884 ArrayList<PackageParser.Package> res = null; 7885 for (PackageParser.Package pkg : mPackages.values()) { 7886 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7887 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7888 if (res == null) { 7889 res = new ArrayList<PackageParser.Package>(); 7890 } 7891 res.add(pkg); 7892 try { 7893 updateSharedLibrariesLPw(pkg, changingPkg); 7894 } catch (PackageManagerException e) { 7895 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7896 } 7897 } 7898 } 7899 return res; 7900 } 7901 7902 /** 7903 * Derive the value of the {@code cpuAbiOverride} based on the provided 7904 * value and an optional stored value from the package settings. 7905 */ 7906 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7907 String cpuAbiOverride = null; 7908 7909 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7910 cpuAbiOverride = null; 7911 } else if (abiOverride != null) { 7912 cpuAbiOverride = abiOverride; 7913 } else if (settings != null) { 7914 cpuAbiOverride = settings.cpuAbiOverrideString; 7915 } 7916 7917 return cpuAbiOverride; 7918 } 7919 7920 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7921 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7922 throws PackageManagerException { 7923 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7924 // If the package has children and this is the first dive in the function 7925 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7926 // whether all packages (parent and children) would be successfully scanned 7927 // before the actual scan since scanning mutates internal state and we want 7928 // to atomically install the package and its children. 7929 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7930 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7931 scanFlags |= SCAN_CHECK_ONLY; 7932 } 7933 } else { 7934 scanFlags &= ~SCAN_CHECK_ONLY; 7935 } 7936 7937 final PackageParser.Package scannedPkg; 7938 try { 7939 // Scan the parent 7940 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7941 // Scan the children 7942 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7943 for (int i = 0; i < childCount; i++) { 7944 PackageParser.Package childPkg = pkg.childPackages.get(i); 7945 scanPackageLI(childPkg, policyFlags, 7946 scanFlags, currentTime, user); 7947 } 7948 } finally { 7949 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7950 } 7951 7952 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7953 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7954 } 7955 7956 return scannedPkg; 7957 } 7958 7959 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7960 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7961 boolean success = false; 7962 try { 7963 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7964 currentTime, user); 7965 success = true; 7966 return res; 7967 } finally { 7968 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7969 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7970 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7971 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7972 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7973 } 7974 } 7975 } 7976 7977 /** 7978 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7979 */ 7980 private static boolean apkHasCode(String fileName) { 7981 StrictJarFile jarFile = null; 7982 try { 7983 jarFile = new StrictJarFile(fileName, 7984 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7985 return jarFile.findEntry("classes.dex") != null; 7986 } catch (IOException ignore) { 7987 } finally { 7988 try { 7989 if (jarFile != null) { 7990 jarFile.close(); 7991 } 7992 } catch (IOException ignore) {} 7993 } 7994 return false; 7995 } 7996 7997 /** 7998 * Enforces code policy for the package. This ensures that if an APK has 7999 * declared hasCode="true" in its manifest that the APK actually contains 8000 * code. 8001 * 8002 * @throws PackageManagerException If bytecode could not be found when it should exist 8003 */ 8004 private static void enforceCodePolicy(PackageParser.Package pkg) 8005 throws PackageManagerException { 8006 final boolean shouldHaveCode = 8007 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8008 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8009 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8010 "Package " + pkg.baseCodePath + " code is missing"); 8011 } 8012 8013 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8014 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8015 final boolean splitShouldHaveCode = 8016 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8017 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8018 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8019 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8020 } 8021 } 8022 } 8023 } 8024 8025 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8026 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8027 throws PackageManagerException { 8028 final File scanFile = new File(pkg.codePath); 8029 if (pkg.applicationInfo.getCodePath() == null || 8030 pkg.applicationInfo.getResourcePath() == null) { 8031 // Bail out. The resource and code paths haven't been set. 8032 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8033 "Code and resource paths haven't been set correctly"); 8034 } 8035 8036 // Apply policy 8037 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8038 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8039 if (pkg.applicationInfo.isDirectBootAware()) { 8040 // we're direct boot aware; set for all components 8041 for (PackageParser.Service s : pkg.services) { 8042 s.info.encryptionAware = s.info.directBootAware = true; 8043 } 8044 for (PackageParser.Provider p : pkg.providers) { 8045 p.info.encryptionAware = p.info.directBootAware = true; 8046 } 8047 for (PackageParser.Activity a : pkg.activities) { 8048 a.info.encryptionAware = a.info.directBootAware = true; 8049 } 8050 for (PackageParser.Activity r : pkg.receivers) { 8051 r.info.encryptionAware = r.info.directBootAware = true; 8052 } 8053 } 8054 } else { 8055 // Only allow system apps to be flagged as core apps. 8056 pkg.coreApp = false; 8057 // clear flags not applicable to regular apps 8058 pkg.applicationInfo.privateFlags &= 8059 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8060 pkg.applicationInfo.privateFlags &= 8061 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8062 } 8063 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8064 8065 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8066 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8067 } 8068 8069 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8070 enforceCodePolicy(pkg); 8071 } 8072 8073 if (mCustomResolverComponentName != null && 8074 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8075 setUpCustomResolverActivity(pkg); 8076 } 8077 8078 if (pkg.packageName.equals("android")) { 8079 synchronized (mPackages) { 8080 if (mAndroidApplication != null) { 8081 Slog.w(TAG, "*************************************************"); 8082 Slog.w(TAG, "Core android package being redefined. Skipping."); 8083 Slog.w(TAG, " file=" + scanFile); 8084 Slog.w(TAG, "*************************************************"); 8085 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8086 "Core android package being redefined. Skipping."); 8087 } 8088 8089 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8090 // Set up information for our fall-back user intent resolution activity. 8091 mPlatformPackage = pkg; 8092 pkg.mVersionCode = mSdkVersion; 8093 mAndroidApplication = pkg.applicationInfo; 8094 8095 if (!mResolverReplaced) { 8096 mResolveActivity.applicationInfo = mAndroidApplication; 8097 mResolveActivity.name = ResolverActivity.class.getName(); 8098 mResolveActivity.packageName = mAndroidApplication.packageName; 8099 mResolveActivity.processName = "system:ui"; 8100 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8101 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8102 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8103 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8104 mResolveActivity.exported = true; 8105 mResolveActivity.enabled = true; 8106 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8107 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8108 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8109 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8110 | ActivityInfo.CONFIG_ORIENTATION 8111 | ActivityInfo.CONFIG_KEYBOARD 8112 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8113 mResolveInfo.activityInfo = mResolveActivity; 8114 mResolveInfo.priority = 0; 8115 mResolveInfo.preferredOrder = 0; 8116 mResolveInfo.match = 0; 8117 mResolveComponentName = new ComponentName( 8118 mAndroidApplication.packageName, mResolveActivity.name); 8119 } 8120 } 8121 } 8122 } 8123 8124 if (DEBUG_PACKAGE_SCANNING) { 8125 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8126 Log.d(TAG, "Scanning package " + pkg.packageName); 8127 } 8128 8129 synchronized (mPackages) { 8130 if (mPackages.containsKey(pkg.packageName) 8131 || mSharedLibraries.containsKey(pkg.packageName)) { 8132 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8133 "Application package " + pkg.packageName 8134 + " already installed. Skipping duplicate."); 8135 } 8136 8137 // If we're only installing presumed-existing packages, require that the 8138 // scanned APK is both already known and at the path previously established 8139 // for it. Previously unknown packages we pick up normally, but if we have an 8140 // a priori expectation about this package's install presence, enforce it. 8141 // With a singular exception for new system packages. When an OTA contains 8142 // a new system package, we allow the codepath to change from a system location 8143 // to the user-installed location. If we don't allow this change, any newer, 8144 // user-installed version of the application will be ignored. 8145 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8146 if (mExpectingBetter.containsKey(pkg.packageName)) { 8147 logCriticalInfo(Log.WARN, 8148 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8149 } else { 8150 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8151 if (known != null) { 8152 if (DEBUG_PACKAGE_SCANNING) { 8153 Log.d(TAG, "Examining " + pkg.codePath 8154 + " and requiring known paths " + known.codePathString 8155 + " & " + known.resourcePathString); 8156 } 8157 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8158 || !pkg.applicationInfo.getResourcePath().equals( 8159 known.resourcePathString)) { 8160 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8161 "Application package " + pkg.packageName 8162 + " found at " + pkg.applicationInfo.getCodePath() 8163 + " but expected at " + known.codePathString 8164 + "; ignoring."); 8165 } 8166 } 8167 } 8168 } 8169 } 8170 8171 // Initialize package source and resource directories 8172 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8173 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8174 8175 SharedUserSetting suid = null; 8176 PackageSetting pkgSetting = null; 8177 8178 if (!isSystemApp(pkg)) { 8179 // Only system apps can use these features. 8180 pkg.mOriginalPackages = null; 8181 pkg.mRealPackage = null; 8182 pkg.mAdoptPermissions = null; 8183 } 8184 8185 // Getting the package setting may have a side-effect, so if we 8186 // are only checking if scan would succeed, stash a copy of the 8187 // old setting to restore at the end. 8188 PackageSetting nonMutatedPs = null; 8189 8190 // writer 8191 synchronized (mPackages) { 8192 if (pkg.mSharedUserId != null) { 8193 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8194 if (suid == null) { 8195 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8196 "Creating application package " + pkg.packageName 8197 + " for shared user failed"); 8198 } 8199 if (DEBUG_PACKAGE_SCANNING) { 8200 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8201 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8202 + "): packages=" + suid.packages); 8203 } 8204 } 8205 8206 // Check if we are renaming from an original package name. 8207 PackageSetting origPackage = null; 8208 String realName = null; 8209 if (pkg.mOriginalPackages != null) { 8210 // This package may need to be renamed to a previously 8211 // installed name. Let's check on that... 8212 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8213 if (pkg.mOriginalPackages.contains(renamed)) { 8214 // This package had originally been installed as the 8215 // original name, and we have already taken care of 8216 // transitioning to the new one. Just update the new 8217 // one to continue using the old name. 8218 realName = pkg.mRealPackage; 8219 if (!pkg.packageName.equals(renamed)) { 8220 // Callers into this function may have already taken 8221 // care of renaming the package; only do it here if 8222 // it is not already done. 8223 pkg.setPackageName(renamed); 8224 } 8225 8226 } else { 8227 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8228 if ((origPackage = mSettings.peekPackageLPr( 8229 pkg.mOriginalPackages.get(i))) != null) { 8230 // We do have the package already installed under its 8231 // original name... should we use it? 8232 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8233 // New package is not compatible with original. 8234 origPackage = null; 8235 continue; 8236 } else if (origPackage.sharedUser != null) { 8237 // Make sure uid is compatible between packages. 8238 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8239 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8240 + " to " + pkg.packageName + ": old uid " 8241 + origPackage.sharedUser.name 8242 + " differs from " + pkg.mSharedUserId); 8243 origPackage = null; 8244 continue; 8245 } 8246 // TODO: Add case when shared user id is added [b/28144775] 8247 } else { 8248 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8249 + pkg.packageName + " to old name " + origPackage.name); 8250 } 8251 break; 8252 } 8253 } 8254 } 8255 } 8256 8257 if (mTransferedPackages.contains(pkg.packageName)) { 8258 Slog.w(TAG, "Package " + pkg.packageName 8259 + " was transferred to another, but its .apk remains"); 8260 } 8261 8262 // See comments in nonMutatedPs declaration 8263 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8264 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8265 if (foundPs != null) { 8266 nonMutatedPs = new PackageSetting(foundPs); 8267 } 8268 } 8269 8270 // Just create the setting, don't add it yet. For already existing packages 8271 // the PkgSetting exists already and doesn't have to be created. 8272 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8273 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8274 pkg.applicationInfo.primaryCpuAbi, 8275 pkg.applicationInfo.secondaryCpuAbi, 8276 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8277 user, false); 8278 if (pkgSetting == null) { 8279 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8280 "Creating application package " + pkg.packageName + " failed"); 8281 } 8282 8283 if (pkgSetting.origPackage != null) { 8284 // If we are first transitioning from an original package, 8285 // fix up the new package's name now. We need to do this after 8286 // looking up the package under its new name, so getPackageLP 8287 // can take care of fiddling things correctly. 8288 pkg.setPackageName(origPackage.name); 8289 8290 // File a report about this. 8291 String msg = "New package " + pkgSetting.realName 8292 + " renamed to replace old package " + pkgSetting.name; 8293 reportSettingsProblem(Log.WARN, msg); 8294 8295 // Make a note of it. 8296 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8297 mTransferedPackages.add(origPackage.name); 8298 } 8299 8300 // No longer need to retain this. 8301 pkgSetting.origPackage = null; 8302 } 8303 8304 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8305 // Make a note of it. 8306 mTransferedPackages.add(pkg.packageName); 8307 } 8308 8309 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8310 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8311 } 8312 8313 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8314 // Check all shared libraries and map to their actual file path. 8315 // We only do this here for apps not on a system dir, because those 8316 // are the only ones that can fail an install due to this. We 8317 // will take care of the system apps by updating all of their 8318 // library paths after the scan is done. 8319 updateSharedLibrariesLPw(pkg, null); 8320 } 8321 8322 if (mFoundPolicyFile) { 8323 SELinuxMMAC.assignSeinfoValue(pkg); 8324 } 8325 8326 pkg.applicationInfo.uid = pkgSetting.appId; 8327 pkg.mExtras = pkgSetting; 8328 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8329 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8330 // We just determined the app is signed correctly, so bring 8331 // over the latest parsed certs. 8332 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8333 } else { 8334 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8335 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8336 "Package " + pkg.packageName + " upgrade keys do not match the " 8337 + "previously installed version"); 8338 } else { 8339 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8340 String msg = "System package " + pkg.packageName 8341 + " signature changed; retaining data."; 8342 reportSettingsProblem(Log.WARN, msg); 8343 } 8344 } 8345 } else { 8346 try { 8347 verifySignaturesLP(pkgSetting, pkg); 8348 // We just determined the app is signed correctly, so bring 8349 // over the latest parsed certs. 8350 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8351 } catch (PackageManagerException e) { 8352 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8353 throw e; 8354 } 8355 // The signature has changed, but this package is in the system 8356 // image... let's recover! 8357 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8358 // However... if this package is part of a shared user, but it 8359 // doesn't match the signature of the shared user, let's fail. 8360 // What this means is that you can't change the signatures 8361 // associated with an overall shared user, which doesn't seem all 8362 // that unreasonable. 8363 if (pkgSetting.sharedUser != null) { 8364 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8365 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8366 throw new PackageManagerException( 8367 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8368 "Signature mismatch for shared user: " 8369 + pkgSetting.sharedUser); 8370 } 8371 } 8372 // File a report about this. 8373 String msg = "System package " + pkg.packageName 8374 + " signature changed; retaining data."; 8375 reportSettingsProblem(Log.WARN, msg); 8376 } 8377 } 8378 // Verify that this new package doesn't have any content providers 8379 // that conflict with existing packages. Only do this if the 8380 // package isn't already installed, since we don't want to break 8381 // things that are installed. 8382 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8383 final int N = pkg.providers.size(); 8384 int i; 8385 for (i=0; i<N; i++) { 8386 PackageParser.Provider p = pkg.providers.get(i); 8387 if (p.info.authority != null) { 8388 String names[] = p.info.authority.split(";"); 8389 for (int j = 0; j < names.length; j++) { 8390 if (mProvidersByAuthority.containsKey(names[j])) { 8391 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8392 final String otherPackageName = 8393 ((other != null && other.getComponentName() != null) ? 8394 other.getComponentName().getPackageName() : "?"); 8395 throw new PackageManagerException( 8396 INSTALL_FAILED_CONFLICTING_PROVIDER, 8397 "Can't install because provider name " + names[j] 8398 + " (in package " + pkg.applicationInfo.packageName 8399 + ") is already used by " + otherPackageName); 8400 } 8401 } 8402 } 8403 } 8404 } 8405 8406 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8407 // This package wants to adopt ownership of permissions from 8408 // another package. 8409 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8410 final String origName = pkg.mAdoptPermissions.get(i); 8411 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8412 if (orig != null) { 8413 if (verifyPackageUpdateLPr(orig, pkg)) { 8414 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8415 + pkg.packageName); 8416 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8417 } 8418 } 8419 } 8420 } 8421 } 8422 8423 final String pkgName = pkg.packageName; 8424 8425 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8426 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8427 pkg.applicationInfo.processName = fixProcessName( 8428 pkg.applicationInfo.packageName, 8429 pkg.applicationInfo.processName, 8430 pkg.applicationInfo.uid); 8431 8432 if (pkg != mPlatformPackage) { 8433 // Get all of our default paths setup 8434 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8435 } 8436 8437 final String path = scanFile.getPath(); 8438 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8439 8440 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8441 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8442 8443 // Some system apps still use directory structure for native libraries 8444 // in which case we might end up not detecting abi solely based on apk 8445 // structure. Try to detect abi based on directory structure. 8446 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8447 pkg.applicationInfo.primaryCpuAbi == null) { 8448 setBundledAppAbisAndRoots(pkg, pkgSetting); 8449 setNativeLibraryPaths(pkg); 8450 } 8451 8452 } else { 8453 if ((scanFlags & SCAN_MOVE) != 0) { 8454 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8455 // but we already have this packages package info in the PackageSetting. We just 8456 // use that and derive the native library path based on the new codepath. 8457 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8458 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8459 } 8460 8461 // Set native library paths again. For moves, the path will be updated based on the 8462 // ABIs we've determined above. For non-moves, the path will be updated based on the 8463 // ABIs we determined during compilation, but the path will depend on the final 8464 // package path (after the rename away from the stage path). 8465 setNativeLibraryPaths(pkg); 8466 } 8467 8468 // This is a special case for the "system" package, where the ABI is 8469 // dictated by the zygote configuration (and init.rc). We should keep track 8470 // of this ABI so that we can deal with "normal" applications that run under 8471 // the same UID correctly. 8472 if (mPlatformPackage == pkg) { 8473 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8474 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8475 } 8476 8477 // If there's a mismatch between the abi-override in the package setting 8478 // and the abiOverride specified for the install. Warn about this because we 8479 // would've already compiled the app without taking the package setting into 8480 // account. 8481 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8482 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8483 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8484 " for package " + pkg.packageName); 8485 } 8486 } 8487 8488 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8489 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8490 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8491 8492 // Copy the derived override back to the parsed package, so that we can 8493 // update the package settings accordingly. 8494 pkg.cpuAbiOverride = cpuAbiOverride; 8495 8496 if (DEBUG_ABI_SELECTION) { 8497 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8498 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8499 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8500 } 8501 8502 // Push the derived path down into PackageSettings so we know what to 8503 // clean up at uninstall time. 8504 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8505 8506 if (DEBUG_ABI_SELECTION) { 8507 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8508 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8509 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8510 } 8511 8512 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8513 // We don't do this here during boot because we can do it all 8514 // at once after scanning all existing packages. 8515 // 8516 // We also do this *before* we perform dexopt on this package, so that 8517 // we can avoid redundant dexopts, and also to make sure we've got the 8518 // code and package path correct. 8519 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8520 pkg, true /* boot complete */); 8521 } 8522 8523 if (mFactoryTest && pkg.requestedPermissions.contains( 8524 android.Manifest.permission.FACTORY_TEST)) { 8525 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8526 } 8527 8528 if (isSystemApp(pkg)) { 8529 pkgSetting.isOrphaned = true; 8530 } 8531 8532 ArrayList<PackageParser.Package> clientLibPkgs = null; 8533 8534 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8535 if (nonMutatedPs != null) { 8536 synchronized (mPackages) { 8537 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8538 } 8539 } 8540 return pkg; 8541 } 8542 8543 // Only privileged apps and updated privileged apps can add child packages. 8544 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8545 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8546 throw new PackageManagerException("Only privileged apps and updated " 8547 + "privileged apps can add child packages. Ignoring package " 8548 + pkg.packageName); 8549 } 8550 final int childCount = pkg.childPackages.size(); 8551 for (int i = 0; i < childCount; i++) { 8552 PackageParser.Package childPkg = pkg.childPackages.get(i); 8553 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8554 childPkg.packageName)) { 8555 throw new PackageManagerException("Cannot override a child package of " 8556 + "another disabled system app. Ignoring package " + pkg.packageName); 8557 } 8558 } 8559 } 8560 8561 // writer 8562 synchronized (mPackages) { 8563 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8564 // Only system apps can add new shared libraries. 8565 if (pkg.libraryNames != null) { 8566 for (int i=0; i<pkg.libraryNames.size(); i++) { 8567 String name = pkg.libraryNames.get(i); 8568 boolean allowed = false; 8569 if (pkg.isUpdatedSystemApp()) { 8570 // New library entries can only be added through the 8571 // system image. This is important to get rid of a lot 8572 // of nasty edge cases: for example if we allowed a non- 8573 // system update of the app to add a library, then uninstalling 8574 // the update would make the library go away, and assumptions 8575 // we made such as through app install filtering would now 8576 // have allowed apps on the device which aren't compatible 8577 // with it. Better to just have the restriction here, be 8578 // conservative, and create many fewer cases that can negatively 8579 // impact the user experience. 8580 final PackageSetting sysPs = mSettings 8581 .getDisabledSystemPkgLPr(pkg.packageName); 8582 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8583 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8584 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8585 allowed = true; 8586 break; 8587 } 8588 } 8589 } 8590 } else { 8591 allowed = true; 8592 } 8593 if (allowed) { 8594 if (!mSharedLibraries.containsKey(name)) { 8595 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8596 } else if (!name.equals(pkg.packageName)) { 8597 Slog.w(TAG, "Package " + pkg.packageName + " library " 8598 + name + " already exists; skipping"); 8599 } 8600 } else { 8601 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8602 + name + " that is not declared on system image; skipping"); 8603 } 8604 } 8605 if ((scanFlags & SCAN_BOOTING) == 0) { 8606 // If we are not booting, we need to update any applications 8607 // that are clients of our shared library. If we are booting, 8608 // this will all be done once the scan is complete. 8609 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8610 } 8611 } 8612 } 8613 } 8614 8615 if ((scanFlags & SCAN_BOOTING) != 0) { 8616 // No apps can run during boot scan, so they don't need to be frozen 8617 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8618 // Caller asked to not kill app, so it's probably not frozen 8619 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8620 // Caller asked us to ignore frozen check for some reason; they 8621 // probably didn't know the package name 8622 } else { 8623 // We're doing major surgery on this package, so it better be frozen 8624 // right now to keep it from launching 8625 checkPackageFrozen(pkgName); 8626 } 8627 8628 // Also need to kill any apps that are dependent on the library. 8629 if (clientLibPkgs != null) { 8630 for (int i=0; i<clientLibPkgs.size(); i++) { 8631 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8632 killApplication(clientPkg.applicationInfo.packageName, 8633 clientPkg.applicationInfo.uid, "update lib"); 8634 } 8635 } 8636 8637 // Make sure we're not adding any bogus keyset info 8638 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8639 ksms.assertScannedPackageValid(pkg); 8640 8641 // writer 8642 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8643 8644 boolean createIdmapFailed = false; 8645 synchronized (mPackages) { 8646 // We don't expect installation to fail beyond this point 8647 8648 if (pkgSetting.pkg != null) { 8649 // Note that |user| might be null during the initial boot scan. If a codePath 8650 // for an app has changed during a boot scan, it's due to an app update that's 8651 // part of the system partition and marker changes must be applied to all users. 8652 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8653 (user != null) ? user : UserHandle.ALL); 8654 } 8655 8656 // Add the new setting to mSettings 8657 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8658 // Add the new setting to mPackages 8659 mPackages.put(pkg.applicationInfo.packageName, pkg); 8660 // Make sure we don't accidentally delete its data. 8661 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8662 while (iter.hasNext()) { 8663 PackageCleanItem item = iter.next(); 8664 if (pkgName.equals(item.packageName)) { 8665 iter.remove(); 8666 } 8667 } 8668 8669 // Take care of first install / last update times. 8670 if (currentTime != 0) { 8671 if (pkgSetting.firstInstallTime == 0) { 8672 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8673 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8674 pkgSetting.lastUpdateTime = currentTime; 8675 } 8676 } else if (pkgSetting.firstInstallTime == 0) { 8677 // We need *something*. Take time time stamp of the file. 8678 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8679 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8680 if (scanFileTime != pkgSetting.timeStamp) { 8681 // A package on the system image has changed; consider this 8682 // to be an update. 8683 pkgSetting.lastUpdateTime = scanFileTime; 8684 } 8685 } 8686 8687 // Add the package's KeySets to the global KeySetManagerService 8688 ksms.addScannedPackageLPw(pkg); 8689 8690 int N = pkg.providers.size(); 8691 StringBuilder r = null; 8692 int i; 8693 for (i=0; i<N; i++) { 8694 PackageParser.Provider p = pkg.providers.get(i); 8695 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8696 p.info.processName, pkg.applicationInfo.uid); 8697 mProviders.addProvider(p); 8698 p.syncable = p.info.isSyncable; 8699 if (p.info.authority != null) { 8700 String names[] = p.info.authority.split(";"); 8701 p.info.authority = null; 8702 for (int j = 0; j < names.length; j++) { 8703 if (j == 1 && p.syncable) { 8704 // We only want the first authority for a provider to possibly be 8705 // syncable, so if we already added this provider using a different 8706 // authority clear the syncable flag. We copy the provider before 8707 // changing it because the mProviders object contains a reference 8708 // to a provider that we don't want to change. 8709 // Only do this for the second authority since the resulting provider 8710 // object can be the same for all future authorities for this provider. 8711 p = new PackageParser.Provider(p); 8712 p.syncable = false; 8713 } 8714 if (!mProvidersByAuthority.containsKey(names[j])) { 8715 mProvidersByAuthority.put(names[j], p); 8716 if (p.info.authority == null) { 8717 p.info.authority = names[j]; 8718 } else { 8719 p.info.authority = p.info.authority + ";" + names[j]; 8720 } 8721 if (DEBUG_PACKAGE_SCANNING) { 8722 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8723 Log.d(TAG, "Registered content provider: " + names[j] 8724 + ", className = " + p.info.name + ", isSyncable = " 8725 + p.info.isSyncable); 8726 } 8727 } else { 8728 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8729 Slog.w(TAG, "Skipping provider name " + names[j] + 8730 " (in package " + pkg.applicationInfo.packageName + 8731 "): name already used by " 8732 + ((other != null && other.getComponentName() != null) 8733 ? other.getComponentName().getPackageName() : "?")); 8734 } 8735 } 8736 } 8737 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8738 if (r == null) { 8739 r = new StringBuilder(256); 8740 } else { 8741 r.append(' '); 8742 } 8743 r.append(p.info.name); 8744 } 8745 } 8746 if (r != null) { 8747 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8748 } 8749 8750 N = pkg.services.size(); 8751 r = null; 8752 for (i=0; i<N; i++) { 8753 PackageParser.Service s = pkg.services.get(i); 8754 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8755 s.info.processName, pkg.applicationInfo.uid); 8756 mServices.addService(s); 8757 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8758 if (r == null) { 8759 r = new StringBuilder(256); 8760 } else { 8761 r.append(' '); 8762 } 8763 r.append(s.info.name); 8764 } 8765 } 8766 if (r != null) { 8767 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8768 } 8769 8770 N = pkg.receivers.size(); 8771 r = null; 8772 for (i=0; i<N; i++) { 8773 PackageParser.Activity a = pkg.receivers.get(i); 8774 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8775 a.info.processName, pkg.applicationInfo.uid); 8776 mReceivers.addActivity(a, "receiver"); 8777 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8778 if (r == null) { 8779 r = new StringBuilder(256); 8780 } else { 8781 r.append(' '); 8782 } 8783 r.append(a.info.name); 8784 } 8785 } 8786 if (r != null) { 8787 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8788 } 8789 8790 N = pkg.activities.size(); 8791 r = null; 8792 for (i=0; i<N; i++) { 8793 PackageParser.Activity a = pkg.activities.get(i); 8794 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8795 a.info.processName, pkg.applicationInfo.uid); 8796 mActivities.addActivity(a, "activity"); 8797 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8798 if (r == null) { 8799 r = new StringBuilder(256); 8800 } else { 8801 r.append(' '); 8802 } 8803 r.append(a.info.name); 8804 } 8805 } 8806 if (r != null) { 8807 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8808 } 8809 8810 N = pkg.permissionGroups.size(); 8811 r = null; 8812 for (i=0; i<N; i++) { 8813 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8814 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8815 final String curPackageName = cur == null ? null : cur.info.packageName; 8816 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8817 if (cur == null || isPackageUpdate) { 8818 mPermissionGroups.put(pg.info.name, pg); 8819 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8820 if (r == null) { 8821 r = new StringBuilder(256); 8822 } else { 8823 r.append(' '); 8824 } 8825 if (isPackageUpdate) { 8826 r.append("UPD:"); 8827 } 8828 r.append(pg.info.name); 8829 } 8830 } else { 8831 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8832 + pg.info.packageName + " ignored: original from " 8833 + cur.info.packageName); 8834 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8835 if (r == null) { 8836 r = new StringBuilder(256); 8837 } else { 8838 r.append(' '); 8839 } 8840 r.append("DUP:"); 8841 r.append(pg.info.name); 8842 } 8843 } 8844 } 8845 if (r != null) { 8846 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8847 } 8848 8849 N = pkg.permissions.size(); 8850 r = null; 8851 for (i=0; i<N; i++) { 8852 PackageParser.Permission p = pkg.permissions.get(i); 8853 8854 // Assume by default that we did not install this permission into the system. 8855 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8856 8857 // Now that permission groups have a special meaning, we ignore permission 8858 // groups for legacy apps to prevent unexpected behavior. In particular, 8859 // permissions for one app being granted to someone just becase they happen 8860 // to be in a group defined by another app (before this had no implications). 8861 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8862 p.group = mPermissionGroups.get(p.info.group); 8863 // Warn for a permission in an unknown group. 8864 if (p.info.group != null && p.group == null) { 8865 Slog.w(TAG, "Permission " + p.info.name + " from package " 8866 + p.info.packageName + " in an unknown group " + p.info.group); 8867 } 8868 } 8869 8870 ArrayMap<String, BasePermission> permissionMap = 8871 p.tree ? mSettings.mPermissionTrees 8872 : mSettings.mPermissions; 8873 BasePermission bp = permissionMap.get(p.info.name); 8874 8875 // Allow system apps to redefine non-system permissions 8876 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8877 final boolean currentOwnerIsSystem = (bp.perm != null 8878 && isSystemApp(bp.perm.owner)); 8879 if (isSystemApp(p.owner)) { 8880 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8881 // It's a built-in permission and no owner, take ownership now 8882 bp.packageSetting = pkgSetting; 8883 bp.perm = p; 8884 bp.uid = pkg.applicationInfo.uid; 8885 bp.sourcePackage = p.info.packageName; 8886 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8887 } else if (!currentOwnerIsSystem) { 8888 String msg = "New decl " + p.owner + " of permission " 8889 + p.info.name + " is system; overriding " + bp.sourcePackage; 8890 reportSettingsProblem(Log.WARN, msg); 8891 bp = null; 8892 } 8893 } 8894 } 8895 8896 if (bp == null) { 8897 bp = new BasePermission(p.info.name, p.info.packageName, 8898 BasePermission.TYPE_NORMAL); 8899 permissionMap.put(p.info.name, bp); 8900 } 8901 8902 if (bp.perm == null) { 8903 if (bp.sourcePackage == null 8904 || bp.sourcePackage.equals(p.info.packageName)) { 8905 BasePermission tree = findPermissionTreeLP(p.info.name); 8906 if (tree == null 8907 || tree.sourcePackage.equals(p.info.packageName)) { 8908 bp.packageSetting = pkgSetting; 8909 bp.perm = p; 8910 bp.uid = pkg.applicationInfo.uid; 8911 bp.sourcePackage = p.info.packageName; 8912 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8913 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8914 if (r == null) { 8915 r = new StringBuilder(256); 8916 } else { 8917 r.append(' '); 8918 } 8919 r.append(p.info.name); 8920 } 8921 } else { 8922 Slog.w(TAG, "Permission " + p.info.name + " from package " 8923 + p.info.packageName + " ignored: base tree " 8924 + tree.name + " is from package " 8925 + tree.sourcePackage); 8926 } 8927 } else { 8928 Slog.w(TAG, "Permission " + p.info.name + " from package " 8929 + p.info.packageName + " ignored: original from " 8930 + bp.sourcePackage); 8931 } 8932 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8933 if (r == null) { 8934 r = new StringBuilder(256); 8935 } else { 8936 r.append(' '); 8937 } 8938 r.append("DUP:"); 8939 r.append(p.info.name); 8940 } 8941 if (bp.perm == p) { 8942 bp.protectionLevel = p.info.protectionLevel; 8943 } 8944 } 8945 8946 if (r != null) { 8947 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8948 } 8949 8950 N = pkg.instrumentation.size(); 8951 r = null; 8952 for (i=0; i<N; i++) { 8953 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8954 a.info.packageName = pkg.applicationInfo.packageName; 8955 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8956 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8957 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8958 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8959 a.info.dataDir = pkg.applicationInfo.dataDir; 8960 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8961 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8962 8963 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8964 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8965 mInstrumentation.put(a.getComponentName(), a); 8966 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8967 if (r == null) { 8968 r = new StringBuilder(256); 8969 } else { 8970 r.append(' '); 8971 } 8972 r.append(a.info.name); 8973 } 8974 } 8975 if (r != null) { 8976 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8977 } 8978 8979 if (pkg.protectedBroadcasts != null) { 8980 N = pkg.protectedBroadcasts.size(); 8981 for (i=0; i<N; i++) { 8982 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8983 } 8984 } 8985 8986 pkgSetting.setTimeStamp(scanFileTime); 8987 8988 // Create idmap files for pairs of (packages, overlay packages). 8989 // Note: "android", ie framework-res.apk, is handled by native layers. 8990 if (pkg.mOverlayTarget != null) { 8991 // This is an overlay package. 8992 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8993 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8994 mOverlays.put(pkg.mOverlayTarget, 8995 new ArrayMap<String, PackageParser.Package>()); 8996 } 8997 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8998 map.put(pkg.packageName, pkg); 8999 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9000 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9001 createIdmapFailed = true; 9002 } 9003 } 9004 } else if (mOverlays.containsKey(pkg.packageName) && 9005 !pkg.packageName.equals("android")) { 9006 // This is a regular package, with one or more known overlay packages. 9007 createIdmapsForPackageLI(pkg); 9008 } 9009 } 9010 9011 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9012 9013 if (createIdmapFailed) { 9014 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9015 "scanPackageLI failed to createIdmap"); 9016 } 9017 return pkg; 9018 } 9019 9020 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9021 PackageParser.Package update, UserHandle user) { 9022 if (existing.applicationInfo == null || update.applicationInfo == null) { 9023 // This isn't due to an app installation. 9024 return; 9025 } 9026 9027 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9028 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9029 9030 // The codePath hasn't changed, so there's nothing for us to do. 9031 if (Objects.equals(oldCodePath, newCodePath)) { 9032 return; 9033 } 9034 9035 File canonicalNewCodePath; 9036 try { 9037 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9038 } catch (IOException e) { 9039 Slog.w(TAG, "Failed to get canonical path.", e); 9040 return; 9041 } 9042 9043 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9044 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9045 // that the last component of the path (i.e, the name) doesn't need canonicalization 9046 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9047 // but may change in the future. Hopefully this function won't exist at that point. 9048 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9049 oldCodePath.getName()); 9050 9051 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9052 // with "@". 9053 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9054 if (!oldMarkerPrefix.endsWith("@")) { 9055 oldMarkerPrefix += "@"; 9056 } 9057 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9058 if (!newMarkerPrefix.endsWith("@")) { 9059 newMarkerPrefix += "@"; 9060 } 9061 9062 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9063 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9064 for (String updatedPath : updatedPaths) { 9065 String updatedPathName = new File(updatedPath).getName(); 9066 markerSuffixes.add(updatedPathName.replace('/', '@')); 9067 } 9068 9069 for (int userId : resolveUserIds(user.getIdentifier())) { 9070 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9071 9072 for (String markerSuffix : markerSuffixes) { 9073 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9074 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9075 if (oldForeignUseMark.exists()) { 9076 try { 9077 Os.rename(oldForeignUseMark.getAbsolutePath(), 9078 newForeignUseMark.getAbsolutePath()); 9079 } catch (ErrnoException e) { 9080 Slog.w(TAG, "Failed to rename foreign use marker", e); 9081 oldForeignUseMark.delete(); 9082 } 9083 } 9084 } 9085 } 9086 } 9087 9088 /** 9089 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9090 * is derived purely on the basis of the contents of {@code scanFile} and 9091 * {@code cpuAbiOverride}. 9092 * 9093 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9094 */ 9095 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9096 String cpuAbiOverride, boolean extractLibs) 9097 throws PackageManagerException { 9098 // TODO: We can probably be smarter about this stuff. For installed apps, 9099 // we can calculate this information at install time once and for all. For 9100 // system apps, we can probably assume that this information doesn't change 9101 // after the first boot scan. As things stand, we do lots of unnecessary work. 9102 9103 // Give ourselves some initial paths; we'll come back for another 9104 // pass once we've determined ABI below. 9105 setNativeLibraryPaths(pkg); 9106 9107 // We would never need to extract libs for forward-locked and external packages, 9108 // since the container service will do it for us. We shouldn't attempt to 9109 // extract libs from system app when it was not updated. 9110 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9111 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9112 extractLibs = false; 9113 } 9114 9115 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9116 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9117 9118 NativeLibraryHelper.Handle handle = null; 9119 try { 9120 handle = NativeLibraryHelper.Handle.create(pkg); 9121 // TODO(multiArch): This can be null for apps that didn't go through the 9122 // usual installation process. We can calculate it again, like we 9123 // do during install time. 9124 // 9125 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9126 // unnecessary. 9127 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9128 9129 // Null out the abis so that they can be recalculated. 9130 pkg.applicationInfo.primaryCpuAbi = null; 9131 pkg.applicationInfo.secondaryCpuAbi = null; 9132 if (isMultiArch(pkg.applicationInfo)) { 9133 // Warn if we've set an abiOverride for multi-lib packages.. 9134 // By definition, we need to copy both 32 and 64 bit libraries for 9135 // such packages. 9136 if (pkg.cpuAbiOverride != null 9137 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9138 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9139 } 9140 9141 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9142 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9143 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9144 if (extractLibs) { 9145 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9146 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9147 useIsaSpecificSubdirs); 9148 } else { 9149 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9150 } 9151 } 9152 9153 maybeThrowExceptionForMultiArchCopy( 9154 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9155 9156 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9157 if (extractLibs) { 9158 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9159 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9160 useIsaSpecificSubdirs); 9161 } else { 9162 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9163 } 9164 } 9165 9166 maybeThrowExceptionForMultiArchCopy( 9167 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9168 9169 if (abi64 >= 0) { 9170 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9171 } 9172 9173 if (abi32 >= 0) { 9174 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9175 if (abi64 >= 0) { 9176 if (pkg.use32bitAbi) { 9177 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9178 pkg.applicationInfo.primaryCpuAbi = abi; 9179 } else { 9180 pkg.applicationInfo.secondaryCpuAbi = abi; 9181 } 9182 } else { 9183 pkg.applicationInfo.primaryCpuAbi = abi; 9184 } 9185 } 9186 9187 } else { 9188 String[] abiList = (cpuAbiOverride != null) ? 9189 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9190 9191 // Enable gross and lame hacks for apps that are built with old 9192 // SDK tools. We must scan their APKs for renderscript bitcode and 9193 // not launch them if it's present. Don't bother checking on devices 9194 // that don't have 64 bit support. 9195 boolean needsRenderScriptOverride = false; 9196 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9197 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9198 abiList = Build.SUPPORTED_32_BIT_ABIS; 9199 needsRenderScriptOverride = true; 9200 } 9201 9202 final int copyRet; 9203 if (extractLibs) { 9204 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9205 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9206 } else { 9207 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9208 } 9209 9210 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9211 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9212 "Error unpackaging native libs for app, errorCode=" + copyRet); 9213 } 9214 9215 if (copyRet >= 0) { 9216 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9217 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9218 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9219 } else if (needsRenderScriptOverride) { 9220 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9221 } 9222 } 9223 } catch (IOException ioe) { 9224 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9225 } finally { 9226 IoUtils.closeQuietly(handle); 9227 } 9228 9229 // Now that we've calculated the ABIs and determined if it's an internal app, 9230 // we will go ahead and populate the nativeLibraryPath. 9231 setNativeLibraryPaths(pkg); 9232 } 9233 9234 /** 9235 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9236 * i.e, so that all packages can be run inside a single process if required. 9237 * 9238 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9239 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9240 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9241 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9242 * updating a package that belongs to a shared user. 9243 * 9244 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9245 * adds unnecessary complexity. 9246 */ 9247 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9248 PackageParser.Package scannedPackage, boolean bootComplete) { 9249 String requiredInstructionSet = null; 9250 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9251 requiredInstructionSet = VMRuntime.getInstructionSet( 9252 scannedPackage.applicationInfo.primaryCpuAbi); 9253 } 9254 9255 PackageSetting requirer = null; 9256 for (PackageSetting ps : packagesForUser) { 9257 // If packagesForUser contains scannedPackage, we skip it. This will happen 9258 // when scannedPackage is an update of an existing package. Without this check, 9259 // we will never be able to change the ABI of any package belonging to a shared 9260 // user, even if it's compatible with other packages. 9261 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9262 if (ps.primaryCpuAbiString == null) { 9263 continue; 9264 } 9265 9266 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9267 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9268 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9269 // this but there's not much we can do. 9270 String errorMessage = "Instruction set mismatch, " 9271 + ((requirer == null) ? "[caller]" : requirer) 9272 + " requires " + requiredInstructionSet + " whereas " + ps 9273 + " requires " + instructionSet; 9274 Slog.w(TAG, errorMessage); 9275 } 9276 9277 if (requiredInstructionSet == null) { 9278 requiredInstructionSet = instructionSet; 9279 requirer = ps; 9280 } 9281 } 9282 } 9283 9284 if (requiredInstructionSet != null) { 9285 String adjustedAbi; 9286 if (requirer != null) { 9287 // requirer != null implies that either scannedPackage was null or that scannedPackage 9288 // did not require an ABI, in which case we have to adjust scannedPackage to match 9289 // the ABI of the set (which is the same as requirer's ABI) 9290 adjustedAbi = requirer.primaryCpuAbiString; 9291 if (scannedPackage != null) { 9292 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9293 } 9294 } else { 9295 // requirer == null implies that we're updating all ABIs in the set to 9296 // match scannedPackage. 9297 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9298 } 9299 9300 for (PackageSetting ps : packagesForUser) { 9301 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9302 if (ps.primaryCpuAbiString != null) { 9303 continue; 9304 } 9305 9306 ps.primaryCpuAbiString = adjustedAbi; 9307 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9308 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9309 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9310 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9311 + " (requirer=" 9312 + (requirer == null ? "null" : requirer.pkg.packageName) 9313 + ", scannedPackage=" 9314 + (scannedPackage != null ? scannedPackage.packageName : "null") 9315 + ")"); 9316 try { 9317 mInstaller.rmdex(ps.codePathString, 9318 getDexCodeInstructionSet(getPreferredInstructionSet())); 9319 } catch (InstallerException ignored) { 9320 } 9321 } 9322 } 9323 } 9324 } 9325 } 9326 9327 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9328 synchronized (mPackages) { 9329 mResolverReplaced = true; 9330 // Set up information for custom user intent resolution activity. 9331 mResolveActivity.applicationInfo = pkg.applicationInfo; 9332 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9333 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9334 mResolveActivity.processName = pkg.applicationInfo.packageName; 9335 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9336 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9337 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9338 mResolveActivity.theme = 0; 9339 mResolveActivity.exported = true; 9340 mResolveActivity.enabled = true; 9341 mResolveInfo.activityInfo = mResolveActivity; 9342 mResolveInfo.priority = 0; 9343 mResolveInfo.preferredOrder = 0; 9344 mResolveInfo.match = 0; 9345 mResolveComponentName = mCustomResolverComponentName; 9346 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9347 mResolveComponentName); 9348 } 9349 } 9350 9351 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9352 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9353 9354 // Set up information for ephemeral installer activity 9355 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9356 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9357 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9358 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9359 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9360 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9361 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9362 mEphemeralInstallerActivity.theme = 0; 9363 mEphemeralInstallerActivity.exported = true; 9364 mEphemeralInstallerActivity.enabled = true; 9365 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9366 mEphemeralInstallerInfo.priority = 0; 9367 mEphemeralInstallerInfo.preferredOrder = 1; 9368 mEphemeralInstallerInfo.isDefault = true; 9369 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9370 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9371 9372 if (DEBUG_EPHEMERAL) { 9373 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9374 } 9375 } 9376 9377 private static String calculateBundledApkRoot(final String codePathString) { 9378 final File codePath = new File(codePathString); 9379 final File codeRoot; 9380 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9381 codeRoot = Environment.getRootDirectory(); 9382 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9383 codeRoot = Environment.getOemDirectory(); 9384 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9385 codeRoot = Environment.getVendorDirectory(); 9386 } else { 9387 // Unrecognized code path; take its top real segment as the apk root: 9388 // e.g. /something/app/blah.apk => /something 9389 try { 9390 File f = codePath.getCanonicalFile(); 9391 File parent = f.getParentFile(); // non-null because codePath is a file 9392 File tmp; 9393 while ((tmp = parent.getParentFile()) != null) { 9394 f = parent; 9395 parent = tmp; 9396 } 9397 codeRoot = f; 9398 Slog.w(TAG, "Unrecognized code path " 9399 + codePath + " - using " + codeRoot); 9400 } catch (IOException e) { 9401 // Can't canonicalize the code path -- shenanigans? 9402 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9403 return Environment.getRootDirectory().getPath(); 9404 } 9405 } 9406 return codeRoot.getPath(); 9407 } 9408 9409 /** 9410 * Derive and set the location of native libraries for the given package, 9411 * which varies depending on where and how the package was installed. 9412 */ 9413 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9414 final ApplicationInfo info = pkg.applicationInfo; 9415 final String codePath = pkg.codePath; 9416 final File codeFile = new File(codePath); 9417 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9418 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9419 9420 info.nativeLibraryRootDir = null; 9421 info.nativeLibraryRootRequiresIsa = false; 9422 info.nativeLibraryDir = null; 9423 info.secondaryNativeLibraryDir = null; 9424 9425 if (isApkFile(codeFile)) { 9426 // Monolithic install 9427 if (bundledApp) { 9428 // If "/system/lib64/apkname" exists, assume that is the per-package 9429 // native library directory to use; otherwise use "/system/lib/apkname". 9430 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9431 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9432 getPrimaryInstructionSet(info)); 9433 9434 // This is a bundled system app so choose the path based on the ABI. 9435 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9436 // is just the default path. 9437 final String apkName = deriveCodePathName(codePath); 9438 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9439 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9440 apkName).getAbsolutePath(); 9441 9442 if (info.secondaryCpuAbi != null) { 9443 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9444 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9445 secondaryLibDir, apkName).getAbsolutePath(); 9446 } 9447 } else if (asecApp) { 9448 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9449 .getAbsolutePath(); 9450 } else { 9451 final String apkName = deriveCodePathName(codePath); 9452 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9453 .getAbsolutePath(); 9454 } 9455 9456 info.nativeLibraryRootRequiresIsa = false; 9457 info.nativeLibraryDir = info.nativeLibraryRootDir; 9458 } else { 9459 // Cluster install 9460 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9461 info.nativeLibraryRootRequiresIsa = true; 9462 9463 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9464 getPrimaryInstructionSet(info)).getAbsolutePath(); 9465 9466 if (info.secondaryCpuAbi != null) { 9467 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9468 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9469 } 9470 } 9471 } 9472 9473 /** 9474 * Calculate the abis and roots for a bundled app. These can uniquely 9475 * be determined from the contents of the system partition, i.e whether 9476 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9477 * of this information, and instead assume that the system was built 9478 * sensibly. 9479 */ 9480 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9481 PackageSetting pkgSetting) { 9482 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9483 9484 // If "/system/lib64/apkname" exists, assume that is the per-package 9485 // native library directory to use; otherwise use "/system/lib/apkname". 9486 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9487 setBundledAppAbi(pkg, apkRoot, apkName); 9488 // pkgSetting might be null during rescan following uninstall of updates 9489 // to a bundled app, so accommodate that possibility. The settings in 9490 // that case will be established later from the parsed package. 9491 // 9492 // If the settings aren't null, sync them up with what we've just derived. 9493 // note that apkRoot isn't stored in the package settings. 9494 if (pkgSetting != null) { 9495 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9496 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9497 } 9498 } 9499 9500 /** 9501 * Deduces the ABI of a bundled app and sets the relevant fields on the 9502 * parsed pkg object. 9503 * 9504 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9505 * under which system libraries are installed. 9506 * @param apkName the name of the installed package. 9507 */ 9508 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9509 final File codeFile = new File(pkg.codePath); 9510 9511 final boolean has64BitLibs; 9512 final boolean has32BitLibs; 9513 if (isApkFile(codeFile)) { 9514 // Monolithic install 9515 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9516 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9517 } else { 9518 // Cluster install 9519 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9520 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9521 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9522 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9523 has64BitLibs = (new File(rootDir, isa)).exists(); 9524 } else { 9525 has64BitLibs = false; 9526 } 9527 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9528 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9529 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9530 has32BitLibs = (new File(rootDir, isa)).exists(); 9531 } else { 9532 has32BitLibs = false; 9533 } 9534 } 9535 9536 if (has64BitLibs && !has32BitLibs) { 9537 // The package has 64 bit libs, but not 32 bit libs. Its primary 9538 // ABI should be 64 bit. We can safely assume here that the bundled 9539 // native libraries correspond to the most preferred ABI in the list. 9540 9541 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9542 pkg.applicationInfo.secondaryCpuAbi = null; 9543 } else if (has32BitLibs && !has64BitLibs) { 9544 // The package has 32 bit libs but not 64 bit libs. Its primary 9545 // ABI should be 32 bit. 9546 9547 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9548 pkg.applicationInfo.secondaryCpuAbi = null; 9549 } else if (has32BitLibs && has64BitLibs) { 9550 // The application has both 64 and 32 bit bundled libraries. We check 9551 // here that the app declares multiArch support, and warn if it doesn't. 9552 // 9553 // We will be lenient here and record both ABIs. The primary will be the 9554 // ABI that's higher on the list, i.e, a device that's configured to prefer 9555 // 64 bit apps will see a 64 bit primary ABI, 9556 9557 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9558 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9559 } 9560 9561 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9562 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9563 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9564 } else { 9565 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9566 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9567 } 9568 } else { 9569 pkg.applicationInfo.primaryCpuAbi = null; 9570 pkg.applicationInfo.secondaryCpuAbi = null; 9571 } 9572 } 9573 9574 private void killApplication(String pkgName, int appId, String reason) { 9575 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9576 } 9577 9578 private void killApplication(String pkgName, int appId, int userId, String reason) { 9579 // Request the ActivityManager to kill the process(only for existing packages) 9580 // so that we do not end up in a confused state while the user is still using the older 9581 // version of the application while the new one gets installed. 9582 final long token = Binder.clearCallingIdentity(); 9583 try { 9584 IActivityManager am = ActivityManagerNative.getDefault(); 9585 if (am != null) { 9586 try { 9587 am.killApplication(pkgName, appId, userId, reason); 9588 } catch (RemoteException e) { 9589 } 9590 } 9591 } finally { 9592 Binder.restoreCallingIdentity(token); 9593 } 9594 } 9595 9596 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9597 // Remove the parent package setting 9598 PackageSetting ps = (PackageSetting) pkg.mExtras; 9599 if (ps != null) { 9600 removePackageLI(ps, chatty); 9601 } 9602 // Remove the child package setting 9603 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9604 for (int i = 0; i < childCount; i++) { 9605 PackageParser.Package childPkg = pkg.childPackages.get(i); 9606 ps = (PackageSetting) childPkg.mExtras; 9607 if (ps != null) { 9608 removePackageLI(ps, chatty); 9609 } 9610 } 9611 } 9612 9613 void removePackageLI(PackageSetting ps, boolean chatty) { 9614 if (DEBUG_INSTALL) { 9615 if (chatty) 9616 Log.d(TAG, "Removing package " + ps.name); 9617 } 9618 9619 // writer 9620 synchronized (mPackages) { 9621 mPackages.remove(ps.name); 9622 final PackageParser.Package pkg = ps.pkg; 9623 if (pkg != null) { 9624 cleanPackageDataStructuresLILPw(pkg, chatty); 9625 } 9626 } 9627 } 9628 9629 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9630 if (DEBUG_INSTALL) { 9631 if (chatty) 9632 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9633 } 9634 9635 // writer 9636 synchronized (mPackages) { 9637 // Remove the parent package 9638 mPackages.remove(pkg.applicationInfo.packageName); 9639 cleanPackageDataStructuresLILPw(pkg, chatty); 9640 9641 // Remove the child packages 9642 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9643 for (int i = 0; i < childCount; i++) { 9644 PackageParser.Package childPkg = pkg.childPackages.get(i); 9645 mPackages.remove(childPkg.applicationInfo.packageName); 9646 cleanPackageDataStructuresLILPw(childPkg, chatty); 9647 } 9648 } 9649 } 9650 9651 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9652 int N = pkg.providers.size(); 9653 StringBuilder r = null; 9654 int i; 9655 for (i=0; i<N; i++) { 9656 PackageParser.Provider p = pkg.providers.get(i); 9657 mProviders.removeProvider(p); 9658 if (p.info.authority == null) { 9659 9660 /* There was another ContentProvider with this authority when 9661 * this app was installed so this authority is null, 9662 * Ignore it as we don't have to unregister the provider. 9663 */ 9664 continue; 9665 } 9666 String names[] = p.info.authority.split(";"); 9667 for (int j = 0; j < names.length; j++) { 9668 if (mProvidersByAuthority.get(names[j]) == p) { 9669 mProvidersByAuthority.remove(names[j]); 9670 if (DEBUG_REMOVE) { 9671 if (chatty) 9672 Log.d(TAG, "Unregistered content provider: " + names[j] 9673 + ", className = " + p.info.name + ", isSyncable = " 9674 + p.info.isSyncable); 9675 } 9676 } 9677 } 9678 if (DEBUG_REMOVE && chatty) { 9679 if (r == null) { 9680 r = new StringBuilder(256); 9681 } else { 9682 r.append(' '); 9683 } 9684 r.append(p.info.name); 9685 } 9686 } 9687 if (r != null) { 9688 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9689 } 9690 9691 N = pkg.services.size(); 9692 r = null; 9693 for (i=0; i<N; i++) { 9694 PackageParser.Service s = pkg.services.get(i); 9695 mServices.removeService(s); 9696 if (chatty) { 9697 if (r == null) { 9698 r = new StringBuilder(256); 9699 } else { 9700 r.append(' '); 9701 } 9702 r.append(s.info.name); 9703 } 9704 } 9705 if (r != null) { 9706 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9707 } 9708 9709 N = pkg.receivers.size(); 9710 r = null; 9711 for (i=0; i<N; i++) { 9712 PackageParser.Activity a = pkg.receivers.get(i); 9713 mReceivers.removeActivity(a, "receiver"); 9714 if (DEBUG_REMOVE && chatty) { 9715 if (r == null) { 9716 r = new StringBuilder(256); 9717 } else { 9718 r.append(' '); 9719 } 9720 r.append(a.info.name); 9721 } 9722 } 9723 if (r != null) { 9724 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9725 } 9726 9727 N = pkg.activities.size(); 9728 r = null; 9729 for (i=0; i<N; i++) { 9730 PackageParser.Activity a = pkg.activities.get(i); 9731 mActivities.removeActivity(a, "activity"); 9732 if (DEBUG_REMOVE && chatty) { 9733 if (r == null) { 9734 r = new StringBuilder(256); 9735 } else { 9736 r.append(' '); 9737 } 9738 r.append(a.info.name); 9739 } 9740 } 9741 if (r != null) { 9742 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9743 } 9744 9745 N = pkg.permissions.size(); 9746 r = null; 9747 for (i=0; i<N; i++) { 9748 PackageParser.Permission p = pkg.permissions.get(i); 9749 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9750 if (bp == null) { 9751 bp = mSettings.mPermissionTrees.get(p.info.name); 9752 } 9753 if (bp != null && bp.perm == p) { 9754 bp.perm = null; 9755 if (DEBUG_REMOVE && chatty) { 9756 if (r == null) { 9757 r = new StringBuilder(256); 9758 } else { 9759 r.append(' '); 9760 } 9761 r.append(p.info.name); 9762 } 9763 } 9764 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9765 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9766 if (appOpPkgs != null) { 9767 appOpPkgs.remove(pkg.packageName); 9768 } 9769 } 9770 } 9771 if (r != null) { 9772 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9773 } 9774 9775 N = pkg.requestedPermissions.size(); 9776 r = null; 9777 for (i=0; i<N; i++) { 9778 String perm = pkg.requestedPermissions.get(i); 9779 BasePermission bp = mSettings.mPermissions.get(perm); 9780 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9781 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9782 if (appOpPkgs != null) { 9783 appOpPkgs.remove(pkg.packageName); 9784 if (appOpPkgs.isEmpty()) { 9785 mAppOpPermissionPackages.remove(perm); 9786 } 9787 } 9788 } 9789 } 9790 if (r != null) { 9791 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9792 } 9793 9794 N = pkg.instrumentation.size(); 9795 r = null; 9796 for (i=0; i<N; i++) { 9797 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9798 mInstrumentation.remove(a.getComponentName()); 9799 if (DEBUG_REMOVE && chatty) { 9800 if (r == null) { 9801 r = new StringBuilder(256); 9802 } else { 9803 r.append(' '); 9804 } 9805 r.append(a.info.name); 9806 } 9807 } 9808 if (r != null) { 9809 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9810 } 9811 9812 r = null; 9813 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9814 // Only system apps can hold shared libraries. 9815 if (pkg.libraryNames != null) { 9816 for (i=0; i<pkg.libraryNames.size(); i++) { 9817 String name = pkg.libraryNames.get(i); 9818 SharedLibraryEntry cur = mSharedLibraries.get(name); 9819 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9820 mSharedLibraries.remove(name); 9821 if (DEBUG_REMOVE && chatty) { 9822 if (r == null) { 9823 r = new StringBuilder(256); 9824 } else { 9825 r.append(' '); 9826 } 9827 r.append(name); 9828 } 9829 } 9830 } 9831 } 9832 } 9833 if (r != null) { 9834 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9835 } 9836 } 9837 9838 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9839 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9840 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9841 return true; 9842 } 9843 } 9844 return false; 9845 } 9846 9847 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9848 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9849 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9850 9851 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9852 // Update the parent permissions 9853 updatePermissionsLPw(pkg.packageName, pkg, flags); 9854 // Update the child permissions 9855 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9856 for (int i = 0; i < childCount; i++) { 9857 PackageParser.Package childPkg = pkg.childPackages.get(i); 9858 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9859 } 9860 } 9861 9862 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9863 int flags) { 9864 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9865 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9866 } 9867 9868 private void updatePermissionsLPw(String changingPkg, 9869 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9870 // Make sure there are no dangling permission trees. 9871 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9872 while (it.hasNext()) { 9873 final BasePermission bp = it.next(); 9874 if (bp.packageSetting == null) { 9875 // We may not yet have parsed the package, so just see if 9876 // we still know about its settings. 9877 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9878 } 9879 if (bp.packageSetting == null) { 9880 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9881 + " from package " + bp.sourcePackage); 9882 it.remove(); 9883 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9884 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9885 Slog.i(TAG, "Removing old permission tree: " + bp.name 9886 + " from package " + bp.sourcePackage); 9887 flags |= UPDATE_PERMISSIONS_ALL; 9888 it.remove(); 9889 } 9890 } 9891 } 9892 9893 // Make sure all dynamic permissions have been assigned to a package, 9894 // and make sure there are no dangling permissions. 9895 it = mSettings.mPermissions.values().iterator(); 9896 while (it.hasNext()) { 9897 final BasePermission bp = it.next(); 9898 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9899 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9900 + bp.name + " pkg=" + bp.sourcePackage 9901 + " info=" + bp.pendingInfo); 9902 if (bp.packageSetting == null && bp.pendingInfo != null) { 9903 final BasePermission tree = findPermissionTreeLP(bp.name); 9904 if (tree != null && tree.perm != null) { 9905 bp.packageSetting = tree.packageSetting; 9906 bp.perm = new PackageParser.Permission(tree.perm.owner, 9907 new PermissionInfo(bp.pendingInfo)); 9908 bp.perm.info.packageName = tree.perm.info.packageName; 9909 bp.perm.info.name = bp.name; 9910 bp.uid = tree.uid; 9911 } 9912 } 9913 } 9914 if (bp.packageSetting == null) { 9915 // We may not yet have parsed the package, so just see if 9916 // we still know about its settings. 9917 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9918 } 9919 if (bp.packageSetting == null) { 9920 Slog.w(TAG, "Removing dangling permission: " + bp.name 9921 + " from package " + bp.sourcePackage); 9922 it.remove(); 9923 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9924 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9925 Slog.i(TAG, "Removing old permission: " + bp.name 9926 + " from package " + bp.sourcePackage); 9927 flags |= UPDATE_PERMISSIONS_ALL; 9928 it.remove(); 9929 } 9930 } 9931 } 9932 9933 // Now update the permissions for all packages, in particular 9934 // replace the granted permissions of the system packages. 9935 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9936 for (PackageParser.Package pkg : mPackages.values()) { 9937 if (pkg != pkgInfo) { 9938 // Only replace for packages on requested volume 9939 final String volumeUuid = getVolumeUuidForPackage(pkg); 9940 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9941 && Objects.equals(replaceVolumeUuid, volumeUuid); 9942 grantPermissionsLPw(pkg, replace, changingPkg); 9943 } 9944 } 9945 } 9946 9947 if (pkgInfo != null) { 9948 // Only replace for packages on requested volume 9949 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9950 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9951 && Objects.equals(replaceVolumeUuid, volumeUuid); 9952 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9953 } 9954 } 9955 9956 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9957 String packageOfInterest) { 9958 // IMPORTANT: There are two types of permissions: install and runtime. 9959 // Install time permissions are granted when the app is installed to 9960 // all device users and users added in the future. Runtime permissions 9961 // are granted at runtime explicitly to specific users. Normal and signature 9962 // protected permissions are install time permissions. Dangerous permissions 9963 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9964 // otherwise they are runtime permissions. This function does not manage 9965 // runtime permissions except for the case an app targeting Lollipop MR1 9966 // being upgraded to target a newer SDK, in which case dangerous permissions 9967 // are transformed from install time to runtime ones. 9968 9969 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9970 if (ps == null) { 9971 return; 9972 } 9973 9974 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9975 9976 PermissionsState permissionsState = ps.getPermissionsState(); 9977 PermissionsState origPermissions = permissionsState; 9978 9979 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9980 9981 boolean runtimePermissionsRevoked = false; 9982 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9983 9984 boolean changedInstallPermission = false; 9985 9986 if (replace) { 9987 ps.installPermissionsFixed = false; 9988 if (!ps.isSharedUser()) { 9989 origPermissions = new PermissionsState(permissionsState); 9990 permissionsState.reset(); 9991 } else { 9992 // We need to know only about runtime permission changes since the 9993 // calling code always writes the install permissions state but 9994 // the runtime ones are written only if changed. The only cases of 9995 // changed runtime permissions here are promotion of an install to 9996 // runtime and revocation of a runtime from a shared user. 9997 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9998 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9999 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10000 runtimePermissionsRevoked = true; 10001 } 10002 } 10003 } 10004 10005 permissionsState.setGlobalGids(mGlobalGids); 10006 10007 final int N = pkg.requestedPermissions.size(); 10008 for (int i=0; i<N; i++) { 10009 final String name = pkg.requestedPermissions.get(i); 10010 final BasePermission bp = mSettings.mPermissions.get(name); 10011 10012 if (DEBUG_INSTALL) { 10013 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10014 } 10015 10016 if (bp == null || bp.packageSetting == null) { 10017 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10018 Slog.w(TAG, "Unknown permission " + name 10019 + " in package " + pkg.packageName); 10020 } 10021 continue; 10022 } 10023 10024 final String perm = bp.name; 10025 boolean allowedSig = false; 10026 int grant = GRANT_DENIED; 10027 10028 // Keep track of app op permissions. 10029 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10030 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10031 if (pkgs == null) { 10032 pkgs = new ArraySet<>(); 10033 mAppOpPermissionPackages.put(bp.name, pkgs); 10034 } 10035 pkgs.add(pkg.packageName); 10036 } 10037 10038 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10039 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10040 >= Build.VERSION_CODES.M; 10041 switch (level) { 10042 case PermissionInfo.PROTECTION_NORMAL: { 10043 // For all apps normal permissions are install time ones. 10044 grant = GRANT_INSTALL; 10045 } break; 10046 10047 case PermissionInfo.PROTECTION_DANGEROUS: { 10048 // If a permission review is required for legacy apps we represent 10049 // their permissions as always granted runtime ones since we need 10050 // to keep the review required permission flag per user while an 10051 // install permission's state is shared across all users. 10052 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired 10053 && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10054 // For legacy apps dangerous permissions are install time ones. 10055 grant = GRANT_INSTALL; 10056 } else if (origPermissions.hasInstallPermission(bp.name)) { 10057 // For legacy apps that became modern, install becomes runtime. 10058 grant = GRANT_UPGRADE; 10059 } else if (mPromoteSystemApps 10060 && isSystemApp(ps) 10061 && mExistingSystemPackages.contains(ps.name)) { 10062 // For legacy system apps, install becomes runtime. 10063 // We cannot check hasInstallPermission() for system apps since those 10064 // permissions were granted implicitly and not persisted pre-M. 10065 grant = GRANT_UPGRADE; 10066 } else { 10067 // For modern apps keep runtime permissions unchanged. 10068 grant = GRANT_RUNTIME; 10069 } 10070 } break; 10071 10072 case PermissionInfo.PROTECTION_SIGNATURE: { 10073 // For all apps signature permissions are install time ones. 10074 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10075 if (allowedSig) { 10076 grant = GRANT_INSTALL; 10077 } 10078 } break; 10079 } 10080 10081 if (DEBUG_INSTALL) { 10082 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10083 } 10084 10085 if (grant != GRANT_DENIED) { 10086 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10087 // If this is an existing, non-system package, then 10088 // we can't add any new permissions to it. 10089 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10090 // Except... if this is a permission that was added 10091 // to the platform (note: need to only do this when 10092 // updating the platform). 10093 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10094 grant = GRANT_DENIED; 10095 } 10096 } 10097 } 10098 10099 switch (grant) { 10100 case GRANT_INSTALL: { 10101 // Revoke this as runtime permission to handle the case of 10102 // a runtime permission being downgraded to an install one. 10103 // Also in permission review mode we keep dangerous permissions 10104 // for legacy apps 10105 for (int userId : UserManagerService.getInstance().getUserIds()) { 10106 if (origPermissions.getRuntimePermissionState( 10107 bp.name, userId) != null) { 10108 // Revoke the runtime permission and clear the flags. 10109 origPermissions.revokeRuntimePermission(bp, userId); 10110 origPermissions.updatePermissionFlags(bp, userId, 10111 PackageManager.MASK_PERMISSION_FLAGS, 0); 10112 // If we revoked a permission permission, we have to write. 10113 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10114 changedRuntimePermissionUserIds, userId); 10115 } 10116 } 10117 // Grant an install permission. 10118 if (permissionsState.grantInstallPermission(bp) != 10119 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10120 changedInstallPermission = true; 10121 } 10122 } break; 10123 10124 case GRANT_RUNTIME: { 10125 // Grant previously granted runtime permissions. 10126 for (int userId : UserManagerService.getInstance().getUserIds()) { 10127 PermissionState permissionState = origPermissions 10128 .getRuntimePermissionState(bp.name, userId); 10129 int flags = permissionState != null 10130 ? permissionState.getFlags() : 0; 10131 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10132 if (permissionsState.grantRuntimePermission(bp, userId) == 10133 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10134 // If we cannot put the permission as it was, we have to write. 10135 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10136 changedRuntimePermissionUserIds, userId); 10137 } 10138 // If the app supports runtime permissions no need for a review. 10139 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 10140 && appSupportsRuntimePermissions 10141 && (flags & PackageManager 10142 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10143 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10144 // Since we changed the flags, we have to write. 10145 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10146 changedRuntimePermissionUserIds, userId); 10147 } 10148 } else if ((mPermissionReviewRequired 10149 || Build.PERMISSIONS_REVIEW_REQUIRED) 10150 && !appSupportsRuntimePermissions) { 10151 // For legacy apps that need a permission review, every new 10152 // runtime permission is granted but it is pending a review. 10153 // We also need to review only platform defined runtime 10154 // permissions as these are the only ones the platform knows 10155 // how to disable the API to simulate revocation as legacy 10156 // apps don't expect to run with revoked permissions. 10157 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10158 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10159 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10160 // We changed the flags, hence have to write. 10161 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10162 changedRuntimePermissionUserIds, userId); 10163 } 10164 } 10165 if (permissionsState.grantRuntimePermission(bp, userId) 10166 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10167 // We changed the permission, hence have to write. 10168 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10169 changedRuntimePermissionUserIds, userId); 10170 } 10171 } 10172 // Propagate the permission flags. 10173 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10174 } 10175 } break; 10176 10177 case GRANT_UPGRADE: { 10178 // Grant runtime permissions for a previously held install permission. 10179 PermissionState permissionState = origPermissions 10180 .getInstallPermissionState(bp.name); 10181 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10182 10183 if (origPermissions.revokeInstallPermission(bp) 10184 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10185 // We will be transferring the permission flags, so clear them. 10186 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10187 PackageManager.MASK_PERMISSION_FLAGS, 0); 10188 changedInstallPermission = true; 10189 } 10190 10191 // If the permission is not to be promoted to runtime we ignore it and 10192 // also its other flags as they are not applicable to install permissions. 10193 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10194 for (int userId : currentUserIds) { 10195 if (permissionsState.grantRuntimePermission(bp, userId) != 10196 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10197 // Transfer the permission flags. 10198 permissionsState.updatePermissionFlags(bp, userId, 10199 flags, flags); 10200 // If we granted the permission, we have to write. 10201 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10202 changedRuntimePermissionUserIds, userId); 10203 } 10204 } 10205 } 10206 } break; 10207 10208 default: { 10209 if (packageOfInterest == null 10210 || packageOfInterest.equals(pkg.packageName)) { 10211 Slog.w(TAG, "Not granting permission " + perm 10212 + " to package " + pkg.packageName 10213 + " because it was previously installed without"); 10214 } 10215 } break; 10216 } 10217 } else { 10218 if (permissionsState.revokeInstallPermission(bp) != 10219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10220 // Also drop the permission flags. 10221 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10222 PackageManager.MASK_PERMISSION_FLAGS, 0); 10223 changedInstallPermission = true; 10224 Slog.i(TAG, "Un-granting permission " + perm 10225 + " from package " + pkg.packageName 10226 + " (protectionLevel=" + bp.protectionLevel 10227 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10228 + ")"); 10229 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10230 // Don't print warning for app op permissions, since it is fine for them 10231 // not to be granted, there is a UI for the user to decide. 10232 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10233 Slog.w(TAG, "Not granting permission " + perm 10234 + " to package " + pkg.packageName 10235 + " (protectionLevel=" + bp.protectionLevel 10236 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10237 + ")"); 10238 } 10239 } 10240 } 10241 } 10242 10243 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10244 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10245 // This is the first that we have heard about this package, so the 10246 // permissions we have now selected are fixed until explicitly 10247 // changed. 10248 ps.installPermissionsFixed = true; 10249 } 10250 10251 // Persist the runtime permissions state for users with changes. If permissions 10252 // were revoked because no app in the shared user declares them we have to 10253 // write synchronously to avoid losing runtime permissions state. 10254 for (int userId : changedRuntimePermissionUserIds) { 10255 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10256 } 10257 10258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10259 } 10260 10261 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10262 boolean allowed = false; 10263 final int NP = PackageParser.NEW_PERMISSIONS.length; 10264 for (int ip=0; ip<NP; ip++) { 10265 final PackageParser.NewPermissionInfo npi 10266 = PackageParser.NEW_PERMISSIONS[ip]; 10267 if (npi.name.equals(perm) 10268 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10269 allowed = true; 10270 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10271 + pkg.packageName); 10272 break; 10273 } 10274 } 10275 return allowed; 10276 } 10277 10278 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10279 BasePermission bp, PermissionsState origPermissions) { 10280 boolean allowed; 10281 allowed = (compareSignatures( 10282 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10283 == PackageManager.SIGNATURE_MATCH) 10284 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10285 == PackageManager.SIGNATURE_MATCH); 10286 if (!allowed && (bp.protectionLevel 10287 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10288 if (isSystemApp(pkg)) { 10289 // For updated system applications, a system permission 10290 // is granted only if it had been defined by the original application. 10291 if (pkg.isUpdatedSystemApp()) { 10292 final PackageSetting sysPs = mSettings 10293 .getDisabledSystemPkgLPr(pkg.packageName); 10294 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10295 // If the original was granted this permission, we take 10296 // that grant decision as read and propagate it to the 10297 // update. 10298 if (sysPs.isPrivileged()) { 10299 allowed = true; 10300 } 10301 } else { 10302 // The system apk may have been updated with an older 10303 // version of the one on the data partition, but which 10304 // granted a new system permission that it didn't have 10305 // before. In this case we do want to allow the app to 10306 // now get the new permission if the ancestral apk is 10307 // privileged to get it. 10308 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10309 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10310 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10311 allowed = true; 10312 break; 10313 } 10314 } 10315 } 10316 // Also if a privileged parent package on the system image or any of 10317 // its children requested a privileged permission, the updated child 10318 // packages can also get the permission. 10319 if (pkg.parentPackage != null) { 10320 final PackageSetting disabledSysParentPs = mSettings 10321 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10322 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10323 && disabledSysParentPs.isPrivileged()) { 10324 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10325 allowed = true; 10326 } else if (disabledSysParentPs.pkg.childPackages != null) { 10327 final int count = disabledSysParentPs.pkg.childPackages.size(); 10328 for (int i = 0; i < count; i++) { 10329 PackageParser.Package disabledSysChildPkg = 10330 disabledSysParentPs.pkg.childPackages.get(i); 10331 if (isPackageRequestingPermission(disabledSysChildPkg, 10332 perm)) { 10333 allowed = true; 10334 break; 10335 } 10336 } 10337 } 10338 } 10339 } 10340 } 10341 } else { 10342 allowed = isPrivilegedApp(pkg); 10343 } 10344 } 10345 } 10346 if (!allowed) { 10347 if (!allowed && (bp.protectionLevel 10348 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10349 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10350 // If this was a previously normal/dangerous permission that got moved 10351 // to a system permission as part of the runtime permission redesign, then 10352 // we still want to blindly grant it to old apps. 10353 allowed = true; 10354 } 10355 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10356 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10357 // If this permission is to be granted to the system installer and 10358 // this app is an installer, then it gets the permission. 10359 allowed = true; 10360 } 10361 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10362 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10363 // If this permission is to be granted to the system verifier and 10364 // this app is a verifier, then it gets the permission. 10365 allowed = true; 10366 } 10367 if (!allowed && (bp.protectionLevel 10368 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10369 && isSystemApp(pkg)) { 10370 // Any pre-installed system app is allowed to get this permission. 10371 allowed = true; 10372 } 10373 if (!allowed && (bp.protectionLevel 10374 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10375 // For development permissions, a development permission 10376 // is granted only if it was already granted. 10377 allowed = origPermissions.hasInstallPermission(perm); 10378 } 10379 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10380 && pkg.packageName.equals(mSetupWizardPackage)) { 10381 // If this permission is to be granted to the system setup wizard and 10382 // this app is a setup wizard, then it gets the permission. 10383 allowed = true; 10384 } 10385 } 10386 return allowed; 10387 } 10388 10389 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10390 final int permCount = pkg.requestedPermissions.size(); 10391 for (int j = 0; j < permCount; j++) { 10392 String requestedPermission = pkg.requestedPermissions.get(j); 10393 if (permission.equals(requestedPermission)) { 10394 return true; 10395 } 10396 } 10397 return false; 10398 } 10399 10400 final class ActivityIntentResolver 10401 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10402 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10403 boolean defaultOnly, int userId) { 10404 if (!sUserManager.exists(userId)) return null; 10405 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10406 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10407 } 10408 10409 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10410 int userId) { 10411 if (!sUserManager.exists(userId)) return null; 10412 mFlags = flags; 10413 return super.queryIntent(intent, resolvedType, 10414 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10415 } 10416 10417 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10418 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10419 if (!sUserManager.exists(userId)) return null; 10420 if (packageActivities == null) { 10421 return null; 10422 } 10423 mFlags = flags; 10424 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10425 final int N = packageActivities.size(); 10426 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10427 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10428 10429 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10430 for (int i = 0; i < N; ++i) { 10431 intentFilters = packageActivities.get(i).intents; 10432 if (intentFilters != null && intentFilters.size() > 0) { 10433 PackageParser.ActivityIntentInfo[] array = 10434 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10435 intentFilters.toArray(array); 10436 listCut.add(array); 10437 } 10438 } 10439 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10440 } 10441 10442 /** 10443 * Finds a privileged activity that matches the specified activity names. 10444 */ 10445 private PackageParser.Activity findMatchingActivity( 10446 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10447 for (PackageParser.Activity sysActivity : activityList) { 10448 if (sysActivity.info.name.equals(activityInfo.name)) { 10449 return sysActivity; 10450 } 10451 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10452 return sysActivity; 10453 } 10454 if (sysActivity.info.targetActivity != null) { 10455 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10456 return sysActivity; 10457 } 10458 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10459 return sysActivity; 10460 } 10461 } 10462 } 10463 return null; 10464 } 10465 10466 public class IterGenerator<E> { 10467 public Iterator<E> generate(ActivityIntentInfo info) { 10468 return null; 10469 } 10470 } 10471 10472 public class ActionIterGenerator extends IterGenerator<String> { 10473 @Override 10474 public Iterator<String> generate(ActivityIntentInfo info) { 10475 return info.actionsIterator(); 10476 } 10477 } 10478 10479 public class CategoriesIterGenerator extends IterGenerator<String> { 10480 @Override 10481 public Iterator<String> generate(ActivityIntentInfo info) { 10482 return info.categoriesIterator(); 10483 } 10484 } 10485 10486 public class SchemesIterGenerator extends IterGenerator<String> { 10487 @Override 10488 public Iterator<String> generate(ActivityIntentInfo info) { 10489 return info.schemesIterator(); 10490 } 10491 } 10492 10493 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10494 @Override 10495 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10496 return info.authoritiesIterator(); 10497 } 10498 } 10499 10500 /** 10501 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10502 * MODIFIED. Do not pass in a list that should not be changed. 10503 */ 10504 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10505 IterGenerator<T> generator, Iterator<T> searchIterator) { 10506 // loop through the set of actions; every one must be found in the intent filter 10507 while (searchIterator.hasNext()) { 10508 // we must have at least one filter in the list to consider a match 10509 if (intentList.size() == 0) { 10510 break; 10511 } 10512 10513 final T searchAction = searchIterator.next(); 10514 10515 // loop through the set of intent filters 10516 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10517 while (intentIter.hasNext()) { 10518 final ActivityIntentInfo intentInfo = intentIter.next(); 10519 boolean selectionFound = false; 10520 10521 // loop through the intent filter's selection criteria; at least one 10522 // of them must match the searched criteria 10523 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10524 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10525 final T intentSelection = intentSelectionIter.next(); 10526 if (intentSelection != null && intentSelection.equals(searchAction)) { 10527 selectionFound = true; 10528 break; 10529 } 10530 } 10531 10532 // the selection criteria wasn't found in this filter's set; this filter 10533 // is not a potential match 10534 if (!selectionFound) { 10535 intentIter.remove(); 10536 } 10537 } 10538 } 10539 } 10540 10541 private boolean isProtectedAction(ActivityIntentInfo filter) { 10542 final Iterator<String> actionsIter = filter.actionsIterator(); 10543 while (actionsIter != null && actionsIter.hasNext()) { 10544 final String filterAction = actionsIter.next(); 10545 if (PROTECTED_ACTIONS.contains(filterAction)) { 10546 return true; 10547 } 10548 } 10549 return false; 10550 } 10551 10552 /** 10553 * Adjusts the priority of the given intent filter according to policy. 10554 * <p> 10555 * <ul> 10556 * <li>The priority for non privileged applications is capped to '0'</li> 10557 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10558 * <li>The priority for unbundled updates to privileged applications is capped to the 10559 * priority defined on the system partition</li> 10560 * </ul> 10561 * <p> 10562 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10563 * allowed to obtain any priority on any action. 10564 */ 10565 private void adjustPriority( 10566 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10567 // nothing to do; priority is fine as-is 10568 if (intent.getPriority() <= 0) { 10569 return; 10570 } 10571 10572 final ActivityInfo activityInfo = intent.activity.info; 10573 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10574 10575 final boolean privilegedApp = 10576 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10577 if (!privilegedApp) { 10578 // non-privileged applications can never define a priority >0 10579 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10580 + " package: " + applicationInfo.packageName 10581 + " activity: " + intent.activity.className 10582 + " origPrio: " + intent.getPriority()); 10583 intent.setPriority(0); 10584 return; 10585 } 10586 10587 if (systemActivities == null) { 10588 // the system package is not disabled; we're parsing the system partition 10589 if (isProtectedAction(intent)) { 10590 if (mDeferProtectedFilters) { 10591 // We can't deal with these just yet. No component should ever obtain a 10592 // >0 priority for a protected actions, with ONE exception -- the setup 10593 // wizard. The setup wizard, however, cannot be known until we're able to 10594 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10595 // until all intent filters have been processed. Chicken, meet egg. 10596 // Let the filter temporarily have a high priority and rectify the 10597 // priorities after all system packages have been scanned. 10598 mProtectedFilters.add(intent); 10599 if (DEBUG_FILTERS) { 10600 Slog.i(TAG, "Protected action; save for later;" 10601 + " package: " + applicationInfo.packageName 10602 + " activity: " + intent.activity.className 10603 + " origPrio: " + intent.getPriority()); 10604 } 10605 return; 10606 } else { 10607 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10608 Slog.i(TAG, "No setup wizard;" 10609 + " All protected intents capped to priority 0"); 10610 } 10611 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10612 if (DEBUG_FILTERS) { 10613 Slog.i(TAG, "Found setup wizard;" 10614 + " allow priority " + intent.getPriority() + ";" 10615 + " package: " + intent.activity.info.packageName 10616 + " activity: " + intent.activity.className 10617 + " priority: " + intent.getPriority()); 10618 } 10619 // setup wizard gets whatever it wants 10620 return; 10621 } 10622 Slog.w(TAG, "Protected action; cap priority to 0;" 10623 + " package: " + intent.activity.info.packageName 10624 + " activity: " + intent.activity.className 10625 + " origPrio: " + intent.getPriority()); 10626 intent.setPriority(0); 10627 return; 10628 } 10629 } 10630 // privileged apps on the system image get whatever priority they request 10631 return; 10632 } 10633 10634 // privileged app unbundled update ... try to find the same activity 10635 final PackageParser.Activity foundActivity = 10636 findMatchingActivity(systemActivities, activityInfo); 10637 if (foundActivity == null) { 10638 // this is a new activity; it cannot obtain >0 priority 10639 if (DEBUG_FILTERS) { 10640 Slog.i(TAG, "New activity; cap priority to 0;" 10641 + " package: " + applicationInfo.packageName 10642 + " activity: " + intent.activity.className 10643 + " origPrio: " + intent.getPriority()); 10644 } 10645 intent.setPriority(0); 10646 return; 10647 } 10648 10649 // found activity, now check for filter equivalence 10650 10651 // a shallow copy is enough; we modify the list, not its contents 10652 final List<ActivityIntentInfo> intentListCopy = 10653 new ArrayList<>(foundActivity.intents); 10654 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10655 10656 // find matching action subsets 10657 final Iterator<String> actionsIterator = intent.actionsIterator(); 10658 if (actionsIterator != null) { 10659 getIntentListSubset( 10660 intentListCopy, new ActionIterGenerator(), actionsIterator); 10661 if (intentListCopy.size() == 0) { 10662 // no more intents to match; we're not equivalent 10663 if (DEBUG_FILTERS) { 10664 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10665 + " package: " + applicationInfo.packageName 10666 + " activity: " + intent.activity.className 10667 + " origPrio: " + intent.getPriority()); 10668 } 10669 intent.setPriority(0); 10670 return; 10671 } 10672 } 10673 10674 // find matching category subsets 10675 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10676 if (categoriesIterator != null) { 10677 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10678 categoriesIterator); 10679 if (intentListCopy.size() == 0) { 10680 // no more intents to match; we're not equivalent 10681 if (DEBUG_FILTERS) { 10682 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10683 + " package: " + applicationInfo.packageName 10684 + " activity: " + intent.activity.className 10685 + " origPrio: " + intent.getPriority()); 10686 } 10687 intent.setPriority(0); 10688 return; 10689 } 10690 } 10691 10692 // find matching schemes subsets 10693 final Iterator<String> schemesIterator = intent.schemesIterator(); 10694 if (schemesIterator != null) { 10695 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10696 schemesIterator); 10697 if (intentListCopy.size() == 0) { 10698 // no more intents to match; we're not equivalent 10699 if (DEBUG_FILTERS) { 10700 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10701 + " package: " + applicationInfo.packageName 10702 + " activity: " + intent.activity.className 10703 + " origPrio: " + intent.getPriority()); 10704 } 10705 intent.setPriority(0); 10706 return; 10707 } 10708 } 10709 10710 // find matching authorities subsets 10711 final Iterator<IntentFilter.AuthorityEntry> 10712 authoritiesIterator = intent.authoritiesIterator(); 10713 if (authoritiesIterator != null) { 10714 getIntentListSubset(intentListCopy, 10715 new AuthoritiesIterGenerator(), 10716 authoritiesIterator); 10717 if (intentListCopy.size() == 0) { 10718 // no more intents to match; we're not equivalent 10719 if (DEBUG_FILTERS) { 10720 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10721 + " package: " + applicationInfo.packageName 10722 + " activity: " + intent.activity.className 10723 + " origPrio: " + intent.getPriority()); 10724 } 10725 intent.setPriority(0); 10726 return; 10727 } 10728 } 10729 10730 // we found matching filter(s); app gets the max priority of all intents 10731 int cappedPriority = 0; 10732 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10733 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10734 } 10735 if (intent.getPriority() > cappedPriority) { 10736 if (DEBUG_FILTERS) { 10737 Slog.i(TAG, "Found matching filter(s);" 10738 + " cap priority to " + cappedPriority + ";" 10739 + " package: " + applicationInfo.packageName 10740 + " activity: " + intent.activity.className 10741 + " origPrio: " + intent.getPriority()); 10742 } 10743 intent.setPriority(cappedPriority); 10744 return; 10745 } 10746 // all this for nothing; the requested priority was <= what was on the system 10747 } 10748 10749 public final void addActivity(PackageParser.Activity a, String type) { 10750 mActivities.put(a.getComponentName(), a); 10751 if (DEBUG_SHOW_INFO) 10752 Log.v( 10753 TAG, " " + type + " " + 10754 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10755 if (DEBUG_SHOW_INFO) 10756 Log.v(TAG, " Class=" + a.info.name); 10757 final int NI = a.intents.size(); 10758 for (int j=0; j<NI; j++) { 10759 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10760 if ("activity".equals(type)) { 10761 final PackageSetting ps = 10762 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10763 final List<PackageParser.Activity> systemActivities = 10764 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10765 adjustPriority(systemActivities, intent); 10766 } 10767 if (DEBUG_SHOW_INFO) { 10768 Log.v(TAG, " IntentFilter:"); 10769 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10770 } 10771 if (!intent.debugCheck()) { 10772 Log.w(TAG, "==> For Activity " + a.info.name); 10773 } 10774 addFilter(intent); 10775 } 10776 } 10777 10778 public final void removeActivity(PackageParser.Activity a, String type) { 10779 mActivities.remove(a.getComponentName()); 10780 if (DEBUG_SHOW_INFO) { 10781 Log.v(TAG, " " + type + " " 10782 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10783 : a.info.name) + ":"); 10784 Log.v(TAG, " Class=" + a.info.name); 10785 } 10786 final int NI = a.intents.size(); 10787 for (int j=0; j<NI; j++) { 10788 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10789 if (DEBUG_SHOW_INFO) { 10790 Log.v(TAG, " IntentFilter:"); 10791 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10792 } 10793 removeFilter(intent); 10794 } 10795 } 10796 10797 @Override 10798 protected boolean allowFilterResult( 10799 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10800 ActivityInfo filterAi = filter.activity.info; 10801 for (int i=dest.size()-1; i>=0; i--) { 10802 ActivityInfo destAi = dest.get(i).activityInfo; 10803 if (destAi.name == filterAi.name 10804 && destAi.packageName == filterAi.packageName) { 10805 return false; 10806 } 10807 } 10808 return true; 10809 } 10810 10811 @Override 10812 protected ActivityIntentInfo[] newArray(int size) { 10813 return new ActivityIntentInfo[size]; 10814 } 10815 10816 @Override 10817 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10818 if (!sUserManager.exists(userId)) return true; 10819 PackageParser.Package p = filter.activity.owner; 10820 if (p != null) { 10821 PackageSetting ps = (PackageSetting)p.mExtras; 10822 if (ps != null) { 10823 // System apps are never considered stopped for purposes of 10824 // filtering, because there may be no way for the user to 10825 // actually re-launch them. 10826 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10827 && ps.getStopped(userId); 10828 } 10829 } 10830 return false; 10831 } 10832 10833 @Override 10834 protected boolean isPackageForFilter(String packageName, 10835 PackageParser.ActivityIntentInfo info) { 10836 return packageName.equals(info.activity.owner.packageName); 10837 } 10838 10839 @Override 10840 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10841 int match, int userId) { 10842 if (!sUserManager.exists(userId)) return null; 10843 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10844 return null; 10845 } 10846 final PackageParser.Activity activity = info.activity; 10847 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10848 if (ps == null) { 10849 return null; 10850 } 10851 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10852 ps.readUserState(userId), userId); 10853 if (ai == null) { 10854 return null; 10855 } 10856 final ResolveInfo res = new ResolveInfo(); 10857 res.activityInfo = ai; 10858 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10859 res.filter = info; 10860 } 10861 if (info != null) { 10862 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10863 } 10864 res.priority = info.getPriority(); 10865 res.preferredOrder = activity.owner.mPreferredOrder; 10866 //System.out.println("Result: " + res.activityInfo.className + 10867 // " = " + res.priority); 10868 res.match = match; 10869 res.isDefault = info.hasDefault; 10870 res.labelRes = info.labelRes; 10871 res.nonLocalizedLabel = info.nonLocalizedLabel; 10872 if (userNeedsBadging(userId)) { 10873 res.noResourceId = true; 10874 } else { 10875 res.icon = info.icon; 10876 } 10877 res.iconResourceId = info.icon; 10878 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10879 return res; 10880 } 10881 10882 @Override 10883 protected void sortResults(List<ResolveInfo> results) { 10884 Collections.sort(results, mResolvePrioritySorter); 10885 } 10886 10887 @Override 10888 protected void dumpFilter(PrintWriter out, String prefix, 10889 PackageParser.ActivityIntentInfo filter) { 10890 out.print(prefix); out.print( 10891 Integer.toHexString(System.identityHashCode(filter.activity))); 10892 out.print(' '); 10893 filter.activity.printComponentShortName(out); 10894 out.print(" filter "); 10895 out.println(Integer.toHexString(System.identityHashCode(filter))); 10896 } 10897 10898 @Override 10899 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10900 return filter.activity; 10901 } 10902 10903 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10904 PackageParser.Activity activity = (PackageParser.Activity)label; 10905 out.print(prefix); out.print( 10906 Integer.toHexString(System.identityHashCode(activity))); 10907 out.print(' '); 10908 activity.printComponentShortName(out); 10909 if (count > 1) { 10910 out.print(" ("); out.print(count); out.print(" filters)"); 10911 } 10912 out.println(); 10913 } 10914 10915 // Keys are String (activity class name), values are Activity. 10916 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10917 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10918 private int mFlags; 10919 } 10920 10921 private final class ServiceIntentResolver 10922 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10923 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10924 boolean defaultOnly, int userId) { 10925 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10926 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10927 } 10928 10929 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10930 int userId) { 10931 if (!sUserManager.exists(userId)) return null; 10932 mFlags = flags; 10933 return super.queryIntent(intent, resolvedType, 10934 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10935 } 10936 10937 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10938 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10939 if (!sUserManager.exists(userId)) return null; 10940 if (packageServices == null) { 10941 return null; 10942 } 10943 mFlags = flags; 10944 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10945 final int N = packageServices.size(); 10946 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10947 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10948 10949 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10950 for (int i = 0; i < N; ++i) { 10951 intentFilters = packageServices.get(i).intents; 10952 if (intentFilters != null && intentFilters.size() > 0) { 10953 PackageParser.ServiceIntentInfo[] array = 10954 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10955 intentFilters.toArray(array); 10956 listCut.add(array); 10957 } 10958 } 10959 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10960 } 10961 10962 public final void addService(PackageParser.Service s) { 10963 mServices.put(s.getComponentName(), s); 10964 if (DEBUG_SHOW_INFO) { 10965 Log.v(TAG, " " 10966 + (s.info.nonLocalizedLabel != null 10967 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10968 Log.v(TAG, " Class=" + s.info.name); 10969 } 10970 final int NI = s.intents.size(); 10971 int j; 10972 for (j=0; j<NI; j++) { 10973 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10974 if (DEBUG_SHOW_INFO) { 10975 Log.v(TAG, " IntentFilter:"); 10976 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10977 } 10978 if (!intent.debugCheck()) { 10979 Log.w(TAG, "==> For Service " + s.info.name); 10980 } 10981 addFilter(intent); 10982 } 10983 } 10984 10985 public final void removeService(PackageParser.Service s) { 10986 mServices.remove(s.getComponentName()); 10987 if (DEBUG_SHOW_INFO) { 10988 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10989 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10990 Log.v(TAG, " Class=" + s.info.name); 10991 } 10992 final int NI = s.intents.size(); 10993 int j; 10994 for (j=0; j<NI; j++) { 10995 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10996 if (DEBUG_SHOW_INFO) { 10997 Log.v(TAG, " IntentFilter:"); 10998 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10999 } 11000 removeFilter(intent); 11001 } 11002 } 11003 11004 @Override 11005 protected boolean allowFilterResult( 11006 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11007 ServiceInfo filterSi = filter.service.info; 11008 for (int i=dest.size()-1; i>=0; i--) { 11009 ServiceInfo destAi = dest.get(i).serviceInfo; 11010 if (destAi.name == filterSi.name 11011 && destAi.packageName == filterSi.packageName) { 11012 return false; 11013 } 11014 } 11015 return true; 11016 } 11017 11018 @Override 11019 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11020 return new PackageParser.ServiceIntentInfo[size]; 11021 } 11022 11023 @Override 11024 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11025 if (!sUserManager.exists(userId)) return true; 11026 PackageParser.Package p = filter.service.owner; 11027 if (p != null) { 11028 PackageSetting ps = (PackageSetting)p.mExtras; 11029 if (ps != null) { 11030 // System apps are never considered stopped for purposes of 11031 // filtering, because there may be no way for the user to 11032 // actually re-launch them. 11033 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11034 && ps.getStopped(userId); 11035 } 11036 } 11037 return false; 11038 } 11039 11040 @Override 11041 protected boolean isPackageForFilter(String packageName, 11042 PackageParser.ServiceIntentInfo info) { 11043 return packageName.equals(info.service.owner.packageName); 11044 } 11045 11046 @Override 11047 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11048 int match, int userId) { 11049 if (!sUserManager.exists(userId)) return null; 11050 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11051 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11052 return null; 11053 } 11054 final PackageParser.Service service = info.service; 11055 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11056 if (ps == null) { 11057 return null; 11058 } 11059 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11060 ps.readUserState(userId), userId); 11061 if (si == null) { 11062 return null; 11063 } 11064 final ResolveInfo res = new ResolveInfo(); 11065 res.serviceInfo = si; 11066 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11067 res.filter = filter; 11068 } 11069 res.priority = info.getPriority(); 11070 res.preferredOrder = service.owner.mPreferredOrder; 11071 res.match = match; 11072 res.isDefault = info.hasDefault; 11073 res.labelRes = info.labelRes; 11074 res.nonLocalizedLabel = info.nonLocalizedLabel; 11075 res.icon = info.icon; 11076 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11077 return res; 11078 } 11079 11080 @Override 11081 protected void sortResults(List<ResolveInfo> results) { 11082 Collections.sort(results, mResolvePrioritySorter); 11083 } 11084 11085 @Override 11086 protected void dumpFilter(PrintWriter out, String prefix, 11087 PackageParser.ServiceIntentInfo filter) { 11088 out.print(prefix); out.print( 11089 Integer.toHexString(System.identityHashCode(filter.service))); 11090 out.print(' '); 11091 filter.service.printComponentShortName(out); 11092 out.print(" filter "); 11093 out.println(Integer.toHexString(System.identityHashCode(filter))); 11094 } 11095 11096 @Override 11097 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11098 return filter.service; 11099 } 11100 11101 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11102 PackageParser.Service service = (PackageParser.Service)label; 11103 out.print(prefix); out.print( 11104 Integer.toHexString(System.identityHashCode(service))); 11105 out.print(' '); 11106 service.printComponentShortName(out); 11107 if (count > 1) { 11108 out.print(" ("); out.print(count); out.print(" filters)"); 11109 } 11110 out.println(); 11111 } 11112 11113// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11114// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11115// final List<ResolveInfo> retList = Lists.newArrayList(); 11116// while (i.hasNext()) { 11117// final ResolveInfo resolveInfo = (ResolveInfo) i; 11118// if (isEnabledLP(resolveInfo.serviceInfo)) { 11119// retList.add(resolveInfo); 11120// } 11121// } 11122// return retList; 11123// } 11124 11125 // Keys are String (activity class name), values are Activity. 11126 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11127 = new ArrayMap<ComponentName, PackageParser.Service>(); 11128 private int mFlags; 11129 }; 11130 11131 private final class ProviderIntentResolver 11132 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11133 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11134 boolean defaultOnly, int userId) { 11135 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11136 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11137 } 11138 11139 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11140 int userId) { 11141 if (!sUserManager.exists(userId)) 11142 return null; 11143 mFlags = flags; 11144 return super.queryIntent(intent, resolvedType, 11145 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11146 } 11147 11148 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11149 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11150 if (!sUserManager.exists(userId)) 11151 return null; 11152 if (packageProviders == null) { 11153 return null; 11154 } 11155 mFlags = flags; 11156 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11157 final int N = packageProviders.size(); 11158 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11159 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11160 11161 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11162 for (int i = 0; i < N; ++i) { 11163 intentFilters = packageProviders.get(i).intents; 11164 if (intentFilters != null && intentFilters.size() > 0) { 11165 PackageParser.ProviderIntentInfo[] array = 11166 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11167 intentFilters.toArray(array); 11168 listCut.add(array); 11169 } 11170 } 11171 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11172 } 11173 11174 public final void addProvider(PackageParser.Provider p) { 11175 if (mProviders.containsKey(p.getComponentName())) { 11176 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11177 return; 11178 } 11179 11180 mProviders.put(p.getComponentName(), p); 11181 if (DEBUG_SHOW_INFO) { 11182 Log.v(TAG, " " 11183 + (p.info.nonLocalizedLabel != null 11184 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11185 Log.v(TAG, " Class=" + p.info.name); 11186 } 11187 final int NI = p.intents.size(); 11188 int j; 11189 for (j = 0; j < NI; j++) { 11190 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11191 if (DEBUG_SHOW_INFO) { 11192 Log.v(TAG, " IntentFilter:"); 11193 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11194 } 11195 if (!intent.debugCheck()) { 11196 Log.w(TAG, "==> For Provider " + p.info.name); 11197 } 11198 addFilter(intent); 11199 } 11200 } 11201 11202 public final void removeProvider(PackageParser.Provider p) { 11203 mProviders.remove(p.getComponentName()); 11204 if (DEBUG_SHOW_INFO) { 11205 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11206 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11207 Log.v(TAG, " Class=" + p.info.name); 11208 } 11209 final int NI = p.intents.size(); 11210 int j; 11211 for (j = 0; j < NI; j++) { 11212 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11213 if (DEBUG_SHOW_INFO) { 11214 Log.v(TAG, " IntentFilter:"); 11215 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11216 } 11217 removeFilter(intent); 11218 } 11219 } 11220 11221 @Override 11222 protected boolean allowFilterResult( 11223 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11224 ProviderInfo filterPi = filter.provider.info; 11225 for (int i = dest.size() - 1; i >= 0; i--) { 11226 ProviderInfo destPi = dest.get(i).providerInfo; 11227 if (destPi.name == filterPi.name 11228 && destPi.packageName == filterPi.packageName) { 11229 return false; 11230 } 11231 } 11232 return true; 11233 } 11234 11235 @Override 11236 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11237 return new PackageParser.ProviderIntentInfo[size]; 11238 } 11239 11240 @Override 11241 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11242 if (!sUserManager.exists(userId)) 11243 return true; 11244 PackageParser.Package p = filter.provider.owner; 11245 if (p != null) { 11246 PackageSetting ps = (PackageSetting) p.mExtras; 11247 if (ps != null) { 11248 // System apps are never considered stopped for purposes of 11249 // filtering, because there may be no way for the user to 11250 // actually re-launch them. 11251 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11252 && ps.getStopped(userId); 11253 } 11254 } 11255 return false; 11256 } 11257 11258 @Override 11259 protected boolean isPackageForFilter(String packageName, 11260 PackageParser.ProviderIntentInfo info) { 11261 return packageName.equals(info.provider.owner.packageName); 11262 } 11263 11264 @Override 11265 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11266 int match, int userId) { 11267 if (!sUserManager.exists(userId)) 11268 return null; 11269 final PackageParser.ProviderIntentInfo info = filter; 11270 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11271 return null; 11272 } 11273 final PackageParser.Provider provider = info.provider; 11274 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11275 if (ps == null) { 11276 return null; 11277 } 11278 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11279 ps.readUserState(userId), userId); 11280 if (pi == null) { 11281 return null; 11282 } 11283 final ResolveInfo res = new ResolveInfo(); 11284 res.providerInfo = pi; 11285 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11286 res.filter = filter; 11287 } 11288 res.priority = info.getPriority(); 11289 res.preferredOrder = provider.owner.mPreferredOrder; 11290 res.match = match; 11291 res.isDefault = info.hasDefault; 11292 res.labelRes = info.labelRes; 11293 res.nonLocalizedLabel = info.nonLocalizedLabel; 11294 res.icon = info.icon; 11295 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11296 return res; 11297 } 11298 11299 @Override 11300 protected void sortResults(List<ResolveInfo> results) { 11301 Collections.sort(results, mResolvePrioritySorter); 11302 } 11303 11304 @Override 11305 protected void dumpFilter(PrintWriter out, String prefix, 11306 PackageParser.ProviderIntentInfo filter) { 11307 out.print(prefix); 11308 out.print( 11309 Integer.toHexString(System.identityHashCode(filter.provider))); 11310 out.print(' '); 11311 filter.provider.printComponentShortName(out); 11312 out.print(" filter "); 11313 out.println(Integer.toHexString(System.identityHashCode(filter))); 11314 } 11315 11316 @Override 11317 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11318 return filter.provider; 11319 } 11320 11321 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11322 PackageParser.Provider provider = (PackageParser.Provider)label; 11323 out.print(prefix); out.print( 11324 Integer.toHexString(System.identityHashCode(provider))); 11325 out.print(' '); 11326 provider.printComponentShortName(out); 11327 if (count > 1) { 11328 out.print(" ("); out.print(count); out.print(" filters)"); 11329 } 11330 out.println(); 11331 } 11332 11333 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11334 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11335 private int mFlags; 11336 } 11337 11338 private static final class EphemeralIntentResolver 11339 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11340 /** 11341 * The result that has the highest defined order. Ordering applies on a 11342 * per-package basis. Mapping is from package name to Pair of order and 11343 * EphemeralResolveInfo. 11344 * <p> 11345 * NOTE: This is implemented as a field variable for convenience and efficiency. 11346 * By having a field variable, we're able to track filter ordering as soon as 11347 * a non-zero order is defined. Otherwise, multiple loops across the result set 11348 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11349 * this needs to be contained entirely within {@link #filterResults()}. 11350 */ 11351 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11352 11353 @Override 11354 protected EphemeralResolveIntentInfo[] newArray(int size) { 11355 return new EphemeralResolveIntentInfo[size]; 11356 } 11357 11358 @Override 11359 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11360 return true; 11361 } 11362 11363 @Override 11364 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11365 int userId) { 11366 if (!sUserManager.exists(userId)) { 11367 return null; 11368 } 11369 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11370 final Integer order = info.getOrder(); 11371 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11372 mOrderResult.get(packageName); 11373 // ordering is enabled and this item's order isn't high enough 11374 if (lastOrderResult != null && lastOrderResult.first >= order) { 11375 return null; 11376 } 11377 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11378 if (order > 0) { 11379 // non-zero order, enable ordering 11380 mOrderResult.put(packageName, new Pair<>(order, res)); 11381 } 11382 return res; 11383 } 11384 11385 @Override 11386 protected void filterResults(List<EphemeralResolveInfo> results) { 11387 // only do work if ordering is enabled [most of the time it won't be] 11388 if (mOrderResult.size() == 0) { 11389 return; 11390 } 11391 int resultSize = results.size(); 11392 for (int i = 0; i < resultSize; i++) { 11393 final EphemeralResolveInfo info = results.get(i); 11394 final String packageName = info.getPackageName(); 11395 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11396 if (savedInfo == null) { 11397 // package doesn't having ordering 11398 continue; 11399 } 11400 if (savedInfo.second == info) { 11401 // circled back to the highest ordered item; remove from order list 11402 mOrderResult.remove(savedInfo); 11403 if (mOrderResult.size() == 0) { 11404 // no more ordered items 11405 break; 11406 } 11407 continue; 11408 } 11409 // item has a worse order, remove it from the result list 11410 results.remove(i); 11411 resultSize--; 11412 i--; 11413 } 11414 } 11415 } 11416 11417 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11418 new Comparator<ResolveInfo>() { 11419 public int compare(ResolveInfo r1, ResolveInfo r2) { 11420 int v1 = r1.priority; 11421 int v2 = r2.priority; 11422 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11423 if (v1 != v2) { 11424 return (v1 > v2) ? -1 : 1; 11425 } 11426 v1 = r1.preferredOrder; 11427 v2 = r2.preferredOrder; 11428 if (v1 != v2) { 11429 return (v1 > v2) ? -1 : 1; 11430 } 11431 if (r1.isDefault != r2.isDefault) { 11432 return r1.isDefault ? -1 : 1; 11433 } 11434 v1 = r1.match; 11435 v2 = r2.match; 11436 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11437 if (v1 != v2) { 11438 return (v1 > v2) ? -1 : 1; 11439 } 11440 if (r1.system != r2.system) { 11441 return r1.system ? -1 : 1; 11442 } 11443 if (r1.activityInfo != null) { 11444 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11445 } 11446 if (r1.serviceInfo != null) { 11447 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11448 } 11449 if (r1.providerInfo != null) { 11450 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11451 } 11452 return 0; 11453 } 11454 }; 11455 11456 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11457 new Comparator<ProviderInfo>() { 11458 public int compare(ProviderInfo p1, ProviderInfo p2) { 11459 final int v1 = p1.initOrder; 11460 final int v2 = p2.initOrder; 11461 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11462 } 11463 }; 11464 11465 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11466 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11467 final int[] userIds) { 11468 mHandler.post(new Runnable() { 11469 @Override 11470 public void run() { 11471 try { 11472 final IActivityManager am = ActivityManagerNative.getDefault(); 11473 if (am == null) return; 11474 final int[] resolvedUserIds; 11475 if (userIds == null) { 11476 resolvedUserIds = am.getRunningUserIds(); 11477 } else { 11478 resolvedUserIds = userIds; 11479 } 11480 for (int id : resolvedUserIds) { 11481 final Intent intent = new Intent(action, 11482 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11483 if (extras != null) { 11484 intent.putExtras(extras); 11485 } 11486 if (targetPkg != null) { 11487 intent.setPackage(targetPkg); 11488 } 11489 // Modify the UID when posting to other users 11490 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11491 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11492 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11493 intent.putExtra(Intent.EXTRA_UID, uid); 11494 } 11495 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11496 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11497 if (DEBUG_BROADCASTS) { 11498 RuntimeException here = new RuntimeException("here"); 11499 here.fillInStackTrace(); 11500 Slog.d(TAG, "Sending to user " + id + ": " 11501 + intent.toShortString(false, true, false, false) 11502 + " " + intent.getExtras(), here); 11503 } 11504 am.broadcastIntent(null, intent, null, finishedReceiver, 11505 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11506 null, finishedReceiver != null, false, id); 11507 } 11508 } catch (RemoteException ex) { 11509 } 11510 } 11511 }); 11512 } 11513 11514 /** 11515 * Check if the external storage media is available. This is true if there 11516 * is a mounted external storage medium or if the external storage is 11517 * emulated. 11518 */ 11519 private boolean isExternalMediaAvailable() { 11520 return mMediaMounted || Environment.isExternalStorageEmulated(); 11521 } 11522 11523 @Override 11524 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11525 // writer 11526 synchronized (mPackages) { 11527 if (!isExternalMediaAvailable()) { 11528 // If the external storage is no longer mounted at this point, 11529 // the caller may not have been able to delete all of this 11530 // packages files and can not delete any more. Bail. 11531 return null; 11532 } 11533 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11534 if (lastPackage != null) { 11535 pkgs.remove(lastPackage); 11536 } 11537 if (pkgs.size() > 0) { 11538 return pkgs.get(0); 11539 } 11540 } 11541 return null; 11542 } 11543 11544 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11545 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11546 userId, andCode ? 1 : 0, packageName); 11547 if (mSystemReady) { 11548 msg.sendToTarget(); 11549 } else { 11550 if (mPostSystemReadyMessages == null) { 11551 mPostSystemReadyMessages = new ArrayList<>(); 11552 } 11553 mPostSystemReadyMessages.add(msg); 11554 } 11555 } 11556 11557 void startCleaningPackages() { 11558 // reader 11559 if (!isExternalMediaAvailable()) { 11560 return; 11561 } 11562 synchronized (mPackages) { 11563 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11564 return; 11565 } 11566 } 11567 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11568 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11569 IActivityManager am = ActivityManagerNative.getDefault(); 11570 if (am != null) { 11571 try { 11572 am.startService(null, intent, null, mContext.getOpPackageName(), 11573 UserHandle.USER_SYSTEM); 11574 } catch (RemoteException e) { 11575 } 11576 } 11577 } 11578 11579 @Override 11580 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11581 int installFlags, String installerPackageName, int userId) { 11582 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11583 11584 final int callingUid = Binder.getCallingUid(); 11585 enforceCrossUserPermission(callingUid, userId, 11586 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11587 11588 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11589 try { 11590 if (observer != null) { 11591 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11592 } 11593 } catch (RemoteException re) { 11594 } 11595 return; 11596 } 11597 11598 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11599 installFlags |= PackageManager.INSTALL_FROM_ADB; 11600 11601 } else { 11602 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11603 // about installerPackageName. 11604 11605 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11606 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11607 } 11608 11609 UserHandle user; 11610 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11611 user = UserHandle.ALL; 11612 } else { 11613 user = new UserHandle(userId); 11614 } 11615 11616 // Only system components can circumvent runtime permissions when installing. 11617 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11618 && mContext.checkCallingOrSelfPermission(Manifest.permission 11619 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11620 throw new SecurityException("You need the " 11621 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11622 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11623 } 11624 11625 final File originFile = new File(originPath); 11626 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11627 11628 final Message msg = mHandler.obtainMessage(INIT_COPY); 11629 final VerificationInfo verificationInfo = new VerificationInfo( 11630 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11631 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11632 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11633 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11634 null /*certificates*/); 11635 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11636 msg.obj = params; 11637 11638 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11639 System.identityHashCode(msg.obj)); 11640 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11641 System.identityHashCode(msg.obj)); 11642 11643 mHandler.sendMessage(msg); 11644 } 11645 11646 void installStage(String packageName, File stagedDir, String stagedCid, 11647 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11648 String installerPackageName, int installerUid, UserHandle user, 11649 Certificate[][] certificates) { 11650 if (DEBUG_EPHEMERAL) { 11651 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11652 Slog.d(TAG, "Ephemeral install of " + packageName); 11653 } 11654 } 11655 final VerificationInfo verificationInfo = new VerificationInfo( 11656 sessionParams.originatingUri, sessionParams.referrerUri, 11657 sessionParams.originatingUid, installerUid); 11658 11659 final OriginInfo origin; 11660 if (stagedDir != null) { 11661 origin = OriginInfo.fromStagedFile(stagedDir); 11662 } else { 11663 origin = OriginInfo.fromStagedContainer(stagedCid); 11664 } 11665 11666 final Message msg = mHandler.obtainMessage(INIT_COPY); 11667 final InstallParams params = new InstallParams(origin, null, observer, 11668 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11669 verificationInfo, user, sessionParams.abiOverride, 11670 sessionParams.grantedRuntimePermissions, certificates); 11671 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11672 msg.obj = params; 11673 11674 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11675 System.identityHashCode(msg.obj)); 11676 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11677 System.identityHashCode(msg.obj)); 11678 11679 mHandler.sendMessage(msg); 11680 } 11681 11682 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11683 int userId) { 11684 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11685 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11686 } 11687 11688 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11689 int appId, int userId) { 11690 Bundle extras = new Bundle(1); 11691 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11692 11693 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11694 packageName, extras, 0, null, null, new int[] {userId}); 11695 try { 11696 IActivityManager am = ActivityManagerNative.getDefault(); 11697 if (isSystem && am.isUserRunning(userId, 0)) { 11698 // The just-installed/enabled app is bundled on the system, so presumed 11699 // to be able to run automatically without needing an explicit launch. 11700 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11701 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11702 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11703 .setPackage(packageName); 11704 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11705 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11706 } 11707 } catch (RemoteException e) { 11708 // shouldn't happen 11709 Slog.w(TAG, "Unable to bootstrap installed package", e); 11710 } 11711 } 11712 11713 @Override 11714 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11715 int userId) { 11716 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11717 PackageSetting pkgSetting; 11718 final int uid = Binder.getCallingUid(); 11719 enforceCrossUserPermission(uid, userId, 11720 true /* requireFullPermission */, true /* checkShell */, 11721 "setApplicationHiddenSetting for user " + userId); 11722 11723 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11724 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11725 return false; 11726 } 11727 11728 long callingId = Binder.clearCallingIdentity(); 11729 try { 11730 boolean sendAdded = false; 11731 boolean sendRemoved = false; 11732 // writer 11733 synchronized (mPackages) { 11734 pkgSetting = mSettings.mPackages.get(packageName); 11735 if (pkgSetting == null) { 11736 return false; 11737 } 11738 // Do not allow "android" is being disabled 11739 if ("android".equals(packageName)) { 11740 Slog.w(TAG, "Cannot hide package: android"); 11741 return false; 11742 } 11743 // Only allow protected packages to hide themselves. 11744 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11745 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11746 Slog.w(TAG, "Not hiding protected package: " + packageName); 11747 return false; 11748 } 11749 11750 if (pkgSetting.getHidden(userId) != hidden) { 11751 pkgSetting.setHidden(hidden, userId); 11752 mSettings.writePackageRestrictionsLPr(userId); 11753 if (hidden) { 11754 sendRemoved = true; 11755 } else { 11756 sendAdded = true; 11757 } 11758 } 11759 } 11760 if (sendAdded) { 11761 sendPackageAddedForUser(packageName, pkgSetting, userId); 11762 return true; 11763 } 11764 if (sendRemoved) { 11765 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11766 "hiding pkg"); 11767 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11768 return true; 11769 } 11770 } finally { 11771 Binder.restoreCallingIdentity(callingId); 11772 } 11773 return false; 11774 } 11775 11776 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11777 int userId) { 11778 final PackageRemovedInfo info = new PackageRemovedInfo(); 11779 info.removedPackage = packageName; 11780 info.removedUsers = new int[] {userId}; 11781 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11782 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11783 } 11784 11785 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11786 if (pkgList.length > 0) { 11787 Bundle extras = new Bundle(1); 11788 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11789 11790 sendPackageBroadcast( 11791 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11792 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11793 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11794 new int[] {userId}); 11795 } 11796 } 11797 11798 /** 11799 * Returns true if application is not found or there was an error. Otherwise it returns 11800 * the hidden state of the package for the given user. 11801 */ 11802 @Override 11803 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11804 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11805 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11806 true /* requireFullPermission */, false /* checkShell */, 11807 "getApplicationHidden for user " + userId); 11808 PackageSetting pkgSetting; 11809 long callingId = Binder.clearCallingIdentity(); 11810 try { 11811 // writer 11812 synchronized (mPackages) { 11813 pkgSetting = mSettings.mPackages.get(packageName); 11814 if (pkgSetting == null) { 11815 return true; 11816 } 11817 return pkgSetting.getHidden(userId); 11818 } 11819 } finally { 11820 Binder.restoreCallingIdentity(callingId); 11821 } 11822 } 11823 11824 /** 11825 * @hide 11826 */ 11827 @Override 11828 public int installExistingPackageAsUser(String packageName, int userId) { 11829 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11830 null); 11831 PackageSetting pkgSetting; 11832 final int uid = Binder.getCallingUid(); 11833 enforceCrossUserPermission(uid, userId, 11834 true /* requireFullPermission */, true /* checkShell */, 11835 "installExistingPackage for user " + userId); 11836 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11837 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11838 } 11839 11840 long callingId = Binder.clearCallingIdentity(); 11841 try { 11842 boolean installed = false; 11843 11844 // writer 11845 synchronized (mPackages) { 11846 pkgSetting = mSettings.mPackages.get(packageName); 11847 if (pkgSetting == null) { 11848 return PackageManager.INSTALL_FAILED_INVALID_URI; 11849 } 11850 if (!pkgSetting.getInstalled(userId)) { 11851 pkgSetting.setInstalled(true, userId); 11852 pkgSetting.setHidden(false, userId); 11853 mSettings.writePackageRestrictionsLPr(userId); 11854 installed = true; 11855 } 11856 } 11857 11858 if (installed) { 11859 if (pkgSetting.pkg != null) { 11860 synchronized (mInstallLock) { 11861 // We don't need to freeze for a brand new install 11862 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11863 } 11864 } 11865 sendPackageAddedForUser(packageName, pkgSetting, userId); 11866 } 11867 } finally { 11868 Binder.restoreCallingIdentity(callingId); 11869 } 11870 11871 return PackageManager.INSTALL_SUCCEEDED; 11872 } 11873 11874 boolean isUserRestricted(int userId, String restrictionKey) { 11875 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11876 if (restrictions.getBoolean(restrictionKey, false)) { 11877 Log.w(TAG, "User is restricted: " + restrictionKey); 11878 return true; 11879 } 11880 return false; 11881 } 11882 11883 @Override 11884 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11885 int userId) { 11886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11887 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11888 true /* requireFullPermission */, true /* checkShell */, 11889 "setPackagesSuspended for user " + userId); 11890 11891 if (ArrayUtils.isEmpty(packageNames)) { 11892 return packageNames; 11893 } 11894 11895 // List of package names for whom the suspended state has changed. 11896 List<String> changedPackages = new ArrayList<>(packageNames.length); 11897 // List of package names for whom the suspended state is not set as requested in this 11898 // method. 11899 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11900 long callingId = Binder.clearCallingIdentity(); 11901 try { 11902 for (int i = 0; i < packageNames.length; i++) { 11903 String packageName = packageNames[i]; 11904 boolean changed = false; 11905 final int appId; 11906 synchronized (mPackages) { 11907 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11908 if (pkgSetting == null) { 11909 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11910 + "\". Skipping suspending/un-suspending."); 11911 unactionedPackages.add(packageName); 11912 continue; 11913 } 11914 appId = pkgSetting.appId; 11915 if (pkgSetting.getSuspended(userId) != suspended) { 11916 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11917 unactionedPackages.add(packageName); 11918 continue; 11919 } 11920 pkgSetting.setSuspended(suspended, userId); 11921 mSettings.writePackageRestrictionsLPr(userId); 11922 changed = true; 11923 changedPackages.add(packageName); 11924 } 11925 } 11926 11927 if (changed && suspended) { 11928 killApplication(packageName, UserHandle.getUid(userId, appId), 11929 "suspending package"); 11930 } 11931 } 11932 } finally { 11933 Binder.restoreCallingIdentity(callingId); 11934 } 11935 11936 if (!changedPackages.isEmpty()) { 11937 sendPackagesSuspendedForUser(changedPackages.toArray( 11938 new String[changedPackages.size()]), userId, suspended); 11939 } 11940 11941 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11942 } 11943 11944 @Override 11945 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11946 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11947 true /* requireFullPermission */, false /* checkShell */, 11948 "isPackageSuspendedForUser for user " + userId); 11949 synchronized (mPackages) { 11950 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11951 if (pkgSetting == null) { 11952 throw new IllegalArgumentException("Unknown target package: " + packageName); 11953 } 11954 return pkgSetting.getSuspended(userId); 11955 } 11956 } 11957 11958 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11959 if (isPackageDeviceAdmin(packageName, userId)) { 11960 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11961 + "\": has an active device admin"); 11962 return false; 11963 } 11964 11965 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11966 if (packageName.equals(activeLauncherPackageName)) { 11967 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11968 + "\": contains the active launcher"); 11969 return false; 11970 } 11971 11972 if (packageName.equals(mRequiredInstallerPackage)) { 11973 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11974 + "\": required for package installation"); 11975 return false; 11976 } 11977 11978 if (packageName.equals(mRequiredUninstallerPackage)) { 11979 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11980 + "\": required for package uninstallation"); 11981 return false; 11982 } 11983 11984 if (packageName.equals(mRequiredVerifierPackage)) { 11985 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11986 + "\": required for package verification"); 11987 return false; 11988 } 11989 11990 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11991 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11992 + "\": is the default dialer"); 11993 return false; 11994 } 11995 11996 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11997 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11998 + "\": protected package"); 11999 return false; 12000 } 12001 12002 return true; 12003 } 12004 12005 private String getActiveLauncherPackageName(int userId) { 12006 Intent intent = new Intent(Intent.ACTION_MAIN); 12007 intent.addCategory(Intent.CATEGORY_HOME); 12008 ResolveInfo resolveInfo = resolveIntent( 12009 intent, 12010 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12011 PackageManager.MATCH_DEFAULT_ONLY, 12012 userId); 12013 12014 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12015 } 12016 12017 private String getDefaultDialerPackageName(int userId) { 12018 synchronized (mPackages) { 12019 return mSettings.getDefaultDialerPackageNameLPw(userId); 12020 } 12021 } 12022 12023 @Override 12024 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12025 mContext.enforceCallingOrSelfPermission( 12026 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12027 "Only package verification agents can verify applications"); 12028 12029 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12030 final PackageVerificationResponse response = new PackageVerificationResponse( 12031 verificationCode, Binder.getCallingUid()); 12032 msg.arg1 = id; 12033 msg.obj = response; 12034 mHandler.sendMessage(msg); 12035 } 12036 12037 @Override 12038 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12039 long millisecondsToDelay) { 12040 mContext.enforceCallingOrSelfPermission( 12041 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12042 "Only package verification agents can extend verification timeouts"); 12043 12044 final PackageVerificationState state = mPendingVerification.get(id); 12045 final PackageVerificationResponse response = new PackageVerificationResponse( 12046 verificationCodeAtTimeout, Binder.getCallingUid()); 12047 12048 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12049 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12050 } 12051 if (millisecondsToDelay < 0) { 12052 millisecondsToDelay = 0; 12053 } 12054 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12055 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12056 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12057 } 12058 12059 if ((state != null) && !state.timeoutExtended()) { 12060 state.extendTimeout(); 12061 12062 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12063 msg.arg1 = id; 12064 msg.obj = response; 12065 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12066 } 12067 } 12068 12069 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12070 int verificationCode, UserHandle user) { 12071 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12072 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12073 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12074 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12075 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12076 12077 mContext.sendBroadcastAsUser(intent, user, 12078 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12079 } 12080 12081 private ComponentName matchComponentForVerifier(String packageName, 12082 List<ResolveInfo> receivers) { 12083 ActivityInfo targetReceiver = null; 12084 12085 final int NR = receivers.size(); 12086 for (int i = 0; i < NR; i++) { 12087 final ResolveInfo info = receivers.get(i); 12088 if (info.activityInfo == null) { 12089 continue; 12090 } 12091 12092 if (packageName.equals(info.activityInfo.packageName)) { 12093 targetReceiver = info.activityInfo; 12094 break; 12095 } 12096 } 12097 12098 if (targetReceiver == null) { 12099 return null; 12100 } 12101 12102 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12103 } 12104 12105 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12106 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12107 if (pkgInfo.verifiers.length == 0) { 12108 return null; 12109 } 12110 12111 final int N = pkgInfo.verifiers.length; 12112 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12113 for (int i = 0; i < N; i++) { 12114 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12115 12116 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12117 receivers); 12118 if (comp == null) { 12119 continue; 12120 } 12121 12122 final int verifierUid = getUidForVerifier(verifierInfo); 12123 if (verifierUid == -1) { 12124 continue; 12125 } 12126 12127 if (DEBUG_VERIFY) { 12128 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12129 + " with the correct signature"); 12130 } 12131 sufficientVerifiers.add(comp); 12132 verificationState.addSufficientVerifier(verifierUid); 12133 } 12134 12135 return sufficientVerifiers; 12136 } 12137 12138 private int getUidForVerifier(VerifierInfo verifierInfo) { 12139 synchronized (mPackages) { 12140 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12141 if (pkg == null) { 12142 return -1; 12143 } else if (pkg.mSignatures.length != 1) { 12144 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12145 + " has more than one signature; ignoring"); 12146 return -1; 12147 } 12148 12149 /* 12150 * If the public key of the package's signature does not match 12151 * our expected public key, then this is a different package and 12152 * we should skip. 12153 */ 12154 12155 final byte[] expectedPublicKey; 12156 try { 12157 final Signature verifierSig = pkg.mSignatures[0]; 12158 final PublicKey publicKey = verifierSig.getPublicKey(); 12159 expectedPublicKey = publicKey.getEncoded(); 12160 } catch (CertificateException e) { 12161 return -1; 12162 } 12163 12164 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12165 12166 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12167 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12168 + " does not have the expected public key; ignoring"); 12169 return -1; 12170 } 12171 12172 return pkg.applicationInfo.uid; 12173 } 12174 } 12175 12176 @Override 12177 public void finishPackageInstall(int token, boolean didLaunch) { 12178 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12179 12180 if (DEBUG_INSTALL) { 12181 Slog.v(TAG, "BM finishing package install for " + token); 12182 } 12183 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12184 12185 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12186 mHandler.sendMessage(msg); 12187 } 12188 12189 /** 12190 * Get the verification agent timeout. 12191 * 12192 * @return verification timeout in milliseconds 12193 */ 12194 private long getVerificationTimeout() { 12195 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12196 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12197 DEFAULT_VERIFICATION_TIMEOUT); 12198 } 12199 12200 /** 12201 * Get the default verification agent response code. 12202 * 12203 * @return default verification response code 12204 */ 12205 private int getDefaultVerificationResponse() { 12206 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12207 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12208 DEFAULT_VERIFICATION_RESPONSE); 12209 } 12210 12211 /** 12212 * Check whether or not package verification has been enabled. 12213 * 12214 * @return true if verification should be performed 12215 */ 12216 private boolean isVerificationEnabled(int userId, int installFlags) { 12217 if (!DEFAULT_VERIFY_ENABLE) { 12218 return false; 12219 } 12220 // Ephemeral apps don't get the full verification treatment 12221 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12222 if (DEBUG_EPHEMERAL) { 12223 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12224 } 12225 return false; 12226 } 12227 12228 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12229 12230 // Check if installing from ADB 12231 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12232 // Do not run verification in a test harness environment 12233 if (ActivityManager.isRunningInTestHarness()) { 12234 return false; 12235 } 12236 if (ensureVerifyAppsEnabled) { 12237 return true; 12238 } 12239 // Check if the developer does not want package verification for ADB installs 12240 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12241 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12242 return false; 12243 } 12244 } 12245 12246 if (ensureVerifyAppsEnabled) { 12247 return true; 12248 } 12249 12250 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12251 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12252 } 12253 12254 @Override 12255 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12256 throws RemoteException { 12257 mContext.enforceCallingOrSelfPermission( 12258 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12259 "Only intentfilter verification agents can verify applications"); 12260 12261 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12262 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12263 Binder.getCallingUid(), verificationCode, failedDomains); 12264 msg.arg1 = id; 12265 msg.obj = response; 12266 mHandler.sendMessage(msg); 12267 } 12268 12269 @Override 12270 public int getIntentVerificationStatus(String packageName, int userId) { 12271 synchronized (mPackages) { 12272 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12273 } 12274 } 12275 12276 @Override 12277 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12278 mContext.enforceCallingOrSelfPermission( 12279 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12280 12281 boolean result = false; 12282 synchronized (mPackages) { 12283 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12284 } 12285 if (result) { 12286 scheduleWritePackageRestrictionsLocked(userId); 12287 } 12288 return result; 12289 } 12290 12291 @Override 12292 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12293 String packageName) { 12294 synchronized (mPackages) { 12295 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12296 } 12297 } 12298 12299 @Override 12300 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12301 if (TextUtils.isEmpty(packageName)) { 12302 return ParceledListSlice.emptyList(); 12303 } 12304 synchronized (mPackages) { 12305 PackageParser.Package pkg = mPackages.get(packageName); 12306 if (pkg == null || pkg.activities == null) { 12307 return ParceledListSlice.emptyList(); 12308 } 12309 final int count = pkg.activities.size(); 12310 ArrayList<IntentFilter> result = new ArrayList<>(); 12311 for (int n=0; n<count; n++) { 12312 PackageParser.Activity activity = pkg.activities.get(n); 12313 if (activity.intents != null && activity.intents.size() > 0) { 12314 result.addAll(activity.intents); 12315 } 12316 } 12317 return new ParceledListSlice<>(result); 12318 } 12319 } 12320 12321 @Override 12322 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12323 mContext.enforceCallingOrSelfPermission( 12324 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12325 12326 synchronized (mPackages) { 12327 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12328 if (packageName != null) { 12329 result |= updateIntentVerificationStatus(packageName, 12330 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12331 userId); 12332 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12333 packageName, userId); 12334 } 12335 return result; 12336 } 12337 } 12338 12339 @Override 12340 public String getDefaultBrowserPackageName(int userId) { 12341 synchronized (mPackages) { 12342 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12343 } 12344 } 12345 12346 /** 12347 * Get the "allow unknown sources" setting. 12348 * 12349 * @return the current "allow unknown sources" setting 12350 */ 12351 private int getUnknownSourcesSettings() { 12352 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12353 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12354 -1); 12355 } 12356 12357 @Override 12358 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12359 final int uid = Binder.getCallingUid(); 12360 // writer 12361 synchronized (mPackages) { 12362 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12363 if (targetPackageSetting == null) { 12364 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12365 } 12366 12367 PackageSetting installerPackageSetting; 12368 if (installerPackageName != null) { 12369 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12370 if (installerPackageSetting == null) { 12371 throw new IllegalArgumentException("Unknown installer package: " 12372 + installerPackageName); 12373 } 12374 } else { 12375 installerPackageSetting = null; 12376 } 12377 12378 Signature[] callerSignature; 12379 Object obj = mSettings.getUserIdLPr(uid); 12380 if (obj != null) { 12381 if (obj instanceof SharedUserSetting) { 12382 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12383 } else if (obj instanceof PackageSetting) { 12384 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12385 } else { 12386 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12387 } 12388 } else { 12389 throw new SecurityException("Unknown calling UID: " + uid); 12390 } 12391 12392 // Verify: can't set installerPackageName to a package that is 12393 // not signed with the same cert as the caller. 12394 if (installerPackageSetting != null) { 12395 if (compareSignatures(callerSignature, 12396 installerPackageSetting.signatures.mSignatures) 12397 != PackageManager.SIGNATURE_MATCH) { 12398 throw new SecurityException( 12399 "Caller does not have same cert as new installer package " 12400 + installerPackageName); 12401 } 12402 } 12403 12404 // Verify: if target already has an installer package, it must 12405 // be signed with the same cert as the caller. 12406 if (targetPackageSetting.installerPackageName != null) { 12407 PackageSetting setting = mSettings.mPackages.get( 12408 targetPackageSetting.installerPackageName); 12409 // If the currently set package isn't valid, then it's always 12410 // okay to change it. 12411 if (setting != null) { 12412 if (compareSignatures(callerSignature, 12413 setting.signatures.mSignatures) 12414 != PackageManager.SIGNATURE_MATCH) { 12415 throw new SecurityException( 12416 "Caller does not have same cert as old installer package " 12417 + targetPackageSetting.installerPackageName); 12418 } 12419 } 12420 } 12421 12422 // Okay! 12423 targetPackageSetting.installerPackageName = installerPackageName; 12424 if (installerPackageName != null) { 12425 mSettings.mInstallerPackages.add(installerPackageName); 12426 } 12427 scheduleWriteSettingsLocked(); 12428 } 12429 } 12430 12431 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12432 // Queue up an async operation since the package installation may take a little while. 12433 mHandler.post(new Runnable() { 12434 public void run() { 12435 mHandler.removeCallbacks(this); 12436 // Result object to be returned 12437 PackageInstalledInfo res = new PackageInstalledInfo(); 12438 res.setReturnCode(currentStatus); 12439 res.uid = -1; 12440 res.pkg = null; 12441 res.removedInfo = null; 12442 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12443 args.doPreInstall(res.returnCode); 12444 synchronized (mInstallLock) { 12445 installPackageTracedLI(args, res); 12446 } 12447 args.doPostInstall(res.returnCode, res.uid); 12448 } 12449 12450 // A restore should be performed at this point if (a) the install 12451 // succeeded, (b) the operation is not an update, and (c) the new 12452 // package has not opted out of backup participation. 12453 final boolean update = res.removedInfo != null 12454 && res.removedInfo.removedPackage != null; 12455 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12456 boolean doRestore = !update 12457 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12458 12459 // Set up the post-install work request bookkeeping. This will be used 12460 // and cleaned up by the post-install event handling regardless of whether 12461 // there's a restore pass performed. Token values are >= 1. 12462 int token; 12463 if (mNextInstallToken < 0) mNextInstallToken = 1; 12464 token = mNextInstallToken++; 12465 12466 PostInstallData data = new PostInstallData(args, res); 12467 mRunningInstalls.put(token, data); 12468 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12469 12470 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12471 // Pass responsibility to the Backup Manager. It will perform a 12472 // restore if appropriate, then pass responsibility back to the 12473 // Package Manager to run the post-install observer callbacks 12474 // and broadcasts. 12475 IBackupManager bm = IBackupManager.Stub.asInterface( 12476 ServiceManager.getService(Context.BACKUP_SERVICE)); 12477 if (bm != null) { 12478 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12479 + " to BM for possible restore"); 12480 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12481 try { 12482 // TODO: http://b/22388012 12483 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12484 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12485 } else { 12486 doRestore = false; 12487 } 12488 } catch (RemoteException e) { 12489 // can't happen; the backup manager is local 12490 } catch (Exception e) { 12491 Slog.e(TAG, "Exception trying to enqueue restore", e); 12492 doRestore = false; 12493 } 12494 } else { 12495 Slog.e(TAG, "Backup Manager not found!"); 12496 doRestore = false; 12497 } 12498 } 12499 12500 if (!doRestore) { 12501 // No restore possible, or the Backup Manager was mysteriously not 12502 // available -- just fire the post-install work request directly. 12503 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12504 12505 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12506 12507 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12508 mHandler.sendMessage(msg); 12509 } 12510 } 12511 }); 12512 } 12513 12514 /** 12515 * Callback from PackageSettings whenever an app is first transitioned out of the 12516 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12517 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12518 * here whether the app is the target of an ongoing install, and only send the 12519 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12520 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12521 * handling. 12522 */ 12523 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12524 // Serialize this with the rest of the install-process message chain. In the 12525 // restore-at-install case, this Runnable will necessarily run before the 12526 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12527 // are coherent. In the non-restore case, the app has already completed install 12528 // and been launched through some other means, so it is not in a problematic 12529 // state for observers to see the FIRST_LAUNCH signal. 12530 mHandler.post(new Runnable() { 12531 @Override 12532 public void run() { 12533 for (int i = 0; i < mRunningInstalls.size(); i++) { 12534 final PostInstallData data = mRunningInstalls.valueAt(i); 12535 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12536 continue; 12537 } 12538 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12539 // right package; but is it for the right user? 12540 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12541 if (userId == data.res.newUsers[uIndex]) { 12542 if (DEBUG_BACKUP) { 12543 Slog.i(TAG, "Package " + pkgName 12544 + " being restored so deferring FIRST_LAUNCH"); 12545 } 12546 return; 12547 } 12548 } 12549 } 12550 } 12551 // didn't find it, so not being restored 12552 if (DEBUG_BACKUP) { 12553 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12554 } 12555 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12556 } 12557 }); 12558 } 12559 12560 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12561 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12562 installerPkg, null, userIds); 12563 } 12564 12565 private abstract class HandlerParams { 12566 private static final int MAX_RETRIES = 4; 12567 12568 /** 12569 * Number of times startCopy() has been attempted and had a non-fatal 12570 * error. 12571 */ 12572 private int mRetries = 0; 12573 12574 /** User handle for the user requesting the information or installation. */ 12575 private final UserHandle mUser; 12576 String traceMethod; 12577 int traceCookie; 12578 12579 HandlerParams(UserHandle user) { 12580 mUser = user; 12581 } 12582 12583 UserHandle getUser() { 12584 return mUser; 12585 } 12586 12587 HandlerParams setTraceMethod(String traceMethod) { 12588 this.traceMethod = traceMethod; 12589 return this; 12590 } 12591 12592 HandlerParams setTraceCookie(int traceCookie) { 12593 this.traceCookie = traceCookie; 12594 return this; 12595 } 12596 12597 final boolean startCopy() { 12598 boolean res; 12599 try { 12600 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12601 12602 if (++mRetries > MAX_RETRIES) { 12603 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12604 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12605 handleServiceError(); 12606 return false; 12607 } else { 12608 handleStartCopy(); 12609 res = true; 12610 } 12611 } catch (RemoteException e) { 12612 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12613 mHandler.sendEmptyMessage(MCS_RECONNECT); 12614 res = false; 12615 } 12616 handleReturnCode(); 12617 return res; 12618 } 12619 12620 final void serviceError() { 12621 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12622 handleServiceError(); 12623 handleReturnCode(); 12624 } 12625 12626 abstract void handleStartCopy() throws RemoteException; 12627 abstract void handleServiceError(); 12628 abstract void handleReturnCode(); 12629 } 12630 12631 class MeasureParams extends HandlerParams { 12632 private final PackageStats mStats; 12633 private boolean mSuccess; 12634 12635 private final IPackageStatsObserver mObserver; 12636 12637 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12638 super(new UserHandle(stats.userHandle)); 12639 mObserver = observer; 12640 mStats = stats; 12641 } 12642 12643 @Override 12644 public String toString() { 12645 return "MeasureParams{" 12646 + Integer.toHexString(System.identityHashCode(this)) 12647 + " " + mStats.packageName + "}"; 12648 } 12649 12650 @Override 12651 void handleStartCopy() throws RemoteException { 12652 synchronized (mInstallLock) { 12653 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12654 } 12655 12656 if (mSuccess) { 12657 boolean mounted = false; 12658 try { 12659 final String status = Environment.getExternalStorageState(); 12660 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12661 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12662 } catch (Exception e) { 12663 } 12664 12665 if (mounted) { 12666 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12667 12668 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12669 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12670 12671 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12672 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12673 12674 // Always subtract cache size, since it's a subdirectory 12675 mStats.externalDataSize -= mStats.externalCacheSize; 12676 12677 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12678 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12679 12680 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12681 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12682 } 12683 } 12684 } 12685 12686 @Override 12687 void handleReturnCode() { 12688 if (mObserver != null) { 12689 try { 12690 mObserver.onGetStatsCompleted(mStats, mSuccess); 12691 } catch (RemoteException e) { 12692 Slog.i(TAG, "Observer no longer exists."); 12693 } 12694 } 12695 } 12696 12697 @Override 12698 void handleServiceError() { 12699 Slog.e(TAG, "Could not measure application " + mStats.packageName 12700 + " external storage"); 12701 } 12702 } 12703 12704 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12705 throws RemoteException { 12706 long result = 0; 12707 for (File path : paths) { 12708 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12709 } 12710 return result; 12711 } 12712 12713 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12714 for (File path : paths) { 12715 try { 12716 mcs.clearDirectory(path.getAbsolutePath()); 12717 } catch (RemoteException e) { 12718 } 12719 } 12720 } 12721 12722 static class OriginInfo { 12723 /** 12724 * Location where install is coming from, before it has been 12725 * copied/renamed into place. This could be a single monolithic APK 12726 * file, or a cluster directory. This location may be untrusted. 12727 */ 12728 final File file; 12729 final String cid; 12730 12731 /** 12732 * Flag indicating that {@link #file} or {@link #cid} has already been 12733 * staged, meaning downstream users don't need to defensively copy the 12734 * contents. 12735 */ 12736 final boolean staged; 12737 12738 /** 12739 * Flag indicating that {@link #file} or {@link #cid} is an already 12740 * installed app that is being moved. 12741 */ 12742 final boolean existing; 12743 12744 final String resolvedPath; 12745 final File resolvedFile; 12746 12747 static OriginInfo fromNothing() { 12748 return new OriginInfo(null, null, false, false); 12749 } 12750 12751 static OriginInfo fromUntrustedFile(File file) { 12752 return new OriginInfo(file, null, false, false); 12753 } 12754 12755 static OriginInfo fromExistingFile(File file) { 12756 return new OriginInfo(file, null, false, true); 12757 } 12758 12759 static OriginInfo fromStagedFile(File file) { 12760 return new OriginInfo(file, null, true, false); 12761 } 12762 12763 static OriginInfo fromStagedContainer(String cid) { 12764 return new OriginInfo(null, cid, true, false); 12765 } 12766 12767 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12768 this.file = file; 12769 this.cid = cid; 12770 this.staged = staged; 12771 this.existing = existing; 12772 12773 if (cid != null) { 12774 resolvedPath = PackageHelper.getSdDir(cid); 12775 resolvedFile = new File(resolvedPath); 12776 } else if (file != null) { 12777 resolvedPath = file.getAbsolutePath(); 12778 resolvedFile = file; 12779 } else { 12780 resolvedPath = null; 12781 resolvedFile = null; 12782 } 12783 } 12784 } 12785 12786 static class MoveInfo { 12787 final int moveId; 12788 final String fromUuid; 12789 final String toUuid; 12790 final String packageName; 12791 final String dataAppName; 12792 final int appId; 12793 final String seinfo; 12794 final int targetSdkVersion; 12795 12796 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12797 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12798 this.moveId = moveId; 12799 this.fromUuid = fromUuid; 12800 this.toUuid = toUuid; 12801 this.packageName = packageName; 12802 this.dataAppName = dataAppName; 12803 this.appId = appId; 12804 this.seinfo = seinfo; 12805 this.targetSdkVersion = targetSdkVersion; 12806 } 12807 } 12808 12809 static class VerificationInfo { 12810 /** A constant used to indicate that a uid value is not present. */ 12811 public static final int NO_UID = -1; 12812 12813 /** URI referencing where the package was downloaded from. */ 12814 final Uri originatingUri; 12815 12816 /** HTTP referrer URI associated with the originatingURI. */ 12817 final Uri referrer; 12818 12819 /** UID of the application that the install request originated from. */ 12820 final int originatingUid; 12821 12822 /** UID of application requesting the install */ 12823 final int installerUid; 12824 12825 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12826 this.originatingUri = originatingUri; 12827 this.referrer = referrer; 12828 this.originatingUid = originatingUid; 12829 this.installerUid = installerUid; 12830 } 12831 } 12832 12833 class InstallParams extends HandlerParams { 12834 final OriginInfo origin; 12835 final MoveInfo move; 12836 final IPackageInstallObserver2 observer; 12837 int installFlags; 12838 final String installerPackageName; 12839 final String volumeUuid; 12840 private InstallArgs mArgs; 12841 private int mRet; 12842 final String packageAbiOverride; 12843 final String[] grantedRuntimePermissions; 12844 final VerificationInfo verificationInfo; 12845 final Certificate[][] certificates; 12846 12847 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12848 int installFlags, String installerPackageName, String volumeUuid, 12849 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12850 String[] grantedPermissions, Certificate[][] certificates) { 12851 super(user); 12852 this.origin = origin; 12853 this.move = move; 12854 this.observer = observer; 12855 this.installFlags = installFlags; 12856 this.installerPackageName = installerPackageName; 12857 this.volumeUuid = volumeUuid; 12858 this.verificationInfo = verificationInfo; 12859 this.packageAbiOverride = packageAbiOverride; 12860 this.grantedRuntimePermissions = grantedPermissions; 12861 this.certificates = certificates; 12862 } 12863 12864 @Override 12865 public String toString() { 12866 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12867 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12868 } 12869 12870 private int installLocationPolicy(PackageInfoLite pkgLite) { 12871 String packageName = pkgLite.packageName; 12872 int installLocation = pkgLite.installLocation; 12873 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12874 // reader 12875 synchronized (mPackages) { 12876 // Currently installed package which the new package is attempting to replace or 12877 // null if no such package is installed. 12878 PackageParser.Package installedPkg = mPackages.get(packageName); 12879 // Package which currently owns the data which the new package will own if installed. 12880 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12881 // will be null whereas dataOwnerPkg will contain information about the package 12882 // which was uninstalled while keeping its data. 12883 PackageParser.Package dataOwnerPkg = installedPkg; 12884 if (dataOwnerPkg == null) { 12885 PackageSetting ps = mSettings.mPackages.get(packageName); 12886 if (ps != null) { 12887 dataOwnerPkg = ps.pkg; 12888 } 12889 } 12890 12891 if (dataOwnerPkg != null) { 12892 // If installed, the package will get access to data left on the device by its 12893 // predecessor. As a security measure, this is permited only if this is not a 12894 // version downgrade or if the predecessor package is marked as debuggable and 12895 // a downgrade is explicitly requested. 12896 // 12897 // On debuggable platform builds, downgrades are permitted even for 12898 // non-debuggable packages to make testing easier. Debuggable platform builds do 12899 // not offer security guarantees and thus it's OK to disable some security 12900 // mechanisms to make debugging/testing easier on those builds. However, even on 12901 // debuggable builds downgrades of packages are permitted only if requested via 12902 // installFlags. This is because we aim to keep the behavior of debuggable 12903 // platform builds as close as possible to the behavior of non-debuggable 12904 // platform builds. 12905 final boolean downgradeRequested = 12906 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12907 final boolean packageDebuggable = 12908 (dataOwnerPkg.applicationInfo.flags 12909 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12910 final boolean downgradePermitted = 12911 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12912 if (!downgradePermitted) { 12913 try { 12914 checkDowngrade(dataOwnerPkg, pkgLite); 12915 } catch (PackageManagerException e) { 12916 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12917 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12918 } 12919 } 12920 } 12921 12922 if (installedPkg != null) { 12923 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12924 // Check for updated system application. 12925 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12926 if (onSd) { 12927 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12928 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12929 } 12930 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12931 } else { 12932 if (onSd) { 12933 // Install flag overrides everything. 12934 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12935 } 12936 // If current upgrade specifies particular preference 12937 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12938 // Application explicitly specified internal. 12939 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12940 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12941 // App explictly prefers external. Let policy decide 12942 } else { 12943 // Prefer previous location 12944 if (isExternal(installedPkg)) { 12945 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12946 } 12947 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12948 } 12949 } 12950 } else { 12951 // Invalid install. Return error code 12952 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12953 } 12954 } 12955 } 12956 // All the special cases have been taken care of. 12957 // Return result based on recommended install location. 12958 if (onSd) { 12959 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12960 } 12961 return pkgLite.recommendedInstallLocation; 12962 } 12963 12964 /* 12965 * Invoke remote method to get package information and install 12966 * location values. Override install location based on default 12967 * policy if needed and then create install arguments based 12968 * on the install location. 12969 */ 12970 public void handleStartCopy() throws RemoteException { 12971 int ret = PackageManager.INSTALL_SUCCEEDED; 12972 12973 // If we're already staged, we've firmly committed to an install location 12974 if (origin.staged) { 12975 if (origin.file != null) { 12976 installFlags |= PackageManager.INSTALL_INTERNAL; 12977 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12978 } else if (origin.cid != null) { 12979 installFlags |= PackageManager.INSTALL_EXTERNAL; 12980 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12981 } else { 12982 throw new IllegalStateException("Invalid stage location"); 12983 } 12984 } 12985 12986 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12987 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12988 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12989 PackageInfoLite pkgLite = null; 12990 12991 if (onInt && onSd) { 12992 // Check if both bits are set. 12993 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12994 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12995 } else if (onSd && ephemeral) { 12996 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12997 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12998 } else { 12999 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13000 packageAbiOverride); 13001 13002 if (DEBUG_EPHEMERAL && ephemeral) { 13003 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13004 } 13005 13006 /* 13007 * If we have too little free space, try to free cache 13008 * before giving up. 13009 */ 13010 if (!origin.staged && pkgLite.recommendedInstallLocation 13011 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13012 // TODO: focus freeing disk space on the target device 13013 final StorageManager storage = StorageManager.from(mContext); 13014 final long lowThreshold = storage.getStorageLowBytes( 13015 Environment.getDataDirectory()); 13016 13017 final long sizeBytes = mContainerService.calculateInstalledSize( 13018 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13019 13020 try { 13021 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13022 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13023 installFlags, packageAbiOverride); 13024 } catch (InstallerException e) { 13025 Slog.w(TAG, "Failed to free cache", e); 13026 } 13027 13028 /* 13029 * The cache free must have deleted the file we 13030 * downloaded to install. 13031 * 13032 * TODO: fix the "freeCache" call to not delete 13033 * the file we care about. 13034 */ 13035 if (pkgLite.recommendedInstallLocation 13036 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13037 pkgLite.recommendedInstallLocation 13038 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13039 } 13040 } 13041 } 13042 13043 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13044 int loc = pkgLite.recommendedInstallLocation; 13045 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13046 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13047 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13048 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13049 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13050 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13051 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13052 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13053 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13054 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13055 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13056 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13057 } else { 13058 // Override with defaults if needed. 13059 loc = installLocationPolicy(pkgLite); 13060 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13061 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13062 } else if (!onSd && !onInt) { 13063 // Override install location with flags 13064 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13065 // Set the flag to install on external media. 13066 installFlags |= PackageManager.INSTALL_EXTERNAL; 13067 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13068 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13069 if (DEBUG_EPHEMERAL) { 13070 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13071 } 13072 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13073 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13074 |PackageManager.INSTALL_INTERNAL); 13075 } else { 13076 // Make sure the flag for installing on external 13077 // media is unset 13078 installFlags |= PackageManager.INSTALL_INTERNAL; 13079 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13080 } 13081 } 13082 } 13083 } 13084 13085 final InstallArgs args = createInstallArgs(this); 13086 mArgs = args; 13087 13088 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13089 // TODO: http://b/22976637 13090 // Apps installed for "all" users use the device owner to verify the app 13091 UserHandle verifierUser = getUser(); 13092 if (verifierUser == UserHandle.ALL) { 13093 verifierUser = UserHandle.SYSTEM; 13094 } 13095 13096 /* 13097 * Determine if we have any installed package verifiers. If we 13098 * do, then we'll defer to them to verify the packages. 13099 */ 13100 final int requiredUid = mRequiredVerifierPackage == null ? -1 13101 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13102 verifierUser.getIdentifier()); 13103 if (!origin.existing && requiredUid != -1 13104 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13105 final Intent verification = new Intent( 13106 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13107 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13108 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13109 PACKAGE_MIME_TYPE); 13110 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13111 13112 // Query all live verifiers based on current user state 13113 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13114 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13115 13116 if (DEBUG_VERIFY) { 13117 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13118 + verification.toString() + " with " + pkgLite.verifiers.length 13119 + " optional verifiers"); 13120 } 13121 13122 final int verificationId = mPendingVerificationToken++; 13123 13124 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13125 13126 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13127 installerPackageName); 13128 13129 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13130 installFlags); 13131 13132 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13133 pkgLite.packageName); 13134 13135 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13136 pkgLite.versionCode); 13137 13138 if (verificationInfo != null) { 13139 if (verificationInfo.originatingUri != null) { 13140 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13141 verificationInfo.originatingUri); 13142 } 13143 if (verificationInfo.referrer != null) { 13144 verification.putExtra(Intent.EXTRA_REFERRER, 13145 verificationInfo.referrer); 13146 } 13147 if (verificationInfo.originatingUid >= 0) { 13148 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13149 verificationInfo.originatingUid); 13150 } 13151 if (verificationInfo.installerUid >= 0) { 13152 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13153 verificationInfo.installerUid); 13154 } 13155 } 13156 13157 final PackageVerificationState verificationState = new PackageVerificationState( 13158 requiredUid, args); 13159 13160 mPendingVerification.append(verificationId, verificationState); 13161 13162 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13163 receivers, verificationState); 13164 13165 /* 13166 * If any sufficient verifiers were listed in the package 13167 * manifest, attempt to ask them. 13168 */ 13169 if (sufficientVerifiers != null) { 13170 final int N = sufficientVerifiers.size(); 13171 if (N == 0) { 13172 Slog.i(TAG, "Additional verifiers required, but none installed."); 13173 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13174 } else { 13175 for (int i = 0; i < N; i++) { 13176 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13177 13178 final Intent sufficientIntent = new Intent(verification); 13179 sufficientIntent.setComponent(verifierComponent); 13180 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13181 } 13182 } 13183 } 13184 13185 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13186 mRequiredVerifierPackage, receivers); 13187 if (ret == PackageManager.INSTALL_SUCCEEDED 13188 && mRequiredVerifierPackage != null) { 13189 Trace.asyncTraceBegin( 13190 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13191 /* 13192 * Send the intent to the required verification agent, 13193 * but only start the verification timeout after the 13194 * target BroadcastReceivers have run. 13195 */ 13196 verification.setComponent(requiredVerifierComponent); 13197 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13198 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13199 new BroadcastReceiver() { 13200 @Override 13201 public void onReceive(Context context, Intent intent) { 13202 final Message msg = mHandler 13203 .obtainMessage(CHECK_PENDING_VERIFICATION); 13204 msg.arg1 = verificationId; 13205 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13206 } 13207 }, null, 0, null, null); 13208 13209 /* 13210 * We don't want the copy to proceed until verification 13211 * succeeds, so null out this field. 13212 */ 13213 mArgs = null; 13214 } 13215 } else { 13216 /* 13217 * No package verification is enabled, so immediately start 13218 * the remote call to initiate copy using temporary file. 13219 */ 13220 ret = args.copyApk(mContainerService, true); 13221 } 13222 } 13223 13224 mRet = ret; 13225 } 13226 13227 @Override 13228 void handleReturnCode() { 13229 // If mArgs is null, then MCS couldn't be reached. When it 13230 // reconnects, it will try again to install. At that point, this 13231 // will succeed. 13232 if (mArgs != null) { 13233 processPendingInstall(mArgs, mRet); 13234 } 13235 } 13236 13237 @Override 13238 void handleServiceError() { 13239 mArgs = createInstallArgs(this); 13240 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13241 } 13242 13243 public boolean isForwardLocked() { 13244 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13245 } 13246 } 13247 13248 /** 13249 * Used during creation of InstallArgs 13250 * 13251 * @param installFlags package installation flags 13252 * @return true if should be installed on external storage 13253 */ 13254 private static boolean installOnExternalAsec(int installFlags) { 13255 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13256 return false; 13257 } 13258 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13259 return true; 13260 } 13261 return false; 13262 } 13263 13264 /** 13265 * Used during creation of InstallArgs 13266 * 13267 * @param installFlags package installation flags 13268 * @return true if should be installed as forward locked 13269 */ 13270 private static boolean installForwardLocked(int installFlags) { 13271 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13272 } 13273 13274 private InstallArgs createInstallArgs(InstallParams params) { 13275 if (params.move != null) { 13276 return new MoveInstallArgs(params); 13277 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13278 return new AsecInstallArgs(params); 13279 } else { 13280 return new FileInstallArgs(params); 13281 } 13282 } 13283 13284 /** 13285 * Create args that describe an existing installed package. Typically used 13286 * when cleaning up old installs, or used as a move source. 13287 */ 13288 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13289 String resourcePath, String[] instructionSets) { 13290 final boolean isInAsec; 13291 if (installOnExternalAsec(installFlags)) { 13292 /* Apps on SD card are always in ASEC containers. */ 13293 isInAsec = true; 13294 } else if (installForwardLocked(installFlags) 13295 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13296 /* 13297 * Forward-locked apps are only in ASEC containers if they're the 13298 * new style 13299 */ 13300 isInAsec = true; 13301 } else { 13302 isInAsec = false; 13303 } 13304 13305 if (isInAsec) { 13306 return new AsecInstallArgs(codePath, instructionSets, 13307 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13308 } else { 13309 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13310 } 13311 } 13312 13313 static abstract class InstallArgs { 13314 /** @see InstallParams#origin */ 13315 final OriginInfo origin; 13316 /** @see InstallParams#move */ 13317 final MoveInfo move; 13318 13319 final IPackageInstallObserver2 observer; 13320 // Always refers to PackageManager flags only 13321 final int installFlags; 13322 final String installerPackageName; 13323 final String volumeUuid; 13324 final UserHandle user; 13325 final String abiOverride; 13326 final String[] installGrantPermissions; 13327 /** If non-null, drop an async trace when the install completes */ 13328 final String traceMethod; 13329 final int traceCookie; 13330 final Certificate[][] certificates; 13331 13332 // The list of instruction sets supported by this app. This is currently 13333 // only used during the rmdex() phase to clean up resources. We can get rid of this 13334 // if we move dex files under the common app path. 13335 /* nullable */ String[] instructionSets; 13336 13337 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13338 int installFlags, String installerPackageName, String volumeUuid, 13339 UserHandle user, String[] instructionSets, 13340 String abiOverride, String[] installGrantPermissions, 13341 String traceMethod, int traceCookie, Certificate[][] certificates) { 13342 this.origin = origin; 13343 this.move = move; 13344 this.installFlags = installFlags; 13345 this.observer = observer; 13346 this.installerPackageName = installerPackageName; 13347 this.volumeUuid = volumeUuid; 13348 this.user = user; 13349 this.instructionSets = instructionSets; 13350 this.abiOverride = abiOverride; 13351 this.installGrantPermissions = installGrantPermissions; 13352 this.traceMethod = traceMethod; 13353 this.traceCookie = traceCookie; 13354 this.certificates = certificates; 13355 } 13356 13357 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13358 abstract int doPreInstall(int status); 13359 13360 /** 13361 * Rename package into final resting place. All paths on the given 13362 * scanned package should be updated to reflect the rename. 13363 */ 13364 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13365 abstract int doPostInstall(int status, int uid); 13366 13367 /** @see PackageSettingBase#codePathString */ 13368 abstract String getCodePath(); 13369 /** @see PackageSettingBase#resourcePathString */ 13370 abstract String getResourcePath(); 13371 13372 // Need installer lock especially for dex file removal. 13373 abstract void cleanUpResourcesLI(); 13374 abstract boolean doPostDeleteLI(boolean delete); 13375 13376 /** 13377 * Called before the source arguments are copied. This is used mostly 13378 * for MoveParams when it needs to read the source file to put it in the 13379 * destination. 13380 */ 13381 int doPreCopy() { 13382 return PackageManager.INSTALL_SUCCEEDED; 13383 } 13384 13385 /** 13386 * Called after the source arguments are copied. This is used mostly for 13387 * MoveParams when it needs to read the source file to put it in the 13388 * destination. 13389 */ 13390 int doPostCopy(int uid) { 13391 return PackageManager.INSTALL_SUCCEEDED; 13392 } 13393 13394 protected boolean isFwdLocked() { 13395 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13396 } 13397 13398 protected boolean isExternalAsec() { 13399 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13400 } 13401 13402 protected boolean isEphemeral() { 13403 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13404 } 13405 13406 UserHandle getUser() { 13407 return user; 13408 } 13409 } 13410 13411 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13412 if (!allCodePaths.isEmpty()) { 13413 if (instructionSets == null) { 13414 throw new IllegalStateException("instructionSet == null"); 13415 } 13416 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13417 for (String codePath : allCodePaths) { 13418 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13419 try { 13420 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13421 } catch (InstallerException ignored) { 13422 } 13423 } 13424 } 13425 } 13426 } 13427 13428 /** 13429 * Logic to handle installation of non-ASEC applications, including copying 13430 * and renaming logic. 13431 */ 13432 class FileInstallArgs extends InstallArgs { 13433 private File codeFile; 13434 private File resourceFile; 13435 13436 // Example topology: 13437 // /data/app/com.example/base.apk 13438 // /data/app/com.example/split_foo.apk 13439 // /data/app/com.example/lib/arm/libfoo.so 13440 // /data/app/com.example/lib/arm64/libfoo.so 13441 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13442 13443 /** New install */ 13444 FileInstallArgs(InstallParams params) { 13445 super(params.origin, params.move, params.observer, params.installFlags, 13446 params.installerPackageName, params.volumeUuid, 13447 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13448 params.grantedRuntimePermissions, 13449 params.traceMethod, params.traceCookie, params.certificates); 13450 if (isFwdLocked()) { 13451 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13452 } 13453 } 13454 13455 /** Existing install */ 13456 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13457 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13458 null, null, null, 0, null /*certificates*/); 13459 this.codeFile = (codePath != null) ? new File(codePath) : null; 13460 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13461 } 13462 13463 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13464 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13465 try { 13466 return doCopyApk(imcs, temp); 13467 } finally { 13468 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13469 } 13470 } 13471 13472 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13473 if (origin.staged) { 13474 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13475 codeFile = origin.file; 13476 resourceFile = origin.file; 13477 return PackageManager.INSTALL_SUCCEEDED; 13478 } 13479 13480 try { 13481 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13482 final File tempDir = 13483 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13484 codeFile = tempDir; 13485 resourceFile = tempDir; 13486 } catch (IOException e) { 13487 Slog.w(TAG, "Failed to create copy file: " + e); 13488 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13489 } 13490 13491 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13492 @Override 13493 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13494 if (!FileUtils.isValidExtFilename(name)) { 13495 throw new IllegalArgumentException("Invalid filename: " + name); 13496 } 13497 try { 13498 final File file = new File(codeFile, name); 13499 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13500 O_RDWR | O_CREAT, 0644); 13501 Os.chmod(file.getAbsolutePath(), 0644); 13502 return new ParcelFileDescriptor(fd); 13503 } catch (ErrnoException e) { 13504 throw new RemoteException("Failed to open: " + e.getMessage()); 13505 } 13506 } 13507 }; 13508 13509 int ret = PackageManager.INSTALL_SUCCEEDED; 13510 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13511 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13512 Slog.e(TAG, "Failed to copy package"); 13513 return ret; 13514 } 13515 13516 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13517 NativeLibraryHelper.Handle handle = null; 13518 try { 13519 handle = NativeLibraryHelper.Handle.create(codeFile); 13520 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13521 abiOverride); 13522 } catch (IOException e) { 13523 Slog.e(TAG, "Copying native libraries failed", e); 13524 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13525 } finally { 13526 IoUtils.closeQuietly(handle); 13527 } 13528 13529 return ret; 13530 } 13531 13532 int doPreInstall(int status) { 13533 if (status != PackageManager.INSTALL_SUCCEEDED) { 13534 cleanUp(); 13535 } 13536 return status; 13537 } 13538 13539 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13540 if (status != PackageManager.INSTALL_SUCCEEDED) { 13541 cleanUp(); 13542 return false; 13543 } 13544 13545 final File targetDir = codeFile.getParentFile(); 13546 final File beforeCodeFile = codeFile; 13547 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13548 13549 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13550 try { 13551 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13552 } catch (ErrnoException e) { 13553 Slog.w(TAG, "Failed to rename", e); 13554 return false; 13555 } 13556 13557 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13558 Slog.w(TAG, "Failed to restorecon"); 13559 return false; 13560 } 13561 13562 // Reflect the rename internally 13563 codeFile = afterCodeFile; 13564 resourceFile = afterCodeFile; 13565 13566 // Reflect the rename in scanned details 13567 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13568 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13569 afterCodeFile, pkg.baseCodePath)); 13570 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13571 afterCodeFile, pkg.splitCodePaths)); 13572 13573 // Reflect the rename in app info 13574 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13575 pkg.setApplicationInfoCodePath(pkg.codePath); 13576 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13577 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13578 pkg.setApplicationInfoResourcePath(pkg.codePath); 13579 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13580 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13581 13582 return true; 13583 } 13584 13585 int doPostInstall(int status, int uid) { 13586 if (status != PackageManager.INSTALL_SUCCEEDED) { 13587 cleanUp(); 13588 } 13589 return status; 13590 } 13591 13592 @Override 13593 String getCodePath() { 13594 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13595 } 13596 13597 @Override 13598 String getResourcePath() { 13599 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13600 } 13601 13602 private boolean cleanUp() { 13603 if (codeFile == null || !codeFile.exists()) { 13604 return false; 13605 } 13606 13607 removeCodePathLI(codeFile); 13608 13609 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13610 resourceFile.delete(); 13611 } 13612 13613 return true; 13614 } 13615 13616 void cleanUpResourcesLI() { 13617 // Try enumerating all code paths before deleting 13618 List<String> allCodePaths = Collections.EMPTY_LIST; 13619 if (codeFile != null && codeFile.exists()) { 13620 try { 13621 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13622 allCodePaths = pkg.getAllCodePaths(); 13623 } catch (PackageParserException e) { 13624 // Ignored; we tried our best 13625 } 13626 } 13627 13628 cleanUp(); 13629 removeDexFiles(allCodePaths, instructionSets); 13630 } 13631 13632 boolean doPostDeleteLI(boolean delete) { 13633 // XXX err, shouldn't we respect the delete flag? 13634 cleanUpResourcesLI(); 13635 return true; 13636 } 13637 } 13638 13639 private boolean isAsecExternal(String cid) { 13640 final String asecPath = PackageHelper.getSdFilesystem(cid); 13641 return !asecPath.startsWith(mAsecInternalPath); 13642 } 13643 13644 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13645 PackageManagerException { 13646 if (copyRet < 0) { 13647 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13648 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13649 throw new PackageManagerException(copyRet, message); 13650 } 13651 } 13652 } 13653 13654 /** 13655 * Extract the MountService "container ID" from the full code path of an 13656 * .apk. 13657 */ 13658 static String cidFromCodePath(String fullCodePath) { 13659 int eidx = fullCodePath.lastIndexOf("/"); 13660 String subStr1 = fullCodePath.substring(0, eidx); 13661 int sidx = subStr1.lastIndexOf("/"); 13662 return subStr1.substring(sidx+1, eidx); 13663 } 13664 13665 /** 13666 * Logic to handle installation of ASEC applications, including copying and 13667 * renaming logic. 13668 */ 13669 class AsecInstallArgs extends InstallArgs { 13670 static final String RES_FILE_NAME = "pkg.apk"; 13671 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13672 13673 String cid; 13674 String packagePath; 13675 String resourcePath; 13676 13677 /** New install */ 13678 AsecInstallArgs(InstallParams params) { 13679 super(params.origin, params.move, params.observer, params.installFlags, 13680 params.installerPackageName, params.volumeUuid, 13681 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13682 params.grantedRuntimePermissions, 13683 params.traceMethod, params.traceCookie, params.certificates); 13684 } 13685 13686 /** Existing install */ 13687 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13688 boolean isExternal, boolean isForwardLocked) { 13689 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13690 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13691 instructionSets, null, null, null, 0, null /*certificates*/); 13692 // Hackily pretend we're still looking at a full code path 13693 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13694 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13695 } 13696 13697 // Extract cid from fullCodePath 13698 int eidx = fullCodePath.lastIndexOf("/"); 13699 String subStr1 = fullCodePath.substring(0, eidx); 13700 int sidx = subStr1.lastIndexOf("/"); 13701 cid = subStr1.substring(sidx+1, eidx); 13702 setMountPath(subStr1); 13703 } 13704 13705 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13706 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13707 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13708 instructionSets, null, null, null, 0, null /*certificates*/); 13709 this.cid = cid; 13710 setMountPath(PackageHelper.getSdDir(cid)); 13711 } 13712 13713 void createCopyFile() { 13714 cid = mInstallerService.allocateExternalStageCidLegacy(); 13715 } 13716 13717 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13718 if (origin.staged && origin.cid != null) { 13719 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13720 cid = origin.cid; 13721 setMountPath(PackageHelper.getSdDir(cid)); 13722 return PackageManager.INSTALL_SUCCEEDED; 13723 } 13724 13725 if (temp) { 13726 createCopyFile(); 13727 } else { 13728 /* 13729 * Pre-emptively destroy the container since it's destroyed if 13730 * copying fails due to it existing anyway. 13731 */ 13732 PackageHelper.destroySdDir(cid); 13733 } 13734 13735 final String newMountPath = imcs.copyPackageToContainer( 13736 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13737 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13738 13739 if (newMountPath != null) { 13740 setMountPath(newMountPath); 13741 return PackageManager.INSTALL_SUCCEEDED; 13742 } else { 13743 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13744 } 13745 } 13746 13747 @Override 13748 String getCodePath() { 13749 return packagePath; 13750 } 13751 13752 @Override 13753 String getResourcePath() { 13754 return resourcePath; 13755 } 13756 13757 int doPreInstall(int status) { 13758 if (status != PackageManager.INSTALL_SUCCEEDED) { 13759 // Destroy container 13760 PackageHelper.destroySdDir(cid); 13761 } else { 13762 boolean mounted = PackageHelper.isContainerMounted(cid); 13763 if (!mounted) { 13764 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13765 Process.SYSTEM_UID); 13766 if (newMountPath != null) { 13767 setMountPath(newMountPath); 13768 } else { 13769 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13770 } 13771 } 13772 } 13773 return status; 13774 } 13775 13776 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13777 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13778 String newMountPath = null; 13779 if (PackageHelper.isContainerMounted(cid)) { 13780 // Unmount the container 13781 if (!PackageHelper.unMountSdDir(cid)) { 13782 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13783 return false; 13784 } 13785 } 13786 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13787 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13788 " which might be stale. Will try to clean up."); 13789 // Clean up the stale container and proceed to recreate. 13790 if (!PackageHelper.destroySdDir(newCacheId)) { 13791 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13792 return false; 13793 } 13794 // Successfully cleaned up stale container. Try to rename again. 13795 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13796 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13797 + " inspite of cleaning it up."); 13798 return false; 13799 } 13800 } 13801 if (!PackageHelper.isContainerMounted(newCacheId)) { 13802 Slog.w(TAG, "Mounting container " + newCacheId); 13803 newMountPath = PackageHelper.mountSdDir(newCacheId, 13804 getEncryptKey(), Process.SYSTEM_UID); 13805 } else { 13806 newMountPath = PackageHelper.getSdDir(newCacheId); 13807 } 13808 if (newMountPath == null) { 13809 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13810 return false; 13811 } 13812 Log.i(TAG, "Succesfully renamed " + cid + 13813 " to " + newCacheId + 13814 " at new path: " + newMountPath); 13815 cid = newCacheId; 13816 13817 final File beforeCodeFile = new File(packagePath); 13818 setMountPath(newMountPath); 13819 final File afterCodeFile = new File(packagePath); 13820 13821 // Reflect the rename in scanned details 13822 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13823 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13824 afterCodeFile, pkg.baseCodePath)); 13825 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13826 afterCodeFile, pkg.splitCodePaths)); 13827 13828 // Reflect the rename in app info 13829 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13830 pkg.setApplicationInfoCodePath(pkg.codePath); 13831 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13832 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13833 pkg.setApplicationInfoResourcePath(pkg.codePath); 13834 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13835 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13836 13837 return true; 13838 } 13839 13840 private void setMountPath(String mountPath) { 13841 final File mountFile = new File(mountPath); 13842 13843 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13844 if (monolithicFile.exists()) { 13845 packagePath = monolithicFile.getAbsolutePath(); 13846 if (isFwdLocked()) { 13847 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13848 } else { 13849 resourcePath = packagePath; 13850 } 13851 } else { 13852 packagePath = mountFile.getAbsolutePath(); 13853 resourcePath = packagePath; 13854 } 13855 } 13856 13857 int doPostInstall(int status, int uid) { 13858 if (status != PackageManager.INSTALL_SUCCEEDED) { 13859 cleanUp(); 13860 } else { 13861 final int groupOwner; 13862 final String protectedFile; 13863 if (isFwdLocked()) { 13864 groupOwner = UserHandle.getSharedAppGid(uid); 13865 protectedFile = RES_FILE_NAME; 13866 } else { 13867 groupOwner = -1; 13868 protectedFile = null; 13869 } 13870 13871 if (uid < Process.FIRST_APPLICATION_UID 13872 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13873 Slog.e(TAG, "Failed to finalize " + cid); 13874 PackageHelper.destroySdDir(cid); 13875 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13876 } 13877 13878 boolean mounted = PackageHelper.isContainerMounted(cid); 13879 if (!mounted) { 13880 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13881 } 13882 } 13883 return status; 13884 } 13885 13886 private void cleanUp() { 13887 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13888 13889 // Destroy secure container 13890 PackageHelper.destroySdDir(cid); 13891 } 13892 13893 private List<String> getAllCodePaths() { 13894 final File codeFile = new File(getCodePath()); 13895 if (codeFile != null && codeFile.exists()) { 13896 try { 13897 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13898 return pkg.getAllCodePaths(); 13899 } catch (PackageParserException e) { 13900 // Ignored; we tried our best 13901 } 13902 } 13903 return Collections.EMPTY_LIST; 13904 } 13905 13906 void cleanUpResourcesLI() { 13907 // Enumerate all code paths before deleting 13908 cleanUpResourcesLI(getAllCodePaths()); 13909 } 13910 13911 private void cleanUpResourcesLI(List<String> allCodePaths) { 13912 cleanUp(); 13913 removeDexFiles(allCodePaths, instructionSets); 13914 } 13915 13916 String getPackageName() { 13917 return getAsecPackageName(cid); 13918 } 13919 13920 boolean doPostDeleteLI(boolean delete) { 13921 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13922 final List<String> allCodePaths = getAllCodePaths(); 13923 boolean mounted = PackageHelper.isContainerMounted(cid); 13924 if (mounted) { 13925 // Unmount first 13926 if (PackageHelper.unMountSdDir(cid)) { 13927 mounted = false; 13928 } 13929 } 13930 if (!mounted && delete) { 13931 cleanUpResourcesLI(allCodePaths); 13932 } 13933 return !mounted; 13934 } 13935 13936 @Override 13937 int doPreCopy() { 13938 if (isFwdLocked()) { 13939 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13940 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13941 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13942 } 13943 } 13944 13945 return PackageManager.INSTALL_SUCCEEDED; 13946 } 13947 13948 @Override 13949 int doPostCopy(int uid) { 13950 if (isFwdLocked()) { 13951 if (uid < Process.FIRST_APPLICATION_UID 13952 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13953 RES_FILE_NAME)) { 13954 Slog.e(TAG, "Failed to finalize " + cid); 13955 PackageHelper.destroySdDir(cid); 13956 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13957 } 13958 } 13959 13960 return PackageManager.INSTALL_SUCCEEDED; 13961 } 13962 } 13963 13964 /** 13965 * Logic to handle movement of existing installed applications. 13966 */ 13967 class MoveInstallArgs extends InstallArgs { 13968 private File codeFile; 13969 private File resourceFile; 13970 13971 /** New install */ 13972 MoveInstallArgs(InstallParams params) { 13973 super(params.origin, params.move, params.observer, params.installFlags, 13974 params.installerPackageName, params.volumeUuid, 13975 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13976 params.grantedRuntimePermissions, 13977 params.traceMethod, params.traceCookie, params.certificates); 13978 } 13979 13980 int copyApk(IMediaContainerService imcs, boolean temp) { 13981 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13982 + move.fromUuid + " to " + move.toUuid); 13983 synchronized (mInstaller) { 13984 try { 13985 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13986 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13987 } catch (InstallerException e) { 13988 Slog.w(TAG, "Failed to move app", e); 13989 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13990 } 13991 } 13992 13993 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13994 resourceFile = codeFile; 13995 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13996 13997 return PackageManager.INSTALL_SUCCEEDED; 13998 } 13999 14000 int doPreInstall(int status) { 14001 if (status != PackageManager.INSTALL_SUCCEEDED) { 14002 cleanUp(move.toUuid); 14003 } 14004 return status; 14005 } 14006 14007 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14008 if (status != PackageManager.INSTALL_SUCCEEDED) { 14009 cleanUp(move.toUuid); 14010 return false; 14011 } 14012 14013 // Reflect the move in app info 14014 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14015 pkg.setApplicationInfoCodePath(pkg.codePath); 14016 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14017 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14018 pkg.setApplicationInfoResourcePath(pkg.codePath); 14019 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14020 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14021 14022 return true; 14023 } 14024 14025 int doPostInstall(int status, int uid) { 14026 if (status == PackageManager.INSTALL_SUCCEEDED) { 14027 cleanUp(move.fromUuid); 14028 } else { 14029 cleanUp(move.toUuid); 14030 } 14031 return status; 14032 } 14033 14034 @Override 14035 String getCodePath() { 14036 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14037 } 14038 14039 @Override 14040 String getResourcePath() { 14041 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14042 } 14043 14044 private boolean cleanUp(String volumeUuid) { 14045 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14046 move.dataAppName); 14047 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14048 final int[] userIds = sUserManager.getUserIds(); 14049 synchronized (mInstallLock) { 14050 // Clean up both app data and code 14051 // All package moves are frozen until finished 14052 for (int userId : userIds) { 14053 try { 14054 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14056 } catch (InstallerException e) { 14057 Slog.w(TAG, String.valueOf(e)); 14058 } 14059 } 14060 removeCodePathLI(codeFile); 14061 } 14062 return true; 14063 } 14064 14065 void cleanUpResourcesLI() { 14066 throw new UnsupportedOperationException(); 14067 } 14068 14069 boolean doPostDeleteLI(boolean delete) { 14070 throw new UnsupportedOperationException(); 14071 } 14072 } 14073 14074 static String getAsecPackageName(String packageCid) { 14075 int idx = packageCid.lastIndexOf("-"); 14076 if (idx == -1) { 14077 return packageCid; 14078 } 14079 return packageCid.substring(0, idx); 14080 } 14081 14082 // Utility method used to create code paths based on package name and available index. 14083 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14084 String idxStr = ""; 14085 int idx = 1; 14086 // Fall back to default value of idx=1 if prefix is not 14087 // part of oldCodePath 14088 if (oldCodePath != null) { 14089 String subStr = oldCodePath; 14090 // Drop the suffix right away 14091 if (suffix != null && subStr.endsWith(suffix)) { 14092 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14093 } 14094 // If oldCodePath already contains prefix find out the 14095 // ending index to either increment or decrement. 14096 int sidx = subStr.lastIndexOf(prefix); 14097 if (sidx != -1) { 14098 subStr = subStr.substring(sidx + prefix.length()); 14099 if (subStr != null) { 14100 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14101 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14102 } 14103 try { 14104 idx = Integer.parseInt(subStr); 14105 if (idx <= 1) { 14106 idx++; 14107 } else { 14108 idx--; 14109 } 14110 } catch(NumberFormatException e) { 14111 } 14112 } 14113 } 14114 } 14115 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14116 return prefix + idxStr; 14117 } 14118 14119 private File getNextCodePath(File targetDir, String packageName) { 14120 int suffix = 1; 14121 File result; 14122 do { 14123 result = new File(targetDir, packageName + "-" + suffix); 14124 suffix++; 14125 } while (result.exists()); 14126 return result; 14127 } 14128 14129 // Utility method that returns the relative package path with respect 14130 // to the installation directory. Like say for /data/data/com.test-1.apk 14131 // string com.test-1 is returned. 14132 static String deriveCodePathName(String codePath) { 14133 if (codePath == null) { 14134 return null; 14135 } 14136 final File codeFile = new File(codePath); 14137 final String name = codeFile.getName(); 14138 if (codeFile.isDirectory()) { 14139 return name; 14140 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14141 final int lastDot = name.lastIndexOf('.'); 14142 return name.substring(0, lastDot); 14143 } else { 14144 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14145 return null; 14146 } 14147 } 14148 14149 static class PackageInstalledInfo { 14150 String name; 14151 int uid; 14152 // The set of users that originally had this package installed. 14153 int[] origUsers; 14154 // The set of users that now have this package installed. 14155 int[] newUsers; 14156 PackageParser.Package pkg; 14157 int returnCode; 14158 String returnMsg; 14159 PackageRemovedInfo removedInfo; 14160 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14161 14162 public void setError(int code, String msg) { 14163 setReturnCode(code); 14164 setReturnMessage(msg); 14165 Slog.w(TAG, msg); 14166 } 14167 14168 public void setError(String msg, PackageParserException e) { 14169 setReturnCode(e.error); 14170 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14171 Slog.w(TAG, msg, e); 14172 } 14173 14174 public void setError(String msg, PackageManagerException e) { 14175 returnCode = e.error; 14176 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14177 Slog.w(TAG, msg, e); 14178 } 14179 14180 public void setReturnCode(int returnCode) { 14181 this.returnCode = returnCode; 14182 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14183 for (int i = 0; i < childCount; i++) { 14184 addedChildPackages.valueAt(i).returnCode = returnCode; 14185 } 14186 } 14187 14188 private void setReturnMessage(String returnMsg) { 14189 this.returnMsg = returnMsg; 14190 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14191 for (int i = 0; i < childCount; i++) { 14192 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14193 } 14194 } 14195 14196 // In some error cases we want to convey more info back to the observer 14197 String origPackage; 14198 String origPermission; 14199 } 14200 14201 /* 14202 * Install a non-existing package. 14203 */ 14204 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14205 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14206 PackageInstalledInfo res) { 14207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14208 14209 // Remember this for later, in case we need to rollback this install 14210 String pkgName = pkg.packageName; 14211 14212 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14213 14214 synchronized(mPackages) { 14215 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14216 // A package with the same name is already installed, though 14217 // it has been renamed to an older name. The package we 14218 // are trying to install should be installed as an update to 14219 // the existing one, but that has not been requested, so bail. 14220 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14221 + " without first uninstalling package running as " 14222 + mSettings.mRenamedPackages.get(pkgName)); 14223 return; 14224 } 14225 if (mPackages.containsKey(pkgName)) { 14226 // Don't allow installation over an existing package with the same name. 14227 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14228 + " without first uninstalling."); 14229 return; 14230 } 14231 } 14232 14233 try { 14234 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14235 System.currentTimeMillis(), user); 14236 14237 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14238 14239 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14240 prepareAppDataAfterInstallLIF(newPackage); 14241 14242 } else { 14243 // Remove package from internal structures, but keep around any 14244 // data that might have already existed 14245 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14246 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14247 } 14248 } catch (PackageManagerException e) { 14249 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14250 } 14251 14252 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14253 } 14254 14255 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14256 // Can't rotate keys during boot or if sharedUser. 14257 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14258 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14259 return false; 14260 } 14261 // app is using upgradeKeySets; make sure all are valid 14262 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14263 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14264 for (int i = 0; i < upgradeKeySets.length; i++) { 14265 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14266 Slog.wtf(TAG, "Package " 14267 + (oldPs.name != null ? oldPs.name : "<null>") 14268 + " contains upgrade-key-set reference to unknown key-set: " 14269 + upgradeKeySets[i] 14270 + " reverting to signatures check."); 14271 return false; 14272 } 14273 } 14274 return true; 14275 } 14276 14277 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14278 // Upgrade keysets are being used. Determine if new package has a superset of the 14279 // required keys. 14280 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14281 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14282 for (int i = 0; i < upgradeKeySets.length; i++) { 14283 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14284 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14285 return true; 14286 } 14287 } 14288 return false; 14289 } 14290 14291 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14292 try (DigestInputStream digestStream = 14293 new DigestInputStream(new FileInputStream(file), digest)) { 14294 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14295 } 14296 } 14297 14298 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14299 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14300 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14301 14302 final PackageParser.Package oldPackage; 14303 final String pkgName = pkg.packageName; 14304 final int[] allUsers; 14305 final int[] installedUsers; 14306 14307 synchronized(mPackages) { 14308 oldPackage = mPackages.get(pkgName); 14309 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14310 14311 // don't allow upgrade to target a release SDK from a pre-release SDK 14312 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14313 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14314 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14315 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14316 if (oldTargetsPreRelease 14317 && !newTargetsPreRelease 14318 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14319 Slog.w(TAG, "Can't install package targeting released sdk"); 14320 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14321 return; 14322 } 14323 14324 // don't allow an upgrade from full to ephemeral 14325 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14326 if (isEphemeral && !oldIsEphemeral) { 14327 // can't downgrade from full to ephemeral 14328 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14329 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14330 return; 14331 } 14332 14333 // verify signatures are valid 14334 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14335 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14336 if (!checkUpgradeKeySetLP(ps, pkg)) { 14337 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14338 "New package not signed by keys specified by upgrade-keysets: " 14339 + pkgName); 14340 return; 14341 } 14342 } else { 14343 // default to original signature matching 14344 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14345 != PackageManager.SIGNATURE_MATCH) { 14346 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14347 "New package has a different signature: " + pkgName); 14348 return; 14349 } 14350 } 14351 14352 // don't allow a system upgrade unless the upgrade hash matches 14353 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14354 byte[] digestBytes = null; 14355 try { 14356 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14357 updateDigest(digest, new File(pkg.baseCodePath)); 14358 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14359 for (String path : pkg.splitCodePaths) { 14360 updateDigest(digest, new File(path)); 14361 } 14362 } 14363 digestBytes = digest.digest(); 14364 } catch (NoSuchAlgorithmException | IOException e) { 14365 res.setError(INSTALL_FAILED_INVALID_APK, 14366 "Could not compute hash: " + pkgName); 14367 return; 14368 } 14369 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14370 res.setError(INSTALL_FAILED_INVALID_APK, 14371 "New package fails restrict-update check: " + pkgName); 14372 return; 14373 } 14374 // retain upgrade restriction 14375 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14376 } 14377 14378 // Check for shared user id changes 14379 String invalidPackageName = 14380 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14381 if (invalidPackageName != null) { 14382 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14383 "Package " + invalidPackageName + " tried to change user " 14384 + oldPackage.mSharedUserId); 14385 return; 14386 } 14387 14388 // In case of rollback, remember per-user/profile install state 14389 allUsers = sUserManager.getUserIds(); 14390 installedUsers = ps.queryInstalledUsers(allUsers, true); 14391 } 14392 14393 // Update what is removed 14394 res.removedInfo = new PackageRemovedInfo(); 14395 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14396 res.removedInfo.removedPackage = oldPackage.packageName; 14397 res.removedInfo.isUpdate = true; 14398 res.removedInfo.origUsers = installedUsers; 14399 final int childCount = (oldPackage.childPackages != null) 14400 ? oldPackage.childPackages.size() : 0; 14401 for (int i = 0; i < childCount; i++) { 14402 boolean childPackageUpdated = false; 14403 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14404 if (res.addedChildPackages != null) { 14405 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14406 if (childRes != null) { 14407 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14408 childRes.removedInfo.removedPackage = childPkg.packageName; 14409 childRes.removedInfo.isUpdate = true; 14410 childPackageUpdated = true; 14411 } 14412 } 14413 if (!childPackageUpdated) { 14414 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14415 childRemovedRes.removedPackage = childPkg.packageName; 14416 childRemovedRes.isUpdate = false; 14417 childRemovedRes.dataRemoved = true; 14418 synchronized (mPackages) { 14419 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14420 if (childPs != null) { 14421 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14422 } 14423 } 14424 if (res.removedInfo.removedChildPackages == null) { 14425 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14426 } 14427 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14428 } 14429 } 14430 14431 boolean sysPkg = (isSystemApp(oldPackage)); 14432 if (sysPkg) { 14433 // Set the system/privileged flags as needed 14434 final boolean privileged = 14435 (oldPackage.applicationInfo.privateFlags 14436 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14437 final int systemPolicyFlags = policyFlags 14438 | PackageParser.PARSE_IS_SYSTEM 14439 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14440 14441 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14442 user, allUsers, installerPackageName, res); 14443 } else { 14444 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14445 user, allUsers, installerPackageName, res); 14446 } 14447 } 14448 14449 public List<String> getPreviousCodePaths(String packageName) { 14450 final PackageSetting ps = mSettings.mPackages.get(packageName); 14451 final List<String> result = new ArrayList<String>(); 14452 if (ps != null && ps.oldCodePaths != null) { 14453 result.addAll(ps.oldCodePaths); 14454 } 14455 return result; 14456 } 14457 14458 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14459 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14460 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14461 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14462 + deletedPackage); 14463 14464 String pkgName = deletedPackage.packageName; 14465 boolean deletedPkg = true; 14466 boolean addedPkg = false; 14467 boolean updatedSettings = false; 14468 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14469 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14470 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14471 14472 final long origUpdateTime = (pkg.mExtras != null) 14473 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14474 14475 // First delete the existing package while retaining the data directory 14476 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14477 res.removedInfo, true, pkg)) { 14478 // If the existing package wasn't successfully deleted 14479 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14480 deletedPkg = false; 14481 } else { 14482 // Successfully deleted the old package; proceed with replace. 14483 14484 // If deleted package lived in a container, give users a chance to 14485 // relinquish resources before killing. 14486 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14487 if (DEBUG_INSTALL) { 14488 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14489 } 14490 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14491 final ArrayList<String> pkgList = new ArrayList<String>(1); 14492 pkgList.add(deletedPackage.applicationInfo.packageName); 14493 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14494 } 14495 14496 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14497 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14498 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14499 14500 try { 14501 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14502 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14503 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14504 14505 // Update the in-memory copy of the previous code paths. 14506 PackageSetting ps = mSettings.mPackages.get(pkgName); 14507 if (!killApp) { 14508 if (ps.oldCodePaths == null) { 14509 ps.oldCodePaths = new ArraySet<>(); 14510 } 14511 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14512 if (deletedPackage.splitCodePaths != null) { 14513 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14514 } 14515 } else { 14516 ps.oldCodePaths = null; 14517 } 14518 if (ps.childPackageNames != null) { 14519 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14520 final String childPkgName = ps.childPackageNames.get(i); 14521 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14522 childPs.oldCodePaths = ps.oldCodePaths; 14523 } 14524 } 14525 prepareAppDataAfterInstallLIF(newPackage); 14526 addedPkg = true; 14527 } catch (PackageManagerException e) { 14528 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14529 } 14530 } 14531 14532 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14533 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14534 14535 // Revert all internal state mutations and added folders for the failed install 14536 if (addedPkg) { 14537 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14538 res.removedInfo, true, null); 14539 } 14540 14541 // Restore the old package 14542 if (deletedPkg) { 14543 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14544 File restoreFile = new File(deletedPackage.codePath); 14545 // Parse old package 14546 boolean oldExternal = isExternal(deletedPackage); 14547 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14548 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14549 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14550 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14551 try { 14552 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14553 null); 14554 } catch (PackageManagerException e) { 14555 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14556 + e.getMessage()); 14557 return; 14558 } 14559 14560 synchronized (mPackages) { 14561 // Ensure the installer package name up to date 14562 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14563 14564 // Update permissions for restored package 14565 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14566 14567 mSettings.writeLPr(); 14568 } 14569 14570 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14571 } 14572 } else { 14573 synchronized (mPackages) { 14574 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14575 if (ps != null) { 14576 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14577 if (res.removedInfo.removedChildPackages != null) { 14578 final int childCount = res.removedInfo.removedChildPackages.size(); 14579 // Iterate in reverse as we may modify the collection 14580 for (int i = childCount - 1; i >= 0; i--) { 14581 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14582 if (res.addedChildPackages.containsKey(childPackageName)) { 14583 res.removedInfo.removedChildPackages.removeAt(i); 14584 } else { 14585 PackageRemovedInfo childInfo = res.removedInfo 14586 .removedChildPackages.valueAt(i); 14587 childInfo.removedForAllUsers = mPackages.get( 14588 childInfo.removedPackage) == null; 14589 } 14590 } 14591 } 14592 } 14593 } 14594 } 14595 } 14596 14597 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14598 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14599 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14600 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14601 + ", old=" + deletedPackage); 14602 14603 final boolean disabledSystem; 14604 14605 // Remove existing system package 14606 removePackageLI(deletedPackage, true); 14607 14608 synchronized (mPackages) { 14609 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14610 } 14611 if (!disabledSystem) { 14612 // We didn't need to disable the .apk as a current system package, 14613 // which means we are replacing another update that is already 14614 // installed. We need to make sure to delete the older one's .apk. 14615 res.removedInfo.args = createInstallArgsForExisting(0, 14616 deletedPackage.applicationInfo.getCodePath(), 14617 deletedPackage.applicationInfo.getResourcePath(), 14618 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14619 } else { 14620 res.removedInfo.args = null; 14621 } 14622 14623 // Successfully disabled the old package. Now proceed with re-installation 14624 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14625 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14626 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14627 14628 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14629 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14630 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14631 14632 PackageParser.Package newPackage = null; 14633 try { 14634 // Add the package to the internal data structures 14635 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14636 14637 // Set the update and install times 14638 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14639 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14640 System.currentTimeMillis()); 14641 14642 // Update the package dynamic state if succeeded 14643 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14644 // Now that the install succeeded make sure we remove data 14645 // directories for any child package the update removed. 14646 final int deletedChildCount = (deletedPackage.childPackages != null) 14647 ? deletedPackage.childPackages.size() : 0; 14648 final int newChildCount = (newPackage.childPackages != null) 14649 ? newPackage.childPackages.size() : 0; 14650 for (int i = 0; i < deletedChildCount; i++) { 14651 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14652 boolean childPackageDeleted = true; 14653 for (int j = 0; j < newChildCount; j++) { 14654 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14655 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14656 childPackageDeleted = false; 14657 break; 14658 } 14659 } 14660 if (childPackageDeleted) { 14661 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14662 deletedChildPkg.packageName); 14663 if (ps != null && res.removedInfo.removedChildPackages != null) { 14664 PackageRemovedInfo removedChildRes = res.removedInfo 14665 .removedChildPackages.get(deletedChildPkg.packageName); 14666 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14667 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14668 } 14669 } 14670 } 14671 14672 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14673 prepareAppDataAfterInstallLIF(newPackage); 14674 } 14675 } catch (PackageManagerException e) { 14676 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14677 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14678 } 14679 14680 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14681 // Re installation failed. Restore old information 14682 // Remove new pkg information 14683 if (newPackage != null) { 14684 removeInstalledPackageLI(newPackage, true); 14685 } 14686 // Add back the old system package 14687 try { 14688 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14689 } catch (PackageManagerException e) { 14690 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14691 } 14692 14693 synchronized (mPackages) { 14694 if (disabledSystem) { 14695 enableSystemPackageLPw(deletedPackage); 14696 } 14697 14698 // Ensure the installer package name up to date 14699 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14700 14701 // Update permissions for restored package 14702 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14703 14704 mSettings.writeLPr(); 14705 } 14706 14707 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14708 + " after failed upgrade"); 14709 } 14710 } 14711 14712 /** 14713 * Checks whether the parent or any of the child packages have a change shared 14714 * user. For a package to be a valid update the shred users of the parent and 14715 * the children should match. We may later support changing child shared users. 14716 * @param oldPkg The updated package. 14717 * @param newPkg The update package. 14718 * @return The shared user that change between the versions. 14719 */ 14720 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14721 PackageParser.Package newPkg) { 14722 // Check parent shared user 14723 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14724 return newPkg.packageName; 14725 } 14726 // Check child shared users 14727 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14728 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14729 for (int i = 0; i < newChildCount; i++) { 14730 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14731 // If this child was present, did it have the same shared user? 14732 for (int j = 0; j < oldChildCount; j++) { 14733 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14734 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14735 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14736 return newChildPkg.packageName; 14737 } 14738 } 14739 } 14740 return null; 14741 } 14742 14743 private void removeNativeBinariesLI(PackageSetting ps) { 14744 // Remove the lib path for the parent package 14745 if (ps != null) { 14746 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14747 // Remove the lib path for the child packages 14748 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14749 for (int i = 0; i < childCount; i++) { 14750 PackageSetting childPs = null; 14751 synchronized (mPackages) { 14752 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14753 } 14754 if (childPs != null) { 14755 NativeLibraryHelper.removeNativeBinariesLI(childPs 14756 .legacyNativeLibraryPathString); 14757 } 14758 } 14759 } 14760 } 14761 14762 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14763 // Enable the parent package 14764 mSettings.enableSystemPackageLPw(pkg.packageName); 14765 // Enable the child packages 14766 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14767 for (int i = 0; i < childCount; i++) { 14768 PackageParser.Package childPkg = pkg.childPackages.get(i); 14769 mSettings.enableSystemPackageLPw(childPkg.packageName); 14770 } 14771 } 14772 14773 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14774 PackageParser.Package newPkg) { 14775 // Disable the parent package (parent always replaced) 14776 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14777 // Disable the child packages 14778 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14779 for (int i = 0; i < childCount; i++) { 14780 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14781 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14782 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14783 } 14784 return disabled; 14785 } 14786 14787 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14788 String installerPackageName) { 14789 // Enable the parent package 14790 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14791 // Enable the child packages 14792 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14793 for (int i = 0; i < childCount; i++) { 14794 PackageParser.Package childPkg = pkg.childPackages.get(i); 14795 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14796 } 14797 } 14798 14799 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14800 // Collect all used permissions in the UID 14801 ArraySet<String> usedPermissions = new ArraySet<>(); 14802 final int packageCount = su.packages.size(); 14803 for (int i = 0; i < packageCount; i++) { 14804 PackageSetting ps = su.packages.valueAt(i); 14805 if (ps.pkg == null) { 14806 continue; 14807 } 14808 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14809 for (int j = 0; j < requestedPermCount; j++) { 14810 String permission = ps.pkg.requestedPermissions.get(j); 14811 BasePermission bp = mSettings.mPermissions.get(permission); 14812 if (bp != null) { 14813 usedPermissions.add(permission); 14814 } 14815 } 14816 } 14817 14818 PermissionsState permissionsState = su.getPermissionsState(); 14819 // Prune install permissions 14820 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14821 final int installPermCount = installPermStates.size(); 14822 for (int i = installPermCount - 1; i >= 0; i--) { 14823 PermissionState permissionState = installPermStates.get(i); 14824 if (!usedPermissions.contains(permissionState.getName())) { 14825 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14826 if (bp != null) { 14827 permissionsState.revokeInstallPermission(bp); 14828 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14829 PackageManager.MASK_PERMISSION_FLAGS, 0); 14830 } 14831 } 14832 } 14833 14834 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14835 14836 // Prune runtime permissions 14837 for (int userId : allUserIds) { 14838 List<PermissionState> runtimePermStates = permissionsState 14839 .getRuntimePermissionStates(userId); 14840 final int runtimePermCount = runtimePermStates.size(); 14841 for (int i = runtimePermCount - 1; i >= 0; i--) { 14842 PermissionState permissionState = runtimePermStates.get(i); 14843 if (!usedPermissions.contains(permissionState.getName())) { 14844 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14845 if (bp != null) { 14846 permissionsState.revokeRuntimePermission(bp, userId); 14847 permissionsState.updatePermissionFlags(bp, userId, 14848 PackageManager.MASK_PERMISSION_FLAGS, 0); 14849 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14850 runtimePermissionChangedUserIds, userId); 14851 } 14852 } 14853 } 14854 } 14855 14856 return runtimePermissionChangedUserIds; 14857 } 14858 14859 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14860 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14861 // Update the parent package setting 14862 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14863 res, user); 14864 // Update the child packages setting 14865 final int childCount = (newPackage.childPackages != null) 14866 ? newPackage.childPackages.size() : 0; 14867 for (int i = 0; i < childCount; i++) { 14868 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14869 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14870 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14871 childRes.origUsers, childRes, user); 14872 } 14873 } 14874 14875 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14876 String installerPackageName, int[] allUsers, int[] installedForUsers, 14877 PackageInstalledInfo res, UserHandle user) { 14878 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14879 14880 String pkgName = newPackage.packageName; 14881 synchronized (mPackages) { 14882 //write settings. the installStatus will be incomplete at this stage. 14883 //note that the new package setting would have already been 14884 //added to mPackages. It hasn't been persisted yet. 14885 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14886 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14887 mSettings.writeLPr(); 14888 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14889 } 14890 14891 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14892 synchronized (mPackages) { 14893 updatePermissionsLPw(newPackage.packageName, newPackage, 14894 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14895 ? UPDATE_PERMISSIONS_ALL : 0)); 14896 // For system-bundled packages, we assume that installing an upgraded version 14897 // of the package implies that the user actually wants to run that new code, 14898 // so we enable the package. 14899 PackageSetting ps = mSettings.mPackages.get(pkgName); 14900 final int userId = user.getIdentifier(); 14901 if (ps != null) { 14902 if (isSystemApp(newPackage)) { 14903 if (DEBUG_INSTALL) { 14904 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14905 } 14906 // Enable system package for requested users 14907 if (res.origUsers != null) { 14908 for (int origUserId : res.origUsers) { 14909 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14910 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14911 origUserId, installerPackageName); 14912 } 14913 } 14914 } 14915 // Also convey the prior install/uninstall state 14916 if (allUsers != null && installedForUsers != null) { 14917 for (int currentUserId : allUsers) { 14918 final boolean installed = ArrayUtils.contains( 14919 installedForUsers, currentUserId); 14920 if (DEBUG_INSTALL) { 14921 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14922 } 14923 ps.setInstalled(installed, currentUserId); 14924 } 14925 // these install state changes will be persisted in the 14926 // upcoming call to mSettings.writeLPr(). 14927 } 14928 } 14929 // It's implied that when a user requests installation, they want the app to be 14930 // installed and enabled. 14931 if (userId != UserHandle.USER_ALL) { 14932 ps.setInstalled(true, userId); 14933 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14934 } 14935 } 14936 res.name = pkgName; 14937 res.uid = newPackage.applicationInfo.uid; 14938 res.pkg = newPackage; 14939 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14940 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14941 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14942 //to update install status 14943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14944 mSettings.writeLPr(); 14945 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14946 } 14947 14948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14949 } 14950 14951 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14952 try { 14953 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14954 installPackageLI(args, res); 14955 } finally { 14956 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14957 } 14958 } 14959 14960 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14961 final int installFlags = args.installFlags; 14962 final String installerPackageName = args.installerPackageName; 14963 final String volumeUuid = args.volumeUuid; 14964 final File tmpPackageFile = new File(args.getCodePath()); 14965 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14966 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14967 || (args.volumeUuid != null)); 14968 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14969 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14970 boolean replace = false; 14971 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14972 if (args.move != null) { 14973 // moving a complete application; perform an initial scan on the new install location 14974 scanFlags |= SCAN_INITIAL; 14975 } 14976 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14977 scanFlags |= SCAN_DONT_KILL_APP; 14978 } 14979 14980 // Result object to be returned 14981 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14982 14983 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14984 14985 // Sanity check 14986 if (ephemeral && (forwardLocked || onExternal)) { 14987 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14988 + " external=" + onExternal); 14989 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14990 return; 14991 } 14992 14993 // Retrieve PackageSettings and parse package 14994 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14995 | PackageParser.PARSE_ENFORCE_CODE 14996 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14997 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14998 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14999 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15000 PackageParser pp = new PackageParser(); 15001 pp.setSeparateProcesses(mSeparateProcesses); 15002 pp.setDisplayMetrics(mMetrics); 15003 15004 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15005 final PackageParser.Package pkg; 15006 try { 15007 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15008 } catch (PackageParserException e) { 15009 res.setError("Failed parse during installPackageLI", e); 15010 return; 15011 } finally { 15012 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15013 } 15014 15015 // If we are installing a clustered package add results for the children 15016 if (pkg.childPackages != null) { 15017 synchronized (mPackages) { 15018 final int childCount = pkg.childPackages.size(); 15019 for (int i = 0; i < childCount; i++) { 15020 PackageParser.Package childPkg = pkg.childPackages.get(i); 15021 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15022 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15023 childRes.pkg = childPkg; 15024 childRes.name = childPkg.packageName; 15025 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15026 if (childPs != null) { 15027 childRes.origUsers = childPs.queryInstalledUsers( 15028 sUserManager.getUserIds(), true); 15029 } 15030 if ((mPackages.containsKey(childPkg.packageName))) { 15031 childRes.removedInfo = new PackageRemovedInfo(); 15032 childRes.removedInfo.removedPackage = childPkg.packageName; 15033 } 15034 if (res.addedChildPackages == null) { 15035 res.addedChildPackages = new ArrayMap<>(); 15036 } 15037 res.addedChildPackages.put(childPkg.packageName, childRes); 15038 } 15039 } 15040 } 15041 15042 // If package doesn't declare API override, mark that we have an install 15043 // time CPU ABI override. 15044 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15045 pkg.cpuAbiOverride = args.abiOverride; 15046 } 15047 15048 String pkgName = res.name = pkg.packageName; 15049 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15050 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15051 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15052 return; 15053 } 15054 } 15055 15056 try { 15057 // either use what we've been given or parse directly from the APK 15058 if (args.certificates != null) { 15059 try { 15060 PackageParser.populateCertificates(pkg, args.certificates); 15061 } catch (PackageParserException e) { 15062 // there was something wrong with the certificates we were given; 15063 // try to pull them from the APK 15064 PackageParser.collectCertificates(pkg, parseFlags); 15065 } 15066 } else { 15067 PackageParser.collectCertificates(pkg, parseFlags); 15068 } 15069 } catch (PackageParserException e) { 15070 res.setError("Failed collect during installPackageLI", e); 15071 return; 15072 } 15073 15074 // Get rid of all references to package scan path via parser. 15075 pp = null; 15076 String oldCodePath = null; 15077 boolean systemApp = false; 15078 synchronized (mPackages) { 15079 // Check if installing already existing package 15080 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15081 String oldName = mSettings.mRenamedPackages.get(pkgName); 15082 if (pkg.mOriginalPackages != null 15083 && pkg.mOriginalPackages.contains(oldName) 15084 && mPackages.containsKey(oldName)) { 15085 // This package is derived from an original package, 15086 // and this device has been updating from that original 15087 // name. We must continue using the original name, so 15088 // rename the new package here. 15089 pkg.setPackageName(oldName); 15090 pkgName = pkg.packageName; 15091 replace = true; 15092 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15093 + oldName + " pkgName=" + pkgName); 15094 } else if (mPackages.containsKey(pkgName)) { 15095 // This package, under its official name, already exists 15096 // on the device; we should replace it. 15097 replace = true; 15098 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15099 } 15100 15101 // Child packages are installed through the parent package 15102 if (pkg.parentPackage != null) { 15103 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15104 "Package " + pkg.packageName + " is child of package " 15105 + pkg.parentPackage.parentPackage + ". Child packages " 15106 + "can be updated only through the parent package."); 15107 return; 15108 } 15109 15110 if (replace) { 15111 // Prevent apps opting out from runtime permissions 15112 PackageParser.Package oldPackage = mPackages.get(pkgName); 15113 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15114 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15115 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15116 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15117 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15118 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15119 + " doesn't support runtime permissions but the old" 15120 + " target SDK " + oldTargetSdk + " does."); 15121 return; 15122 } 15123 15124 // Prevent installing of child packages 15125 if (oldPackage.parentPackage != null) { 15126 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15127 "Package " + pkg.packageName + " is child of package " 15128 + oldPackage.parentPackage + ". Child packages " 15129 + "can be updated only through the parent package."); 15130 return; 15131 } 15132 } 15133 } 15134 15135 PackageSetting ps = mSettings.mPackages.get(pkgName); 15136 if (ps != null) { 15137 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15138 15139 // Quick sanity check that we're signed correctly if updating; 15140 // we'll check this again later when scanning, but we want to 15141 // bail early here before tripping over redefined permissions. 15142 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15143 if (!checkUpgradeKeySetLP(ps, pkg)) { 15144 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15145 + pkg.packageName + " upgrade keys do not match the " 15146 + "previously installed version"); 15147 return; 15148 } 15149 } else { 15150 try { 15151 verifySignaturesLP(ps, pkg); 15152 } catch (PackageManagerException e) { 15153 res.setError(e.error, e.getMessage()); 15154 return; 15155 } 15156 } 15157 15158 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15159 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15160 systemApp = (ps.pkg.applicationInfo.flags & 15161 ApplicationInfo.FLAG_SYSTEM) != 0; 15162 } 15163 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15164 } 15165 15166 // Check whether the newly-scanned package wants to define an already-defined perm 15167 int N = pkg.permissions.size(); 15168 for (int i = N-1; i >= 0; i--) { 15169 PackageParser.Permission perm = pkg.permissions.get(i); 15170 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15171 if (bp != null) { 15172 // If the defining package is signed with our cert, it's okay. This 15173 // also includes the "updating the same package" case, of course. 15174 // "updating same package" could also involve key-rotation. 15175 final boolean sigsOk; 15176 if (bp.sourcePackage.equals(pkg.packageName) 15177 && (bp.packageSetting instanceof PackageSetting) 15178 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15179 scanFlags))) { 15180 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15181 } else { 15182 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15183 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15184 } 15185 if (!sigsOk) { 15186 // If the owning package is the system itself, we log but allow 15187 // install to proceed; we fail the install on all other permission 15188 // redefinitions. 15189 if (!bp.sourcePackage.equals("android")) { 15190 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15191 + pkg.packageName + " attempting to redeclare permission " 15192 + perm.info.name + " already owned by " + bp.sourcePackage); 15193 res.origPermission = perm.info.name; 15194 res.origPackage = bp.sourcePackage; 15195 return; 15196 } else { 15197 Slog.w(TAG, "Package " + pkg.packageName 15198 + " attempting to redeclare system permission " 15199 + perm.info.name + "; ignoring new declaration"); 15200 pkg.permissions.remove(i); 15201 } 15202 } 15203 } 15204 } 15205 } 15206 15207 if (systemApp) { 15208 if (onExternal) { 15209 // Abort update; system app can't be replaced with app on sdcard 15210 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15211 "Cannot install updates to system apps on sdcard"); 15212 return; 15213 } else if (ephemeral) { 15214 // Abort update; system app can't be replaced with an ephemeral app 15215 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15216 "Cannot update a system app with an ephemeral app"); 15217 return; 15218 } 15219 } 15220 15221 if (args.move != null) { 15222 // We did an in-place move, so dex is ready to roll 15223 scanFlags |= SCAN_NO_DEX; 15224 scanFlags |= SCAN_MOVE; 15225 15226 synchronized (mPackages) { 15227 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15228 if (ps == null) { 15229 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15230 "Missing settings for moved package " + pkgName); 15231 } 15232 15233 // We moved the entire application as-is, so bring over the 15234 // previously derived ABI information. 15235 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15236 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15237 } 15238 15239 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15240 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15241 scanFlags |= SCAN_NO_DEX; 15242 15243 try { 15244 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15245 args.abiOverride : pkg.cpuAbiOverride); 15246 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15247 true /* extract libs */); 15248 } catch (PackageManagerException pme) { 15249 Slog.e(TAG, "Error deriving application ABI", pme); 15250 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15251 return; 15252 } 15253 15254 // Shared libraries for the package need to be updated. 15255 synchronized (mPackages) { 15256 try { 15257 updateSharedLibrariesLPw(pkg, null); 15258 } catch (PackageManagerException e) { 15259 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15260 } 15261 } 15262 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15263 // Do not run PackageDexOptimizer through the local performDexOpt 15264 // method because `pkg` may not be in `mPackages` yet. 15265 // 15266 // Also, don't fail application installs if the dexopt step fails. 15267 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15268 null /* instructionSets */, false /* checkProfiles */, 15269 getCompilerFilterForReason(REASON_INSTALL), 15270 getOrCreateCompilerPackageStats(pkg)); 15271 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15272 15273 // Notify BackgroundDexOptService that the package has been changed. 15274 // If this is an update of a package which used to fail to compile, 15275 // BDOS will remove it from its blacklist. 15276 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15277 } 15278 15279 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15280 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15281 return; 15282 } 15283 15284 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15285 15286 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15287 "installPackageLI")) { 15288 if (replace) { 15289 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15290 installerPackageName, res); 15291 } else { 15292 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15293 args.user, installerPackageName, volumeUuid, res); 15294 } 15295 } 15296 synchronized (mPackages) { 15297 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15298 if (ps != null) { 15299 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15300 } 15301 15302 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15303 for (int i = 0; i < childCount; i++) { 15304 PackageParser.Package childPkg = pkg.childPackages.get(i); 15305 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15306 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15307 if (childPs != null) { 15308 childRes.newUsers = childPs.queryInstalledUsers( 15309 sUserManager.getUserIds(), true); 15310 } 15311 } 15312 } 15313 } 15314 15315 private void startIntentFilterVerifications(int userId, boolean replacing, 15316 PackageParser.Package pkg) { 15317 if (mIntentFilterVerifierComponent == null) { 15318 Slog.w(TAG, "No IntentFilter verification will not be done as " 15319 + "there is no IntentFilterVerifier available!"); 15320 return; 15321 } 15322 15323 final int verifierUid = getPackageUid( 15324 mIntentFilterVerifierComponent.getPackageName(), 15325 MATCH_DEBUG_TRIAGED_MISSING, 15326 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15327 15328 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15329 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15330 mHandler.sendMessage(msg); 15331 15332 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15333 for (int i = 0; i < childCount; i++) { 15334 PackageParser.Package childPkg = pkg.childPackages.get(i); 15335 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15336 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15337 mHandler.sendMessage(msg); 15338 } 15339 } 15340 15341 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15342 PackageParser.Package pkg) { 15343 int size = pkg.activities.size(); 15344 if (size == 0) { 15345 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15346 "No activity, so no need to verify any IntentFilter!"); 15347 return; 15348 } 15349 15350 final boolean hasDomainURLs = hasDomainURLs(pkg); 15351 if (!hasDomainURLs) { 15352 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15353 "No domain URLs, so no need to verify any IntentFilter!"); 15354 return; 15355 } 15356 15357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15358 + " if any IntentFilter from the " + size 15359 + " Activities needs verification ..."); 15360 15361 int count = 0; 15362 final String packageName = pkg.packageName; 15363 15364 synchronized (mPackages) { 15365 // If this is a new install and we see that we've already run verification for this 15366 // package, we have nothing to do: it means the state was restored from backup. 15367 if (!replacing) { 15368 IntentFilterVerificationInfo ivi = 15369 mSettings.getIntentFilterVerificationLPr(packageName); 15370 if (ivi != null) { 15371 if (DEBUG_DOMAIN_VERIFICATION) { 15372 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15373 + ivi.getStatusString()); 15374 } 15375 return; 15376 } 15377 } 15378 15379 // If any filters need to be verified, then all need to be. 15380 boolean needToVerify = false; 15381 for (PackageParser.Activity a : pkg.activities) { 15382 for (ActivityIntentInfo filter : a.intents) { 15383 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15384 if (DEBUG_DOMAIN_VERIFICATION) { 15385 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15386 } 15387 needToVerify = true; 15388 break; 15389 } 15390 } 15391 } 15392 15393 if (needToVerify) { 15394 final int verificationId = mIntentFilterVerificationToken++; 15395 for (PackageParser.Activity a : pkg.activities) { 15396 for (ActivityIntentInfo filter : a.intents) { 15397 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15398 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15399 "Verification needed for IntentFilter:" + filter.toString()); 15400 mIntentFilterVerifier.addOneIntentFilterVerification( 15401 verifierUid, userId, verificationId, filter, packageName); 15402 count++; 15403 } 15404 } 15405 } 15406 } 15407 } 15408 15409 if (count > 0) { 15410 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15411 + " IntentFilter verification" + (count > 1 ? "s" : "") 15412 + " for userId:" + userId); 15413 mIntentFilterVerifier.startVerifications(userId); 15414 } else { 15415 if (DEBUG_DOMAIN_VERIFICATION) { 15416 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15417 } 15418 } 15419 } 15420 15421 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15422 final ComponentName cn = filter.activity.getComponentName(); 15423 final String packageName = cn.getPackageName(); 15424 15425 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15426 packageName); 15427 if (ivi == null) { 15428 return true; 15429 } 15430 int status = ivi.getStatus(); 15431 switch (status) { 15432 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15433 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15434 return true; 15435 15436 default: 15437 // Nothing to do 15438 return false; 15439 } 15440 } 15441 15442 private static boolean isMultiArch(ApplicationInfo info) { 15443 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15444 } 15445 15446 private static boolean isExternal(PackageParser.Package pkg) { 15447 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15448 } 15449 15450 private static boolean isExternal(PackageSetting ps) { 15451 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15452 } 15453 15454 private static boolean isEphemeral(PackageParser.Package pkg) { 15455 return pkg.applicationInfo.isEphemeralApp(); 15456 } 15457 15458 private static boolean isEphemeral(PackageSetting ps) { 15459 return ps.pkg != null && isEphemeral(ps.pkg); 15460 } 15461 15462 private static boolean isSystemApp(PackageParser.Package pkg) { 15463 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15464 } 15465 15466 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15467 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15468 } 15469 15470 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15471 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15472 } 15473 15474 private static boolean isSystemApp(PackageSetting ps) { 15475 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15476 } 15477 15478 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15479 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15480 } 15481 15482 private int packageFlagsToInstallFlags(PackageSetting ps) { 15483 int installFlags = 0; 15484 if (isEphemeral(ps)) { 15485 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15486 } 15487 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15488 // This existing package was an external ASEC install when we have 15489 // the external flag without a UUID 15490 installFlags |= PackageManager.INSTALL_EXTERNAL; 15491 } 15492 if (ps.isForwardLocked()) { 15493 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15494 } 15495 return installFlags; 15496 } 15497 15498 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15499 if (isExternal(pkg)) { 15500 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15501 return StorageManager.UUID_PRIMARY_PHYSICAL; 15502 } else { 15503 return pkg.volumeUuid; 15504 } 15505 } else { 15506 return StorageManager.UUID_PRIVATE_INTERNAL; 15507 } 15508 } 15509 15510 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15511 if (isExternal(pkg)) { 15512 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15513 return mSettings.getExternalVersion(); 15514 } else { 15515 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15516 } 15517 } else { 15518 return mSettings.getInternalVersion(); 15519 } 15520 } 15521 15522 private void deleteTempPackageFiles() { 15523 final FilenameFilter filter = new FilenameFilter() { 15524 public boolean accept(File dir, String name) { 15525 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15526 } 15527 }; 15528 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15529 file.delete(); 15530 } 15531 } 15532 15533 @Override 15534 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15535 int flags) { 15536 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15537 flags); 15538 } 15539 15540 @Override 15541 public void deletePackage(final String packageName, 15542 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15543 mContext.enforceCallingOrSelfPermission( 15544 android.Manifest.permission.DELETE_PACKAGES, null); 15545 Preconditions.checkNotNull(packageName); 15546 Preconditions.checkNotNull(observer); 15547 final int uid = Binder.getCallingUid(); 15548 if (!isOrphaned(packageName) 15549 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15550 try { 15551 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15552 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15553 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15554 observer.onUserActionRequired(intent); 15555 } catch (RemoteException re) { 15556 } 15557 return; 15558 } 15559 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15560 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15561 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15562 mContext.enforceCallingOrSelfPermission( 15563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15564 "deletePackage for user " + userId); 15565 } 15566 15567 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15568 try { 15569 observer.onPackageDeleted(packageName, 15570 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15571 } catch (RemoteException re) { 15572 } 15573 return; 15574 } 15575 15576 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15577 try { 15578 observer.onPackageDeleted(packageName, 15579 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15580 } catch (RemoteException re) { 15581 } 15582 return; 15583 } 15584 15585 if (DEBUG_REMOVE) { 15586 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15587 + " deleteAllUsers: " + deleteAllUsers ); 15588 } 15589 // Queue up an async operation since the package deletion may take a little while. 15590 mHandler.post(new Runnable() { 15591 public void run() { 15592 mHandler.removeCallbacks(this); 15593 int returnCode; 15594 if (!deleteAllUsers) { 15595 returnCode = deletePackageX(packageName, userId, deleteFlags); 15596 } else { 15597 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15598 // If nobody is blocking uninstall, proceed with delete for all users 15599 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15600 returnCode = deletePackageX(packageName, userId, deleteFlags); 15601 } else { 15602 // Otherwise uninstall individually for users with blockUninstalls=false 15603 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15604 for (int userId : users) { 15605 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15606 returnCode = deletePackageX(packageName, userId, userFlags); 15607 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15608 Slog.w(TAG, "Package delete failed for user " + userId 15609 + ", returnCode " + returnCode); 15610 } 15611 } 15612 } 15613 // The app has only been marked uninstalled for certain users. 15614 // We still need to report that delete was blocked 15615 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15616 } 15617 } 15618 try { 15619 observer.onPackageDeleted(packageName, returnCode, null); 15620 } catch (RemoteException e) { 15621 Log.i(TAG, "Observer no longer exists."); 15622 } //end catch 15623 } //end run 15624 }); 15625 } 15626 15627 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15628 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15629 || callingUid == Process.SYSTEM_UID) { 15630 return true; 15631 } 15632 final int callingUserId = UserHandle.getUserId(callingUid); 15633 // If the caller installed the pkgName, then allow it to silently uninstall. 15634 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15635 return true; 15636 } 15637 15638 // Allow package verifier to silently uninstall. 15639 if (mRequiredVerifierPackage != null && 15640 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15641 return true; 15642 } 15643 15644 // Allow package uninstaller to silently uninstall. 15645 if (mRequiredUninstallerPackage != null && 15646 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15647 return true; 15648 } 15649 15650 // Allow storage manager to silently uninstall. 15651 if (mStorageManagerPackage != null && 15652 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15653 return true; 15654 } 15655 return false; 15656 } 15657 15658 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15659 int[] result = EMPTY_INT_ARRAY; 15660 for (int userId : userIds) { 15661 if (getBlockUninstallForUser(packageName, userId)) { 15662 result = ArrayUtils.appendInt(result, userId); 15663 } 15664 } 15665 return result; 15666 } 15667 15668 @Override 15669 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15670 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15671 } 15672 15673 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15674 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15675 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15676 try { 15677 if (dpm != null) { 15678 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15679 /* callingUserOnly =*/ false); 15680 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15681 : deviceOwnerComponentName.getPackageName(); 15682 // Does the package contains the device owner? 15683 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15684 // this check is probably not needed, since DO should be registered as a device 15685 // admin on some user too. (Original bug for this: b/17657954) 15686 if (packageName.equals(deviceOwnerPackageName)) { 15687 return true; 15688 } 15689 // Does it contain a device admin for any user? 15690 int[] users; 15691 if (userId == UserHandle.USER_ALL) { 15692 users = sUserManager.getUserIds(); 15693 } else { 15694 users = new int[]{userId}; 15695 } 15696 for (int i = 0; i < users.length; ++i) { 15697 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15698 return true; 15699 } 15700 } 15701 } 15702 } catch (RemoteException e) { 15703 } 15704 return false; 15705 } 15706 15707 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15708 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15709 } 15710 15711 /** 15712 * This method is an internal method that could be get invoked either 15713 * to delete an installed package or to clean up a failed installation. 15714 * After deleting an installed package, a broadcast is sent to notify any 15715 * listeners that the package has been removed. For cleaning up a failed 15716 * installation, the broadcast is not necessary since the package's 15717 * installation wouldn't have sent the initial broadcast either 15718 * The key steps in deleting a package are 15719 * deleting the package information in internal structures like mPackages, 15720 * deleting the packages base directories through installd 15721 * updating mSettings to reflect current status 15722 * persisting settings for later use 15723 * sending a broadcast if necessary 15724 */ 15725 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15726 final PackageRemovedInfo info = new PackageRemovedInfo(); 15727 final boolean res; 15728 15729 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15730 ? UserHandle.USER_ALL : userId; 15731 15732 if (isPackageDeviceAdmin(packageName, removeUser)) { 15733 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15734 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15735 } 15736 15737 PackageSetting uninstalledPs = null; 15738 15739 // for the uninstall-updates case and restricted profiles, remember the per- 15740 // user handle installed state 15741 int[] allUsers; 15742 synchronized (mPackages) { 15743 uninstalledPs = mSettings.mPackages.get(packageName); 15744 if (uninstalledPs == null) { 15745 Slog.w(TAG, "Not removing non-existent package " + packageName); 15746 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15747 } 15748 allUsers = sUserManager.getUserIds(); 15749 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15750 } 15751 15752 final int freezeUser; 15753 if (isUpdatedSystemApp(uninstalledPs) 15754 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15755 // We're downgrading a system app, which will apply to all users, so 15756 // freeze them all during the downgrade 15757 freezeUser = UserHandle.USER_ALL; 15758 } else { 15759 freezeUser = removeUser; 15760 } 15761 15762 synchronized (mInstallLock) { 15763 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15764 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15765 deleteFlags, "deletePackageX")) { 15766 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15767 deleteFlags | REMOVE_CHATTY, info, true, null); 15768 } 15769 synchronized (mPackages) { 15770 if (res) { 15771 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15772 } 15773 } 15774 } 15775 15776 if (res) { 15777 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15778 info.sendPackageRemovedBroadcasts(killApp); 15779 info.sendSystemPackageUpdatedBroadcasts(); 15780 info.sendSystemPackageAppearedBroadcasts(); 15781 } 15782 // Force a gc here. 15783 Runtime.getRuntime().gc(); 15784 // Delete the resources here after sending the broadcast to let 15785 // other processes clean up before deleting resources. 15786 if (info.args != null) { 15787 synchronized (mInstallLock) { 15788 info.args.doPostDeleteLI(true); 15789 } 15790 } 15791 15792 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15793 } 15794 15795 class PackageRemovedInfo { 15796 String removedPackage; 15797 int uid = -1; 15798 int removedAppId = -1; 15799 int[] origUsers; 15800 int[] removedUsers = null; 15801 boolean isRemovedPackageSystemUpdate = false; 15802 boolean isUpdate; 15803 boolean dataRemoved; 15804 boolean removedForAllUsers; 15805 // Clean up resources deleted packages. 15806 InstallArgs args = null; 15807 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15808 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15809 15810 void sendPackageRemovedBroadcasts(boolean killApp) { 15811 sendPackageRemovedBroadcastInternal(killApp); 15812 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15813 for (int i = 0; i < childCount; i++) { 15814 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15815 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15816 } 15817 } 15818 15819 void sendSystemPackageUpdatedBroadcasts() { 15820 if (isRemovedPackageSystemUpdate) { 15821 sendSystemPackageUpdatedBroadcastsInternal(); 15822 final int childCount = (removedChildPackages != null) 15823 ? removedChildPackages.size() : 0; 15824 for (int i = 0; i < childCount; i++) { 15825 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15826 if (childInfo.isRemovedPackageSystemUpdate) { 15827 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15828 } 15829 } 15830 } 15831 } 15832 15833 void sendSystemPackageAppearedBroadcasts() { 15834 final int packageCount = (appearedChildPackages != null) 15835 ? appearedChildPackages.size() : 0; 15836 for (int i = 0; i < packageCount; i++) { 15837 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15838 for (int userId : installedInfo.newUsers) { 15839 sendPackageAddedForUser(installedInfo.name, true, 15840 UserHandle.getAppId(installedInfo.uid), userId); 15841 } 15842 } 15843 } 15844 15845 private void sendSystemPackageUpdatedBroadcastsInternal() { 15846 Bundle extras = new Bundle(2); 15847 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15848 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15849 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15850 extras, 0, null, null, null); 15851 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15852 extras, 0, null, null, null); 15853 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15854 null, 0, removedPackage, null, null); 15855 } 15856 15857 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15858 Bundle extras = new Bundle(2); 15859 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15860 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15861 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15862 if (isUpdate || isRemovedPackageSystemUpdate) { 15863 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15864 } 15865 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15866 if (removedPackage != null) { 15867 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15868 extras, 0, null, null, removedUsers); 15869 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15870 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15871 removedPackage, extras, 0, null, null, removedUsers); 15872 } 15873 } 15874 if (removedAppId >= 0) { 15875 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15876 removedUsers); 15877 } 15878 } 15879 } 15880 15881 /* 15882 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15883 * flag is not set, the data directory is removed as well. 15884 * make sure this flag is set for partially installed apps. If not its meaningless to 15885 * delete a partially installed application. 15886 */ 15887 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15888 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15889 String packageName = ps.name; 15890 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15891 // Retrieve object to delete permissions for shared user later on 15892 final PackageParser.Package deletedPkg; 15893 final PackageSetting deletedPs; 15894 // reader 15895 synchronized (mPackages) { 15896 deletedPkg = mPackages.get(packageName); 15897 deletedPs = mSettings.mPackages.get(packageName); 15898 if (outInfo != null) { 15899 outInfo.removedPackage = packageName; 15900 outInfo.removedUsers = deletedPs != null 15901 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15902 : null; 15903 } 15904 } 15905 15906 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15907 15908 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15909 final PackageParser.Package resolvedPkg; 15910 if (deletedPkg != null) { 15911 resolvedPkg = deletedPkg; 15912 } else { 15913 // We don't have a parsed package when it lives on an ejected 15914 // adopted storage device, so fake something together 15915 resolvedPkg = new PackageParser.Package(ps.name); 15916 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15917 } 15918 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15919 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15920 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15921 if (outInfo != null) { 15922 outInfo.dataRemoved = true; 15923 } 15924 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15925 } 15926 15927 // writer 15928 synchronized (mPackages) { 15929 if (deletedPs != null) { 15930 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15931 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15932 clearDefaultBrowserIfNeeded(packageName); 15933 if (outInfo != null) { 15934 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15935 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15936 } 15937 updatePermissionsLPw(deletedPs.name, null, 0); 15938 if (deletedPs.sharedUser != null) { 15939 // Remove permissions associated with package. Since runtime 15940 // permissions are per user we have to kill the removed package 15941 // or packages running under the shared user of the removed 15942 // package if revoking the permissions requested only by the removed 15943 // package is successful and this causes a change in gids. 15944 for (int userId : UserManagerService.getInstance().getUserIds()) { 15945 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15946 userId); 15947 if (userIdToKill == UserHandle.USER_ALL 15948 || userIdToKill >= UserHandle.USER_SYSTEM) { 15949 // If gids changed for this user, kill all affected packages. 15950 mHandler.post(new Runnable() { 15951 @Override 15952 public void run() { 15953 // This has to happen with no lock held. 15954 killApplication(deletedPs.name, deletedPs.appId, 15955 KILL_APP_REASON_GIDS_CHANGED); 15956 } 15957 }); 15958 break; 15959 } 15960 } 15961 } 15962 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15963 } 15964 // make sure to preserve per-user disabled state if this removal was just 15965 // a downgrade of a system app to the factory package 15966 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15967 if (DEBUG_REMOVE) { 15968 Slog.d(TAG, "Propagating install state across downgrade"); 15969 } 15970 for (int userId : allUserHandles) { 15971 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15972 if (DEBUG_REMOVE) { 15973 Slog.d(TAG, " user " + userId + " => " + installed); 15974 } 15975 ps.setInstalled(installed, userId); 15976 } 15977 } 15978 } 15979 // can downgrade to reader 15980 if (writeSettings) { 15981 // Save settings now 15982 mSettings.writeLPr(); 15983 } 15984 } 15985 if (outInfo != null) { 15986 // A user ID was deleted here. Go through all users and remove it 15987 // from KeyStore. 15988 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15989 } 15990 } 15991 15992 static boolean locationIsPrivileged(File path) { 15993 try { 15994 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15995 .getCanonicalPath(); 15996 return path.getCanonicalPath().startsWith(privilegedAppDir); 15997 } catch (IOException e) { 15998 Slog.e(TAG, "Unable to access code path " + path); 15999 } 16000 return false; 16001 } 16002 16003 /* 16004 * Tries to delete system package. 16005 */ 16006 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16007 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16008 boolean writeSettings) { 16009 if (deletedPs.parentPackageName != null) { 16010 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16011 return false; 16012 } 16013 16014 final boolean applyUserRestrictions 16015 = (allUserHandles != null) && (outInfo.origUsers != null); 16016 final PackageSetting disabledPs; 16017 // Confirm if the system package has been updated 16018 // An updated system app can be deleted. This will also have to restore 16019 // the system pkg from system partition 16020 // reader 16021 synchronized (mPackages) { 16022 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16023 } 16024 16025 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16026 + " disabledPs=" + disabledPs); 16027 16028 if (disabledPs == null) { 16029 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16030 return false; 16031 } else if (DEBUG_REMOVE) { 16032 Slog.d(TAG, "Deleting system pkg from data partition"); 16033 } 16034 16035 if (DEBUG_REMOVE) { 16036 if (applyUserRestrictions) { 16037 Slog.d(TAG, "Remembering install states:"); 16038 for (int userId : allUserHandles) { 16039 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16040 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16041 } 16042 } 16043 } 16044 16045 // Delete the updated package 16046 outInfo.isRemovedPackageSystemUpdate = true; 16047 if (outInfo.removedChildPackages != null) { 16048 final int childCount = (deletedPs.childPackageNames != null) 16049 ? deletedPs.childPackageNames.size() : 0; 16050 for (int i = 0; i < childCount; i++) { 16051 String childPackageName = deletedPs.childPackageNames.get(i); 16052 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16053 .contains(childPackageName)) { 16054 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16055 childPackageName); 16056 if (childInfo != null) { 16057 childInfo.isRemovedPackageSystemUpdate = true; 16058 } 16059 } 16060 } 16061 } 16062 16063 if (disabledPs.versionCode < deletedPs.versionCode) { 16064 // Delete data for downgrades 16065 flags &= ~PackageManager.DELETE_KEEP_DATA; 16066 } else { 16067 // Preserve data by setting flag 16068 flags |= PackageManager.DELETE_KEEP_DATA; 16069 } 16070 16071 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16072 outInfo, writeSettings, disabledPs.pkg); 16073 if (!ret) { 16074 return false; 16075 } 16076 16077 // writer 16078 synchronized (mPackages) { 16079 // Reinstate the old system package 16080 enableSystemPackageLPw(disabledPs.pkg); 16081 // Remove any native libraries from the upgraded package. 16082 removeNativeBinariesLI(deletedPs); 16083 } 16084 16085 // Install the system package 16086 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16087 int parseFlags = mDefParseFlags 16088 | PackageParser.PARSE_MUST_BE_APK 16089 | PackageParser.PARSE_IS_SYSTEM 16090 | PackageParser.PARSE_IS_SYSTEM_DIR; 16091 if (locationIsPrivileged(disabledPs.codePath)) { 16092 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16093 } 16094 16095 final PackageParser.Package newPkg; 16096 try { 16097 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16098 } catch (PackageManagerException e) { 16099 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16100 + e.getMessage()); 16101 return false; 16102 } 16103 try { 16104 // update shared libraries for the newly re-installed system package 16105 updateSharedLibrariesLPw(newPkg, null); 16106 } catch (PackageManagerException e) { 16107 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16108 } 16109 16110 prepareAppDataAfterInstallLIF(newPkg); 16111 16112 // writer 16113 synchronized (mPackages) { 16114 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16115 16116 // Propagate the permissions state as we do not want to drop on the floor 16117 // runtime permissions. The update permissions method below will take 16118 // care of removing obsolete permissions and grant install permissions. 16119 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16120 updatePermissionsLPw(newPkg.packageName, newPkg, 16121 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16122 16123 if (applyUserRestrictions) { 16124 if (DEBUG_REMOVE) { 16125 Slog.d(TAG, "Propagating install state across reinstall"); 16126 } 16127 for (int userId : allUserHandles) { 16128 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16129 if (DEBUG_REMOVE) { 16130 Slog.d(TAG, " user " + userId + " => " + installed); 16131 } 16132 ps.setInstalled(installed, userId); 16133 16134 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16135 } 16136 // Regardless of writeSettings we need to ensure that this restriction 16137 // state propagation is persisted 16138 mSettings.writeAllUsersPackageRestrictionsLPr(); 16139 } 16140 // can downgrade to reader here 16141 if (writeSettings) { 16142 mSettings.writeLPr(); 16143 } 16144 } 16145 return true; 16146 } 16147 16148 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16149 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16150 PackageRemovedInfo outInfo, boolean writeSettings, 16151 PackageParser.Package replacingPackage) { 16152 synchronized (mPackages) { 16153 if (outInfo != null) { 16154 outInfo.uid = ps.appId; 16155 } 16156 16157 if (outInfo != null && outInfo.removedChildPackages != null) { 16158 final int childCount = (ps.childPackageNames != null) 16159 ? ps.childPackageNames.size() : 0; 16160 for (int i = 0; i < childCount; i++) { 16161 String childPackageName = ps.childPackageNames.get(i); 16162 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16163 if (childPs == null) { 16164 return false; 16165 } 16166 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16167 childPackageName); 16168 if (childInfo != null) { 16169 childInfo.uid = childPs.appId; 16170 } 16171 } 16172 } 16173 } 16174 16175 // Delete package data from internal structures and also remove data if flag is set 16176 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16177 16178 // Delete the child packages data 16179 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16180 for (int i = 0; i < childCount; i++) { 16181 PackageSetting childPs; 16182 synchronized (mPackages) { 16183 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16184 } 16185 if (childPs != null) { 16186 PackageRemovedInfo childOutInfo = (outInfo != null 16187 && outInfo.removedChildPackages != null) 16188 ? outInfo.removedChildPackages.get(childPs.name) : null; 16189 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16190 && (replacingPackage != null 16191 && !replacingPackage.hasChildPackage(childPs.name)) 16192 ? flags & ~DELETE_KEEP_DATA : flags; 16193 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16194 deleteFlags, writeSettings); 16195 } 16196 } 16197 16198 // Delete application code and resources only for parent packages 16199 if (ps.parentPackageName == null) { 16200 if (deleteCodeAndResources && (outInfo != null)) { 16201 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16202 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16203 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16204 } 16205 } 16206 16207 return true; 16208 } 16209 16210 @Override 16211 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16212 int userId) { 16213 mContext.enforceCallingOrSelfPermission( 16214 android.Manifest.permission.DELETE_PACKAGES, null); 16215 synchronized (mPackages) { 16216 PackageSetting ps = mSettings.mPackages.get(packageName); 16217 if (ps == null) { 16218 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16219 return false; 16220 } 16221 if (!ps.getInstalled(userId)) { 16222 // Can't block uninstall for an app that is not installed or enabled. 16223 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16224 return false; 16225 } 16226 ps.setBlockUninstall(blockUninstall, userId); 16227 mSettings.writePackageRestrictionsLPr(userId); 16228 } 16229 return true; 16230 } 16231 16232 @Override 16233 public boolean getBlockUninstallForUser(String packageName, int userId) { 16234 synchronized (mPackages) { 16235 PackageSetting ps = mSettings.mPackages.get(packageName); 16236 if (ps == null) { 16237 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16238 return false; 16239 } 16240 return ps.getBlockUninstall(userId); 16241 } 16242 } 16243 16244 @Override 16245 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16246 int callingUid = Binder.getCallingUid(); 16247 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16248 throw new SecurityException( 16249 "setRequiredForSystemUser can only be run by the system or root"); 16250 } 16251 synchronized (mPackages) { 16252 PackageSetting ps = mSettings.mPackages.get(packageName); 16253 if (ps == null) { 16254 Log.w(TAG, "Package doesn't exist: " + packageName); 16255 return false; 16256 } 16257 if (systemUserApp) { 16258 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16259 } else { 16260 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16261 } 16262 mSettings.writeLPr(); 16263 } 16264 return true; 16265 } 16266 16267 /* 16268 * This method handles package deletion in general 16269 */ 16270 private boolean deletePackageLIF(String packageName, UserHandle user, 16271 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16272 PackageRemovedInfo outInfo, boolean writeSettings, 16273 PackageParser.Package replacingPackage) { 16274 if (packageName == null) { 16275 Slog.w(TAG, "Attempt to delete null packageName."); 16276 return false; 16277 } 16278 16279 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16280 16281 PackageSetting ps; 16282 16283 synchronized (mPackages) { 16284 ps = mSettings.mPackages.get(packageName); 16285 if (ps == null) { 16286 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16287 return false; 16288 } 16289 16290 if (ps.parentPackageName != null && (!isSystemApp(ps) 16291 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16292 if (DEBUG_REMOVE) { 16293 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16294 + ((user == null) ? UserHandle.USER_ALL : user)); 16295 } 16296 final int removedUserId = (user != null) ? user.getIdentifier() 16297 : UserHandle.USER_ALL; 16298 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16299 return false; 16300 } 16301 markPackageUninstalledForUserLPw(ps, user); 16302 scheduleWritePackageRestrictionsLocked(user); 16303 return true; 16304 } 16305 } 16306 16307 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16308 && user.getIdentifier() != UserHandle.USER_ALL)) { 16309 // The caller is asking that the package only be deleted for a single 16310 // user. To do this, we just mark its uninstalled state and delete 16311 // its data. If this is a system app, we only allow this to happen if 16312 // they have set the special DELETE_SYSTEM_APP which requests different 16313 // semantics than normal for uninstalling system apps. 16314 markPackageUninstalledForUserLPw(ps, user); 16315 16316 if (!isSystemApp(ps)) { 16317 // Do not uninstall the APK if an app should be cached 16318 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16319 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16320 // Other user still have this package installed, so all 16321 // we need to do is clear this user's data and save that 16322 // it is uninstalled. 16323 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16324 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16325 return false; 16326 } 16327 scheduleWritePackageRestrictionsLocked(user); 16328 return true; 16329 } else { 16330 // We need to set it back to 'installed' so the uninstall 16331 // broadcasts will be sent correctly. 16332 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16333 ps.setInstalled(true, user.getIdentifier()); 16334 } 16335 } else { 16336 // This is a system app, so we assume that the 16337 // other users still have this package installed, so all 16338 // we need to do is clear this user's data and save that 16339 // it is uninstalled. 16340 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16341 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16342 return false; 16343 } 16344 scheduleWritePackageRestrictionsLocked(user); 16345 return true; 16346 } 16347 } 16348 16349 // If we are deleting a composite package for all users, keep track 16350 // of result for each child. 16351 if (ps.childPackageNames != null && outInfo != null) { 16352 synchronized (mPackages) { 16353 final int childCount = ps.childPackageNames.size(); 16354 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16355 for (int i = 0; i < childCount; i++) { 16356 String childPackageName = ps.childPackageNames.get(i); 16357 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16358 childInfo.removedPackage = childPackageName; 16359 outInfo.removedChildPackages.put(childPackageName, childInfo); 16360 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16361 if (childPs != null) { 16362 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16363 } 16364 } 16365 } 16366 } 16367 16368 boolean ret = false; 16369 if (isSystemApp(ps)) { 16370 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16371 // When an updated system application is deleted we delete the existing resources 16372 // as well and fall back to existing code in system partition 16373 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16374 } else { 16375 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16376 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16377 outInfo, writeSettings, replacingPackage); 16378 } 16379 16380 // Take a note whether we deleted the package for all users 16381 if (outInfo != null) { 16382 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16383 if (outInfo.removedChildPackages != null) { 16384 synchronized (mPackages) { 16385 final int childCount = outInfo.removedChildPackages.size(); 16386 for (int i = 0; i < childCount; i++) { 16387 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16388 if (childInfo != null) { 16389 childInfo.removedForAllUsers = mPackages.get( 16390 childInfo.removedPackage) == null; 16391 } 16392 } 16393 } 16394 } 16395 // If we uninstalled an update to a system app there may be some 16396 // child packages that appeared as they are declared in the system 16397 // app but were not declared in the update. 16398 if (isSystemApp(ps)) { 16399 synchronized (mPackages) { 16400 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16401 final int childCount = (updatedPs.childPackageNames != null) 16402 ? updatedPs.childPackageNames.size() : 0; 16403 for (int i = 0; i < childCount; i++) { 16404 String childPackageName = updatedPs.childPackageNames.get(i); 16405 if (outInfo.removedChildPackages == null 16406 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16407 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16408 if (childPs == null) { 16409 continue; 16410 } 16411 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16412 installRes.name = childPackageName; 16413 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16414 installRes.pkg = mPackages.get(childPackageName); 16415 installRes.uid = childPs.pkg.applicationInfo.uid; 16416 if (outInfo.appearedChildPackages == null) { 16417 outInfo.appearedChildPackages = new ArrayMap<>(); 16418 } 16419 outInfo.appearedChildPackages.put(childPackageName, installRes); 16420 } 16421 } 16422 } 16423 } 16424 } 16425 16426 return ret; 16427 } 16428 16429 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16430 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16431 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16432 for (int nextUserId : userIds) { 16433 if (DEBUG_REMOVE) { 16434 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16435 } 16436 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16437 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16438 false /*hidden*/, false /*suspended*/, null, null, null, 16439 false /*blockUninstall*/, 16440 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16441 } 16442 } 16443 16444 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16445 PackageRemovedInfo outInfo) { 16446 final PackageParser.Package pkg; 16447 synchronized (mPackages) { 16448 pkg = mPackages.get(ps.name); 16449 } 16450 16451 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16452 : new int[] {userId}; 16453 for (int nextUserId : userIds) { 16454 if (DEBUG_REMOVE) { 16455 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16456 + nextUserId); 16457 } 16458 16459 destroyAppDataLIF(pkg, userId, 16460 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16461 destroyAppProfilesLIF(pkg, userId); 16462 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16463 schedulePackageCleaning(ps.name, nextUserId, false); 16464 synchronized (mPackages) { 16465 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16466 scheduleWritePackageRestrictionsLocked(nextUserId); 16467 } 16468 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16469 } 16470 } 16471 16472 if (outInfo != null) { 16473 outInfo.removedPackage = ps.name; 16474 outInfo.removedAppId = ps.appId; 16475 outInfo.removedUsers = userIds; 16476 } 16477 16478 return true; 16479 } 16480 16481 private final class ClearStorageConnection implements ServiceConnection { 16482 IMediaContainerService mContainerService; 16483 16484 @Override 16485 public void onServiceConnected(ComponentName name, IBinder service) { 16486 synchronized (this) { 16487 mContainerService = IMediaContainerService.Stub.asInterface(service); 16488 notifyAll(); 16489 } 16490 } 16491 16492 @Override 16493 public void onServiceDisconnected(ComponentName name) { 16494 } 16495 } 16496 16497 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16498 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16499 16500 final boolean mounted; 16501 if (Environment.isExternalStorageEmulated()) { 16502 mounted = true; 16503 } else { 16504 final String status = Environment.getExternalStorageState(); 16505 16506 mounted = status.equals(Environment.MEDIA_MOUNTED) 16507 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16508 } 16509 16510 if (!mounted) { 16511 return; 16512 } 16513 16514 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16515 int[] users; 16516 if (userId == UserHandle.USER_ALL) { 16517 users = sUserManager.getUserIds(); 16518 } else { 16519 users = new int[] { userId }; 16520 } 16521 final ClearStorageConnection conn = new ClearStorageConnection(); 16522 if (mContext.bindServiceAsUser( 16523 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16524 try { 16525 for (int curUser : users) { 16526 long timeout = SystemClock.uptimeMillis() + 5000; 16527 synchronized (conn) { 16528 long now; 16529 while (conn.mContainerService == null && 16530 (now = SystemClock.uptimeMillis()) < timeout) { 16531 try { 16532 conn.wait(timeout - now); 16533 } catch (InterruptedException e) { 16534 } 16535 } 16536 } 16537 if (conn.mContainerService == null) { 16538 return; 16539 } 16540 16541 final UserEnvironment userEnv = new UserEnvironment(curUser); 16542 clearDirectory(conn.mContainerService, 16543 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16544 if (allData) { 16545 clearDirectory(conn.mContainerService, 16546 userEnv.buildExternalStorageAppDataDirs(packageName)); 16547 clearDirectory(conn.mContainerService, 16548 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16549 } 16550 } 16551 } finally { 16552 mContext.unbindService(conn); 16553 } 16554 } 16555 } 16556 16557 @Override 16558 public void clearApplicationProfileData(String packageName) { 16559 enforceSystemOrRoot("Only the system can clear all profile data"); 16560 16561 final PackageParser.Package pkg; 16562 synchronized (mPackages) { 16563 pkg = mPackages.get(packageName); 16564 } 16565 16566 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16567 synchronized (mInstallLock) { 16568 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16569 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16570 true /* removeBaseMarker */); 16571 } 16572 } 16573 } 16574 16575 @Override 16576 public void clearApplicationUserData(final String packageName, 16577 final IPackageDataObserver observer, final int userId) { 16578 mContext.enforceCallingOrSelfPermission( 16579 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16580 16581 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16582 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16583 16584 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16585 throw new SecurityException("Cannot clear data for a protected package: " 16586 + packageName); 16587 } 16588 // Queue up an async operation since the package deletion may take a little while. 16589 mHandler.post(new Runnable() { 16590 public void run() { 16591 mHandler.removeCallbacks(this); 16592 final boolean succeeded; 16593 try (PackageFreezer freezer = freezePackage(packageName, 16594 "clearApplicationUserData")) { 16595 synchronized (mInstallLock) { 16596 succeeded = clearApplicationUserDataLIF(packageName, userId); 16597 } 16598 clearExternalStorageDataSync(packageName, userId, true); 16599 } 16600 if (succeeded) { 16601 // invoke DeviceStorageMonitor's update method to clear any notifications 16602 DeviceStorageMonitorInternal dsm = LocalServices 16603 .getService(DeviceStorageMonitorInternal.class); 16604 if (dsm != null) { 16605 dsm.checkMemory(); 16606 } 16607 } 16608 if(observer != null) { 16609 try { 16610 observer.onRemoveCompleted(packageName, succeeded); 16611 } catch (RemoteException e) { 16612 Log.i(TAG, "Observer no longer exists."); 16613 } 16614 } //end if observer 16615 } //end run 16616 }); 16617 } 16618 16619 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16620 if (packageName == null) { 16621 Slog.w(TAG, "Attempt to delete null packageName."); 16622 return false; 16623 } 16624 16625 // Try finding details about the requested package 16626 PackageParser.Package pkg; 16627 synchronized (mPackages) { 16628 pkg = mPackages.get(packageName); 16629 if (pkg == null) { 16630 final PackageSetting ps = mSettings.mPackages.get(packageName); 16631 if (ps != null) { 16632 pkg = ps.pkg; 16633 } 16634 } 16635 16636 if (pkg == null) { 16637 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16638 return false; 16639 } 16640 16641 PackageSetting ps = (PackageSetting) pkg.mExtras; 16642 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16643 } 16644 16645 clearAppDataLIF(pkg, userId, 16646 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16647 16648 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16649 removeKeystoreDataIfNeeded(userId, appId); 16650 16651 UserManagerInternal umInternal = getUserManagerInternal(); 16652 final int flags; 16653 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16654 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16655 } else if (umInternal.isUserRunning(userId)) { 16656 flags = StorageManager.FLAG_STORAGE_DE; 16657 } else { 16658 flags = 0; 16659 } 16660 prepareAppDataContentsLIF(pkg, userId, flags); 16661 16662 return true; 16663 } 16664 16665 /** 16666 * Reverts user permission state changes (permissions and flags) in 16667 * all packages for a given user. 16668 * 16669 * @param userId The device user for which to do a reset. 16670 */ 16671 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16672 final int packageCount = mPackages.size(); 16673 for (int i = 0; i < packageCount; i++) { 16674 PackageParser.Package pkg = mPackages.valueAt(i); 16675 PackageSetting ps = (PackageSetting) pkg.mExtras; 16676 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16677 } 16678 } 16679 16680 private void resetNetworkPolicies(int userId) { 16681 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16682 } 16683 16684 /** 16685 * Reverts user permission state changes (permissions and flags). 16686 * 16687 * @param ps The package for which to reset. 16688 * @param userId The device user for which to do a reset. 16689 */ 16690 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16691 final PackageSetting ps, final int userId) { 16692 if (ps.pkg == null) { 16693 return; 16694 } 16695 16696 // These are flags that can change base on user actions. 16697 final int userSettableMask = FLAG_PERMISSION_USER_SET 16698 | FLAG_PERMISSION_USER_FIXED 16699 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16700 | FLAG_PERMISSION_REVIEW_REQUIRED; 16701 16702 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16703 | FLAG_PERMISSION_POLICY_FIXED; 16704 16705 boolean writeInstallPermissions = false; 16706 boolean writeRuntimePermissions = false; 16707 16708 final int permissionCount = ps.pkg.requestedPermissions.size(); 16709 for (int i = 0; i < permissionCount; i++) { 16710 String permission = ps.pkg.requestedPermissions.get(i); 16711 16712 BasePermission bp = mSettings.mPermissions.get(permission); 16713 if (bp == null) { 16714 continue; 16715 } 16716 16717 // If shared user we just reset the state to which only this app contributed. 16718 if (ps.sharedUser != null) { 16719 boolean used = false; 16720 final int packageCount = ps.sharedUser.packages.size(); 16721 for (int j = 0; j < packageCount; j++) { 16722 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16723 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16724 && pkg.pkg.requestedPermissions.contains(permission)) { 16725 used = true; 16726 break; 16727 } 16728 } 16729 if (used) { 16730 continue; 16731 } 16732 } 16733 16734 PermissionsState permissionsState = ps.getPermissionsState(); 16735 16736 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16737 16738 // Always clear the user settable flags. 16739 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16740 bp.name) != null; 16741 // If permission review is enabled and this is a legacy app, mark the 16742 // permission as requiring a review as this is the initial state. 16743 int flags = 0; 16744 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 16745 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16746 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16747 } 16748 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16749 if (hasInstallState) { 16750 writeInstallPermissions = true; 16751 } else { 16752 writeRuntimePermissions = true; 16753 } 16754 } 16755 16756 // Below is only runtime permission handling. 16757 if (!bp.isRuntime()) { 16758 continue; 16759 } 16760 16761 // Never clobber system or policy. 16762 if ((oldFlags & policyOrSystemFlags) != 0) { 16763 continue; 16764 } 16765 16766 // If this permission was granted by default, make sure it is. 16767 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16768 if (permissionsState.grantRuntimePermission(bp, userId) 16769 != PERMISSION_OPERATION_FAILURE) { 16770 writeRuntimePermissions = true; 16771 } 16772 // If permission review is enabled the permissions for a legacy apps 16773 // are represented as constantly granted runtime ones, so don't revoke. 16774 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16775 // Otherwise, reset the permission. 16776 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16777 switch (revokeResult) { 16778 case PERMISSION_OPERATION_SUCCESS: 16779 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16780 writeRuntimePermissions = true; 16781 final int appId = ps.appId; 16782 mHandler.post(new Runnable() { 16783 @Override 16784 public void run() { 16785 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16786 } 16787 }); 16788 } break; 16789 } 16790 } 16791 } 16792 16793 // Synchronously write as we are taking permissions away. 16794 if (writeRuntimePermissions) { 16795 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16796 } 16797 16798 // Synchronously write as we are taking permissions away. 16799 if (writeInstallPermissions) { 16800 mSettings.writeLPr(); 16801 } 16802 } 16803 16804 /** 16805 * Remove entries from the keystore daemon. Will only remove it if the 16806 * {@code appId} is valid. 16807 */ 16808 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16809 if (appId < 0) { 16810 return; 16811 } 16812 16813 final KeyStore keyStore = KeyStore.getInstance(); 16814 if (keyStore != null) { 16815 if (userId == UserHandle.USER_ALL) { 16816 for (final int individual : sUserManager.getUserIds()) { 16817 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16818 } 16819 } else { 16820 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16821 } 16822 } else { 16823 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16824 } 16825 } 16826 16827 @Override 16828 public void deleteApplicationCacheFiles(final String packageName, 16829 final IPackageDataObserver observer) { 16830 final int userId = UserHandle.getCallingUserId(); 16831 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16832 } 16833 16834 @Override 16835 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16836 final IPackageDataObserver observer) { 16837 mContext.enforceCallingOrSelfPermission( 16838 android.Manifest.permission.DELETE_CACHE_FILES, null); 16839 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16840 /* requireFullPermission= */ true, /* checkShell= */ false, 16841 "delete application cache files"); 16842 16843 final PackageParser.Package pkg; 16844 synchronized (mPackages) { 16845 pkg = mPackages.get(packageName); 16846 } 16847 16848 // Queue up an async operation since the package deletion may take a little while. 16849 mHandler.post(new Runnable() { 16850 public void run() { 16851 synchronized (mInstallLock) { 16852 final int flags = StorageManager.FLAG_STORAGE_DE 16853 | StorageManager.FLAG_STORAGE_CE; 16854 // We're only clearing cache files, so we don't care if the 16855 // app is unfrozen and still able to run 16856 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16857 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16858 } 16859 clearExternalStorageDataSync(packageName, userId, false); 16860 if (observer != null) { 16861 try { 16862 observer.onRemoveCompleted(packageName, true); 16863 } catch (RemoteException e) { 16864 Log.i(TAG, "Observer no longer exists."); 16865 } 16866 } 16867 } 16868 }); 16869 } 16870 16871 @Override 16872 public void getPackageSizeInfo(final String packageName, int userHandle, 16873 final IPackageStatsObserver observer) { 16874 mContext.enforceCallingOrSelfPermission( 16875 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16876 if (packageName == null) { 16877 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16878 } 16879 16880 PackageStats stats = new PackageStats(packageName, userHandle); 16881 16882 /* 16883 * Queue up an async operation since the package measurement may take a 16884 * little while. 16885 */ 16886 Message msg = mHandler.obtainMessage(INIT_COPY); 16887 msg.obj = new MeasureParams(stats, observer); 16888 mHandler.sendMessage(msg); 16889 } 16890 16891 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16892 final PackageSetting ps; 16893 synchronized (mPackages) { 16894 ps = mSettings.mPackages.get(packageName); 16895 if (ps == null) { 16896 Slog.w(TAG, "Failed to find settings for " + packageName); 16897 return false; 16898 } 16899 } 16900 try { 16901 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16902 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16903 ps.getCeDataInode(userId), ps.codePathString, stats); 16904 } catch (InstallerException e) { 16905 Slog.w(TAG, String.valueOf(e)); 16906 return false; 16907 } 16908 16909 // For now, ignore code size of packages on system partition 16910 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16911 stats.codeSize = 0; 16912 } 16913 16914 return true; 16915 } 16916 16917 private int getUidTargetSdkVersionLockedLPr(int uid) { 16918 Object obj = mSettings.getUserIdLPr(uid); 16919 if (obj instanceof SharedUserSetting) { 16920 final SharedUserSetting sus = (SharedUserSetting) obj; 16921 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16922 final Iterator<PackageSetting> it = sus.packages.iterator(); 16923 while (it.hasNext()) { 16924 final PackageSetting ps = it.next(); 16925 if (ps.pkg != null) { 16926 int v = ps.pkg.applicationInfo.targetSdkVersion; 16927 if (v < vers) vers = v; 16928 } 16929 } 16930 return vers; 16931 } else if (obj instanceof PackageSetting) { 16932 final PackageSetting ps = (PackageSetting) obj; 16933 if (ps.pkg != null) { 16934 return ps.pkg.applicationInfo.targetSdkVersion; 16935 } 16936 } 16937 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16938 } 16939 16940 @Override 16941 public void addPreferredActivity(IntentFilter filter, int match, 16942 ComponentName[] set, ComponentName activity, int userId) { 16943 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16944 "Adding preferred"); 16945 } 16946 16947 private void addPreferredActivityInternal(IntentFilter filter, int match, 16948 ComponentName[] set, ComponentName activity, boolean always, int userId, 16949 String opname) { 16950 // writer 16951 int callingUid = Binder.getCallingUid(); 16952 enforceCrossUserPermission(callingUid, userId, 16953 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16954 if (filter.countActions() == 0) { 16955 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16956 return; 16957 } 16958 synchronized (mPackages) { 16959 if (mContext.checkCallingOrSelfPermission( 16960 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16961 != PackageManager.PERMISSION_GRANTED) { 16962 if (getUidTargetSdkVersionLockedLPr(callingUid) 16963 < Build.VERSION_CODES.FROYO) { 16964 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16965 + callingUid); 16966 return; 16967 } 16968 mContext.enforceCallingOrSelfPermission( 16969 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16970 } 16971 16972 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16973 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16974 + userId + ":"); 16975 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16976 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16977 scheduleWritePackageRestrictionsLocked(userId); 16978 postPreferredActivityChangedBroadcast(userId); 16979 } 16980 } 16981 16982 private void postPreferredActivityChangedBroadcast(int userId) { 16983 mHandler.post(() -> { 16984 final IActivityManager am = ActivityManagerNative.getDefault(); 16985 if (am == null) { 16986 return; 16987 } 16988 16989 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16990 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16991 try { 16992 am.broadcastIntent(null, intent, null, null, 16993 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16994 null, false, false, userId); 16995 } catch (RemoteException e) { 16996 } 16997 }); 16998 } 16999 17000 @Override 17001 public void replacePreferredActivity(IntentFilter filter, int match, 17002 ComponentName[] set, ComponentName activity, int userId) { 17003 if (filter.countActions() != 1) { 17004 throw new IllegalArgumentException( 17005 "replacePreferredActivity expects filter to have only 1 action."); 17006 } 17007 if (filter.countDataAuthorities() != 0 17008 || filter.countDataPaths() != 0 17009 || filter.countDataSchemes() > 1 17010 || filter.countDataTypes() != 0) { 17011 throw new IllegalArgumentException( 17012 "replacePreferredActivity expects filter to have no data authorities, " + 17013 "paths, or types; and at most one scheme."); 17014 } 17015 17016 final int callingUid = Binder.getCallingUid(); 17017 enforceCrossUserPermission(callingUid, userId, 17018 true /* requireFullPermission */, false /* checkShell */, 17019 "replace preferred activity"); 17020 synchronized (mPackages) { 17021 if (mContext.checkCallingOrSelfPermission( 17022 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17023 != PackageManager.PERMISSION_GRANTED) { 17024 if (getUidTargetSdkVersionLockedLPr(callingUid) 17025 < Build.VERSION_CODES.FROYO) { 17026 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17027 + Binder.getCallingUid()); 17028 return; 17029 } 17030 mContext.enforceCallingOrSelfPermission( 17031 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17032 } 17033 17034 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17035 if (pir != null) { 17036 // Get all of the existing entries that exactly match this filter. 17037 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17038 if (existing != null && existing.size() == 1) { 17039 PreferredActivity cur = existing.get(0); 17040 if (DEBUG_PREFERRED) { 17041 Slog.i(TAG, "Checking replace of preferred:"); 17042 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17043 if (!cur.mPref.mAlways) { 17044 Slog.i(TAG, " -- CUR; not mAlways!"); 17045 } else { 17046 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17047 Slog.i(TAG, " -- CUR: mSet=" 17048 + Arrays.toString(cur.mPref.mSetComponents)); 17049 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17050 Slog.i(TAG, " -- NEW: mMatch=" 17051 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17052 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17053 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17054 } 17055 } 17056 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17057 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17058 && cur.mPref.sameSet(set)) { 17059 // Setting the preferred activity to what it happens to be already 17060 if (DEBUG_PREFERRED) { 17061 Slog.i(TAG, "Replacing with same preferred activity " 17062 + cur.mPref.mShortComponent + " for user " 17063 + userId + ":"); 17064 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17065 } 17066 return; 17067 } 17068 } 17069 17070 if (existing != null) { 17071 if (DEBUG_PREFERRED) { 17072 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17073 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17074 } 17075 for (int i = 0; i < existing.size(); i++) { 17076 PreferredActivity pa = existing.get(i); 17077 if (DEBUG_PREFERRED) { 17078 Slog.i(TAG, "Removing existing preferred activity " 17079 + pa.mPref.mComponent + ":"); 17080 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17081 } 17082 pir.removeFilter(pa); 17083 } 17084 } 17085 } 17086 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17087 "Replacing preferred"); 17088 } 17089 } 17090 17091 @Override 17092 public void clearPackagePreferredActivities(String packageName) { 17093 final int uid = Binder.getCallingUid(); 17094 // writer 17095 synchronized (mPackages) { 17096 PackageParser.Package pkg = mPackages.get(packageName); 17097 if (pkg == null || pkg.applicationInfo.uid != uid) { 17098 if (mContext.checkCallingOrSelfPermission( 17099 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17100 != PackageManager.PERMISSION_GRANTED) { 17101 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17102 < Build.VERSION_CODES.FROYO) { 17103 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17104 + Binder.getCallingUid()); 17105 return; 17106 } 17107 mContext.enforceCallingOrSelfPermission( 17108 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17109 } 17110 } 17111 17112 int user = UserHandle.getCallingUserId(); 17113 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17114 scheduleWritePackageRestrictionsLocked(user); 17115 } 17116 } 17117 } 17118 17119 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17120 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17121 ArrayList<PreferredActivity> removed = null; 17122 boolean changed = false; 17123 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17124 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17125 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17126 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17127 continue; 17128 } 17129 Iterator<PreferredActivity> it = pir.filterIterator(); 17130 while (it.hasNext()) { 17131 PreferredActivity pa = it.next(); 17132 // Mark entry for removal only if it matches the package name 17133 // and the entry is of type "always". 17134 if (packageName == null || 17135 (pa.mPref.mComponent.getPackageName().equals(packageName) 17136 && pa.mPref.mAlways)) { 17137 if (removed == null) { 17138 removed = new ArrayList<PreferredActivity>(); 17139 } 17140 removed.add(pa); 17141 } 17142 } 17143 if (removed != null) { 17144 for (int j=0; j<removed.size(); j++) { 17145 PreferredActivity pa = removed.get(j); 17146 pir.removeFilter(pa); 17147 } 17148 changed = true; 17149 } 17150 } 17151 if (changed) { 17152 postPreferredActivityChangedBroadcast(userId); 17153 } 17154 return changed; 17155 } 17156 17157 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17158 private void clearIntentFilterVerificationsLPw(int userId) { 17159 final int packageCount = mPackages.size(); 17160 for (int i = 0; i < packageCount; i++) { 17161 PackageParser.Package pkg = mPackages.valueAt(i); 17162 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17163 } 17164 } 17165 17166 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17167 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17168 if (userId == UserHandle.USER_ALL) { 17169 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17170 sUserManager.getUserIds())) { 17171 for (int oneUserId : sUserManager.getUserIds()) { 17172 scheduleWritePackageRestrictionsLocked(oneUserId); 17173 } 17174 } 17175 } else { 17176 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17177 scheduleWritePackageRestrictionsLocked(userId); 17178 } 17179 } 17180 } 17181 17182 void clearDefaultBrowserIfNeeded(String packageName) { 17183 for (int oneUserId : sUserManager.getUserIds()) { 17184 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17185 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17186 if (packageName.equals(defaultBrowserPackageName)) { 17187 setDefaultBrowserPackageName(null, oneUserId); 17188 } 17189 } 17190 } 17191 17192 @Override 17193 public void resetApplicationPreferences(int userId) { 17194 mContext.enforceCallingOrSelfPermission( 17195 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17196 final long identity = Binder.clearCallingIdentity(); 17197 // writer 17198 try { 17199 synchronized (mPackages) { 17200 clearPackagePreferredActivitiesLPw(null, userId); 17201 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17202 // TODO: We have to reset the default SMS and Phone. This requires 17203 // significant refactoring to keep all default apps in the package 17204 // manager (cleaner but more work) or have the services provide 17205 // callbacks to the package manager to request a default app reset. 17206 applyFactoryDefaultBrowserLPw(userId); 17207 clearIntentFilterVerificationsLPw(userId); 17208 primeDomainVerificationsLPw(userId); 17209 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17210 scheduleWritePackageRestrictionsLocked(userId); 17211 } 17212 resetNetworkPolicies(userId); 17213 } finally { 17214 Binder.restoreCallingIdentity(identity); 17215 } 17216 } 17217 17218 @Override 17219 public int getPreferredActivities(List<IntentFilter> outFilters, 17220 List<ComponentName> outActivities, String packageName) { 17221 17222 int num = 0; 17223 final int userId = UserHandle.getCallingUserId(); 17224 // reader 17225 synchronized (mPackages) { 17226 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17227 if (pir != null) { 17228 final Iterator<PreferredActivity> it = pir.filterIterator(); 17229 while (it.hasNext()) { 17230 final PreferredActivity pa = it.next(); 17231 if (packageName == null 17232 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17233 && pa.mPref.mAlways)) { 17234 if (outFilters != null) { 17235 outFilters.add(new IntentFilter(pa)); 17236 } 17237 if (outActivities != null) { 17238 outActivities.add(pa.mPref.mComponent); 17239 } 17240 } 17241 } 17242 } 17243 } 17244 17245 return num; 17246 } 17247 17248 @Override 17249 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17250 int userId) { 17251 int callingUid = Binder.getCallingUid(); 17252 if (callingUid != Process.SYSTEM_UID) { 17253 throw new SecurityException( 17254 "addPersistentPreferredActivity can only be run by the system"); 17255 } 17256 if (filter.countActions() == 0) { 17257 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17258 return; 17259 } 17260 synchronized (mPackages) { 17261 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17262 ":"); 17263 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17264 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17265 new PersistentPreferredActivity(filter, activity)); 17266 scheduleWritePackageRestrictionsLocked(userId); 17267 postPreferredActivityChangedBroadcast(userId); 17268 } 17269 } 17270 17271 @Override 17272 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17273 int callingUid = Binder.getCallingUid(); 17274 if (callingUid != Process.SYSTEM_UID) { 17275 throw new SecurityException( 17276 "clearPackagePersistentPreferredActivities can only be run by the system"); 17277 } 17278 ArrayList<PersistentPreferredActivity> removed = null; 17279 boolean changed = false; 17280 synchronized (mPackages) { 17281 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17282 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17283 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17284 .valueAt(i); 17285 if (userId != thisUserId) { 17286 continue; 17287 } 17288 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17289 while (it.hasNext()) { 17290 PersistentPreferredActivity ppa = it.next(); 17291 // Mark entry for removal only if it matches the package name. 17292 if (ppa.mComponent.getPackageName().equals(packageName)) { 17293 if (removed == null) { 17294 removed = new ArrayList<PersistentPreferredActivity>(); 17295 } 17296 removed.add(ppa); 17297 } 17298 } 17299 if (removed != null) { 17300 for (int j=0; j<removed.size(); j++) { 17301 PersistentPreferredActivity ppa = removed.get(j); 17302 ppir.removeFilter(ppa); 17303 } 17304 changed = true; 17305 } 17306 } 17307 17308 if (changed) { 17309 scheduleWritePackageRestrictionsLocked(userId); 17310 postPreferredActivityChangedBroadcast(userId); 17311 } 17312 } 17313 } 17314 17315 /** 17316 * Common machinery for picking apart a restored XML blob and passing 17317 * it to a caller-supplied functor to be applied to the running system. 17318 */ 17319 private void restoreFromXml(XmlPullParser parser, int userId, 17320 String expectedStartTag, BlobXmlRestorer functor) 17321 throws IOException, XmlPullParserException { 17322 int type; 17323 while ((type = parser.next()) != XmlPullParser.START_TAG 17324 && type != XmlPullParser.END_DOCUMENT) { 17325 } 17326 if (type != XmlPullParser.START_TAG) { 17327 // oops didn't find a start tag?! 17328 if (DEBUG_BACKUP) { 17329 Slog.e(TAG, "Didn't find start tag during restore"); 17330 } 17331 return; 17332 } 17333Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17334 // this is supposed to be TAG_PREFERRED_BACKUP 17335 if (!expectedStartTag.equals(parser.getName())) { 17336 if (DEBUG_BACKUP) { 17337 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17338 } 17339 return; 17340 } 17341 17342 // skip interfering stuff, then we're aligned with the backing implementation 17343 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17344Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17345 functor.apply(parser, userId); 17346 } 17347 17348 private interface BlobXmlRestorer { 17349 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17350 } 17351 17352 /** 17353 * Non-Binder method, support for the backup/restore mechanism: write the 17354 * full set of preferred activities in its canonical XML format. Returns the 17355 * XML output as a byte array, or null if there is none. 17356 */ 17357 @Override 17358 public byte[] getPreferredActivityBackup(int userId) { 17359 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17360 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17361 } 17362 17363 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17364 try { 17365 final XmlSerializer serializer = new FastXmlSerializer(); 17366 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17367 serializer.startDocument(null, true); 17368 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17369 17370 synchronized (mPackages) { 17371 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17372 } 17373 17374 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17375 serializer.endDocument(); 17376 serializer.flush(); 17377 } catch (Exception e) { 17378 if (DEBUG_BACKUP) { 17379 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17380 } 17381 return null; 17382 } 17383 17384 return dataStream.toByteArray(); 17385 } 17386 17387 @Override 17388 public void restorePreferredActivities(byte[] backup, int userId) { 17389 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17390 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17391 } 17392 17393 try { 17394 final XmlPullParser parser = Xml.newPullParser(); 17395 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17396 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17397 new BlobXmlRestorer() { 17398 @Override 17399 public void apply(XmlPullParser parser, int userId) 17400 throws XmlPullParserException, IOException { 17401 synchronized (mPackages) { 17402 mSettings.readPreferredActivitiesLPw(parser, userId); 17403 } 17404 } 17405 } ); 17406 } catch (Exception e) { 17407 if (DEBUG_BACKUP) { 17408 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17409 } 17410 } 17411 } 17412 17413 /** 17414 * Non-Binder method, support for the backup/restore mechanism: write the 17415 * default browser (etc) settings in its canonical XML format. Returns the default 17416 * browser XML representation as a byte array, or null if there is none. 17417 */ 17418 @Override 17419 public byte[] getDefaultAppsBackup(int userId) { 17420 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17421 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17422 } 17423 17424 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17425 try { 17426 final XmlSerializer serializer = new FastXmlSerializer(); 17427 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17428 serializer.startDocument(null, true); 17429 serializer.startTag(null, TAG_DEFAULT_APPS); 17430 17431 synchronized (mPackages) { 17432 mSettings.writeDefaultAppsLPr(serializer, userId); 17433 } 17434 17435 serializer.endTag(null, TAG_DEFAULT_APPS); 17436 serializer.endDocument(); 17437 serializer.flush(); 17438 } catch (Exception e) { 17439 if (DEBUG_BACKUP) { 17440 Slog.e(TAG, "Unable to write default apps for backup", e); 17441 } 17442 return null; 17443 } 17444 17445 return dataStream.toByteArray(); 17446 } 17447 17448 @Override 17449 public void restoreDefaultApps(byte[] backup, int userId) { 17450 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17451 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17452 } 17453 17454 try { 17455 final XmlPullParser parser = Xml.newPullParser(); 17456 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17457 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17458 new BlobXmlRestorer() { 17459 @Override 17460 public void apply(XmlPullParser parser, int userId) 17461 throws XmlPullParserException, IOException { 17462 synchronized (mPackages) { 17463 mSettings.readDefaultAppsLPw(parser, userId); 17464 } 17465 } 17466 } ); 17467 } catch (Exception e) { 17468 if (DEBUG_BACKUP) { 17469 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17470 } 17471 } 17472 } 17473 17474 @Override 17475 public byte[] getIntentFilterVerificationBackup(int userId) { 17476 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17477 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17478 } 17479 17480 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17481 try { 17482 final XmlSerializer serializer = new FastXmlSerializer(); 17483 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17484 serializer.startDocument(null, true); 17485 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17486 17487 synchronized (mPackages) { 17488 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17489 } 17490 17491 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17492 serializer.endDocument(); 17493 serializer.flush(); 17494 } catch (Exception e) { 17495 if (DEBUG_BACKUP) { 17496 Slog.e(TAG, "Unable to write default apps for backup", e); 17497 } 17498 return null; 17499 } 17500 17501 return dataStream.toByteArray(); 17502 } 17503 17504 @Override 17505 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17506 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17507 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17508 } 17509 17510 try { 17511 final XmlPullParser parser = Xml.newPullParser(); 17512 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17513 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17514 new BlobXmlRestorer() { 17515 @Override 17516 public void apply(XmlPullParser parser, int userId) 17517 throws XmlPullParserException, IOException { 17518 synchronized (mPackages) { 17519 mSettings.readAllDomainVerificationsLPr(parser, userId); 17520 mSettings.writeLPr(); 17521 } 17522 } 17523 } ); 17524 } catch (Exception e) { 17525 if (DEBUG_BACKUP) { 17526 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17527 } 17528 } 17529 } 17530 17531 @Override 17532 public byte[] getPermissionGrantBackup(int userId) { 17533 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17534 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17535 } 17536 17537 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17538 try { 17539 final XmlSerializer serializer = new FastXmlSerializer(); 17540 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17541 serializer.startDocument(null, true); 17542 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17543 17544 synchronized (mPackages) { 17545 serializeRuntimePermissionGrantsLPr(serializer, userId); 17546 } 17547 17548 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17549 serializer.endDocument(); 17550 serializer.flush(); 17551 } catch (Exception e) { 17552 if (DEBUG_BACKUP) { 17553 Slog.e(TAG, "Unable to write default apps for backup", e); 17554 } 17555 return null; 17556 } 17557 17558 return dataStream.toByteArray(); 17559 } 17560 17561 @Override 17562 public void restorePermissionGrants(byte[] backup, int userId) { 17563 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17564 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17565 } 17566 17567 try { 17568 final XmlPullParser parser = Xml.newPullParser(); 17569 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17570 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17571 new BlobXmlRestorer() { 17572 @Override 17573 public void apply(XmlPullParser parser, int userId) 17574 throws XmlPullParserException, IOException { 17575 synchronized (mPackages) { 17576 processRestoredPermissionGrantsLPr(parser, userId); 17577 } 17578 } 17579 } ); 17580 } catch (Exception e) { 17581 if (DEBUG_BACKUP) { 17582 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17583 } 17584 } 17585 } 17586 17587 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17588 throws IOException { 17589 serializer.startTag(null, TAG_ALL_GRANTS); 17590 17591 final int N = mSettings.mPackages.size(); 17592 for (int i = 0; i < N; i++) { 17593 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17594 boolean pkgGrantsKnown = false; 17595 17596 PermissionsState packagePerms = ps.getPermissionsState(); 17597 17598 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17599 final int grantFlags = state.getFlags(); 17600 // only look at grants that are not system/policy fixed 17601 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17602 final boolean isGranted = state.isGranted(); 17603 // And only back up the user-twiddled state bits 17604 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17605 final String packageName = mSettings.mPackages.keyAt(i); 17606 if (!pkgGrantsKnown) { 17607 serializer.startTag(null, TAG_GRANT); 17608 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17609 pkgGrantsKnown = true; 17610 } 17611 17612 final boolean userSet = 17613 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17614 final boolean userFixed = 17615 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17616 final boolean revoke = 17617 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17618 17619 serializer.startTag(null, TAG_PERMISSION); 17620 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17621 if (isGranted) { 17622 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17623 } 17624 if (userSet) { 17625 serializer.attribute(null, ATTR_USER_SET, "true"); 17626 } 17627 if (userFixed) { 17628 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17629 } 17630 if (revoke) { 17631 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17632 } 17633 serializer.endTag(null, TAG_PERMISSION); 17634 } 17635 } 17636 } 17637 17638 if (pkgGrantsKnown) { 17639 serializer.endTag(null, TAG_GRANT); 17640 } 17641 } 17642 17643 serializer.endTag(null, TAG_ALL_GRANTS); 17644 } 17645 17646 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17647 throws XmlPullParserException, IOException { 17648 String pkgName = null; 17649 int outerDepth = parser.getDepth(); 17650 int type; 17651 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17652 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17653 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17654 continue; 17655 } 17656 17657 final String tagName = parser.getName(); 17658 if (tagName.equals(TAG_GRANT)) { 17659 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17660 if (DEBUG_BACKUP) { 17661 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17662 } 17663 } else if (tagName.equals(TAG_PERMISSION)) { 17664 17665 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17666 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17667 17668 int newFlagSet = 0; 17669 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17670 newFlagSet |= FLAG_PERMISSION_USER_SET; 17671 } 17672 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17673 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17674 } 17675 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17676 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17677 } 17678 if (DEBUG_BACKUP) { 17679 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17680 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17681 } 17682 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17683 if (ps != null) { 17684 // Already installed so we apply the grant immediately 17685 if (DEBUG_BACKUP) { 17686 Slog.v(TAG, " + already installed; applying"); 17687 } 17688 PermissionsState perms = ps.getPermissionsState(); 17689 BasePermission bp = mSettings.mPermissions.get(permName); 17690 if (bp != null) { 17691 if (isGranted) { 17692 perms.grantRuntimePermission(bp, userId); 17693 } 17694 if (newFlagSet != 0) { 17695 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17696 } 17697 } 17698 } else { 17699 // Need to wait for post-restore install to apply the grant 17700 if (DEBUG_BACKUP) { 17701 Slog.v(TAG, " - not yet installed; saving for later"); 17702 } 17703 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17704 isGranted, newFlagSet, userId); 17705 } 17706 } else { 17707 PackageManagerService.reportSettingsProblem(Log.WARN, 17708 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17709 XmlUtils.skipCurrentTag(parser); 17710 } 17711 } 17712 17713 scheduleWriteSettingsLocked(); 17714 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17715 } 17716 17717 @Override 17718 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17719 int sourceUserId, int targetUserId, int flags) { 17720 mContext.enforceCallingOrSelfPermission( 17721 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17722 int callingUid = Binder.getCallingUid(); 17723 enforceOwnerRights(ownerPackage, callingUid); 17724 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17725 if (intentFilter.countActions() == 0) { 17726 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17727 return; 17728 } 17729 synchronized (mPackages) { 17730 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17731 ownerPackage, targetUserId, flags); 17732 CrossProfileIntentResolver resolver = 17733 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17734 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17735 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17736 if (existing != null) { 17737 int size = existing.size(); 17738 for (int i = 0; i < size; i++) { 17739 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17740 return; 17741 } 17742 } 17743 } 17744 resolver.addFilter(newFilter); 17745 scheduleWritePackageRestrictionsLocked(sourceUserId); 17746 } 17747 } 17748 17749 @Override 17750 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17751 mContext.enforceCallingOrSelfPermission( 17752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17753 int callingUid = Binder.getCallingUid(); 17754 enforceOwnerRights(ownerPackage, callingUid); 17755 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17756 synchronized (mPackages) { 17757 CrossProfileIntentResolver resolver = 17758 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17759 ArraySet<CrossProfileIntentFilter> set = 17760 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17761 for (CrossProfileIntentFilter filter : set) { 17762 if (filter.getOwnerPackage().equals(ownerPackage)) { 17763 resolver.removeFilter(filter); 17764 } 17765 } 17766 scheduleWritePackageRestrictionsLocked(sourceUserId); 17767 } 17768 } 17769 17770 // Enforcing that callingUid is owning pkg on userId 17771 private void enforceOwnerRights(String pkg, int callingUid) { 17772 // The system owns everything. 17773 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17774 return; 17775 } 17776 int callingUserId = UserHandle.getUserId(callingUid); 17777 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17778 if (pi == null) { 17779 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17780 + callingUserId); 17781 } 17782 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17783 throw new SecurityException("Calling uid " + callingUid 17784 + " does not own package " + pkg); 17785 } 17786 } 17787 17788 @Override 17789 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17790 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17791 } 17792 17793 private Intent getHomeIntent() { 17794 Intent intent = new Intent(Intent.ACTION_MAIN); 17795 intent.addCategory(Intent.CATEGORY_HOME); 17796 intent.addCategory(Intent.CATEGORY_DEFAULT); 17797 return intent; 17798 } 17799 17800 private IntentFilter getHomeFilter() { 17801 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17802 filter.addCategory(Intent.CATEGORY_HOME); 17803 filter.addCategory(Intent.CATEGORY_DEFAULT); 17804 return filter; 17805 } 17806 17807 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17808 int userId) { 17809 Intent intent = getHomeIntent(); 17810 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17811 PackageManager.GET_META_DATA, userId); 17812 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17813 true, false, false, userId); 17814 17815 allHomeCandidates.clear(); 17816 if (list != null) { 17817 for (ResolveInfo ri : list) { 17818 allHomeCandidates.add(ri); 17819 } 17820 } 17821 return (preferred == null || preferred.activityInfo == null) 17822 ? null 17823 : new ComponentName(preferred.activityInfo.packageName, 17824 preferred.activityInfo.name); 17825 } 17826 17827 @Override 17828 public void setHomeActivity(ComponentName comp, int userId) { 17829 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17830 getHomeActivitiesAsUser(homeActivities, userId); 17831 17832 boolean found = false; 17833 17834 final int size = homeActivities.size(); 17835 final ComponentName[] set = new ComponentName[size]; 17836 for (int i = 0; i < size; i++) { 17837 final ResolveInfo candidate = homeActivities.get(i); 17838 final ActivityInfo info = candidate.activityInfo; 17839 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17840 set[i] = activityName; 17841 if (!found && activityName.equals(comp)) { 17842 found = true; 17843 } 17844 } 17845 if (!found) { 17846 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17847 + userId); 17848 } 17849 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17850 set, comp, userId); 17851 } 17852 17853 private @Nullable String getSetupWizardPackageName() { 17854 final Intent intent = new Intent(Intent.ACTION_MAIN); 17855 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17856 17857 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17858 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17859 | MATCH_DISABLED_COMPONENTS, 17860 UserHandle.myUserId()); 17861 if (matches.size() == 1) { 17862 return matches.get(0).getComponentInfo().packageName; 17863 } else { 17864 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17865 + ": matches=" + matches); 17866 return null; 17867 } 17868 } 17869 17870 private @Nullable String getStorageManagerPackageName() { 17871 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17872 17873 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17874 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17875 | MATCH_DISABLED_COMPONENTS, 17876 UserHandle.myUserId()); 17877 if (matches.size() == 1) { 17878 return matches.get(0).getComponentInfo().packageName; 17879 } else { 17880 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17881 + matches.size() + ": matches=" + matches); 17882 return null; 17883 } 17884 } 17885 17886 @Override 17887 public void setApplicationEnabledSetting(String appPackageName, 17888 int newState, int flags, int userId, String callingPackage) { 17889 if (!sUserManager.exists(userId)) return; 17890 if (callingPackage == null) { 17891 callingPackage = Integer.toString(Binder.getCallingUid()); 17892 } 17893 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17894 } 17895 17896 @Override 17897 public void setComponentEnabledSetting(ComponentName componentName, 17898 int newState, int flags, int userId) { 17899 if (!sUserManager.exists(userId)) return; 17900 setEnabledSetting(componentName.getPackageName(), 17901 componentName.getClassName(), newState, flags, userId, null); 17902 } 17903 17904 private void setEnabledSetting(final String packageName, String className, int newState, 17905 final int flags, int userId, String callingPackage) { 17906 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17907 || newState == COMPONENT_ENABLED_STATE_ENABLED 17908 || newState == COMPONENT_ENABLED_STATE_DISABLED 17909 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17910 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17911 throw new IllegalArgumentException("Invalid new component state: " 17912 + newState); 17913 } 17914 PackageSetting pkgSetting; 17915 final int uid = Binder.getCallingUid(); 17916 final int permission; 17917 if (uid == Process.SYSTEM_UID) { 17918 permission = PackageManager.PERMISSION_GRANTED; 17919 } else { 17920 permission = mContext.checkCallingOrSelfPermission( 17921 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17922 } 17923 enforceCrossUserPermission(uid, userId, 17924 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17925 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17926 boolean sendNow = false; 17927 boolean isApp = (className == null); 17928 String componentName = isApp ? packageName : className; 17929 int packageUid = -1; 17930 ArrayList<String> components; 17931 17932 // writer 17933 synchronized (mPackages) { 17934 pkgSetting = mSettings.mPackages.get(packageName); 17935 if (pkgSetting == null) { 17936 if (className == null) { 17937 throw new IllegalArgumentException("Unknown package: " + packageName); 17938 } 17939 throw new IllegalArgumentException( 17940 "Unknown component: " + packageName + "/" + className); 17941 } 17942 } 17943 17944 // Limit who can change which apps 17945 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17946 // Don't allow apps that don't have permission to modify other apps 17947 if (!allowedByPermission) { 17948 throw new SecurityException( 17949 "Permission Denial: attempt to change component state from pid=" 17950 + Binder.getCallingPid() 17951 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17952 } 17953 // Don't allow changing protected packages. 17954 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17955 throw new SecurityException("Cannot disable a protected package: " + packageName); 17956 } 17957 } 17958 17959 synchronized (mPackages) { 17960 if (uid == Process.SHELL_UID) { 17961 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17962 int oldState = pkgSetting.getEnabled(userId); 17963 if (className == null 17964 && 17965 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17966 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17967 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17968 && 17969 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17970 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17971 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17972 // ok 17973 } else { 17974 throw new SecurityException( 17975 "Shell cannot change component state for " + packageName + "/" 17976 + className + " to " + newState); 17977 } 17978 } 17979 if (className == null) { 17980 // We're dealing with an application/package level state change 17981 if (pkgSetting.getEnabled(userId) == newState) { 17982 // Nothing to do 17983 return; 17984 } 17985 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17986 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17987 // Don't care about who enables an app. 17988 callingPackage = null; 17989 } 17990 pkgSetting.setEnabled(newState, userId, callingPackage); 17991 // pkgSetting.pkg.mSetEnabled = newState; 17992 } else { 17993 // We're dealing with a component level state change 17994 // First, verify that this is a valid class name. 17995 PackageParser.Package pkg = pkgSetting.pkg; 17996 if (pkg == null || !pkg.hasComponentClassName(className)) { 17997 if (pkg != null && 17998 pkg.applicationInfo.targetSdkVersion >= 17999 Build.VERSION_CODES.JELLY_BEAN) { 18000 throw new IllegalArgumentException("Component class " + className 18001 + " does not exist in " + packageName); 18002 } else { 18003 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18004 + className + " does not exist in " + packageName); 18005 } 18006 } 18007 switch (newState) { 18008 case COMPONENT_ENABLED_STATE_ENABLED: 18009 if (!pkgSetting.enableComponentLPw(className, userId)) { 18010 return; 18011 } 18012 break; 18013 case COMPONENT_ENABLED_STATE_DISABLED: 18014 if (!pkgSetting.disableComponentLPw(className, userId)) { 18015 return; 18016 } 18017 break; 18018 case COMPONENT_ENABLED_STATE_DEFAULT: 18019 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18020 return; 18021 } 18022 break; 18023 default: 18024 Slog.e(TAG, "Invalid new component state: " + newState); 18025 return; 18026 } 18027 } 18028 scheduleWritePackageRestrictionsLocked(userId); 18029 components = mPendingBroadcasts.get(userId, packageName); 18030 final boolean newPackage = components == null; 18031 if (newPackage) { 18032 components = new ArrayList<String>(); 18033 } 18034 if (!components.contains(componentName)) { 18035 components.add(componentName); 18036 } 18037 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18038 sendNow = true; 18039 // Purge entry from pending broadcast list if another one exists already 18040 // since we are sending one right away. 18041 mPendingBroadcasts.remove(userId, packageName); 18042 } else { 18043 if (newPackage) { 18044 mPendingBroadcasts.put(userId, packageName, components); 18045 } 18046 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18047 // Schedule a message 18048 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18049 } 18050 } 18051 } 18052 18053 long callingId = Binder.clearCallingIdentity(); 18054 try { 18055 if (sendNow) { 18056 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18057 sendPackageChangedBroadcast(packageName, 18058 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18059 } 18060 } finally { 18061 Binder.restoreCallingIdentity(callingId); 18062 } 18063 } 18064 18065 @Override 18066 public void flushPackageRestrictionsAsUser(int userId) { 18067 if (!sUserManager.exists(userId)) { 18068 return; 18069 } 18070 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18071 false /* checkShell */, "flushPackageRestrictions"); 18072 synchronized (mPackages) { 18073 mSettings.writePackageRestrictionsLPr(userId); 18074 mDirtyUsers.remove(userId); 18075 if (mDirtyUsers.isEmpty()) { 18076 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18077 } 18078 } 18079 } 18080 18081 private void sendPackageChangedBroadcast(String packageName, 18082 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18083 if (DEBUG_INSTALL) 18084 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18085 + componentNames); 18086 Bundle extras = new Bundle(4); 18087 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18088 String nameList[] = new String[componentNames.size()]; 18089 componentNames.toArray(nameList); 18090 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18091 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18092 extras.putInt(Intent.EXTRA_UID, packageUid); 18093 // If this is not reporting a change of the overall package, then only send it 18094 // to registered receivers. We don't want to launch a swath of apps for every 18095 // little component state change. 18096 final int flags = !componentNames.contains(packageName) 18097 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18098 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18099 new int[] {UserHandle.getUserId(packageUid)}); 18100 } 18101 18102 @Override 18103 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18104 if (!sUserManager.exists(userId)) return; 18105 final int uid = Binder.getCallingUid(); 18106 final int permission = mContext.checkCallingOrSelfPermission( 18107 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18108 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18109 enforceCrossUserPermission(uid, userId, 18110 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18111 // writer 18112 synchronized (mPackages) { 18113 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18114 allowedByPermission, uid, userId)) { 18115 scheduleWritePackageRestrictionsLocked(userId); 18116 } 18117 } 18118 } 18119 18120 @Override 18121 public String getInstallerPackageName(String packageName) { 18122 // reader 18123 synchronized (mPackages) { 18124 return mSettings.getInstallerPackageNameLPr(packageName); 18125 } 18126 } 18127 18128 public boolean isOrphaned(String packageName) { 18129 // reader 18130 synchronized (mPackages) { 18131 return mSettings.isOrphaned(packageName); 18132 } 18133 } 18134 18135 @Override 18136 public int getApplicationEnabledSetting(String packageName, int userId) { 18137 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18138 int uid = Binder.getCallingUid(); 18139 enforceCrossUserPermission(uid, userId, 18140 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18141 // reader 18142 synchronized (mPackages) { 18143 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18144 } 18145 } 18146 18147 @Override 18148 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18149 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18150 int uid = Binder.getCallingUid(); 18151 enforceCrossUserPermission(uid, userId, 18152 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18153 // reader 18154 synchronized (mPackages) { 18155 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18156 } 18157 } 18158 18159 @Override 18160 public void enterSafeMode() { 18161 enforceSystemOrRoot("Only the system can request entering safe mode"); 18162 18163 if (!mSystemReady) { 18164 mSafeMode = true; 18165 } 18166 } 18167 18168 @Override 18169 public void systemReady() { 18170 mSystemReady = true; 18171 18172 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18173 // disabled after already being started. 18174 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18175 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18176 18177 // Read the compatibilty setting when the system is ready. 18178 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18179 mContext.getContentResolver(), 18180 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18181 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18182 if (DEBUG_SETTINGS) { 18183 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18184 } 18185 18186 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18187 18188 synchronized (mPackages) { 18189 // Verify that all of the preferred activity components actually 18190 // exist. It is possible for applications to be updated and at 18191 // that point remove a previously declared activity component that 18192 // had been set as a preferred activity. We try to clean this up 18193 // the next time we encounter that preferred activity, but it is 18194 // possible for the user flow to never be able to return to that 18195 // situation so here we do a sanity check to make sure we haven't 18196 // left any junk around. 18197 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18198 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18199 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18200 removed.clear(); 18201 for (PreferredActivity pa : pir.filterSet()) { 18202 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18203 removed.add(pa); 18204 } 18205 } 18206 if (removed.size() > 0) { 18207 for (int r=0; r<removed.size(); r++) { 18208 PreferredActivity pa = removed.get(r); 18209 Slog.w(TAG, "Removing dangling preferred activity: " 18210 + pa.mPref.mComponent); 18211 pir.removeFilter(pa); 18212 } 18213 mSettings.writePackageRestrictionsLPr( 18214 mSettings.mPreferredActivities.keyAt(i)); 18215 } 18216 } 18217 18218 for (int userId : UserManagerService.getInstance().getUserIds()) { 18219 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18220 grantPermissionsUserIds = ArrayUtils.appendInt( 18221 grantPermissionsUserIds, userId); 18222 } 18223 } 18224 } 18225 sUserManager.systemReady(); 18226 18227 // If we upgraded grant all default permissions before kicking off. 18228 for (int userId : grantPermissionsUserIds) { 18229 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18230 } 18231 18232 // If we did not grant default permissions, we preload from this the 18233 // default permission exceptions lazily to ensure we don't hit the 18234 // disk on a new user creation. 18235 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18236 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18237 } 18238 18239 // Kick off any messages waiting for system ready 18240 if (mPostSystemReadyMessages != null) { 18241 for (Message msg : mPostSystemReadyMessages) { 18242 msg.sendToTarget(); 18243 } 18244 mPostSystemReadyMessages = null; 18245 } 18246 18247 // Watch for external volumes that come and go over time 18248 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18249 storage.registerListener(mStorageListener); 18250 18251 mInstallerService.systemReady(); 18252 mPackageDexOptimizer.systemReady(); 18253 18254 MountServiceInternal mountServiceInternal = LocalServices.getService( 18255 MountServiceInternal.class); 18256 mountServiceInternal.addExternalStoragePolicy( 18257 new MountServiceInternal.ExternalStorageMountPolicy() { 18258 @Override 18259 public int getMountMode(int uid, String packageName) { 18260 if (Process.isIsolated(uid)) { 18261 return Zygote.MOUNT_EXTERNAL_NONE; 18262 } 18263 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18264 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18265 } 18266 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18267 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18268 } 18269 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18270 return Zygote.MOUNT_EXTERNAL_READ; 18271 } 18272 return Zygote.MOUNT_EXTERNAL_WRITE; 18273 } 18274 18275 @Override 18276 public boolean hasExternalStorage(int uid, String packageName) { 18277 return true; 18278 } 18279 }); 18280 18281 // Now that we're mostly running, clean up stale users and apps 18282 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18283 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18284 } 18285 18286 @Override 18287 public boolean isSafeMode() { 18288 return mSafeMode; 18289 } 18290 18291 @Override 18292 public boolean hasSystemUidErrors() { 18293 return mHasSystemUidErrors; 18294 } 18295 18296 static String arrayToString(int[] array) { 18297 StringBuffer buf = new StringBuffer(128); 18298 buf.append('['); 18299 if (array != null) { 18300 for (int i=0; i<array.length; i++) { 18301 if (i > 0) buf.append(", "); 18302 buf.append(array[i]); 18303 } 18304 } 18305 buf.append(']'); 18306 return buf.toString(); 18307 } 18308 18309 static class DumpState { 18310 public static final int DUMP_LIBS = 1 << 0; 18311 public static final int DUMP_FEATURES = 1 << 1; 18312 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18313 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18314 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18315 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18316 public static final int DUMP_PERMISSIONS = 1 << 6; 18317 public static final int DUMP_PACKAGES = 1 << 7; 18318 public static final int DUMP_SHARED_USERS = 1 << 8; 18319 public static final int DUMP_MESSAGES = 1 << 9; 18320 public static final int DUMP_PROVIDERS = 1 << 10; 18321 public static final int DUMP_VERIFIERS = 1 << 11; 18322 public static final int DUMP_PREFERRED = 1 << 12; 18323 public static final int DUMP_PREFERRED_XML = 1 << 13; 18324 public static final int DUMP_KEYSETS = 1 << 14; 18325 public static final int DUMP_VERSION = 1 << 15; 18326 public static final int DUMP_INSTALLS = 1 << 16; 18327 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18328 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18329 public static final int DUMP_FROZEN = 1 << 19; 18330 public static final int DUMP_DEXOPT = 1 << 20; 18331 public static final int DUMP_COMPILER_STATS = 1 << 21; 18332 18333 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18334 18335 private int mTypes; 18336 18337 private int mOptions; 18338 18339 private boolean mTitlePrinted; 18340 18341 private SharedUserSetting mSharedUser; 18342 18343 public boolean isDumping(int type) { 18344 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18345 return true; 18346 } 18347 18348 return (mTypes & type) != 0; 18349 } 18350 18351 public void setDump(int type) { 18352 mTypes |= type; 18353 } 18354 18355 public boolean isOptionEnabled(int option) { 18356 return (mOptions & option) != 0; 18357 } 18358 18359 public void setOptionEnabled(int option) { 18360 mOptions |= option; 18361 } 18362 18363 public boolean onTitlePrinted() { 18364 final boolean printed = mTitlePrinted; 18365 mTitlePrinted = true; 18366 return printed; 18367 } 18368 18369 public boolean getTitlePrinted() { 18370 return mTitlePrinted; 18371 } 18372 18373 public void setTitlePrinted(boolean enabled) { 18374 mTitlePrinted = enabled; 18375 } 18376 18377 public SharedUserSetting getSharedUser() { 18378 return mSharedUser; 18379 } 18380 18381 public void setSharedUser(SharedUserSetting user) { 18382 mSharedUser = user; 18383 } 18384 } 18385 18386 @Override 18387 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18388 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18389 (new PackageManagerShellCommand(this)).exec( 18390 this, in, out, err, args, resultReceiver); 18391 } 18392 18393 @Override 18394 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18395 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18396 != PackageManager.PERMISSION_GRANTED) { 18397 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18398 + Binder.getCallingPid() 18399 + ", uid=" + Binder.getCallingUid() 18400 + " without permission " 18401 + android.Manifest.permission.DUMP); 18402 return; 18403 } 18404 18405 DumpState dumpState = new DumpState(); 18406 boolean fullPreferred = false; 18407 boolean checkin = false; 18408 18409 String packageName = null; 18410 ArraySet<String> permissionNames = null; 18411 18412 int opti = 0; 18413 while (opti < args.length) { 18414 String opt = args[opti]; 18415 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18416 break; 18417 } 18418 opti++; 18419 18420 if ("-a".equals(opt)) { 18421 // Right now we only know how to print all. 18422 } else if ("-h".equals(opt)) { 18423 pw.println("Package manager dump options:"); 18424 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18425 pw.println(" --checkin: dump for a checkin"); 18426 pw.println(" -f: print details of intent filters"); 18427 pw.println(" -h: print this help"); 18428 pw.println(" cmd may be one of:"); 18429 pw.println(" l[ibraries]: list known shared libraries"); 18430 pw.println(" f[eatures]: list device features"); 18431 pw.println(" k[eysets]: print known keysets"); 18432 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18433 pw.println(" perm[issions]: dump permissions"); 18434 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18435 pw.println(" pref[erred]: print preferred package settings"); 18436 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18437 pw.println(" prov[iders]: dump content providers"); 18438 pw.println(" p[ackages]: dump installed packages"); 18439 pw.println(" s[hared-users]: dump shared user IDs"); 18440 pw.println(" m[essages]: print collected runtime messages"); 18441 pw.println(" v[erifiers]: print package verifier info"); 18442 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18443 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18444 pw.println(" version: print database version info"); 18445 pw.println(" write: write current settings now"); 18446 pw.println(" installs: details about install sessions"); 18447 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18448 pw.println(" dexopt: dump dexopt state"); 18449 pw.println(" compiler-stats: dump compiler statistics"); 18450 pw.println(" <package.name>: info about given package"); 18451 return; 18452 } else if ("--checkin".equals(opt)) { 18453 checkin = true; 18454 } else if ("-f".equals(opt)) { 18455 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18456 } else { 18457 pw.println("Unknown argument: " + opt + "; use -h for help"); 18458 } 18459 } 18460 18461 // Is the caller requesting to dump a particular piece of data? 18462 if (opti < args.length) { 18463 String cmd = args[opti]; 18464 opti++; 18465 // Is this a package name? 18466 if ("android".equals(cmd) || cmd.contains(".")) { 18467 packageName = cmd; 18468 // When dumping a single package, we always dump all of its 18469 // filter information since the amount of data will be reasonable. 18470 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18471 } else if ("check-permission".equals(cmd)) { 18472 if (opti >= args.length) { 18473 pw.println("Error: check-permission missing permission argument"); 18474 return; 18475 } 18476 String perm = args[opti]; 18477 opti++; 18478 if (opti >= args.length) { 18479 pw.println("Error: check-permission missing package argument"); 18480 return; 18481 } 18482 String pkg = args[opti]; 18483 opti++; 18484 int user = UserHandle.getUserId(Binder.getCallingUid()); 18485 if (opti < args.length) { 18486 try { 18487 user = Integer.parseInt(args[opti]); 18488 } catch (NumberFormatException e) { 18489 pw.println("Error: check-permission user argument is not a number: " 18490 + args[opti]); 18491 return; 18492 } 18493 } 18494 pw.println(checkPermission(perm, pkg, user)); 18495 return; 18496 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18497 dumpState.setDump(DumpState.DUMP_LIBS); 18498 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18499 dumpState.setDump(DumpState.DUMP_FEATURES); 18500 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18501 if (opti >= args.length) { 18502 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18503 | DumpState.DUMP_SERVICE_RESOLVERS 18504 | DumpState.DUMP_RECEIVER_RESOLVERS 18505 | DumpState.DUMP_CONTENT_RESOLVERS); 18506 } else { 18507 while (opti < args.length) { 18508 String name = args[opti]; 18509 if ("a".equals(name) || "activity".equals(name)) { 18510 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18511 } else if ("s".equals(name) || "service".equals(name)) { 18512 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18513 } else if ("r".equals(name) || "receiver".equals(name)) { 18514 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18515 } else if ("c".equals(name) || "content".equals(name)) { 18516 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18517 } else { 18518 pw.println("Error: unknown resolver table type: " + name); 18519 return; 18520 } 18521 opti++; 18522 } 18523 } 18524 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18525 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18526 } else if ("permission".equals(cmd)) { 18527 if (opti >= args.length) { 18528 pw.println("Error: permission requires permission name"); 18529 return; 18530 } 18531 permissionNames = new ArraySet<>(); 18532 while (opti < args.length) { 18533 permissionNames.add(args[opti]); 18534 opti++; 18535 } 18536 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18537 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18538 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18539 dumpState.setDump(DumpState.DUMP_PREFERRED); 18540 } else if ("preferred-xml".equals(cmd)) { 18541 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18542 if (opti < args.length && "--full".equals(args[opti])) { 18543 fullPreferred = true; 18544 opti++; 18545 } 18546 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18547 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18548 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18549 dumpState.setDump(DumpState.DUMP_PACKAGES); 18550 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18551 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18552 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18553 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18554 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18555 dumpState.setDump(DumpState.DUMP_MESSAGES); 18556 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18557 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18558 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18559 || "intent-filter-verifiers".equals(cmd)) { 18560 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18561 } else if ("version".equals(cmd)) { 18562 dumpState.setDump(DumpState.DUMP_VERSION); 18563 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18564 dumpState.setDump(DumpState.DUMP_KEYSETS); 18565 } else if ("installs".equals(cmd)) { 18566 dumpState.setDump(DumpState.DUMP_INSTALLS); 18567 } else if ("frozen".equals(cmd)) { 18568 dumpState.setDump(DumpState.DUMP_FROZEN); 18569 } else if ("dexopt".equals(cmd)) { 18570 dumpState.setDump(DumpState.DUMP_DEXOPT); 18571 } else if ("compiler-stats".equals(cmd)) { 18572 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18573 } else if ("write".equals(cmd)) { 18574 synchronized (mPackages) { 18575 mSettings.writeLPr(); 18576 pw.println("Settings written."); 18577 return; 18578 } 18579 } 18580 } 18581 18582 if (checkin) { 18583 pw.println("vers,1"); 18584 } 18585 18586 // reader 18587 synchronized (mPackages) { 18588 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18589 if (!checkin) { 18590 if (dumpState.onTitlePrinted()) 18591 pw.println(); 18592 pw.println("Database versions:"); 18593 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18594 } 18595 } 18596 18597 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18598 if (!checkin) { 18599 if (dumpState.onTitlePrinted()) 18600 pw.println(); 18601 pw.println("Verifiers:"); 18602 pw.print(" Required: "); 18603 pw.print(mRequiredVerifierPackage); 18604 pw.print(" (uid="); 18605 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18606 UserHandle.USER_SYSTEM)); 18607 pw.println(")"); 18608 } else if (mRequiredVerifierPackage != null) { 18609 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18610 pw.print(","); 18611 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18612 UserHandle.USER_SYSTEM)); 18613 } 18614 } 18615 18616 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18617 packageName == null) { 18618 if (mIntentFilterVerifierComponent != null) { 18619 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18620 if (!checkin) { 18621 if (dumpState.onTitlePrinted()) 18622 pw.println(); 18623 pw.println("Intent Filter Verifier:"); 18624 pw.print(" Using: "); 18625 pw.print(verifierPackageName); 18626 pw.print(" (uid="); 18627 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18628 UserHandle.USER_SYSTEM)); 18629 pw.println(")"); 18630 } else if (verifierPackageName != null) { 18631 pw.print("ifv,"); pw.print(verifierPackageName); 18632 pw.print(","); 18633 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18634 UserHandle.USER_SYSTEM)); 18635 } 18636 } else { 18637 pw.println(); 18638 pw.println("No Intent Filter Verifier available!"); 18639 } 18640 } 18641 18642 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18643 boolean printedHeader = false; 18644 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18645 while (it.hasNext()) { 18646 String name = it.next(); 18647 SharedLibraryEntry ent = mSharedLibraries.get(name); 18648 if (!checkin) { 18649 if (!printedHeader) { 18650 if (dumpState.onTitlePrinted()) 18651 pw.println(); 18652 pw.println("Libraries:"); 18653 printedHeader = true; 18654 } 18655 pw.print(" "); 18656 } else { 18657 pw.print("lib,"); 18658 } 18659 pw.print(name); 18660 if (!checkin) { 18661 pw.print(" -> "); 18662 } 18663 if (ent.path != null) { 18664 if (!checkin) { 18665 pw.print("(jar) "); 18666 pw.print(ent.path); 18667 } else { 18668 pw.print(",jar,"); 18669 pw.print(ent.path); 18670 } 18671 } else { 18672 if (!checkin) { 18673 pw.print("(apk) "); 18674 pw.print(ent.apk); 18675 } else { 18676 pw.print(",apk,"); 18677 pw.print(ent.apk); 18678 } 18679 } 18680 pw.println(); 18681 } 18682 } 18683 18684 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18685 if (dumpState.onTitlePrinted()) 18686 pw.println(); 18687 if (!checkin) { 18688 pw.println("Features:"); 18689 } 18690 18691 for (FeatureInfo feat : mAvailableFeatures.values()) { 18692 if (checkin) { 18693 pw.print("feat,"); 18694 pw.print(feat.name); 18695 pw.print(","); 18696 pw.println(feat.version); 18697 } else { 18698 pw.print(" "); 18699 pw.print(feat.name); 18700 if (feat.version > 0) { 18701 pw.print(" version="); 18702 pw.print(feat.version); 18703 } 18704 pw.println(); 18705 } 18706 } 18707 } 18708 18709 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18710 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18711 : "Activity Resolver Table:", " ", packageName, 18712 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18713 dumpState.setTitlePrinted(true); 18714 } 18715 } 18716 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18717 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18718 : "Receiver Resolver Table:", " ", packageName, 18719 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18720 dumpState.setTitlePrinted(true); 18721 } 18722 } 18723 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18724 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18725 : "Service Resolver Table:", " ", packageName, 18726 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18727 dumpState.setTitlePrinted(true); 18728 } 18729 } 18730 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18731 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18732 : "Provider Resolver Table:", " ", packageName, 18733 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18734 dumpState.setTitlePrinted(true); 18735 } 18736 } 18737 18738 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18739 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18740 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18741 int user = mSettings.mPreferredActivities.keyAt(i); 18742 if (pir.dump(pw, 18743 dumpState.getTitlePrinted() 18744 ? "\nPreferred Activities User " + user + ":" 18745 : "Preferred Activities User " + user + ":", " ", 18746 packageName, true, false)) { 18747 dumpState.setTitlePrinted(true); 18748 } 18749 } 18750 } 18751 18752 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18753 pw.flush(); 18754 FileOutputStream fout = new FileOutputStream(fd); 18755 BufferedOutputStream str = new BufferedOutputStream(fout); 18756 XmlSerializer serializer = new FastXmlSerializer(); 18757 try { 18758 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18759 serializer.startDocument(null, true); 18760 serializer.setFeature( 18761 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18762 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18763 serializer.endDocument(); 18764 serializer.flush(); 18765 } catch (IllegalArgumentException e) { 18766 pw.println("Failed writing: " + e); 18767 } catch (IllegalStateException e) { 18768 pw.println("Failed writing: " + e); 18769 } catch (IOException e) { 18770 pw.println("Failed writing: " + e); 18771 } 18772 } 18773 18774 if (!checkin 18775 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18776 && packageName == null) { 18777 pw.println(); 18778 int count = mSettings.mPackages.size(); 18779 if (count == 0) { 18780 pw.println("No applications!"); 18781 pw.println(); 18782 } else { 18783 final String prefix = " "; 18784 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18785 if (allPackageSettings.size() == 0) { 18786 pw.println("No domain preferred apps!"); 18787 pw.println(); 18788 } else { 18789 pw.println("App verification status:"); 18790 pw.println(); 18791 count = 0; 18792 for (PackageSetting ps : allPackageSettings) { 18793 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18794 if (ivi == null || ivi.getPackageName() == null) continue; 18795 pw.println(prefix + "Package: " + ivi.getPackageName()); 18796 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18797 pw.println(prefix + "Status: " + ivi.getStatusString()); 18798 pw.println(); 18799 count++; 18800 } 18801 if (count == 0) { 18802 pw.println(prefix + "No app verification established."); 18803 pw.println(); 18804 } 18805 for (int userId : sUserManager.getUserIds()) { 18806 pw.println("App linkages for user " + userId + ":"); 18807 pw.println(); 18808 count = 0; 18809 for (PackageSetting ps : allPackageSettings) { 18810 final long status = ps.getDomainVerificationStatusForUser(userId); 18811 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18812 continue; 18813 } 18814 pw.println(prefix + "Package: " + ps.name); 18815 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18816 String statusStr = IntentFilterVerificationInfo. 18817 getStatusStringFromValue(status); 18818 pw.println(prefix + "Status: " + statusStr); 18819 pw.println(); 18820 count++; 18821 } 18822 if (count == 0) { 18823 pw.println(prefix + "No configured app linkages."); 18824 pw.println(); 18825 } 18826 } 18827 } 18828 } 18829 } 18830 18831 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18832 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18833 if (packageName == null && permissionNames == null) { 18834 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18835 if (iperm == 0) { 18836 if (dumpState.onTitlePrinted()) 18837 pw.println(); 18838 pw.println("AppOp Permissions:"); 18839 } 18840 pw.print(" AppOp Permission "); 18841 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18842 pw.println(":"); 18843 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18844 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18845 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18846 } 18847 } 18848 } 18849 } 18850 18851 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18852 boolean printedSomething = false; 18853 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18854 if (packageName != null && !packageName.equals(p.info.packageName)) { 18855 continue; 18856 } 18857 if (!printedSomething) { 18858 if (dumpState.onTitlePrinted()) 18859 pw.println(); 18860 pw.println("Registered ContentProviders:"); 18861 printedSomething = true; 18862 } 18863 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18864 pw.print(" "); pw.println(p.toString()); 18865 } 18866 printedSomething = false; 18867 for (Map.Entry<String, PackageParser.Provider> entry : 18868 mProvidersByAuthority.entrySet()) { 18869 PackageParser.Provider p = entry.getValue(); 18870 if (packageName != null && !packageName.equals(p.info.packageName)) { 18871 continue; 18872 } 18873 if (!printedSomething) { 18874 if (dumpState.onTitlePrinted()) 18875 pw.println(); 18876 pw.println("ContentProvider Authorities:"); 18877 printedSomething = true; 18878 } 18879 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18880 pw.print(" "); pw.println(p.toString()); 18881 if (p.info != null && p.info.applicationInfo != null) { 18882 final String appInfo = p.info.applicationInfo.toString(); 18883 pw.print(" applicationInfo="); pw.println(appInfo); 18884 } 18885 } 18886 } 18887 18888 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18889 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18890 } 18891 18892 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18893 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18894 } 18895 18896 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18897 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18898 } 18899 18900 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18901 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18902 } 18903 18904 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18905 // XXX should handle packageName != null by dumping only install data that 18906 // the given package is involved with. 18907 if (dumpState.onTitlePrinted()) pw.println(); 18908 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18909 } 18910 18911 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18912 // XXX should handle packageName != null by dumping only install data that 18913 // the given package is involved with. 18914 if (dumpState.onTitlePrinted()) pw.println(); 18915 18916 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18917 ipw.println(); 18918 ipw.println("Frozen packages:"); 18919 ipw.increaseIndent(); 18920 if (mFrozenPackages.size() == 0) { 18921 ipw.println("(none)"); 18922 } else { 18923 for (int i = 0; i < mFrozenPackages.size(); i++) { 18924 ipw.println(mFrozenPackages.valueAt(i)); 18925 } 18926 } 18927 ipw.decreaseIndent(); 18928 } 18929 18930 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18931 if (dumpState.onTitlePrinted()) pw.println(); 18932 dumpDexoptStateLPr(pw, packageName); 18933 } 18934 18935 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18936 if (dumpState.onTitlePrinted()) pw.println(); 18937 dumpCompilerStatsLPr(pw, packageName); 18938 } 18939 18940 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18941 if (dumpState.onTitlePrinted()) pw.println(); 18942 mSettings.dumpReadMessagesLPr(pw, dumpState); 18943 18944 pw.println(); 18945 pw.println("Package warning messages:"); 18946 BufferedReader in = null; 18947 String line = null; 18948 try { 18949 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18950 while ((line = in.readLine()) != null) { 18951 if (line.contains("ignored: updated version")) continue; 18952 pw.println(line); 18953 } 18954 } catch (IOException ignored) { 18955 } finally { 18956 IoUtils.closeQuietly(in); 18957 } 18958 } 18959 18960 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18961 BufferedReader in = null; 18962 String line = null; 18963 try { 18964 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18965 while ((line = in.readLine()) != null) { 18966 if (line.contains("ignored: updated version")) continue; 18967 pw.print("msg,"); 18968 pw.println(line); 18969 } 18970 } catch (IOException ignored) { 18971 } finally { 18972 IoUtils.closeQuietly(in); 18973 } 18974 } 18975 } 18976 } 18977 18978 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18979 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18980 ipw.println(); 18981 ipw.println("Dexopt state:"); 18982 ipw.increaseIndent(); 18983 Collection<PackageParser.Package> packages = null; 18984 if (packageName != null) { 18985 PackageParser.Package targetPackage = mPackages.get(packageName); 18986 if (targetPackage != null) { 18987 packages = Collections.singletonList(targetPackage); 18988 } else { 18989 ipw.println("Unable to find package: " + packageName); 18990 return; 18991 } 18992 } else { 18993 packages = mPackages.values(); 18994 } 18995 18996 for (PackageParser.Package pkg : packages) { 18997 ipw.println("[" + pkg.packageName + "]"); 18998 ipw.increaseIndent(); 18999 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19000 ipw.decreaseIndent(); 19001 } 19002 } 19003 19004 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19005 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19006 ipw.println(); 19007 ipw.println("Compiler stats:"); 19008 ipw.increaseIndent(); 19009 Collection<PackageParser.Package> packages = null; 19010 if (packageName != null) { 19011 PackageParser.Package targetPackage = mPackages.get(packageName); 19012 if (targetPackage != null) { 19013 packages = Collections.singletonList(targetPackage); 19014 } else { 19015 ipw.println("Unable to find package: " + packageName); 19016 return; 19017 } 19018 } else { 19019 packages = mPackages.values(); 19020 } 19021 19022 for (PackageParser.Package pkg : packages) { 19023 ipw.println("[" + pkg.packageName + "]"); 19024 ipw.increaseIndent(); 19025 19026 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19027 if (stats == null) { 19028 ipw.println("(No recorded stats)"); 19029 } else { 19030 stats.dump(ipw); 19031 } 19032 ipw.decreaseIndent(); 19033 } 19034 } 19035 19036 private String dumpDomainString(String packageName) { 19037 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19038 .getList(); 19039 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19040 19041 ArraySet<String> result = new ArraySet<>(); 19042 if (iviList.size() > 0) { 19043 for (IntentFilterVerificationInfo ivi : iviList) { 19044 for (String host : ivi.getDomains()) { 19045 result.add(host); 19046 } 19047 } 19048 } 19049 if (filters != null && filters.size() > 0) { 19050 for (IntentFilter filter : filters) { 19051 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19052 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19053 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19054 result.addAll(filter.getHostsList()); 19055 } 19056 } 19057 } 19058 19059 StringBuilder sb = new StringBuilder(result.size() * 16); 19060 for (String domain : result) { 19061 if (sb.length() > 0) sb.append(" "); 19062 sb.append(domain); 19063 } 19064 return sb.toString(); 19065 } 19066 19067 // ------- apps on sdcard specific code ------- 19068 static final boolean DEBUG_SD_INSTALL = false; 19069 19070 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19071 19072 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19073 19074 private boolean mMediaMounted = false; 19075 19076 static String getEncryptKey() { 19077 try { 19078 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19079 SD_ENCRYPTION_KEYSTORE_NAME); 19080 if (sdEncKey == null) { 19081 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19082 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19083 if (sdEncKey == null) { 19084 Slog.e(TAG, "Failed to create encryption keys"); 19085 return null; 19086 } 19087 } 19088 return sdEncKey; 19089 } catch (NoSuchAlgorithmException nsae) { 19090 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19091 return null; 19092 } catch (IOException ioe) { 19093 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19094 return null; 19095 } 19096 } 19097 19098 /* 19099 * Update media status on PackageManager. 19100 */ 19101 @Override 19102 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19103 int callingUid = Binder.getCallingUid(); 19104 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19105 throw new SecurityException("Media status can only be updated by the system"); 19106 } 19107 // reader; this apparently protects mMediaMounted, but should probably 19108 // be a different lock in that case. 19109 synchronized (mPackages) { 19110 Log.i(TAG, "Updating external media status from " 19111 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19112 + (mediaStatus ? "mounted" : "unmounted")); 19113 if (DEBUG_SD_INSTALL) 19114 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19115 + ", mMediaMounted=" + mMediaMounted); 19116 if (mediaStatus == mMediaMounted) { 19117 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19118 : 0, -1); 19119 mHandler.sendMessage(msg); 19120 return; 19121 } 19122 mMediaMounted = mediaStatus; 19123 } 19124 // Queue up an async operation since the package installation may take a 19125 // little while. 19126 mHandler.post(new Runnable() { 19127 public void run() { 19128 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19129 } 19130 }); 19131 } 19132 19133 /** 19134 * Called by MountService when the initial ASECs to scan are available. 19135 * Should block until all the ASEC containers are finished being scanned. 19136 */ 19137 public void scanAvailableAsecs() { 19138 updateExternalMediaStatusInner(true, false, false); 19139 } 19140 19141 /* 19142 * Collect information of applications on external media, map them against 19143 * existing containers and update information based on current mount status. 19144 * Please note that we always have to report status if reportStatus has been 19145 * set to true especially when unloading packages. 19146 */ 19147 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19148 boolean externalStorage) { 19149 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19150 int[] uidArr = EmptyArray.INT; 19151 19152 final String[] list = PackageHelper.getSecureContainerList(); 19153 if (ArrayUtils.isEmpty(list)) { 19154 Log.i(TAG, "No secure containers found"); 19155 } else { 19156 // Process list of secure containers and categorize them 19157 // as active or stale based on their package internal state. 19158 19159 // reader 19160 synchronized (mPackages) { 19161 for (String cid : list) { 19162 // Leave stages untouched for now; installer service owns them 19163 if (PackageInstallerService.isStageName(cid)) continue; 19164 19165 if (DEBUG_SD_INSTALL) 19166 Log.i(TAG, "Processing container " + cid); 19167 String pkgName = getAsecPackageName(cid); 19168 if (pkgName == null) { 19169 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19170 continue; 19171 } 19172 if (DEBUG_SD_INSTALL) 19173 Log.i(TAG, "Looking for pkg : " + pkgName); 19174 19175 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19176 if (ps == null) { 19177 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19178 continue; 19179 } 19180 19181 /* 19182 * Skip packages that are not external if we're unmounting 19183 * external storage. 19184 */ 19185 if (externalStorage && !isMounted && !isExternal(ps)) { 19186 continue; 19187 } 19188 19189 final AsecInstallArgs args = new AsecInstallArgs(cid, 19190 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19191 // The package status is changed only if the code path 19192 // matches between settings and the container id. 19193 if (ps.codePathString != null 19194 && ps.codePathString.startsWith(args.getCodePath())) { 19195 if (DEBUG_SD_INSTALL) { 19196 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19197 + " at code path: " + ps.codePathString); 19198 } 19199 19200 // We do have a valid package installed on sdcard 19201 processCids.put(args, ps.codePathString); 19202 final int uid = ps.appId; 19203 if (uid != -1) { 19204 uidArr = ArrayUtils.appendInt(uidArr, uid); 19205 } 19206 } else { 19207 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19208 + ps.codePathString); 19209 } 19210 } 19211 } 19212 19213 Arrays.sort(uidArr); 19214 } 19215 19216 // Process packages with valid entries. 19217 if (isMounted) { 19218 if (DEBUG_SD_INSTALL) 19219 Log.i(TAG, "Loading packages"); 19220 loadMediaPackages(processCids, uidArr, externalStorage); 19221 startCleaningPackages(); 19222 mInstallerService.onSecureContainersAvailable(); 19223 } else { 19224 if (DEBUG_SD_INSTALL) 19225 Log.i(TAG, "Unloading packages"); 19226 unloadMediaPackages(processCids, uidArr, reportStatus); 19227 } 19228 } 19229 19230 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19231 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19232 final int size = infos.size(); 19233 final String[] packageNames = new String[size]; 19234 final int[] packageUids = new int[size]; 19235 for (int i = 0; i < size; i++) { 19236 final ApplicationInfo info = infos.get(i); 19237 packageNames[i] = info.packageName; 19238 packageUids[i] = info.uid; 19239 } 19240 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19241 finishedReceiver); 19242 } 19243 19244 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19245 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19246 sendResourcesChangedBroadcast(mediaStatus, replacing, 19247 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19248 } 19249 19250 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19251 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19252 int size = pkgList.length; 19253 if (size > 0) { 19254 // Send broadcasts here 19255 Bundle extras = new Bundle(); 19256 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19257 if (uidArr != null) { 19258 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19259 } 19260 if (replacing) { 19261 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19262 } 19263 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19264 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19265 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19266 } 19267 } 19268 19269 /* 19270 * Look at potentially valid container ids from processCids If package 19271 * information doesn't match the one on record or package scanning fails, 19272 * the cid is added to list of removeCids. We currently don't delete stale 19273 * containers. 19274 */ 19275 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19276 boolean externalStorage) { 19277 ArrayList<String> pkgList = new ArrayList<String>(); 19278 Set<AsecInstallArgs> keys = processCids.keySet(); 19279 19280 for (AsecInstallArgs args : keys) { 19281 String codePath = processCids.get(args); 19282 if (DEBUG_SD_INSTALL) 19283 Log.i(TAG, "Loading container : " + args.cid); 19284 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19285 try { 19286 // Make sure there are no container errors first. 19287 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19288 Slog.e(TAG, "Failed to mount cid : " + args.cid 19289 + " when installing from sdcard"); 19290 continue; 19291 } 19292 // Check code path here. 19293 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19294 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19295 + " does not match one in settings " + codePath); 19296 continue; 19297 } 19298 // Parse package 19299 int parseFlags = mDefParseFlags; 19300 if (args.isExternalAsec()) { 19301 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19302 } 19303 if (args.isFwdLocked()) { 19304 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19305 } 19306 19307 synchronized (mInstallLock) { 19308 PackageParser.Package pkg = null; 19309 try { 19310 // Sadly we don't know the package name yet to freeze it 19311 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19312 SCAN_IGNORE_FROZEN, 0, null); 19313 } catch (PackageManagerException e) { 19314 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19315 } 19316 // Scan the package 19317 if (pkg != null) { 19318 /* 19319 * TODO why is the lock being held? doPostInstall is 19320 * called in other places without the lock. This needs 19321 * to be straightened out. 19322 */ 19323 // writer 19324 synchronized (mPackages) { 19325 retCode = PackageManager.INSTALL_SUCCEEDED; 19326 pkgList.add(pkg.packageName); 19327 // Post process args 19328 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19329 pkg.applicationInfo.uid); 19330 } 19331 } else { 19332 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19333 } 19334 } 19335 19336 } finally { 19337 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19338 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19339 } 19340 } 19341 } 19342 // writer 19343 synchronized (mPackages) { 19344 // If the platform SDK has changed since the last time we booted, 19345 // we need to re-grant app permission to catch any new ones that 19346 // appear. This is really a hack, and means that apps can in some 19347 // cases get permissions that the user didn't initially explicitly 19348 // allow... it would be nice to have some better way to handle 19349 // this situation. 19350 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19351 : mSettings.getInternalVersion(); 19352 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19353 : StorageManager.UUID_PRIVATE_INTERNAL; 19354 19355 int updateFlags = UPDATE_PERMISSIONS_ALL; 19356 if (ver.sdkVersion != mSdkVersion) { 19357 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19358 + mSdkVersion + "; regranting permissions for external"); 19359 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19360 } 19361 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19362 19363 // Yay, everything is now upgraded 19364 ver.forceCurrent(); 19365 19366 // can downgrade to reader 19367 // Persist settings 19368 mSettings.writeLPr(); 19369 } 19370 // Send a broadcast to let everyone know we are done processing 19371 if (pkgList.size() > 0) { 19372 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19373 } 19374 } 19375 19376 /* 19377 * Utility method to unload a list of specified containers 19378 */ 19379 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19380 // Just unmount all valid containers. 19381 for (AsecInstallArgs arg : cidArgs) { 19382 synchronized (mInstallLock) { 19383 arg.doPostDeleteLI(false); 19384 } 19385 } 19386 } 19387 19388 /* 19389 * Unload packages mounted on external media. This involves deleting package 19390 * data from internal structures, sending broadcasts about disabled packages, 19391 * gc'ing to free up references, unmounting all secure containers 19392 * corresponding to packages on external media, and posting a 19393 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19394 * that we always have to post this message if status has been requested no 19395 * matter what. 19396 */ 19397 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19398 final boolean reportStatus) { 19399 if (DEBUG_SD_INSTALL) 19400 Log.i(TAG, "unloading media packages"); 19401 ArrayList<String> pkgList = new ArrayList<String>(); 19402 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19403 final Set<AsecInstallArgs> keys = processCids.keySet(); 19404 for (AsecInstallArgs args : keys) { 19405 String pkgName = args.getPackageName(); 19406 if (DEBUG_SD_INSTALL) 19407 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19408 // Delete package internally 19409 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19410 synchronized (mInstallLock) { 19411 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19412 final boolean res; 19413 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19414 "unloadMediaPackages")) { 19415 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19416 null); 19417 } 19418 if (res) { 19419 pkgList.add(pkgName); 19420 } else { 19421 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19422 failedList.add(args); 19423 } 19424 } 19425 } 19426 19427 // reader 19428 synchronized (mPackages) { 19429 // We didn't update the settings after removing each package; 19430 // write them now for all packages. 19431 mSettings.writeLPr(); 19432 } 19433 19434 // We have to absolutely send UPDATED_MEDIA_STATUS only 19435 // after confirming that all the receivers processed the ordered 19436 // broadcast when packages get disabled, force a gc to clean things up. 19437 // and unload all the containers. 19438 if (pkgList.size() > 0) { 19439 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19440 new IIntentReceiver.Stub() { 19441 public void performReceive(Intent intent, int resultCode, String data, 19442 Bundle extras, boolean ordered, boolean sticky, 19443 int sendingUser) throws RemoteException { 19444 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19445 reportStatus ? 1 : 0, 1, keys); 19446 mHandler.sendMessage(msg); 19447 } 19448 }); 19449 } else { 19450 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19451 keys); 19452 mHandler.sendMessage(msg); 19453 } 19454 } 19455 19456 private void loadPrivatePackages(final VolumeInfo vol) { 19457 mHandler.post(new Runnable() { 19458 @Override 19459 public void run() { 19460 loadPrivatePackagesInner(vol); 19461 } 19462 }); 19463 } 19464 19465 private void loadPrivatePackagesInner(VolumeInfo vol) { 19466 final String volumeUuid = vol.fsUuid; 19467 if (TextUtils.isEmpty(volumeUuid)) { 19468 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19469 return; 19470 } 19471 19472 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19473 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19474 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19475 19476 final VersionInfo ver; 19477 final List<PackageSetting> packages; 19478 synchronized (mPackages) { 19479 ver = mSettings.findOrCreateVersion(volumeUuid); 19480 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19481 } 19482 19483 for (PackageSetting ps : packages) { 19484 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19485 synchronized (mInstallLock) { 19486 final PackageParser.Package pkg; 19487 try { 19488 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19489 loaded.add(pkg.applicationInfo); 19490 19491 } catch (PackageManagerException e) { 19492 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19493 } 19494 19495 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19496 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19497 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19498 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19499 } 19500 } 19501 } 19502 19503 // Reconcile app data for all started/unlocked users 19504 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19505 final UserManager um = mContext.getSystemService(UserManager.class); 19506 UserManagerInternal umInternal = getUserManagerInternal(); 19507 for (UserInfo user : um.getUsers()) { 19508 final int flags; 19509 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19510 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19511 } else if (umInternal.isUserRunning(user.id)) { 19512 flags = StorageManager.FLAG_STORAGE_DE; 19513 } else { 19514 continue; 19515 } 19516 19517 try { 19518 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19519 synchronized (mInstallLock) { 19520 reconcileAppsDataLI(volumeUuid, user.id, flags); 19521 } 19522 } catch (IllegalStateException e) { 19523 // Device was probably ejected, and we'll process that event momentarily 19524 Slog.w(TAG, "Failed to prepare storage: " + e); 19525 } 19526 } 19527 19528 synchronized (mPackages) { 19529 int updateFlags = UPDATE_PERMISSIONS_ALL; 19530 if (ver.sdkVersion != mSdkVersion) { 19531 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19532 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19533 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19534 } 19535 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19536 19537 // Yay, everything is now upgraded 19538 ver.forceCurrent(); 19539 19540 mSettings.writeLPr(); 19541 } 19542 19543 for (PackageFreezer freezer : freezers) { 19544 freezer.close(); 19545 } 19546 19547 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19548 sendResourcesChangedBroadcast(true, false, loaded, null); 19549 } 19550 19551 private void unloadPrivatePackages(final VolumeInfo vol) { 19552 mHandler.post(new Runnable() { 19553 @Override 19554 public void run() { 19555 unloadPrivatePackagesInner(vol); 19556 } 19557 }); 19558 } 19559 19560 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19561 final String volumeUuid = vol.fsUuid; 19562 if (TextUtils.isEmpty(volumeUuid)) { 19563 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19564 return; 19565 } 19566 19567 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19568 synchronized (mInstallLock) { 19569 synchronized (mPackages) { 19570 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19571 for (PackageSetting ps : packages) { 19572 if (ps.pkg == null) continue; 19573 19574 final ApplicationInfo info = ps.pkg.applicationInfo; 19575 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19576 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19577 19578 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19579 "unloadPrivatePackagesInner")) { 19580 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19581 false, null)) { 19582 unloaded.add(info); 19583 } else { 19584 Slog.w(TAG, "Failed to unload " + ps.codePath); 19585 } 19586 } 19587 19588 // Try very hard to release any references to this package 19589 // so we don't risk the system server being killed due to 19590 // open FDs 19591 AttributeCache.instance().removePackage(ps.name); 19592 } 19593 19594 mSettings.writeLPr(); 19595 } 19596 } 19597 19598 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19599 sendResourcesChangedBroadcast(false, false, unloaded, null); 19600 19601 // Try very hard to release any references to this path so we don't risk 19602 // the system server being killed due to open FDs 19603 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19604 19605 for (int i = 0; i < 3; i++) { 19606 System.gc(); 19607 System.runFinalization(); 19608 } 19609 } 19610 19611 /** 19612 * Prepare storage areas for given user on all mounted devices. 19613 */ 19614 void prepareUserData(int userId, int userSerial, int flags) { 19615 synchronized (mInstallLock) { 19616 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19617 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19618 final String volumeUuid = vol.getFsUuid(); 19619 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19620 } 19621 } 19622 } 19623 19624 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19625 boolean allowRecover) { 19626 // Prepare storage and verify that serial numbers are consistent; if 19627 // there's a mismatch we need to destroy to avoid leaking data 19628 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19629 try { 19630 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19631 19632 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19633 UserManagerService.enforceSerialNumber( 19634 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19635 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19636 UserManagerService.enforceSerialNumber( 19637 Environment.getDataSystemDeDirectory(userId), userSerial); 19638 } 19639 } 19640 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19641 UserManagerService.enforceSerialNumber( 19642 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19643 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19644 UserManagerService.enforceSerialNumber( 19645 Environment.getDataSystemCeDirectory(userId), userSerial); 19646 } 19647 } 19648 19649 synchronized (mInstallLock) { 19650 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19651 } 19652 } catch (Exception e) { 19653 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19654 + " because we failed to prepare: " + e); 19655 destroyUserDataLI(volumeUuid, userId, 19656 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19657 19658 if (allowRecover) { 19659 // Try one last time; if we fail again we're really in trouble 19660 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19661 } 19662 } 19663 } 19664 19665 /** 19666 * Destroy storage areas for given user on all mounted devices. 19667 */ 19668 void destroyUserData(int userId, int flags) { 19669 synchronized (mInstallLock) { 19670 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19671 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19672 final String volumeUuid = vol.getFsUuid(); 19673 destroyUserDataLI(volumeUuid, userId, flags); 19674 } 19675 } 19676 } 19677 19678 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19679 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19680 try { 19681 // Clean up app data, profile data, and media data 19682 mInstaller.destroyUserData(volumeUuid, userId, flags); 19683 19684 // Clean up system data 19685 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19686 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19687 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19688 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19689 } 19690 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19691 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19692 } 19693 } 19694 19695 // Data with special labels is now gone, so finish the job 19696 storage.destroyUserStorage(volumeUuid, userId, flags); 19697 19698 } catch (Exception e) { 19699 logCriticalInfo(Log.WARN, 19700 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19701 } 19702 } 19703 19704 /** 19705 * Examine all users present on given mounted volume, and destroy data 19706 * belonging to users that are no longer valid, or whose user ID has been 19707 * recycled. 19708 */ 19709 private void reconcileUsers(String volumeUuid) { 19710 final List<File> files = new ArrayList<>(); 19711 Collections.addAll(files, FileUtils 19712 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19713 Collections.addAll(files, FileUtils 19714 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19715 Collections.addAll(files, FileUtils 19716 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19717 Collections.addAll(files, FileUtils 19718 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19719 for (File file : files) { 19720 if (!file.isDirectory()) continue; 19721 19722 final int userId; 19723 final UserInfo info; 19724 try { 19725 userId = Integer.parseInt(file.getName()); 19726 info = sUserManager.getUserInfo(userId); 19727 } catch (NumberFormatException e) { 19728 Slog.w(TAG, "Invalid user directory " + file); 19729 continue; 19730 } 19731 19732 boolean destroyUser = false; 19733 if (info == null) { 19734 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19735 + " because no matching user was found"); 19736 destroyUser = true; 19737 } else if (!mOnlyCore) { 19738 try { 19739 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19740 } catch (IOException e) { 19741 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19742 + " because we failed to enforce serial number: " + e); 19743 destroyUser = true; 19744 } 19745 } 19746 19747 if (destroyUser) { 19748 synchronized (mInstallLock) { 19749 destroyUserDataLI(volumeUuid, userId, 19750 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19751 } 19752 } 19753 } 19754 } 19755 19756 private void assertPackageKnown(String volumeUuid, String packageName) 19757 throws PackageManagerException { 19758 synchronized (mPackages) { 19759 // Normalize package name to handle renamed packages 19760 packageName = normalizePackageNameLPr(packageName); 19761 19762 final PackageSetting ps = mSettings.mPackages.get(packageName); 19763 if (ps == null) { 19764 throw new PackageManagerException("Package " + packageName + " is unknown"); 19765 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19766 throw new PackageManagerException( 19767 "Package " + packageName + " found on unknown volume " + volumeUuid 19768 + "; expected volume " + ps.volumeUuid); 19769 } 19770 } 19771 } 19772 19773 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19774 throws PackageManagerException { 19775 synchronized (mPackages) { 19776 // Normalize package name to handle renamed packages 19777 packageName = normalizePackageNameLPr(packageName); 19778 19779 final PackageSetting ps = mSettings.mPackages.get(packageName); 19780 if (ps == null) { 19781 throw new PackageManagerException("Package " + packageName + " is unknown"); 19782 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19783 throw new PackageManagerException( 19784 "Package " + packageName + " found on unknown volume " + volumeUuid 19785 + "; expected volume " + ps.volumeUuid); 19786 } else if (!ps.getInstalled(userId)) { 19787 throw new PackageManagerException( 19788 "Package " + packageName + " not installed for user " + userId); 19789 } 19790 } 19791 } 19792 19793 /** 19794 * Examine all apps present on given mounted volume, and destroy apps that 19795 * aren't expected, either due to uninstallation or reinstallation on 19796 * another volume. 19797 */ 19798 private void reconcileApps(String volumeUuid) { 19799 final File[] files = FileUtils 19800 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19801 for (File file : files) { 19802 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19803 && !PackageInstallerService.isStageName(file.getName()); 19804 if (!isPackage) { 19805 // Ignore entries which are not packages 19806 continue; 19807 } 19808 19809 try { 19810 final PackageLite pkg = PackageParser.parsePackageLite(file, 19811 PackageParser.PARSE_MUST_BE_APK); 19812 assertPackageKnown(volumeUuid, pkg.packageName); 19813 19814 } catch (PackageParserException | PackageManagerException e) { 19815 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19816 synchronized (mInstallLock) { 19817 removeCodePathLI(file); 19818 } 19819 } 19820 } 19821 } 19822 19823 /** 19824 * Reconcile all app data for the given user. 19825 * <p> 19826 * Verifies that directories exist and that ownership and labeling is 19827 * correct for all installed apps on all mounted volumes. 19828 */ 19829 void reconcileAppsData(int userId, int flags) { 19830 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19831 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19832 final String volumeUuid = vol.getFsUuid(); 19833 synchronized (mInstallLock) { 19834 reconcileAppsDataLI(volumeUuid, userId, flags); 19835 } 19836 } 19837 } 19838 19839 /** 19840 * Reconcile all app data on given mounted volume. 19841 * <p> 19842 * Destroys app data that isn't expected, either due to uninstallation or 19843 * reinstallation on another volume. 19844 * <p> 19845 * Verifies that directories exist and that ownership and labeling is 19846 * correct for all installed apps. 19847 */ 19848 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19849 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19850 + Integer.toHexString(flags)); 19851 19852 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19853 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19854 19855 // First look for stale data that doesn't belong, and check if things 19856 // have changed since we did our last restorecon 19857 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19858 if (StorageManager.isFileEncryptedNativeOrEmulated() 19859 && !StorageManager.isUserKeyUnlocked(userId)) { 19860 throw new RuntimeException( 19861 "Yikes, someone asked us to reconcile CE storage while " + userId 19862 + " was still locked; this would have caused massive data loss!"); 19863 } 19864 19865 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19866 for (File file : files) { 19867 final String packageName = file.getName(); 19868 try { 19869 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19870 } catch (PackageManagerException e) { 19871 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19872 try { 19873 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19874 StorageManager.FLAG_STORAGE_CE, 0); 19875 } catch (InstallerException e2) { 19876 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19877 } 19878 } 19879 } 19880 } 19881 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19882 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19883 for (File file : files) { 19884 final String packageName = file.getName(); 19885 try { 19886 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19887 } catch (PackageManagerException e) { 19888 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19889 try { 19890 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19891 StorageManager.FLAG_STORAGE_DE, 0); 19892 } catch (InstallerException e2) { 19893 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19894 } 19895 } 19896 } 19897 } 19898 19899 // Ensure that data directories are ready to roll for all packages 19900 // installed for this volume and user 19901 final List<PackageSetting> packages; 19902 synchronized (mPackages) { 19903 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19904 } 19905 int preparedCount = 0; 19906 for (PackageSetting ps : packages) { 19907 final String packageName = ps.name; 19908 if (ps.pkg == null) { 19909 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19910 // TODO: might be due to legacy ASEC apps; we should circle back 19911 // and reconcile again once they're scanned 19912 continue; 19913 } 19914 19915 if (ps.getInstalled(userId)) { 19916 prepareAppDataLIF(ps.pkg, userId, flags); 19917 19918 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19919 // We may have just shuffled around app data directories, so 19920 // prepare them one more time 19921 prepareAppDataLIF(ps.pkg, userId, flags); 19922 } 19923 19924 preparedCount++; 19925 } 19926 } 19927 19928 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19929 } 19930 19931 /** 19932 * Prepare app data for the given app just after it was installed or 19933 * upgraded. This method carefully only touches users that it's installed 19934 * for, and it forces a restorecon to handle any seinfo changes. 19935 * <p> 19936 * Verifies that directories exist and that ownership and labeling is 19937 * correct for all installed apps. If there is an ownership mismatch, it 19938 * will try recovering system apps by wiping data; third-party app data is 19939 * left intact. 19940 * <p> 19941 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19942 */ 19943 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19944 final PackageSetting ps; 19945 synchronized (mPackages) { 19946 ps = mSettings.mPackages.get(pkg.packageName); 19947 mSettings.writeKernelMappingLPr(ps); 19948 } 19949 19950 final UserManager um = mContext.getSystemService(UserManager.class); 19951 UserManagerInternal umInternal = getUserManagerInternal(); 19952 for (UserInfo user : um.getUsers()) { 19953 final int flags; 19954 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19955 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19956 } else if (umInternal.isUserRunning(user.id)) { 19957 flags = StorageManager.FLAG_STORAGE_DE; 19958 } else { 19959 continue; 19960 } 19961 19962 if (ps.getInstalled(user.id)) { 19963 // TODO: when user data is locked, mark that we're still dirty 19964 prepareAppDataLIF(pkg, user.id, flags); 19965 } 19966 } 19967 } 19968 19969 /** 19970 * Prepare app data for the given app. 19971 * <p> 19972 * Verifies that directories exist and that ownership and labeling is 19973 * correct for all installed apps. If there is an ownership mismatch, this 19974 * will try recovering system apps by wiping data; third-party app data is 19975 * left intact. 19976 */ 19977 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 19978 if (pkg == null) { 19979 Slog.wtf(TAG, "Package was null!", new Throwable()); 19980 return; 19981 } 19982 prepareAppDataLeafLIF(pkg, userId, flags); 19983 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19984 for (int i = 0; i < childCount; i++) { 19985 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 19986 } 19987 } 19988 19989 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19990 if (DEBUG_APP_DATA) { 19991 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19992 + Integer.toHexString(flags)); 19993 } 19994 19995 final String volumeUuid = pkg.volumeUuid; 19996 final String packageName = pkg.packageName; 19997 final ApplicationInfo app = pkg.applicationInfo; 19998 final int appId = UserHandle.getAppId(app.uid); 19999 20000 Preconditions.checkNotNull(app.seinfo); 20001 20002 try { 20003 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20004 appId, app.seinfo, app.targetSdkVersion); 20005 } catch (InstallerException e) { 20006 if (app.isSystemApp()) { 20007 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20008 + ", but trying to recover: " + e); 20009 destroyAppDataLeafLIF(pkg, userId, flags); 20010 try { 20011 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20012 appId, app.seinfo, app.targetSdkVersion); 20013 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20014 } catch (InstallerException e2) { 20015 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20016 } 20017 } else { 20018 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20019 } 20020 } 20021 20022 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20023 try { 20024 // CE storage is unlocked right now, so read out the inode and 20025 // remember for use later when it's locked 20026 // TODO: mark this structure as dirty so we persist it! 20027 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20028 StorageManager.FLAG_STORAGE_CE); 20029 synchronized (mPackages) { 20030 final PackageSetting ps = mSettings.mPackages.get(packageName); 20031 if (ps != null) { 20032 ps.setCeDataInode(ceDataInode, userId); 20033 } 20034 } 20035 } catch (InstallerException e) { 20036 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20037 } 20038 } 20039 20040 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20041 } 20042 20043 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20044 if (pkg == null) { 20045 Slog.wtf(TAG, "Package was null!", new Throwable()); 20046 return; 20047 } 20048 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20049 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20050 for (int i = 0; i < childCount; i++) { 20051 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20052 } 20053 } 20054 20055 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20056 final String volumeUuid = pkg.volumeUuid; 20057 final String packageName = pkg.packageName; 20058 final ApplicationInfo app = pkg.applicationInfo; 20059 20060 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20061 // Create a native library symlink only if we have native libraries 20062 // and if the native libraries are 32 bit libraries. We do not provide 20063 // this symlink for 64 bit libraries. 20064 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20065 final String nativeLibPath = app.nativeLibraryDir; 20066 try { 20067 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20068 nativeLibPath, userId); 20069 } catch (InstallerException e) { 20070 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20071 } 20072 } 20073 } 20074 } 20075 20076 /** 20077 * For system apps on non-FBE devices, this method migrates any existing 20078 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20079 * requested by the app. 20080 */ 20081 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20082 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20083 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20084 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20085 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20086 try { 20087 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20088 storageTarget); 20089 } catch (InstallerException e) { 20090 logCriticalInfo(Log.WARN, 20091 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20092 } 20093 return true; 20094 } else { 20095 return false; 20096 } 20097 } 20098 20099 public PackageFreezer freezePackage(String packageName, String killReason) { 20100 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20101 } 20102 20103 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20104 return new PackageFreezer(packageName, userId, killReason); 20105 } 20106 20107 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20108 String killReason) { 20109 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20110 } 20111 20112 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20113 String killReason) { 20114 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20115 return new PackageFreezer(); 20116 } else { 20117 return freezePackage(packageName, userId, killReason); 20118 } 20119 } 20120 20121 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20122 String killReason) { 20123 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20124 } 20125 20126 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20127 String killReason) { 20128 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20129 return new PackageFreezer(); 20130 } else { 20131 return freezePackage(packageName, userId, killReason); 20132 } 20133 } 20134 20135 /** 20136 * Class that freezes and kills the given package upon creation, and 20137 * unfreezes it upon closing. This is typically used when doing surgery on 20138 * app code/data to prevent the app from running while you're working. 20139 */ 20140 private class PackageFreezer implements AutoCloseable { 20141 private final String mPackageName; 20142 private final PackageFreezer[] mChildren; 20143 20144 private final boolean mWeFroze; 20145 20146 private final AtomicBoolean mClosed = new AtomicBoolean(); 20147 private final CloseGuard mCloseGuard = CloseGuard.get(); 20148 20149 /** 20150 * Create and return a stub freezer that doesn't actually do anything, 20151 * typically used when someone requested 20152 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20153 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20154 */ 20155 public PackageFreezer() { 20156 mPackageName = null; 20157 mChildren = null; 20158 mWeFroze = false; 20159 mCloseGuard.open("close"); 20160 } 20161 20162 public PackageFreezer(String packageName, int userId, String killReason) { 20163 synchronized (mPackages) { 20164 mPackageName = packageName; 20165 mWeFroze = mFrozenPackages.add(mPackageName); 20166 20167 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20168 if (ps != null) { 20169 killApplication(ps.name, ps.appId, userId, killReason); 20170 } 20171 20172 final PackageParser.Package p = mPackages.get(packageName); 20173 if (p != null && p.childPackages != null) { 20174 final int N = p.childPackages.size(); 20175 mChildren = new PackageFreezer[N]; 20176 for (int i = 0; i < N; i++) { 20177 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20178 userId, killReason); 20179 } 20180 } else { 20181 mChildren = null; 20182 } 20183 } 20184 mCloseGuard.open("close"); 20185 } 20186 20187 @Override 20188 protected void finalize() throws Throwable { 20189 try { 20190 mCloseGuard.warnIfOpen(); 20191 close(); 20192 } finally { 20193 super.finalize(); 20194 } 20195 } 20196 20197 @Override 20198 public void close() { 20199 mCloseGuard.close(); 20200 if (mClosed.compareAndSet(false, true)) { 20201 synchronized (mPackages) { 20202 if (mWeFroze) { 20203 mFrozenPackages.remove(mPackageName); 20204 } 20205 20206 if (mChildren != null) { 20207 for (PackageFreezer freezer : mChildren) { 20208 freezer.close(); 20209 } 20210 } 20211 } 20212 } 20213 } 20214 } 20215 20216 /** 20217 * Verify that given package is currently frozen. 20218 */ 20219 private void checkPackageFrozen(String packageName) { 20220 synchronized (mPackages) { 20221 if (!mFrozenPackages.contains(packageName)) { 20222 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20223 } 20224 } 20225 } 20226 20227 @Override 20228 public int movePackage(final String packageName, final String volumeUuid) { 20229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20230 20231 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20232 final int moveId = mNextMoveId.getAndIncrement(); 20233 mHandler.post(new Runnable() { 20234 @Override 20235 public void run() { 20236 try { 20237 movePackageInternal(packageName, volumeUuid, moveId, user); 20238 } catch (PackageManagerException e) { 20239 Slog.w(TAG, "Failed to move " + packageName, e); 20240 mMoveCallbacks.notifyStatusChanged(moveId, 20241 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20242 } 20243 } 20244 }); 20245 return moveId; 20246 } 20247 20248 private void movePackageInternal(final String packageName, final String volumeUuid, 20249 final int moveId, UserHandle user) throws PackageManagerException { 20250 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20251 final PackageManager pm = mContext.getPackageManager(); 20252 20253 final boolean currentAsec; 20254 final String currentVolumeUuid; 20255 final File codeFile; 20256 final String installerPackageName; 20257 final String packageAbiOverride; 20258 final int appId; 20259 final String seinfo; 20260 final String label; 20261 final int targetSdkVersion; 20262 final PackageFreezer freezer; 20263 final int[] installedUserIds; 20264 20265 // reader 20266 synchronized (mPackages) { 20267 final PackageParser.Package pkg = mPackages.get(packageName); 20268 final PackageSetting ps = mSettings.mPackages.get(packageName); 20269 if (pkg == null || ps == null) { 20270 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20271 } 20272 20273 if (pkg.applicationInfo.isSystemApp()) { 20274 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20275 "Cannot move system application"); 20276 } 20277 20278 if (pkg.applicationInfo.isExternalAsec()) { 20279 currentAsec = true; 20280 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20281 } else if (pkg.applicationInfo.isForwardLocked()) { 20282 currentAsec = true; 20283 currentVolumeUuid = "forward_locked"; 20284 } else { 20285 currentAsec = false; 20286 currentVolumeUuid = ps.volumeUuid; 20287 20288 final File probe = new File(pkg.codePath); 20289 final File probeOat = new File(probe, "oat"); 20290 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20291 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20292 "Move only supported for modern cluster style installs"); 20293 } 20294 } 20295 20296 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20297 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20298 "Package already moved to " + volumeUuid); 20299 } 20300 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20301 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20302 "Device admin cannot be moved"); 20303 } 20304 20305 if (mFrozenPackages.contains(packageName)) { 20306 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20307 "Failed to move already frozen package"); 20308 } 20309 20310 codeFile = new File(pkg.codePath); 20311 installerPackageName = ps.installerPackageName; 20312 packageAbiOverride = ps.cpuAbiOverrideString; 20313 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20314 seinfo = pkg.applicationInfo.seinfo; 20315 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20316 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20317 freezer = freezePackage(packageName, "movePackageInternal"); 20318 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20319 } 20320 20321 final Bundle extras = new Bundle(); 20322 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20323 extras.putString(Intent.EXTRA_TITLE, label); 20324 mMoveCallbacks.notifyCreated(moveId, extras); 20325 20326 int installFlags; 20327 final boolean moveCompleteApp; 20328 final File measurePath; 20329 20330 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20331 installFlags = INSTALL_INTERNAL; 20332 moveCompleteApp = !currentAsec; 20333 measurePath = Environment.getDataAppDirectory(volumeUuid); 20334 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20335 installFlags = INSTALL_EXTERNAL; 20336 moveCompleteApp = false; 20337 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20338 } else { 20339 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20340 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20341 || !volume.isMountedWritable()) { 20342 freezer.close(); 20343 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20344 "Move location not mounted private volume"); 20345 } 20346 20347 Preconditions.checkState(!currentAsec); 20348 20349 installFlags = INSTALL_INTERNAL; 20350 moveCompleteApp = true; 20351 measurePath = Environment.getDataAppDirectory(volumeUuid); 20352 } 20353 20354 final PackageStats stats = new PackageStats(null, -1); 20355 synchronized (mInstaller) { 20356 for (int userId : installedUserIds) { 20357 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20358 freezer.close(); 20359 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20360 "Failed to measure package size"); 20361 } 20362 } 20363 } 20364 20365 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20366 + stats.dataSize); 20367 20368 final long startFreeBytes = measurePath.getFreeSpace(); 20369 final long sizeBytes; 20370 if (moveCompleteApp) { 20371 sizeBytes = stats.codeSize + stats.dataSize; 20372 } else { 20373 sizeBytes = stats.codeSize; 20374 } 20375 20376 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20377 freezer.close(); 20378 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20379 "Not enough free space to move"); 20380 } 20381 20382 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20383 20384 final CountDownLatch installedLatch = new CountDownLatch(1); 20385 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20386 @Override 20387 public void onUserActionRequired(Intent intent) throws RemoteException { 20388 throw new IllegalStateException(); 20389 } 20390 20391 @Override 20392 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20393 Bundle extras) throws RemoteException { 20394 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20395 + PackageManager.installStatusToString(returnCode, msg)); 20396 20397 installedLatch.countDown(); 20398 freezer.close(); 20399 20400 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20401 switch (status) { 20402 case PackageInstaller.STATUS_SUCCESS: 20403 mMoveCallbacks.notifyStatusChanged(moveId, 20404 PackageManager.MOVE_SUCCEEDED); 20405 break; 20406 case PackageInstaller.STATUS_FAILURE_STORAGE: 20407 mMoveCallbacks.notifyStatusChanged(moveId, 20408 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20409 break; 20410 default: 20411 mMoveCallbacks.notifyStatusChanged(moveId, 20412 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20413 break; 20414 } 20415 } 20416 }; 20417 20418 final MoveInfo move; 20419 if (moveCompleteApp) { 20420 // Kick off a thread to report progress estimates 20421 new Thread() { 20422 @Override 20423 public void run() { 20424 while (true) { 20425 try { 20426 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20427 break; 20428 } 20429 } catch (InterruptedException ignored) { 20430 } 20431 20432 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20433 final int progress = 10 + (int) MathUtils.constrain( 20434 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20435 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20436 } 20437 } 20438 }.start(); 20439 20440 final String dataAppName = codeFile.getName(); 20441 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20442 dataAppName, appId, seinfo, targetSdkVersion); 20443 } else { 20444 move = null; 20445 } 20446 20447 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20448 20449 final Message msg = mHandler.obtainMessage(INIT_COPY); 20450 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20451 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20452 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20453 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20454 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20455 msg.obj = params; 20456 20457 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20458 System.identityHashCode(msg.obj)); 20459 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20460 System.identityHashCode(msg.obj)); 20461 20462 mHandler.sendMessage(msg); 20463 } 20464 20465 @Override 20466 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20467 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20468 20469 final int realMoveId = mNextMoveId.getAndIncrement(); 20470 final Bundle extras = new Bundle(); 20471 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20472 mMoveCallbacks.notifyCreated(realMoveId, extras); 20473 20474 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20475 @Override 20476 public void onCreated(int moveId, Bundle extras) { 20477 // Ignored 20478 } 20479 20480 @Override 20481 public void onStatusChanged(int moveId, int status, long estMillis) { 20482 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20483 } 20484 }; 20485 20486 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20487 storage.setPrimaryStorageUuid(volumeUuid, callback); 20488 return realMoveId; 20489 } 20490 20491 @Override 20492 public int getMoveStatus(int moveId) { 20493 mContext.enforceCallingOrSelfPermission( 20494 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20495 return mMoveCallbacks.mLastStatus.get(moveId); 20496 } 20497 20498 @Override 20499 public void registerMoveCallback(IPackageMoveObserver callback) { 20500 mContext.enforceCallingOrSelfPermission( 20501 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20502 mMoveCallbacks.register(callback); 20503 } 20504 20505 @Override 20506 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20507 mContext.enforceCallingOrSelfPermission( 20508 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20509 mMoveCallbacks.unregister(callback); 20510 } 20511 20512 @Override 20513 public boolean setInstallLocation(int loc) { 20514 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20515 null); 20516 if (getInstallLocation() == loc) { 20517 return true; 20518 } 20519 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20520 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20521 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20522 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20523 return true; 20524 } 20525 return false; 20526 } 20527 20528 @Override 20529 public int getInstallLocation() { 20530 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20531 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20532 PackageHelper.APP_INSTALL_AUTO); 20533 } 20534 20535 /** Called by UserManagerService */ 20536 void cleanUpUser(UserManagerService userManager, int userHandle) { 20537 synchronized (mPackages) { 20538 mDirtyUsers.remove(userHandle); 20539 mUserNeedsBadging.delete(userHandle); 20540 mSettings.removeUserLPw(userHandle); 20541 mPendingBroadcasts.remove(userHandle); 20542 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20543 removeUnusedPackagesLPw(userManager, userHandle); 20544 } 20545 } 20546 20547 /** 20548 * We're removing userHandle and would like to remove any downloaded packages 20549 * that are no longer in use by any other user. 20550 * @param userHandle the user being removed 20551 */ 20552 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20553 final boolean DEBUG_CLEAN_APKS = false; 20554 int [] users = userManager.getUserIds(); 20555 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20556 while (psit.hasNext()) { 20557 PackageSetting ps = psit.next(); 20558 if (ps.pkg == null) { 20559 continue; 20560 } 20561 final String packageName = ps.pkg.packageName; 20562 // Skip over if system app 20563 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20564 continue; 20565 } 20566 if (DEBUG_CLEAN_APKS) { 20567 Slog.i(TAG, "Checking package " + packageName); 20568 } 20569 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20570 if (keep) { 20571 if (DEBUG_CLEAN_APKS) { 20572 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20573 } 20574 } else { 20575 for (int i = 0; i < users.length; i++) { 20576 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20577 keep = true; 20578 if (DEBUG_CLEAN_APKS) { 20579 Slog.i(TAG, " Keeping package " + packageName + " for user " 20580 + users[i]); 20581 } 20582 break; 20583 } 20584 } 20585 } 20586 if (!keep) { 20587 if (DEBUG_CLEAN_APKS) { 20588 Slog.i(TAG, " Removing package " + packageName); 20589 } 20590 mHandler.post(new Runnable() { 20591 public void run() { 20592 deletePackageX(packageName, userHandle, 0); 20593 } //end run 20594 }); 20595 } 20596 } 20597 } 20598 20599 /** Called by UserManagerService */ 20600 void createNewUser(int userId) { 20601 synchronized (mInstallLock) { 20602 mSettings.createNewUserLI(this, mInstaller, userId); 20603 } 20604 synchronized (mPackages) { 20605 scheduleWritePackageRestrictionsLocked(userId); 20606 scheduleWritePackageListLocked(userId); 20607 applyFactoryDefaultBrowserLPw(userId); 20608 primeDomainVerificationsLPw(userId); 20609 } 20610 } 20611 20612 void onNewUserCreated(final int userId) { 20613 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20614 // If permission review for legacy apps is required, we represent 20615 // dagerous permissions for such apps as always granted runtime 20616 // permissions to keep per user flag state whether review is needed. 20617 // Hence, if a new user is added we have to propagate dangerous 20618 // permission grants for these legacy apps. 20619 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) { 20620 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20621 | UPDATE_PERMISSIONS_REPLACE_ALL); 20622 } 20623 } 20624 20625 @Override 20626 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20627 mContext.enforceCallingOrSelfPermission( 20628 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20629 "Only package verification agents can read the verifier device identity"); 20630 20631 synchronized (mPackages) { 20632 return mSettings.getVerifierDeviceIdentityLPw(); 20633 } 20634 } 20635 20636 @Override 20637 public void setPermissionEnforced(String permission, boolean enforced) { 20638 // TODO: Now that we no longer change GID for storage, this should to away. 20639 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20640 "setPermissionEnforced"); 20641 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20642 synchronized (mPackages) { 20643 if (mSettings.mReadExternalStorageEnforced == null 20644 || mSettings.mReadExternalStorageEnforced != enforced) { 20645 mSettings.mReadExternalStorageEnforced = enforced; 20646 mSettings.writeLPr(); 20647 } 20648 } 20649 // kill any non-foreground processes so we restart them and 20650 // grant/revoke the GID. 20651 final IActivityManager am = ActivityManagerNative.getDefault(); 20652 if (am != null) { 20653 final long token = Binder.clearCallingIdentity(); 20654 try { 20655 am.killProcessesBelowForeground("setPermissionEnforcement"); 20656 } catch (RemoteException e) { 20657 } finally { 20658 Binder.restoreCallingIdentity(token); 20659 } 20660 } 20661 } else { 20662 throw new IllegalArgumentException("No selective enforcement for " + permission); 20663 } 20664 } 20665 20666 @Override 20667 @Deprecated 20668 public boolean isPermissionEnforced(String permission) { 20669 return true; 20670 } 20671 20672 @Override 20673 public boolean isStorageLow() { 20674 final long token = Binder.clearCallingIdentity(); 20675 try { 20676 final DeviceStorageMonitorInternal 20677 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20678 if (dsm != null) { 20679 return dsm.isMemoryLow(); 20680 } else { 20681 return false; 20682 } 20683 } finally { 20684 Binder.restoreCallingIdentity(token); 20685 } 20686 } 20687 20688 @Override 20689 public IPackageInstaller getPackageInstaller() { 20690 return mInstallerService; 20691 } 20692 20693 private boolean userNeedsBadging(int userId) { 20694 int index = mUserNeedsBadging.indexOfKey(userId); 20695 if (index < 0) { 20696 final UserInfo userInfo; 20697 final long token = Binder.clearCallingIdentity(); 20698 try { 20699 userInfo = sUserManager.getUserInfo(userId); 20700 } finally { 20701 Binder.restoreCallingIdentity(token); 20702 } 20703 final boolean b; 20704 if (userInfo != null && userInfo.isManagedProfile()) { 20705 b = true; 20706 } else { 20707 b = false; 20708 } 20709 mUserNeedsBadging.put(userId, b); 20710 return b; 20711 } 20712 return mUserNeedsBadging.valueAt(index); 20713 } 20714 20715 @Override 20716 public KeySet getKeySetByAlias(String packageName, String alias) { 20717 if (packageName == null || alias == null) { 20718 return null; 20719 } 20720 synchronized(mPackages) { 20721 final PackageParser.Package pkg = mPackages.get(packageName); 20722 if (pkg == null) { 20723 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20724 throw new IllegalArgumentException("Unknown package: " + packageName); 20725 } 20726 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20727 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20728 } 20729 } 20730 20731 @Override 20732 public KeySet getSigningKeySet(String packageName) { 20733 if (packageName == null) { 20734 return null; 20735 } 20736 synchronized(mPackages) { 20737 final PackageParser.Package pkg = mPackages.get(packageName); 20738 if (pkg == null) { 20739 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20740 throw new IllegalArgumentException("Unknown package: " + packageName); 20741 } 20742 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20743 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20744 throw new SecurityException("May not access signing KeySet of other apps."); 20745 } 20746 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20747 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20748 } 20749 } 20750 20751 @Override 20752 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20753 if (packageName == null || ks == null) { 20754 return false; 20755 } 20756 synchronized(mPackages) { 20757 final PackageParser.Package pkg = mPackages.get(packageName); 20758 if (pkg == null) { 20759 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20760 throw new IllegalArgumentException("Unknown package: " + packageName); 20761 } 20762 IBinder ksh = ks.getToken(); 20763 if (ksh instanceof KeySetHandle) { 20764 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20765 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20766 } 20767 return false; 20768 } 20769 } 20770 20771 @Override 20772 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20773 if (packageName == null || ks == null) { 20774 return false; 20775 } 20776 synchronized(mPackages) { 20777 final PackageParser.Package pkg = mPackages.get(packageName); 20778 if (pkg == null) { 20779 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20780 throw new IllegalArgumentException("Unknown package: " + packageName); 20781 } 20782 IBinder ksh = ks.getToken(); 20783 if (ksh instanceof KeySetHandle) { 20784 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20785 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20786 } 20787 return false; 20788 } 20789 } 20790 20791 private void deletePackageIfUnusedLPr(final String packageName) { 20792 PackageSetting ps = mSettings.mPackages.get(packageName); 20793 if (ps == null) { 20794 return; 20795 } 20796 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20797 // TODO Implement atomic delete if package is unused 20798 // It is currently possible that the package will be deleted even if it is installed 20799 // after this method returns. 20800 mHandler.post(new Runnable() { 20801 public void run() { 20802 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20803 } 20804 }); 20805 } 20806 } 20807 20808 /** 20809 * Check and throw if the given before/after packages would be considered a 20810 * downgrade. 20811 */ 20812 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20813 throws PackageManagerException { 20814 if (after.versionCode < before.mVersionCode) { 20815 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20816 "Update version code " + after.versionCode + " is older than current " 20817 + before.mVersionCode); 20818 } else if (after.versionCode == before.mVersionCode) { 20819 if (after.baseRevisionCode < before.baseRevisionCode) { 20820 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20821 "Update base revision code " + after.baseRevisionCode 20822 + " is older than current " + before.baseRevisionCode); 20823 } 20824 20825 if (!ArrayUtils.isEmpty(after.splitNames)) { 20826 for (int i = 0; i < after.splitNames.length; i++) { 20827 final String splitName = after.splitNames[i]; 20828 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20829 if (j != -1) { 20830 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20831 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20832 "Update split " + splitName + " revision code " 20833 + after.splitRevisionCodes[i] + " is older than current " 20834 + before.splitRevisionCodes[j]); 20835 } 20836 } 20837 } 20838 } 20839 } 20840 } 20841 20842 private static class MoveCallbacks extends Handler { 20843 private static final int MSG_CREATED = 1; 20844 private static final int MSG_STATUS_CHANGED = 2; 20845 20846 private final RemoteCallbackList<IPackageMoveObserver> 20847 mCallbacks = new RemoteCallbackList<>(); 20848 20849 private final SparseIntArray mLastStatus = new SparseIntArray(); 20850 20851 public MoveCallbacks(Looper looper) { 20852 super(looper); 20853 } 20854 20855 public void register(IPackageMoveObserver callback) { 20856 mCallbacks.register(callback); 20857 } 20858 20859 public void unregister(IPackageMoveObserver callback) { 20860 mCallbacks.unregister(callback); 20861 } 20862 20863 @Override 20864 public void handleMessage(Message msg) { 20865 final SomeArgs args = (SomeArgs) msg.obj; 20866 final int n = mCallbacks.beginBroadcast(); 20867 for (int i = 0; i < n; i++) { 20868 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20869 try { 20870 invokeCallback(callback, msg.what, args); 20871 } catch (RemoteException ignored) { 20872 } 20873 } 20874 mCallbacks.finishBroadcast(); 20875 args.recycle(); 20876 } 20877 20878 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20879 throws RemoteException { 20880 switch (what) { 20881 case MSG_CREATED: { 20882 callback.onCreated(args.argi1, (Bundle) args.arg2); 20883 break; 20884 } 20885 case MSG_STATUS_CHANGED: { 20886 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20887 break; 20888 } 20889 } 20890 } 20891 20892 private void notifyCreated(int moveId, Bundle extras) { 20893 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20894 20895 final SomeArgs args = SomeArgs.obtain(); 20896 args.argi1 = moveId; 20897 args.arg2 = extras; 20898 obtainMessage(MSG_CREATED, args).sendToTarget(); 20899 } 20900 20901 private void notifyStatusChanged(int moveId, int status) { 20902 notifyStatusChanged(moveId, status, -1); 20903 } 20904 20905 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20906 Slog.v(TAG, "Move " + moveId + " status " + status); 20907 20908 final SomeArgs args = SomeArgs.obtain(); 20909 args.argi1 = moveId; 20910 args.argi2 = status; 20911 args.arg3 = estMillis; 20912 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20913 20914 synchronized (mLastStatus) { 20915 mLastStatus.put(moveId, status); 20916 } 20917 } 20918 } 20919 20920 private final static class OnPermissionChangeListeners extends Handler { 20921 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20922 20923 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20924 new RemoteCallbackList<>(); 20925 20926 public OnPermissionChangeListeners(Looper looper) { 20927 super(looper); 20928 } 20929 20930 @Override 20931 public void handleMessage(Message msg) { 20932 switch (msg.what) { 20933 case MSG_ON_PERMISSIONS_CHANGED: { 20934 final int uid = msg.arg1; 20935 handleOnPermissionsChanged(uid); 20936 } break; 20937 } 20938 } 20939 20940 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20941 mPermissionListeners.register(listener); 20942 20943 } 20944 20945 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20946 mPermissionListeners.unregister(listener); 20947 } 20948 20949 public void onPermissionsChanged(int uid) { 20950 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20951 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20952 } 20953 } 20954 20955 private void handleOnPermissionsChanged(int uid) { 20956 final int count = mPermissionListeners.beginBroadcast(); 20957 try { 20958 for (int i = 0; i < count; i++) { 20959 IOnPermissionsChangeListener callback = mPermissionListeners 20960 .getBroadcastItem(i); 20961 try { 20962 callback.onPermissionsChanged(uid); 20963 } catch (RemoteException e) { 20964 Log.e(TAG, "Permission listener is dead", e); 20965 } 20966 } 20967 } finally { 20968 mPermissionListeners.finishBroadcast(); 20969 } 20970 } 20971 } 20972 20973 private class PackageManagerInternalImpl extends PackageManagerInternal { 20974 @Override 20975 public void setLocationPackagesProvider(PackagesProvider provider) { 20976 synchronized (mPackages) { 20977 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20978 } 20979 } 20980 20981 @Override 20982 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20983 synchronized (mPackages) { 20984 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20985 } 20986 } 20987 20988 @Override 20989 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20990 synchronized (mPackages) { 20991 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20992 } 20993 } 20994 20995 @Override 20996 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20997 synchronized (mPackages) { 20998 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20999 } 21000 } 21001 21002 @Override 21003 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21004 synchronized (mPackages) { 21005 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21006 } 21007 } 21008 21009 @Override 21010 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21011 synchronized (mPackages) { 21012 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21013 } 21014 } 21015 21016 @Override 21017 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21018 synchronized (mPackages) { 21019 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21020 packageName, userId); 21021 } 21022 } 21023 21024 @Override 21025 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21026 synchronized (mPackages) { 21027 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21028 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21029 packageName, userId); 21030 } 21031 } 21032 21033 @Override 21034 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21035 synchronized (mPackages) { 21036 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21037 packageName, userId); 21038 } 21039 } 21040 21041 @Override 21042 public void setKeepUninstalledPackages(final List<String> packageList) { 21043 Preconditions.checkNotNull(packageList); 21044 List<String> removedFromList = null; 21045 synchronized (mPackages) { 21046 if (mKeepUninstalledPackages != null) { 21047 final int packagesCount = mKeepUninstalledPackages.size(); 21048 for (int i = 0; i < packagesCount; i++) { 21049 String oldPackage = mKeepUninstalledPackages.get(i); 21050 if (packageList != null && packageList.contains(oldPackage)) { 21051 continue; 21052 } 21053 if (removedFromList == null) { 21054 removedFromList = new ArrayList<>(); 21055 } 21056 removedFromList.add(oldPackage); 21057 } 21058 } 21059 mKeepUninstalledPackages = new ArrayList<>(packageList); 21060 if (removedFromList != null) { 21061 final int removedCount = removedFromList.size(); 21062 for (int i = 0; i < removedCount; i++) { 21063 deletePackageIfUnusedLPr(removedFromList.get(i)); 21064 } 21065 } 21066 } 21067 } 21068 21069 @Override 21070 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21071 synchronized (mPackages) { 21072 // If we do not support permission review, done. 21073 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) { 21074 return false; 21075 } 21076 21077 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21078 if (packageSetting == null) { 21079 return false; 21080 } 21081 21082 // Permission review applies only to apps not supporting the new permission model. 21083 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21084 return false; 21085 } 21086 21087 // Legacy apps have the permission and get user consent on launch. 21088 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21089 return permissionsState.isPermissionReviewRequired(userId); 21090 } 21091 } 21092 21093 @Override 21094 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21095 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21096 } 21097 21098 @Override 21099 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21100 int userId) { 21101 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21102 } 21103 21104 @Override 21105 public void setDeviceAndProfileOwnerPackages( 21106 int deviceOwnerUserId, String deviceOwnerPackage, 21107 SparseArray<String> profileOwnerPackages) { 21108 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21109 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21110 } 21111 21112 @Override 21113 public boolean isPackageDataProtected(int userId, String packageName) { 21114 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21115 } 21116 21117 @Override 21118 public boolean wasPackageEverLaunched(String packageName, int userId) { 21119 synchronized (mPackages) { 21120 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21121 } 21122 } 21123 } 21124 21125 @Override 21126 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21127 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21128 synchronized (mPackages) { 21129 final long identity = Binder.clearCallingIdentity(); 21130 try { 21131 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21132 packageNames, userId); 21133 } finally { 21134 Binder.restoreCallingIdentity(identity); 21135 } 21136 } 21137 } 21138 21139 private static void enforceSystemOrPhoneCaller(String tag) { 21140 int callingUid = Binder.getCallingUid(); 21141 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21142 throw new SecurityException( 21143 "Cannot call " + tag + " from UID " + callingUid); 21144 } 21145 } 21146 21147 boolean isHistoricalPackageUsageAvailable() { 21148 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21149 } 21150 21151 /** 21152 * Return a <b>copy</b> of the collection of packages known to the package manager. 21153 * @return A copy of the values of mPackages. 21154 */ 21155 Collection<PackageParser.Package> getPackages() { 21156 synchronized (mPackages) { 21157 return new ArrayList<>(mPackages.values()); 21158 } 21159 } 21160 21161 /** 21162 * Logs process start information (including base APK hash) to the security log. 21163 * @hide 21164 */ 21165 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21166 String apkFile, int pid) { 21167 if (!SecurityLog.isLoggingEnabled()) { 21168 return; 21169 } 21170 Bundle data = new Bundle(); 21171 data.putLong("startTimestamp", System.currentTimeMillis()); 21172 data.putString("processName", processName); 21173 data.putInt("uid", uid); 21174 data.putString("seinfo", seinfo); 21175 data.putString("apkFile", apkFile); 21176 data.putInt("pid", pid); 21177 Message msg = mProcessLoggingHandler.obtainMessage( 21178 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21179 msg.setData(data); 21180 mProcessLoggingHandler.sendMessage(msg); 21181 } 21182 21183 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21184 return mCompilerStats.getPackageStats(pkgName); 21185 } 21186 21187 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21188 return getOrCreateCompilerPackageStats(pkg.packageName); 21189 } 21190 21191 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21192 return mCompilerStats.getOrCreatePackageStats(pkgName); 21193 } 21194 21195 public void deleteCompilerPackageStats(String pkgName) { 21196 mCompilerStats.deletePackageStats(pkgName); 21197 } 21198} 21199