PackageManagerService.java revision be880349fa58efc8781eafe28cd603e8a8d3c1c9
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_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.PackageLite; 153import android.content.pm.PackageParser.PackageParserException; 154import android.content.pm.PackageStats; 155import android.content.pm.PackageUserState; 156import android.content.pm.ParceledListSlice; 157import android.content.pm.PermissionGroupInfo; 158import android.content.pm.PermissionInfo; 159import android.content.pm.ProviderInfo; 160import android.content.pm.ResolveInfo; 161import android.content.pm.ServiceInfo; 162import android.content.pm.Signature; 163import android.content.pm.UserInfo; 164import android.content.pm.VerifierDeviceIdentity; 165import android.content.pm.VerifierInfo; 166import android.content.res.Resources; 167import android.graphics.Bitmap; 168import android.hardware.display.DisplayManager; 169import android.net.Uri; 170import android.os.Binder; 171import android.os.Build; 172import android.os.Bundle; 173import android.os.Debug; 174import android.os.Environment; 175import android.os.Environment.UserEnvironment; 176import android.os.FileUtils; 177import android.os.Handler; 178import android.os.IBinder; 179import android.os.Looper; 180import android.os.Message; 181import android.os.Parcel; 182import android.os.ParcelFileDescriptor; 183import android.os.Process; 184import android.os.RemoteCallbackList; 185import android.os.RemoteException; 186import android.os.ResultReceiver; 187import android.os.SELinux; 188import android.os.ServiceManager; 189import android.os.SystemClock; 190import android.os.SystemProperties; 191import android.os.Trace; 192import android.os.UserHandle; 193import android.os.UserManager; 194import android.os.UserManagerInternal; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.provider.Settings.Global; 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.AtomicFile; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.PrintStreamPrinter; 218import android.util.Slog; 219import android.util.SparseArray; 220import android.util.SparseBooleanArray; 221import android.util.SparseIntArray; 222import android.util.Xml; 223import android.util.jar.StrictJarFile; 224import android.view.Display; 225 226import com.android.internal.R; 227import com.android.internal.annotations.GuardedBy; 228import com.android.internal.app.IMediaContainerService; 229import com.android.internal.app.ResolverActivity; 230import com.android.internal.content.NativeLibraryHelper; 231import com.android.internal.content.PackageHelper; 232import com.android.internal.logging.MetricsLogger; 233import com.android.internal.os.IParcelFileDescriptorFactory; 234import com.android.internal.os.InstallerConnection.InstallerException; 235import com.android.internal.os.SomeArgs; 236import com.android.internal.os.Zygote; 237import com.android.internal.telephony.CarrierAppUtils; 238import com.android.internal.util.ArrayUtils; 239import com.android.internal.util.FastPrintWriter; 240import com.android.internal.util.FastXmlSerializer; 241import com.android.internal.util.IndentingPrintWriter; 242import com.android.internal.util.Preconditions; 243import com.android.internal.util.XmlUtils; 244import com.android.server.AttributeCache; 245import com.android.server.EventLogTags; 246import com.android.server.FgThread; 247import com.android.server.IntentResolver; 248import com.android.server.LocalServices; 249import com.android.server.ServiceThread; 250import com.android.server.SystemConfig; 251import com.android.server.Watchdog; 252import com.android.server.net.NetworkPolicyManagerInternal; 253import com.android.server.pm.PermissionsState.PermissionState; 254import com.android.server.pm.Settings.DatabaseVersion; 255import com.android.server.pm.Settings.VersionInfo; 256import com.android.server.storage.DeviceStorageMonitorInternal; 257 258import dalvik.system.CloseGuard; 259import dalvik.system.DexFile; 260import dalvik.system.VMRuntime; 261 262import libcore.io.IoUtils; 263import libcore.util.EmptyArray; 264 265import org.xmlpull.v1.XmlPullParser; 266import org.xmlpull.v1.XmlPullParserException; 267import org.xmlpull.v1.XmlSerializer; 268 269import java.io.BufferedInputStream; 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.InputStream; 283import java.io.PrintWriter; 284import java.nio.charset.StandardCharsets; 285import java.security.DigestInputStream; 286import java.security.MessageDigest; 287import java.security.NoSuchAlgorithmException; 288import java.security.PublicKey; 289import java.security.cert.Certificate; 290import java.security.cert.CertificateEncodingException; 291import java.security.cert.CertificateException; 292import java.text.SimpleDateFormat; 293import java.util.ArrayList; 294import java.util.Arrays; 295import java.util.Collection; 296import java.util.Collections; 297import java.util.Comparator; 298import java.util.Date; 299import java.util.HashSet; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309import java.util.concurrent.atomic.AtomicLong; 310 311/** 312 * Keep track of all those APKs everywhere. 313 * <p> 314 * Internally there are two important locks: 315 * <ul> 316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 317 * and other related state. It is a fine-grained lock that should only be held 318 * momentarily, as it's one of the most contended locks in the system. 319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 320 * operations typically involve heavy lifting of application data on disk. Since 321 * {@code installd} is single-threaded, and it's operations can often be slow, 322 * this lock should never be acquired while already holding {@link #mPackages}. 323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 324 * holding {@link #mInstallLock}. 325 * </ul> 326 * Many internal methods rely on the caller to hold the appropriate locks, and 327 * this contract is expressed through method name suffixes: 328 * <ul> 329 * <li>fooLI(): the caller must hold {@link #mInstallLock} 330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 331 * being modified must be frozen 332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 334 * </ul> 335 * <p> 336 * Because this class is very central to the platform's security; please run all 337 * CTS and unit tests whenever making modifications: 338 * 339 * <pre> 340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 342 * </pre> 343 */ 344public class PackageManagerService extends IPackageManager.Stub { 345 static final String TAG = "PackageManager"; 346 static final boolean DEBUG_SETTINGS = false; 347 static final boolean DEBUG_PREFERRED = false; 348 static final boolean DEBUG_UPGRADE = false; 349 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 350 private static final boolean DEBUG_BACKUP = false; 351 private static final boolean DEBUG_INSTALL = false; 352 private static final boolean DEBUG_REMOVE = false; 353 private static final boolean DEBUG_BROADCASTS = false; 354 private static final boolean DEBUG_SHOW_INFO = false; 355 private static final boolean DEBUG_PACKAGE_INFO = false; 356 private static final boolean DEBUG_INTENT_MATCHING = false; 357 private static final boolean DEBUG_PACKAGE_SCANNING = false; 358 private static final boolean DEBUG_VERIFY = false; 359 private static final boolean DEBUG_FILTERS = false; 360 361 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 362 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 363 // user, but by default initialize to this. 364 static final boolean DEBUG_DEXOPT = false; 365 366 private static final boolean DEBUG_ABI_SELECTION = false; 367 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 368 private static final boolean DEBUG_TRIAGED_MISSING = false; 369 private static final boolean DEBUG_APP_DATA = false; 370 371 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 372 373 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 374 375 private static final int RADIO_UID = Process.PHONE_UID; 376 private static final int LOG_UID = Process.LOG_UID; 377 private static final int NFC_UID = Process.NFC_UID; 378 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 379 private static final int SHELL_UID = Process.SHELL_UID; 380 381 // Cap the size of permission trees that 3rd party apps can define 382 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 383 384 // Suffix used during package installation when copying/moving 385 // package apks to install directory. 386 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 387 388 static final int SCAN_NO_DEX = 1<<1; 389 static final int SCAN_FORCE_DEX = 1<<2; 390 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 391 static final int SCAN_NEW_INSTALL = 1<<4; 392 static final int SCAN_NO_PATHS = 1<<5; 393 static final int SCAN_UPDATE_TIME = 1<<6; 394 static final int SCAN_DEFER_DEX = 1<<7; 395 static final int SCAN_BOOTING = 1<<8; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 398 static final int SCAN_REPLACING = 1<<11; 399 static final int SCAN_REQUIRE_KNOWN = 1<<12; 400 static final int SCAN_MOVE = 1<<13; 401 static final int SCAN_INITIAL = 1<<14; 402 static final int SCAN_CHECK_ONLY = 1<<15; 403 static final int SCAN_DONT_KILL_APP = 1<<17; 404 static final int SCAN_IGNORE_FROZEN = 1<<18; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 466 467 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 468 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 469 470 /** Permission grant: not grant the permission. */ 471 private static final int GRANT_DENIED = 1; 472 473 /** Permission grant: grant the permission as an install permission. */ 474 private static final int GRANT_INSTALL = 2; 475 476 /** Permission grant: grant the permission as a runtime one. */ 477 private static final int GRANT_RUNTIME = 3; 478 479 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 480 private static final int GRANT_UPGRADE = 4; 481 482 /** Canonical intent used to identify what counts as a "web browser" app */ 483 private static final Intent sBrowserIntent; 484 static { 485 sBrowserIntent = new Intent(); 486 sBrowserIntent.setAction(Intent.ACTION_VIEW); 487 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 488 sBrowserIntent.setData(Uri.parse("http:")); 489 } 490 491 /** 492 * The set of all protected actions [i.e. those actions for which a high priority 493 * intent filter is disallowed]. 494 */ 495 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 496 static { 497 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 498 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 499 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 500 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 501 } 502 503 // Compilation reasons. 504 public static final int REASON_FIRST_BOOT = 0; 505 public static final int REASON_BOOT = 1; 506 public static final int REASON_INSTALL = 2; 507 public static final int REASON_BACKGROUND_DEXOPT = 3; 508 public static final int REASON_AB_OTA = 4; 509 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 510 public static final int REASON_SHARED_APK = 6; 511 public static final int REASON_FORCED_DEXOPT = 7; 512 public static final int REASON_CORE_APP = 8; 513 514 public static final int REASON_LAST = REASON_CORE_APP; 515 516 /** Special library name that skips shared libraries check during compilation. */ 517 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 518 519 final ServiceThread mHandlerThread; 520 521 final PackageHandler mHandler; 522 523 private final ProcessLoggingHandler mProcessLoggingHandler; 524 525 /** 526 * Messages for {@link #mHandler} that need to wait for system ready before 527 * being dispatched. 528 */ 529 private ArrayList<Message> mPostSystemReadyMessages; 530 531 final int mSdkVersion = Build.VERSION.SDK_INT; 532 533 final Context mContext; 534 final boolean mFactoryTest; 535 final boolean mOnlyCore; 536 final DisplayMetrics mMetrics; 537 final int mDefParseFlags; 538 final String[] mSeparateProcesses; 539 final boolean mIsUpgrade; 540 final boolean mIsPreNUpgrade; 541 542 /** The location for ASEC container files on internal storage. */ 543 final String mAsecInternalPath; 544 545 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 546 // LOCK HELD. Can be called with mInstallLock held. 547 @GuardedBy("mInstallLock") 548 final Installer mInstaller; 549 550 /** Directory where installed third-party apps stored */ 551 final File mAppInstallDir; 552 final File mEphemeralInstallDir; 553 554 /** 555 * Directory to which applications installed internally have their 556 * 32 bit native libraries copied. 557 */ 558 private File mAppLib32InstallDir; 559 560 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 561 // apps. 562 final File mDrmAppPrivateInstallDir; 563 564 // ---------------------------------------------------------------- 565 566 // Lock for state used when installing and doing other long running 567 // operations. Methods that must be called with this lock held have 568 // the suffix "LI". 569 final Object mInstallLock = new Object(); 570 571 // ---------------------------------------------------------------- 572 573 // Keys are String (package name), values are Package. This also serves 574 // as the lock for the global state. Methods that must be called with 575 // this lock held have the prefix "LP". 576 @GuardedBy("mPackages") 577 final ArrayMap<String, PackageParser.Package> mPackages = 578 new ArrayMap<String, PackageParser.Package>(); 579 580 final ArrayMap<String, Set<String>> mKnownCodebase = 581 new ArrayMap<String, Set<String>>(); 582 583 // Tracks available target package names -> overlay package paths. 584 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 585 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 586 587 /** 588 * Tracks new system packages [received in an OTA] that we expect to 589 * find updated user-installed versions. Keys are package name, values 590 * are package location. 591 */ 592 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 593 /** 594 * Tracks high priority intent filters for protected actions. During boot, certain 595 * filter actions are protected and should never be allowed to have a high priority 596 * intent filter for them. However, there is one, and only one exception -- the 597 * setup wizard. It must be able to define a high priority intent filter for these 598 * actions to ensure there are no escapes from the wizard. We need to delay processing 599 * of these during boot as we need to look at all of the system packages in order 600 * to know which component is the setup wizard. 601 */ 602 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 603 /** 604 * Whether or not processing protected filters should be deferred. 605 */ 606 private boolean mDeferProtectedFilters = true; 607 608 /** 609 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 610 */ 611 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 612 /** 613 * Whether or not system app permissions should be promoted from install to runtime. 614 */ 615 boolean mPromoteSystemApps; 616 617 @GuardedBy("mPackages") 618 final Settings mSettings; 619 620 /** 621 * Set of package names that are currently "frozen", which means active 622 * surgery is being done on the code/data for that package. The platform 623 * will refuse to launch frozen packages to avoid race conditions. 624 * 625 * @see PackageFreezer 626 */ 627 @GuardedBy("mPackages") 628 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 629 630 final ProtectedPackages mProtectedPackages = new ProtectedPackages(); 631 632 boolean mRestoredSettings; 633 634 // System configuration read by SystemConfig. 635 final int[] mGlobalGids; 636 final SparseArray<ArraySet<String>> mSystemPermissions; 637 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 638 639 // If mac_permissions.xml was found for seinfo labeling. 640 boolean mFoundPolicyFile; 641 642 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 643 644 public static final class SharedLibraryEntry { 645 public final String path; 646 public final String apk; 647 648 SharedLibraryEntry(String _path, String _apk) { 649 path = _path; 650 apk = _apk; 651 } 652 } 653 654 // Currently known shared libraries. 655 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 656 new ArrayMap<String, SharedLibraryEntry>(); 657 658 // All available activities, for your resolving pleasure. 659 final ActivityIntentResolver mActivities = 660 new ActivityIntentResolver(); 661 662 // All available receivers, for your resolving pleasure. 663 final ActivityIntentResolver mReceivers = 664 new ActivityIntentResolver(); 665 666 // All available services, for your resolving pleasure. 667 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 668 669 // All available providers, for your resolving pleasure. 670 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 671 672 // Mapping from provider base names (first directory in content URI codePath) 673 // to the provider information. 674 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 675 new ArrayMap<String, PackageParser.Provider>(); 676 677 // Mapping from instrumentation class names to info about them. 678 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 679 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 680 681 // Mapping from permission names to info about them. 682 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 683 new ArrayMap<String, PackageParser.PermissionGroup>(); 684 685 // Packages whose data we have transfered into another package, thus 686 // should no longer exist. 687 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 688 689 // Broadcast actions that are only available to the system. 690 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 691 692 /** List of packages waiting for verification. */ 693 final SparseArray<PackageVerificationState> mPendingVerification 694 = new SparseArray<PackageVerificationState>(); 695 696 /** Set of packages associated with each app op permission. */ 697 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 698 699 final PackageInstallerService mInstallerService; 700 701 private final PackageDexOptimizer mPackageDexOptimizer; 702 703 private AtomicInteger mNextMoveId = new AtomicInteger(); 704 private final MoveCallbacks mMoveCallbacks; 705 706 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 707 708 // Cache of users who need badging. 709 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 710 711 /** Token for keys in mPendingVerification. */ 712 private int mPendingVerificationToken = 0; 713 714 volatile boolean mSystemReady; 715 volatile boolean mSafeMode; 716 volatile boolean mHasSystemUidErrors; 717 718 ApplicationInfo mAndroidApplication; 719 final ActivityInfo mResolveActivity = new ActivityInfo(); 720 final ResolveInfo mResolveInfo = new ResolveInfo(); 721 ComponentName mResolveComponentName; 722 PackageParser.Package mPlatformPackage; 723 ComponentName mCustomResolverComponentName; 724 725 boolean mResolverReplaced = false; 726 727 private final @Nullable ComponentName mIntentFilterVerifierComponent; 728 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 729 730 private int mIntentFilterVerificationToken = 0; 731 732 /** Component that knows whether or not an ephemeral application exists */ 733 final ComponentName mEphemeralResolverComponent; 734 /** The service connection to the ephemeral resolver */ 735 final EphemeralResolverConnection mEphemeralResolverConnection; 736 737 /** Component used to install ephemeral applications */ 738 final ComponentName mEphemeralInstallerComponent; 739 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 740 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 741 742 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 743 = new SparseArray<IntentFilterVerificationState>(); 744 745 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 746 new DefaultPermissionGrantPolicy(this); 747 748 // List of packages names to keep cached, even if they are uninstalled for all users 749 private List<String> mKeepUninstalledPackages; 750 751 private UserManagerInternal mUserManagerInternal; 752 753 private static class IFVerificationParams { 754 PackageParser.Package pkg; 755 boolean replacing; 756 int userId; 757 int verifierUid; 758 759 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 760 int _userId, int _verifierUid) { 761 pkg = _pkg; 762 replacing = _replacing; 763 userId = _userId; 764 replacing = _replacing; 765 verifierUid = _verifierUid; 766 } 767 } 768 769 private interface IntentFilterVerifier<T extends IntentFilter> { 770 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 771 T filter, String packageName); 772 void startVerifications(int userId); 773 void receiveVerificationResponse(int verificationId); 774 } 775 776 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 777 private Context mContext; 778 private ComponentName mIntentFilterVerifierComponent; 779 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 780 781 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 782 mContext = context; 783 mIntentFilterVerifierComponent = verifierComponent; 784 } 785 786 private String getDefaultScheme() { 787 return IntentFilter.SCHEME_HTTPS; 788 } 789 790 @Override 791 public void startVerifications(int userId) { 792 // Launch verifications requests 793 int count = mCurrentIntentFilterVerifications.size(); 794 for (int n=0; n<count; n++) { 795 int verificationId = mCurrentIntentFilterVerifications.get(n); 796 final IntentFilterVerificationState ivs = 797 mIntentFilterVerificationStates.get(verificationId); 798 799 String packageName = ivs.getPackageName(); 800 801 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 802 final int filterCount = filters.size(); 803 ArraySet<String> domainsSet = new ArraySet<>(); 804 for (int m=0; m<filterCount; m++) { 805 PackageParser.ActivityIntentInfo filter = filters.get(m); 806 domainsSet.addAll(filter.getHostsList()); 807 } 808 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 809 synchronized (mPackages) { 810 if (mSettings.createIntentFilterVerificationIfNeededLPw( 811 packageName, domainsList) != null) { 812 scheduleWriteSettingsLocked(); 813 } 814 } 815 sendVerificationRequest(userId, verificationId, ivs); 816 } 817 mCurrentIntentFilterVerifications.clear(); 818 } 819 820 private void sendVerificationRequest(int userId, int verificationId, 821 IntentFilterVerificationState ivs) { 822 823 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 826 verificationId); 827 verificationIntent.putExtra( 828 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 829 getDefaultScheme()); 830 verificationIntent.putExtra( 831 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 832 ivs.getHostsString()); 833 verificationIntent.putExtra( 834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 835 ivs.getPackageName()); 836 verificationIntent.setComponent(mIntentFilterVerifierComponent); 837 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 838 839 UserHandle user = new UserHandle(userId); 840 mContext.sendBroadcastAsUser(verificationIntent, user); 841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 842 "Sending IntentFilter verification broadcast"); 843 } 844 845 public void receiveVerificationResponse(int verificationId) { 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 848 final boolean verified = ivs.isVerified(); 849 850 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 851 final int count = filters.size(); 852 if (DEBUG_DOMAIN_VERIFICATION) { 853 Slog.i(TAG, "Received verification response " + verificationId 854 + " for " + count + " filters, verified=" + verified); 855 } 856 for (int n=0; n<count; n++) { 857 PackageParser.ActivityIntentInfo filter = filters.get(n); 858 filter.setVerified(verified); 859 860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 861 + " verified with result:" + verified + " and hosts:" 862 + ivs.getHostsString()); 863 } 864 865 mIntentFilterVerificationStates.remove(verificationId); 866 867 final String packageName = ivs.getPackageName(); 868 IntentFilterVerificationInfo ivi = null; 869 870 synchronized (mPackages) { 871 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 872 } 873 if (ivi == null) { 874 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 875 + verificationId + " packageName:" + packageName); 876 return; 877 } 878 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 879 "Updating IntentFilterVerificationInfo for package " + packageName 880 +" verificationId:" + verificationId); 881 882 synchronized (mPackages) { 883 if (verified) { 884 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 885 } else { 886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 887 } 888 scheduleWriteSettingsLocked(); 889 890 final int userId = ivs.getUserId(); 891 if (userId != UserHandle.USER_ALL) { 892 final int userStatus = 893 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 894 895 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 896 boolean needUpdate = false; 897 898 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 899 // already been set by the User thru the Disambiguation dialog 900 switch (userStatus) { 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 } else { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 906 } 907 needUpdate = true; 908 break; 909 910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 911 if (verified) { 912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 913 needUpdate = true; 914 } 915 break; 916 917 default: 918 // Nothing to do 919 } 920 921 if (needUpdate) { 922 mSettings.updateIntentFilterVerificationStatusLPw( 923 packageName, updatedStatus, userId); 924 scheduleWritePackageRestrictionsLocked(userId); 925 } 926 } 927 } 928 } 929 930 @Override 931 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 932 ActivityIntentInfo filter, String packageName) { 933 if (!hasValidDomains(filter)) { 934 return false; 935 } 936 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 937 if (ivs == null) { 938 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 939 packageName); 940 } 941 if (DEBUG_DOMAIN_VERIFICATION) { 942 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 943 } 944 ivs.addFilter(filter); 945 return true; 946 } 947 948 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 949 int userId, int verificationId, String packageName) { 950 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 951 verifierUid, userId, packageName); 952 ivs.setPendingState(); 953 synchronized (mPackages) { 954 mIntentFilterVerificationStates.append(verificationId, ivs); 955 mCurrentIntentFilterVerifications.add(verificationId); 956 } 957 return ivs; 958 } 959 } 960 961 private static boolean hasValidDomains(ActivityIntentInfo filter) { 962 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 963 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 964 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 965 } 966 967 // Set of pending broadcasts for aggregating enable/disable of components. 968 static class PendingPackageBroadcasts { 969 // for each user id, a map of <package name -> components within that package> 970 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 971 972 public PendingPackageBroadcasts() { 973 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 974 } 975 976 public ArrayList<String> get(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 return packages.get(packageName); 979 } 980 981 public void put(int userId, String packageName, ArrayList<String> components) { 982 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 983 packages.put(packageName, components); 984 } 985 986 public void remove(int userId, String packageName) { 987 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 988 if (packages != null) { 989 packages.remove(packageName); 990 } 991 } 992 993 public void remove(int userId) { 994 mUidMap.remove(userId); 995 } 996 997 public int userIdCount() { 998 return mUidMap.size(); 999 } 1000 1001 public int userIdAt(int n) { 1002 return mUidMap.keyAt(n); 1003 } 1004 1005 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1006 return mUidMap.get(userId); 1007 } 1008 1009 public int size() { 1010 // total number of pending broadcast entries across all userIds 1011 int num = 0; 1012 for (int i = 0; i< mUidMap.size(); i++) { 1013 num += mUidMap.valueAt(i).size(); 1014 } 1015 return num; 1016 } 1017 1018 public void clear() { 1019 mUidMap.clear(); 1020 } 1021 1022 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1023 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1024 if (map == null) { 1025 map = new ArrayMap<String, ArrayList<String>>(); 1026 mUidMap.put(userId, map); 1027 } 1028 return map; 1029 } 1030 } 1031 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1032 1033 // Service Connection to remote media container service to copy 1034 // package uri's from external media onto secure containers 1035 // or internal storage. 1036 private IMediaContainerService mContainerService = null; 1037 1038 static final int SEND_PENDING_BROADCAST = 1; 1039 static final int MCS_BOUND = 3; 1040 static final int END_COPY = 4; 1041 static final int INIT_COPY = 5; 1042 static final int MCS_UNBIND = 6; 1043 static final int START_CLEANING_PACKAGE = 7; 1044 static final int FIND_INSTALL_LOC = 8; 1045 static final int POST_INSTALL = 9; 1046 static final int MCS_RECONNECT = 10; 1047 static final int MCS_GIVE_UP = 11; 1048 static final int UPDATED_MEDIA_STATUS = 12; 1049 static final int WRITE_SETTINGS = 13; 1050 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1051 static final int PACKAGE_VERIFIED = 15; 1052 static final int CHECK_PENDING_VERIFICATION = 16; 1053 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1054 static final int INTENT_FILTER_VERIFIED = 18; 1055 static final int WRITE_PACKAGE_LIST = 19; 1056 1057 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1058 1059 // Delay time in millisecs 1060 static final int BROADCAST_DELAY = 10 * 1000; 1061 1062 static UserManagerService sUserManager; 1063 1064 // Stores a list of users whose package restrictions file needs to be updated 1065 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1066 1067 final private DefaultContainerConnection mDefContainerConn = 1068 new DefaultContainerConnection(); 1069 class DefaultContainerConnection implements ServiceConnection { 1070 public void onServiceConnected(ComponentName name, IBinder service) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1072 IMediaContainerService imcs = 1073 IMediaContainerService.Stub.asInterface(service); 1074 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1075 } 1076 1077 public void onServiceDisconnected(ComponentName name) { 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1079 } 1080 } 1081 1082 // Recordkeeping of restore-after-install operations that are currently in flight 1083 // between the Package Manager and the Backup Manager 1084 static class PostInstallData { 1085 public InstallArgs args; 1086 public PackageInstalledInfo res; 1087 1088 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1089 args = _a; 1090 res = _r; 1091 } 1092 } 1093 1094 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1095 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1096 1097 // XML tags for backup/restore of various bits of state 1098 private static final String TAG_PREFERRED_BACKUP = "pa"; 1099 private static final String TAG_DEFAULT_APPS = "da"; 1100 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1101 1102 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1103 private static final String TAG_ALL_GRANTS = "rt-grants"; 1104 private static final String TAG_GRANT = "grant"; 1105 private static final String ATTR_PACKAGE_NAME = "pkg"; 1106 1107 private static final String TAG_PERMISSION = "perm"; 1108 private static final String ATTR_PERMISSION_NAME = "name"; 1109 private static final String ATTR_IS_GRANTED = "g"; 1110 private static final String ATTR_USER_SET = "set"; 1111 private static final String ATTR_USER_FIXED = "fixed"; 1112 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1113 1114 // System/policy permission grants are not backed up 1115 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1116 FLAG_PERMISSION_POLICY_FIXED 1117 | FLAG_PERMISSION_SYSTEM_FIXED 1118 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1119 1120 // And we back up these user-adjusted states 1121 private static final int USER_RUNTIME_GRANT_MASK = 1122 FLAG_PERMISSION_USER_SET 1123 | FLAG_PERMISSION_USER_FIXED 1124 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1125 1126 final @Nullable String mRequiredVerifierPackage; 1127 final @NonNull String mRequiredInstallerPackage; 1128 final @Nullable String mSetupWizardPackage; 1129 final @NonNull String mServicesSystemSharedLibraryPackageName; 1130 final @NonNull String mSharedSystemSharedLibraryPackageName; 1131 1132 private final PackageUsage mPackageUsage = new PackageUsage(); 1133 1134 private class PackageUsage { 1135 private static final int WRITE_INTERVAL 1136 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1137 1138 private final Object mFileLock = new Object(); 1139 private final AtomicLong mLastWritten = new AtomicLong(0); 1140 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1141 1142 private boolean mIsHistoricalPackageUsageAvailable = true; 1143 1144 boolean isHistoricalPackageUsageAvailable() { 1145 return mIsHistoricalPackageUsageAvailable; 1146 } 1147 1148 void write(boolean force) { 1149 if (force) { 1150 writeInternal(); 1151 return; 1152 } 1153 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1154 && !DEBUG_DEXOPT) { 1155 return; 1156 } 1157 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1158 new Thread("PackageUsage_DiskWriter") { 1159 @Override 1160 public void run() { 1161 try { 1162 writeInternal(); 1163 } finally { 1164 mBackgroundWriteRunning.set(false); 1165 } 1166 } 1167 }.start(); 1168 } 1169 } 1170 1171 private void writeInternal() { 1172 synchronized (mPackages) { 1173 synchronized (mFileLock) { 1174 AtomicFile file = getFile(); 1175 FileOutputStream f = null; 1176 try { 1177 f = file.startWrite(); 1178 BufferedOutputStream out = new BufferedOutputStream(f); 1179 FileUtils.setPermissions(file.getBaseFile().getPath(), 1180 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1181 StringBuilder sb = new StringBuilder(); 1182 1183 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1184 sb.append('\n'); 1185 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1186 1187 for (PackageParser.Package pkg : mPackages.values()) { 1188 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1189 continue; 1190 } 1191 sb.setLength(0); 1192 sb.append(pkg.packageName); 1193 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1194 sb.append(' '); 1195 sb.append(usageTimeInMillis); 1196 } 1197 sb.append('\n'); 1198 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1199 } 1200 out.flush(); 1201 file.finishWrite(f); 1202 } catch (IOException e) { 1203 if (f != null) { 1204 file.failWrite(f); 1205 } 1206 Log.e(TAG, "Failed to write package usage times", e); 1207 } 1208 } 1209 } 1210 mLastWritten.set(SystemClock.elapsedRealtime()); 1211 } 1212 1213 void readLP() { 1214 synchronized (mFileLock) { 1215 AtomicFile file = getFile(); 1216 BufferedInputStream in = null; 1217 try { 1218 in = new BufferedInputStream(file.openRead()); 1219 StringBuffer sb = new StringBuffer(); 1220 1221 String firstLine = readLine(in, sb); 1222 if (firstLine == null) { 1223 // Empty file. Do nothing. 1224 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1225 readVersion1LP(in, sb); 1226 } else { 1227 readVersion0LP(in, sb, firstLine); 1228 } 1229 } catch (FileNotFoundException expected) { 1230 mIsHistoricalPackageUsageAvailable = false; 1231 } catch (IOException e) { 1232 Log.w(TAG, "Failed to read package usage times", e); 1233 } finally { 1234 IoUtils.closeQuietly(in); 1235 } 1236 } 1237 mLastWritten.set(SystemClock.elapsedRealtime()); 1238 } 1239 1240 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1241 throws IOException { 1242 // Initial version of the file had no version number and stored one 1243 // package-timestamp pair per line. 1244 // Note that the first line has already been read from the InputStream. 1245 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1246 String[] tokens = line.split(" "); 1247 if (tokens.length != 2) { 1248 throw new IOException("Failed to parse " + line + 1249 " as package-timestamp pair."); 1250 } 1251 1252 String packageName = tokens[0]; 1253 PackageParser.Package pkg = mPackages.get(packageName); 1254 if (pkg == null) { 1255 continue; 1256 } 1257 1258 long timestamp = parseAsLong(tokens[1]); 1259 for (int reason = 0; 1260 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1261 reason++) { 1262 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1263 } 1264 } 1265 } 1266 1267 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1268 // Version 1 of the file started with the corresponding version 1269 // number and then stored a package name and eight timestamps per line. 1270 String line; 1271 while ((line = readLine(in, sb)) != null) { 1272 String[] tokens = line.split(" "); 1273 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1274 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1275 } 1276 1277 String packageName = tokens[0]; 1278 PackageParser.Package pkg = mPackages.get(packageName); 1279 if (pkg == null) { 1280 continue; 1281 } 1282 1283 for (int reason = 0; 1284 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1285 reason++) { 1286 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1287 } 1288 } 1289 } 1290 1291 private long parseAsLong(String token) throws IOException { 1292 try { 1293 return Long.parseLong(token); 1294 } catch (NumberFormatException e) { 1295 throw new IOException("Failed to parse " + token + " as a long.", e); 1296 } 1297 } 1298 1299 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1300 return readToken(in, sb, '\n'); 1301 } 1302 1303 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1304 throws IOException { 1305 sb.setLength(0); 1306 while (true) { 1307 int ch = in.read(); 1308 if (ch == -1) { 1309 if (sb.length() == 0) { 1310 return null; 1311 } 1312 throw new IOException("Unexpected EOF"); 1313 } 1314 if (ch == endOfToken) { 1315 return sb.toString(); 1316 } 1317 sb.append((char)ch); 1318 } 1319 } 1320 1321 private AtomicFile getFile() { 1322 File dataDir = Environment.getDataDirectory(); 1323 File systemDir = new File(dataDir, "system"); 1324 File fname = new File(systemDir, "package-usage.list"); 1325 return new AtomicFile(fname); 1326 } 1327 1328 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1329 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1330 } 1331 1332 class PackageHandler extends Handler { 1333 private boolean mBound = false; 1334 final ArrayList<HandlerParams> mPendingInstalls = 1335 new ArrayList<HandlerParams>(); 1336 1337 private boolean connectToService() { 1338 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1339 " DefaultContainerService"); 1340 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1343 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1345 mBound = true; 1346 return true; 1347 } 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 return false; 1350 } 1351 1352 private void disconnectService() { 1353 mContainerService = null; 1354 mBound = false; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 mContext.unbindService(mDefContainerConn); 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 } 1359 1360 PackageHandler(Looper looper) { 1361 super(looper); 1362 } 1363 1364 public void handleMessage(Message msg) { 1365 try { 1366 doHandleMessage(msg); 1367 } finally { 1368 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1369 } 1370 } 1371 1372 void doHandleMessage(Message msg) { 1373 switch (msg.what) { 1374 case INIT_COPY: { 1375 HandlerParams params = (HandlerParams) msg.obj; 1376 int idx = mPendingInstalls.size(); 1377 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1378 // If a bind was already initiated we dont really 1379 // need to do anything. The pending install 1380 // will be processed later on. 1381 if (!mBound) { 1382 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1383 System.identityHashCode(mHandler)); 1384 // If this is the only one pending we might 1385 // have to bind to the service again. 1386 if (!connectToService()) { 1387 Slog.e(TAG, "Failed to bind to media container service"); 1388 params.serviceError(); 1389 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1390 System.identityHashCode(mHandler)); 1391 if (params.traceMethod != null) { 1392 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1393 params.traceCookie); 1394 } 1395 return; 1396 } else { 1397 // Once we bind to the service, the first 1398 // pending request will be processed. 1399 mPendingInstalls.add(idx, params); 1400 } 1401 } else { 1402 mPendingInstalls.add(idx, params); 1403 // Already bound to the service. Just make 1404 // sure we trigger off processing the first request. 1405 if (idx == 0) { 1406 mHandler.sendEmptyMessage(MCS_BOUND); 1407 } 1408 } 1409 break; 1410 } 1411 case MCS_BOUND: { 1412 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1413 if (msg.obj != null) { 1414 mContainerService = (IMediaContainerService) msg.obj; 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1416 System.identityHashCode(mHandler)); 1417 } 1418 if (mContainerService == null) { 1419 if (!mBound) { 1420 // Something seriously wrong since we are not bound and we are not 1421 // waiting for connection. Bail out. 1422 Slog.e(TAG, "Cannot bind to media container service"); 1423 for (HandlerParams params : mPendingInstalls) { 1424 // Indicate service bind error 1425 params.serviceError(); 1426 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1427 System.identityHashCode(params)); 1428 if (params.traceMethod != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1430 params.traceMethod, params.traceCookie); 1431 } 1432 return; 1433 } 1434 mPendingInstalls.clear(); 1435 } else { 1436 Slog.w(TAG, "Waiting to connect to media container service"); 1437 } 1438 } else if (mPendingInstalls.size() > 0) { 1439 HandlerParams params = mPendingInstalls.get(0); 1440 if (params != null) { 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1442 System.identityHashCode(params)); 1443 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1444 if (params.startCopy()) { 1445 // We are done... look for more work or to 1446 // go idle. 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, 1448 "Checking for more work or unbind..."); 1449 // Delete pending install 1450 if (mPendingInstalls.size() > 0) { 1451 mPendingInstalls.remove(0); 1452 } 1453 if (mPendingInstalls.size() == 0) { 1454 if (mBound) { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting delayed MCS_UNBIND"); 1457 removeMessages(MCS_UNBIND); 1458 Message ubmsg = obtainMessage(MCS_UNBIND); 1459 // Unbind after a little delay, to avoid 1460 // continual thrashing. 1461 sendMessageDelayed(ubmsg, 10000); 1462 } 1463 } else { 1464 // There are more pending requests in queue. 1465 // Just post MCS_BOUND message to trigger processing 1466 // of next pending install. 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, 1468 "Posting MCS_BOUND for next work"); 1469 mHandler.sendEmptyMessage(MCS_BOUND); 1470 } 1471 } 1472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1473 } 1474 } else { 1475 // Should never happen ideally. 1476 Slog.w(TAG, "Empty queue"); 1477 } 1478 break; 1479 } 1480 case MCS_RECONNECT: { 1481 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1482 if (mPendingInstalls.size() > 0) { 1483 if (mBound) { 1484 disconnectService(); 1485 } 1486 if (!connectToService()) { 1487 Slog.e(TAG, "Failed to bind to media container service"); 1488 for (HandlerParams params : mPendingInstalls) { 1489 // Indicate service bind error 1490 params.serviceError(); 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1492 System.identityHashCode(params)); 1493 } 1494 mPendingInstalls.clear(); 1495 } 1496 } 1497 break; 1498 } 1499 case MCS_UNBIND: { 1500 // If there is no actual work left, then time to unbind. 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1502 1503 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1504 if (mBound) { 1505 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1506 1507 disconnectService(); 1508 } 1509 } else if (mPendingInstalls.size() > 0) { 1510 // There are more pending requests in queue. 1511 // Just post MCS_BOUND message to trigger processing 1512 // of next pending install. 1513 mHandler.sendEmptyMessage(MCS_BOUND); 1514 } 1515 1516 break; 1517 } 1518 case MCS_GIVE_UP: { 1519 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1520 HandlerParams params = mPendingInstalls.remove(0); 1521 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1522 System.identityHashCode(params)); 1523 break; 1524 } 1525 case SEND_PENDING_BROADCAST: { 1526 String packages[]; 1527 ArrayList<String> components[]; 1528 int size = 0; 1529 int uids[]; 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 if (mPendingBroadcasts == null) { 1533 return; 1534 } 1535 size = mPendingBroadcasts.size(); 1536 if (size <= 0) { 1537 // Nothing to be done. Just return 1538 return; 1539 } 1540 packages = new String[size]; 1541 components = new ArrayList[size]; 1542 uids = new int[size]; 1543 int i = 0; // filling out the above arrays 1544 1545 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1546 int packageUserId = mPendingBroadcasts.userIdAt(n); 1547 Iterator<Map.Entry<String, ArrayList<String>>> it 1548 = mPendingBroadcasts.packagesForUserId(packageUserId) 1549 .entrySet().iterator(); 1550 while (it.hasNext() && i < size) { 1551 Map.Entry<String, ArrayList<String>> ent = it.next(); 1552 packages[i] = ent.getKey(); 1553 components[i] = ent.getValue(); 1554 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1555 uids[i] = (ps != null) 1556 ? UserHandle.getUid(packageUserId, ps.appId) 1557 : -1; 1558 i++; 1559 } 1560 } 1561 size = i; 1562 mPendingBroadcasts.clear(); 1563 } 1564 // Send broadcasts 1565 for (int i = 0; i < size; i++) { 1566 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 break; 1570 } 1571 case START_CLEANING_PACKAGE: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 final String packageName = (String)msg.obj; 1574 final int userId = msg.arg1; 1575 final boolean andCode = msg.arg2 != 0; 1576 synchronized (mPackages) { 1577 if (userId == UserHandle.USER_ALL) { 1578 int[] users = sUserManager.getUserIds(); 1579 for (int user : users) { 1580 mSettings.addPackageToCleanLPw( 1581 new PackageCleanItem(user, packageName, andCode)); 1582 } 1583 } else { 1584 mSettings.addPackageToCleanLPw( 1585 new PackageCleanItem(userId, packageName, andCode)); 1586 } 1587 } 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1589 startCleaningPackages(); 1590 } break; 1591 case POST_INSTALL: { 1592 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1593 1594 PostInstallData data = mRunningInstalls.get(msg.arg1); 1595 final boolean didRestore = (msg.arg2 != 0); 1596 mRunningInstalls.delete(msg.arg1); 1597 1598 if (data != null) { 1599 InstallArgs args = data.args; 1600 PackageInstalledInfo parentRes = data.res; 1601 1602 final boolean grantPermissions = (args.installFlags 1603 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1604 final boolean killApp = (args.installFlags 1605 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1606 final String[] grantedPermissions = args.installGrantPermissions; 1607 1608 // Handle the parent package 1609 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1610 grantedPermissions, didRestore, args.installerPackageName, 1611 args.observer); 1612 1613 // Handle the child packages 1614 final int childCount = (parentRes.addedChildPackages != null) 1615 ? parentRes.addedChildPackages.size() : 0; 1616 for (int i = 0; i < childCount; i++) { 1617 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1618 handlePackagePostInstall(childRes, grantPermissions, killApp, 1619 grantedPermissions, false, args.installerPackageName, 1620 args.observer); 1621 } 1622 1623 // Log tracing if needed 1624 if (args.traceMethod != null) { 1625 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1626 args.traceCookie); 1627 } 1628 } else { 1629 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1630 } 1631 1632 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1633 } break; 1634 case UPDATED_MEDIA_STATUS: { 1635 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1636 boolean reportStatus = msg.arg1 == 1; 1637 boolean doGc = msg.arg2 == 1; 1638 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1639 if (doGc) { 1640 // Force a gc to clear up stale containers. 1641 Runtime.getRuntime().gc(); 1642 } 1643 if (msg.obj != null) { 1644 @SuppressWarnings("unchecked") 1645 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1647 // Unload containers 1648 unloadAllContainers(args); 1649 } 1650 if (reportStatus) { 1651 try { 1652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1653 PackageHelper.getMountService().finishMediaUpdate(); 1654 } catch (RemoteException e) { 1655 Log.e(TAG, "MountService not running?"); 1656 } 1657 } 1658 } break; 1659 case WRITE_SETTINGS: { 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1661 synchronized (mPackages) { 1662 removeMessages(WRITE_SETTINGS); 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 mSettings.writeLPr(); 1665 mDirtyUsers.clear(); 1666 } 1667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1668 } break; 1669 case WRITE_PACKAGE_RESTRICTIONS: { 1670 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1671 synchronized (mPackages) { 1672 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1673 for (int userId : mDirtyUsers) { 1674 mSettings.writePackageRestrictionsLPr(userId); 1675 } 1676 mDirtyUsers.clear(); 1677 } 1678 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1679 } break; 1680 case WRITE_PACKAGE_LIST: { 1681 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1682 synchronized (mPackages) { 1683 removeMessages(WRITE_PACKAGE_LIST); 1684 mSettings.writePackageListLPr(msg.arg1); 1685 } 1686 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1687 } break; 1688 case CHECK_PENDING_VERIFICATION: { 1689 final int verificationId = msg.arg1; 1690 final PackageVerificationState state = mPendingVerification.get(verificationId); 1691 1692 if ((state != null) && !state.timeoutExtended()) { 1693 final InstallArgs args = state.getInstallArgs(); 1694 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1695 1696 Slog.i(TAG, "Verification timed out for " + originUri); 1697 mPendingVerification.remove(verificationId); 1698 1699 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1700 1701 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1702 Slog.i(TAG, "Continuing with installation of " + originUri); 1703 state.setVerifierResponse(Binder.getCallingUid(), 1704 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_ALLOW, 1707 state.getInstallArgs().getUser()); 1708 try { 1709 ret = args.copyApk(mContainerService, true); 1710 } catch (RemoteException e) { 1711 Slog.e(TAG, "Could not contact the ContainerService"); 1712 } 1713 } else { 1714 broadcastPackageVerified(verificationId, originUri, 1715 PackageManager.VERIFICATION_REJECT, 1716 state.getInstallArgs().getUser()); 1717 } 1718 1719 Trace.asyncTraceEnd( 1720 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1721 1722 processPendingInstall(args, ret); 1723 mHandler.sendEmptyMessage(MCS_UNBIND); 1724 } 1725 break; 1726 } 1727 case PACKAGE_VERIFIED: { 1728 final int verificationId = msg.arg1; 1729 1730 final PackageVerificationState state = mPendingVerification.get(verificationId); 1731 if (state == null) { 1732 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1733 break; 1734 } 1735 1736 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1737 1738 state.setVerifierResponse(response.callerUid, response.code); 1739 1740 if (state.isVerificationComplete()) { 1741 mPendingVerification.remove(verificationId); 1742 1743 final InstallArgs args = state.getInstallArgs(); 1744 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1745 1746 int ret; 1747 if (state.isInstallAllowed()) { 1748 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1749 broadcastPackageVerified(verificationId, originUri, 1750 response.code, state.getInstallArgs().getUser()); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1758 } 1759 1760 Trace.asyncTraceEnd( 1761 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1762 1763 processPendingInstall(args, ret); 1764 mHandler.sendEmptyMessage(MCS_UNBIND); 1765 } 1766 1767 break; 1768 } 1769 case START_INTENT_FILTER_VERIFICATIONS: { 1770 IFVerificationParams params = (IFVerificationParams) msg.obj; 1771 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1772 params.replacing, params.pkg); 1773 break; 1774 } 1775 case INTENT_FILTER_VERIFIED: { 1776 final int verificationId = msg.arg1; 1777 1778 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1779 verificationId); 1780 if (state == null) { 1781 Slog.w(TAG, "Invalid IntentFilter verification token " 1782 + verificationId + " received"); 1783 break; 1784 } 1785 1786 final int userId = state.getUserId(); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "Processing IntentFilter verification with token:" 1790 + verificationId + " and userId:" + userId); 1791 1792 final IntentFilterVerificationResponse response = 1793 (IntentFilterVerificationResponse) msg.obj; 1794 1795 state.setVerifierResponse(response.callerUid, response.code); 1796 1797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1798 "IntentFilter verification with token:" + verificationId 1799 + " and userId:" + userId 1800 + " is settings verifier response with response code:" 1801 + response.code); 1802 1803 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1805 + response.getFailedDomainsString()); 1806 } 1807 1808 if (state.isVerificationComplete()) { 1809 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1810 } else { 1811 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1812 "IntentFilter verification with token:" + verificationId 1813 + " was not said to be complete"); 1814 } 1815 1816 break; 1817 } 1818 } 1819 } 1820 } 1821 1822 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1823 boolean killApp, String[] grantedPermissions, 1824 boolean launchedForRestore, String installerPackage, 1825 IPackageInstallObserver2 installObserver) { 1826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1827 // Send the removed broadcasts 1828 if (res.removedInfo != null) { 1829 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1830 } 1831 1832 // Now that we successfully installed the package, grant runtime 1833 // permissions if requested before broadcasting the install. 1834 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1835 >= Build.VERSION_CODES.M) { 1836 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1837 } 1838 1839 final boolean update = res.removedInfo != null 1840 && res.removedInfo.removedPackage != null; 1841 1842 // If this is the first time we have child packages for a disabled privileged 1843 // app that had no children, we grant requested runtime permissions to the new 1844 // children if the parent on the system image had them already granted. 1845 if (res.pkg.parentPackage != null) { 1846 synchronized (mPackages) { 1847 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1848 } 1849 } 1850 1851 synchronized (mPackages) { 1852 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1853 } 1854 1855 final String packageName = res.pkg.applicationInfo.packageName; 1856 Bundle extras = new Bundle(1); 1857 extras.putInt(Intent.EXTRA_UID, res.uid); 1858 1859 // Determine the set of users who are adding this package for 1860 // the first time vs. those who are seeing an update. 1861 int[] firstUsers = EMPTY_INT_ARRAY; 1862 int[] updateUsers = EMPTY_INT_ARRAY; 1863 if (res.origUsers == null || res.origUsers.length == 0) { 1864 firstUsers = res.newUsers; 1865 } else { 1866 for (int newUser : res.newUsers) { 1867 boolean isNew = true; 1868 for (int origUser : res.origUsers) { 1869 if (origUser == newUser) { 1870 isNew = false; 1871 break; 1872 } 1873 } 1874 if (isNew) { 1875 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1876 } else { 1877 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1878 } 1879 } 1880 } 1881 1882 // Send installed broadcasts if the install/update is not ephemeral 1883 if (!isEphemeral(res.pkg)) { 1884 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1885 1886 // Send added for users that see the package for the first time 1887 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1888 extras, 0 /*flags*/, null /*targetPackage*/, 1889 null /*finishedReceiver*/, firstUsers); 1890 1891 // Send added for users that don't see the package for the first time 1892 if (update) { 1893 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1894 } 1895 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1896 extras, 0 /*flags*/, null /*targetPackage*/, 1897 null /*finishedReceiver*/, updateUsers); 1898 1899 // Send replaced for users that don't see the package for the first time 1900 if (update) { 1901 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1902 packageName, extras, 0 /*flags*/, 1903 null /*targetPackage*/, null /*finishedReceiver*/, 1904 updateUsers); 1905 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1906 null /*package*/, null /*extras*/, 0 /*flags*/, 1907 packageName /*targetPackage*/, 1908 null /*finishedReceiver*/, updateUsers); 1909 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1910 // First-install and we did a restore, so we're responsible for the 1911 // first-launch broadcast. 1912 if (DEBUG_BACKUP) { 1913 Slog.i(TAG, "Post-restore of " + packageName 1914 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1915 } 1916 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1917 } 1918 1919 // Send broadcast package appeared if forward locked/external for all users 1920 // treat asec-hosted packages like removable media on upgrade 1921 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1922 if (DEBUG_INSTALL) { 1923 Slog.i(TAG, "upgrading pkg " + res.pkg 1924 + " is ASEC-hosted -> AVAILABLE"); 1925 } 1926 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1927 ArrayList<String> pkgList = new ArrayList<>(1); 1928 pkgList.add(packageName); 1929 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1930 } 1931 } 1932 1933 // Work that needs to happen on first install within each user 1934 if (firstUsers != null && firstUsers.length > 0) { 1935 synchronized (mPackages) { 1936 for (int userId : firstUsers) { 1937 // If this app is a browser and it's newly-installed for some 1938 // users, clear any default-browser state in those users. The 1939 // app's nature doesn't depend on the user, so we can just check 1940 // its browser nature in any user and generalize. 1941 if (packageIsBrowser(packageName, userId)) { 1942 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1943 } 1944 1945 // We may also need to apply pending (restored) runtime 1946 // permission grants within these users. 1947 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1948 } 1949 } 1950 } 1951 1952 // Log current value of "unknown sources" setting 1953 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1954 getUnknownSourcesSettings()); 1955 1956 // Force a gc to clear up things 1957 Runtime.getRuntime().gc(); 1958 1959 // Remove the replaced package's older resources safely now 1960 // We delete after a gc for applications on sdcard. 1961 if (res.removedInfo != null && res.removedInfo.args != null) { 1962 synchronized (mInstallLock) { 1963 res.removedInfo.args.doPostDeleteLI(true); 1964 } 1965 } 1966 } 1967 1968 // If someone is watching installs - notify them 1969 if (installObserver != null) { 1970 try { 1971 Bundle extras = extrasForInstallResult(res); 1972 installObserver.onPackageInstalled(res.name, res.returnCode, 1973 res.returnMsg, extras); 1974 } catch (RemoteException e) { 1975 Slog.i(TAG, "Observer no longer exists."); 1976 } 1977 } 1978 } 1979 1980 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1981 PackageParser.Package pkg) { 1982 if (pkg.parentPackage == null) { 1983 return; 1984 } 1985 if (pkg.requestedPermissions == null) { 1986 return; 1987 } 1988 final PackageSetting disabledSysParentPs = mSettings 1989 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1990 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1991 || !disabledSysParentPs.isPrivileged() 1992 || (disabledSysParentPs.childPackageNames != null 1993 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1994 return; 1995 } 1996 final int[] allUserIds = sUserManager.getUserIds(); 1997 final int permCount = pkg.requestedPermissions.size(); 1998 for (int i = 0; i < permCount; i++) { 1999 String permission = pkg.requestedPermissions.get(i); 2000 BasePermission bp = mSettings.mPermissions.get(permission); 2001 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2002 continue; 2003 } 2004 for (int userId : allUserIds) { 2005 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2006 permission, userId)) { 2007 grantRuntimePermission(pkg.packageName, permission, userId); 2008 } 2009 } 2010 } 2011 } 2012 2013 private StorageEventListener mStorageListener = new StorageEventListener() { 2014 @Override 2015 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2016 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 final String volumeUuid = vol.getFsUuid(); 2019 2020 // Clean up any users or apps that were removed or recreated 2021 // while this volume was missing 2022 reconcileUsers(volumeUuid); 2023 reconcileApps(volumeUuid); 2024 2025 // Clean up any install sessions that expired or were 2026 // cancelled while this volume was missing 2027 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2028 2029 loadPrivatePackages(vol); 2030 2031 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2032 unloadPrivatePackages(vol); 2033 } 2034 } 2035 2036 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2037 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2038 updateExternalMediaStatus(true, false); 2039 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2040 updateExternalMediaStatus(false, false); 2041 } 2042 } 2043 } 2044 2045 @Override 2046 public void onVolumeForgotten(String fsUuid) { 2047 if (TextUtils.isEmpty(fsUuid)) { 2048 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2049 return; 2050 } 2051 2052 // Remove any apps installed on the forgotten volume 2053 synchronized (mPackages) { 2054 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2055 for (PackageSetting ps : packages) { 2056 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2057 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2058 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2059 } 2060 2061 mSettings.onVolumeForgotten(fsUuid); 2062 mSettings.writeLPr(); 2063 } 2064 } 2065 }; 2066 2067 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2068 String[] grantedPermissions) { 2069 for (int userId : userIds) { 2070 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2071 } 2072 2073 // We could have touched GID membership, so flush out packages.list 2074 synchronized (mPackages) { 2075 mSettings.writePackageListLPr(); 2076 } 2077 } 2078 2079 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2080 String[] grantedPermissions) { 2081 SettingBase sb = (SettingBase) pkg.mExtras; 2082 if (sb == null) { 2083 return; 2084 } 2085 2086 PermissionsState permissionsState = sb.getPermissionsState(); 2087 2088 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2089 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2090 2091 for (String permission : pkg.requestedPermissions) { 2092 final BasePermission bp; 2093 synchronized (mPackages) { 2094 bp = mSettings.mPermissions.get(permission); 2095 } 2096 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2097 && (grantedPermissions == null 2098 || ArrayUtils.contains(grantedPermissions, permission))) { 2099 final int flags = permissionsState.getPermissionFlags(permission, userId); 2100 // Installer cannot change immutable permissions. 2101 if ((flags & immutableFlags) == 0) { 2102 grantRuntimePermission(pkg.packageName, permission, userId); 2103 } 2104 } 2105 } 2106 } 2107 2108 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2109 Bundle extras = null; 2110 switch (res.returnCode) { 2111 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2112 extras = new Bundle(); 2113 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2114 res.origPermission); 2115 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2116 res.origPackage); 2117 break; 2118 } 2119 case PackageManager.INSTALL_SUCCEEDED: { 2120 extras = new Bundle(); 2121 extras.putBoolean(Intent.EXTRA_REPLACING, 2122 res.removedInfo != null && res.removedInfo.removedPackage != null); 2123 break; 2124 } 2125 } 2126 return extras; 2127 } 2128 2129 void scheduleWriteSettingsLocked() { 2130 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2131 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2132 } 2133 } 2134 2135 void scheduleWritePackageListLocked(int userId) { 2136 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2137 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2138 msg.arg1 = userId; 2139 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2140 } 2141 } 2142 2143 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2144 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2145 scheduleWritePackageRestrictionsLocked(userId); 2146 } 2147 2148 void scheduleWritePackageRestrictionsLocked(int userId) { 2149 final int[] userIds = (userId == UserHandle.USER_ALL) 2150 ? sUserManager.getUserIds() : new int[]{userId}; 2151 for (int nextUserId : userIds) { 2152 if (!sUserManager.exists(nextUserId)) return; 2153 mDirtyUsers.add(nextUserId); 2154 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2155 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2156 } 2157 } 2158 } 2159 2160 public static PackageManagerService main(Context context, Installer installer, 2161 boolean factoryTest, boolean onlyCore) { 2162 // Self-check for initial settings. 2163 PackageManagerServiceCompilerMapping.checkProperties(); 2164 2165 PackageManagerService m = new PackageManagerService(context, installer, 2166 factoryTest, onlyCore); 2167 m.enableSystemUserPackages(); 2168 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2169 // disabled after already being started. 2170 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2171 UserHandle.USER_SYSTEM); 2172 ServiceManager.addService("package", m); 2173 return m; 2174 } 2175 2176 private void enableSystemUserPackages() { 2177 if (!UserManager.isSplitSystemUser()) { 2178 return; 2179 } 2180 // For system user, enable apps based on the following conditions: 2181 // - app is whitelisted or belong to one of these groups: 2182 // -- system app which has no launcher icons 2183 // -- system app which has INTERACT_ACROSS_USERS permission 2184 // -- system IME app 2185 // - app is not in the blacklist 2186 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2187 Set<String> enableApps = new ArraySet<>(); 2188 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2189 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2190 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2191 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2192 enableApps.addAll(wlApps); 2193 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2194 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2195 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2196 enableApps.removeAll(blApps); 2197 Log.i(TAG, "Applications installed for system user: " + enableApps); 2198 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2199 UserHandle.SYSTEM); 2200 final int allAppsSize = allAps.size(); 2201 synchronized (mPackages) { 2202 for (int i = 0; i < allAppsSize; i++) { 2203 String pName = allAps.get(i); 2204 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2205 // Should not happen, but we shouldn't be failing if it does 2206 if (pkgSetting == null) { 2207 continue; 2208 } 2209 boolean install = enableApps.contains(pName); 2210 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2211 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2212 + " for system user"); 2213 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2214 } 2215 } 2216 } 2217 } 2218 2219 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2220 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2221 Context.DISPLAY_SERVICE); 2222 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2223 } 2224 2225 public PackageManagerService(Context context, Installer installer, 2226 boolean factoryTest, boolean onlyCore) { 2227 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2228 SystemClock.uptimeMillis()); 2229 2230 if (mSdkVersion <= 0) { 2231 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2232 } 2233 2234 mContext = context; 2235 mFactoryTest = factoryTest; 2236 mOnlyCore = onlyCore; 2237 mMetrics = new DisplayMetrics(); 2238 mSettings = new Settings(mPackages); 2239 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2242 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2243 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2244 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2245 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2246 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2247 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2248 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2249 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2250 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2251 2252 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2253 if (separateProcesses != null && separateProcesses.length() > 0) { 2254 if ("*".equals(separateProcesses)) { 2255 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2256 mSeparateProcesses = null; 2257 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2258 } else { 2259 mDefParseFlags = 0; 2260 mSeparateProcesses = separateProcesses.split(","); 2261 Slog.w(TAG, "Running with debug.separate_processes: " 2262 + separateProcesses); 2263 } 2264 } else { 2265 mDefParseFlags = 0; 2266 mSeparateProcesses = null; 2267 } 2268 2269 mInstaller = installer; 2270 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2271 "*dexopt*"); 2272 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2273 2274 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2275 FgThread.get().getLooper()); 2276 2277 getDefaultDisplayMetrics(context, mMetrics); 2278 2279 SystemConfig systemConfig = SystemConfig.getInstance(); 2280 mGlobalGids = systemConfig.getGlobalGids(); 2281 mSystemPermissions = systemConfig.getSystemPermissions(); 2282 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2283 2284 synchronized (mInstallLock) { 2285 // writer 2286 synchronized (mPackages) { 2287 mHandlerThread = new ServiceThread(TAG, 2288 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2289 mHandlerThread.start(); 2290 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2291 mProcessLoggingHandler = new ProcessLoggingHandler(); 2292 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2293 2294 File dataDir = Environment.getDataDirectory(); 2295 mAppInstallDir = new File(dataDir, "app"); 2296 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2297 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2298 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2299 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2300 2301 sUserManager = new UserManagerService(context, this, mPackages); 2302 2303 // Propagate permission configuration in to package manager. 2304 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2305 = systemConfig.getPermissions(); 2306 for (int i=0; i<permConfig.size(); i++) { 2307 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2308 BasePermission bp = mSettings.mPermissions.get(perm.name); 2309 if (bp == null) { 2310 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2311 mSettings.mPermissions.put(perm.name, bp); 2312 } 2313 if (perm.gids != null) { 2314 bp.setGids(perm.gids, perm.perUser); 2315 } 2316 } 2317 2318 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2319 for (int i=0; i<libConfig.size(); i++) { 2320 mSharedLibraries.put(libConfig.keyAt(i), 2321 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2322 } 2323 2324 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2325 2326 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2327 2328 String customResolverActivity = Resources.getSystem().getString( 2329 R.string.config_customResolverActivity); 2330 if (TextUtils.isEmpty(customResolverActivity)) { 2331 customResolverActivity = null; 2332 } else { 2333 mCustomResolverComponentName = ComponentName.unflattenFromString( 2334 customResolverActivity); 2335 } 2336 2337 long startTime = SystemClock.uptimeMillis(); 2338 2339 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2340 startTime); 2341 2342 // Set flag to monitor and not change apk file paths when 2343 // scanning install directories. 2344 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2345 2346 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2347 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2348 2349 if (bootClassPath == null) { 2350 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2351 } 2352 2353 if (systemServerClassPath == null) { 2354 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2355 } 2356 2357 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2358 final String[] dexCodeInstructionSets = 2359 getDexCodeInstructionSets( 2360 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2361 2362 /** 2363 * Ensure all external libraries have had dexopt run on them. 2364 */ 2365 if (mSharedLibraries.size() > 0) { 2366 // NOTE: For now, we're compiling these system "shared libraries" 2367 // (and framework jars) into all available architectures. It's possible 2368 // to compile them only when we come across an app that uses them (there's 2369 // already logic for that in scanPackageLI) but that adds some complexity. 2370 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2371 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2372 final String lib = libEntry.path; 2373 if (lib == null) { 2374 continue; 2375 } 2376 2377 try { 2378 // Shared libraries do not have profiles so we perform a full 2379 // AOT compilation (if needed). 2380 int dexoptNeeded = DexFile.getDexOptNeeded( 2381 lib, dexCodeInstructionSet, 2382 getCompilerFilterForReason(REASON_SHARED_APK), 2383 false /* newProfile */); 2384 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2385 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2386 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2387 getCompilerFilterForReason(REASON_SHARED_APK), 2388 StorageManager.UUID_PRIVATE_INTERNAL, 2389 SKIP_SHARED_LIBRARY_CHECK); 2390 } 2391 } catch (FileNotFoundException e) { 2392 Slog.w(TAG, "Library not found: " + lib); 2393 } catch (IOException | InstallerException e) { 2394 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2395 + e.getMessage()); 2396 } 2397 } 2398 } 2399 } 2400 2401 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2402 2403 final VersionInfo ver = mSettings.getInternalVersion(); 2404 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2405 2406 // when upgrading from pre-M, promote system app permissions from install to runtime 2407 mPromoteSystemApps = 2408 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2409 2410 // When upgrading from pre-N, we need to handle package extraction like first boot, 2411 // as there is no profiling data available. 2412 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2413 2414 // save off the names of pre-existing system packages prior to scanning; we don't 2415 // want to automatically grant runtime permissions for new system apps 2416 if (mPromoteSystemApps) { 2417 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2418 while (pkgSettingIter.hasNext()) { 2419 PackageSetting ps = pkgSettingIter.next(); 2420 if (isSystemApp(ps)) { 2421 mExistingSystemPackages.add(ps.name); 2422 } 2423 } 2424 } 2425 2426 // Collect vendor overlay packages. 2427 // (Do this before scanning any apps.) 2428 // For security and version matching reason, only consider 2429 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2430 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2431 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2432 | PackageParser.PARSE_IS_SYSTEM 2433 | PackageParser.PARSE_IS_SYSTEM_DIR 2434 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2435 2436 // Find base frameworks (resource packages without code). 2437 scanDirTracedLI(frameworkDir, mDefParseFlags 2438 | PackageParser.PARSE_IS_SYSTEM 2439 | PackageParser.PARSE_IS_SYSTEM_DIR 2440 | PackageParser.PARSE_IS_PRIVILEGED, 2441 scanFlags | SCAN_NO_DEX, 0); 2442 2443 // Collected privileged system packages. 2444 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2445 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2446 | PackageParser.PARSE_IS_SYSTEM 2447 | PackageParser.PARSE_IS_SYSTEM_DIR 2448 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2449 2450 // Collect ordinary system packages. 2451 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2452 scanDirTracedLI(systemAppDir, mDefParseFlags 2453 | PackageParser.PARSE_IS_SYSTEM 2454 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2455 2456 // Collect all vendor packages. 2457 File vendorAppDir = new File("/vendor/app"); 2458 try { 2459 vendorAppDir = vendorAppDir.getCanonicalFile(); 2460 } catch (IOException e) { 2461 // failed to look up canonical path, continue with original one 2462 } 2463 scanDirTracedLI(vendorAppDir, mDefParseFlags 2464 | PackageParser.PARSE_IS_SYSTEM 2465 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2466 2467 // Collect all OEM packages. 2468 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2469 scanDirTracedLI(oemAppDir, mDefParseFlags 2470 | PackageParser.PARSE_IS_SYSTEM 2471 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2472 2473 // Prune any system packages that no longer exist. 2474 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2475 if (!mOnlyCore) { 2476 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2477 while (psit.hasNext()) { 2478 PackageSetting ps = psit.next(); 2479 2480 /* 2481 * If this is not a system app, it can't be a 2482 * disable system app. 2483 */ 2484 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2485 continue; 2486 } 2487 2488 /* 2489 * If the package is scanned, it's not erased. 2490 */ 2491 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2492 if (scannedPkg != null) { 2493 /* 2494 * If the system app is both scanned and in the 2495 * disabled packages list, then it must have been 2496 * added via OTA. Remove it from the currently 2497 * scanned package so the previously user-installed 2498 * application can be scanned. 2499 */ 2500 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2501 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2502 + ps.name + "; removing system app. Last known codePath=" 2503 + ps.codePathString + ", installStatus=" + ps.installStatus 2504 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2505 + scannedPkg.mVersionCode); 2506 removePackageLI(scannedPkg, true); 2507 mExpectingBetter.put(ps.name, ps.codePath); 2508 } 2509 2510 continue; 2511 } 2512 2513 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2514 psit.remove(); 2515 logCriticalInfo(Log.WARN, "System package " + ps.name 2516 + " no longer exists; it's data will be wiped"); 2517 // Actual deletion of code and data will be handled by later 2518 // reconciliation step 2519 } else { 2520 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2521 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2522 possiblyDeletedUpdatedSystemApps.add(ps.name); 2523 } 2524 } 2525 } 2526 } 2527 2528 //look for any incomplete package installations 2529 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2530 for (int i = 0; i < deletePkgsList.size(); i++) { 2531 // Actual deletion of code and data will be handled by later 2532 // reconciliation step 2533 final String packageName = deletePkgsList.get(i).name; 2534 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2535 synchronized (mPackages) { 2536 mSettings.removePackageLPw(packageName); 2537 } 2538 } 2539 2540 //delete tmp files 2541 deleteTempPackageFiles(); 2542 2543 // Remove any shared userIDs that have no associated packages 2544 mSettings.pruneSharedUsersLPw(); 2545 2546 if (!mOnlyCore) { 2547 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2548 SystemClock.uptimeMillis()); 2549 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2550 2551 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2552 | PackageParser.PARSE_FORWARD_LOCK, 2553 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2554 2555 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2556 | PackageParser.PARSE_IS_EPHEMERAL, 2557 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2558 2559 /** 2560 * Remove disable package settings for any updated system 2561 * apps that were removed via an OTA. If they're not a 2562 * previously-updated app, remove them completely. 2563 * Otherwise, just revoke their system-level permissions. 2564 */ 2565 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2566 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2567 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2568 2569 String msg; 2570 if (deletedPkg == null) { 2571 msg = "Updated system package " + deletedAppName 2572 + " no longer exists; it's data will be wiped"; 2573 // Actual deletion of code and data will be handled by later 2574 // reconciliation step 2575 } else { 2576 msg = "Updated system app + " + deletedAppName 2577 + " no longer present; removing system privileges for " 2578 + deletedAppName; 2579 2580 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2581 2582 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2583 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2584 } 2585 logCriticalInfo(Log.WARN, msg); 2586 } 2587 2588 /** 2589 * Make sure all system apps that we expected to appear on 2590 * the userdata partition actually showed up. If they never 2591 * appeared, crawl back and revive the system version. 2592 */ 2593 for (int i = 0; i < mExpectingBetter.size(); i++) { 2594 final String packageName = mExpectingBetter.keyAt(i); 2595 if (!mPackages.containsKey(packageName)) { 2596 final File scanFile = mExpectingBetter.valueAt(i); 2597 2598 logCriticalInfo(Log.WARN, "Expected better " + packageName 2599 + " but never showed up; reverting to system"); 2600 2601 int reparseFlags = mDefParseFlags; 2602 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2603 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR 2605 | PackageParser.PARSE_IS_PRIVILEGED; 2606 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2607 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2608 | PackageParser.PARSE_IS_SYSTEM_DIR; 2609 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2610 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2611 | PackageParser.PARSE_IS_SYSTEM_DIR; 2612 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2613 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2614 | PackageParser.PARSE_IS_SYSTEM_DIR; 2615 } else { 2616 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2617 continue; 2618 } 2619 2620 mSettings.enableSystemPackageLPw(packageName); 2621 2622 try { 2623 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2624 } catch (PackageManagerException e) { 2625 Slog.e(TAG, "Failed to parse original system package: " 2626 + e.getMessage()); 2627 } 2628 } 2629 } 2630 } 2631 mExpectingBetter.clear(); 2632 2633 // Resolve protected action filters. Only the setup wizard is allowed to 2634 // have a high priority filter for these actions. 2635 mSetupWizardPackage = getSetupWizardPackageName(); 2636 if (mProtectedFilters.size() > 0) { 2637 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2638 Slog.i(TAG, "No setup wizard;" 2639 + " All protected intents capped to priority 0"); 2640 } 2641 for (ActivityIntentInfo filter : mProtectedFilters) { 2642 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2643 if (DEBUG_FILTERS) { 2644 Slog.i(TAG, "Found setup wizard;" 2645 + " allow priority " + filter.getPriority() + ";" 2646 + " package: " + filter.activity.info.packageName 2647 + " activity: " + filter.activity.className 2648 + " priority: " + filter.getPriority()); 2649 } 2650 // skip setup wizard; allow it to keep the high priority filter 2651 continue; 2652 } 2653 Slog.w(TAG, "Protected action; cap priority to 0;" 2654 + " package: " + filter.activity.info.packageName 2655 + " activity: " + filter.activity.className 2656 + " origPrio: " + filter.getPriority()); 2657 filter.setPriority(0); 2658 } 2659 } 2660 mDeferProtectedFilters = false; 2661 mProtectedFilters.clear(); 2662 2663 // Now that we know all of the shared libraries, update all clients to have 2664 // the correct library paths. 2665 updateAllSharedLibrariesLPw(); 2666 2667 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2668 // NOTE: We ignore potential failures here during a system scan (like 2669 // the rest of the commands above) because there's precious little we 2670 // can do about it. A settings error is reported, though. 2671 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2672 false /* boot complete */); 2673 } 2674 2675 // Now that we know all the packages we are keeping, 2676 // read and update their last usage times. 2677 mPackageUsage.readLP(); 2678 2679 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2680 SystemClock.uptimeMillis()); 2681 Slog.i(TAG, "Time to scan packages: " 2682 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2683 + " seconds"); 2684 2685 // If the platform SDK has changed since the last time we booted, 2686 // we need to re-grant app permission to catch any new ones that 2687 // appear. This is really a hack, and means that apps can in some 2688 // cases get permissions that the user didn't initially explicitly 2689 // allow... it would be nice to have some better way to handle 2690 // this situation. 2691 int updateFlags = UPDATE_PERMISSIONS_ALL; 2692 if (ver.sdkVersion != mSdkVersion) { 2693 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2694 + mSdkVersion + "; regranting permissions for internal storage"); 2695 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2696 } 2697 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2698 ver.sdkVersion = mSdkVersion; 2699 2700 // If this is the first boot or an update from pre-M, and it is a normal 2701 // boot, then we need to initialize the default preferred apps across 2702 // all defined users. 2703 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2704 for (UserInfo user : sUserManager.getUsers(true)) { 2705 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2706 applyFactoryDefaultBrowserLPw(user.id); 2707 primeDomainVerificationsLPw(user.id); 2708 } 2709 } 2710 2711 // Prepare storage for system user really early during boot, 2712 // since core system apps like SettingsProvider and SystemUI 2713 // can't wait for user to start 2714 final int storageFlags; 2715 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2716 storageFlags = StorageManager.FLAG_STORAGE_DE; 2717 } else { 2718 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2719 } 2720 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2721 storageFlags); 2722 2723 // If this is first boot after an OTA, and a normal boot, then 2724 // we need to clear code cache directories. 2725 // Note that we do *not* clear the application profiles. These remain valid 2726 // across OTAs and are used to drive profile verification (post OTA) and 2727 // profile compilation (without waiting to collect a fresh set of profiles). 2728 if (mIsUpgrade && !onlyCore) { 2729 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2730 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2731 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2732 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2733 // No apps are running this early, so no need to freeze 2734 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2735 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2736 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2737 } 2738 } 2739 ver.fingerprint = Build.FINGERPRINT; 2740 } 2741 2742 checkDefaultBrowser(); 2743 2744 // clear only after permissions and other defaults have been updated 2745 mExistingSystemPackages.clear(); 2746 mPromoteSystemApps = false; 2747 2748 // All the changes are done during package scanning. 2749 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2750 2751 // can downgrade to reader 2752 mSettings.writeLPr(); 2753 2754 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2755 // early on (before the package manager declares itself as early) because other 2756 // components in the system server might ask for package contexts for these apps. 2757 // 2758 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2759 // (i.e, that the data partition is unavailable). 2760 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2761 long start = System.nanoTime(); 2762 List<PackageParser.Package> coreApps = new ArrayList<>(); 2763 for (PackageParser.Package pkg : mPackages.values()) { 2764 if (pkg.coreApp) { 2765 coreApps.add(pkg); 2766 } 2767 } 2768 2769 int[] stats = performDexOpt(coreApps, false, 2770 getCompilerFilterForReason(REASON_CORE_APP)); 2771 2772 final int elapsedTimeSeconds = 2773 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2774 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2775 2776 if (DEBUG_DEXOPT) { 2777 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2778 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2779 } 2780 2781 2782 // TODO: Should we log these stats to tron too ? 2783 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2784 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2785 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2786 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2787 } 2788 2789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2790 SystemClock.uptimeMillis()); 2791 2792 if (!mOnlyCore) { 2793 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2794 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2795 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2796 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2797 mIntentFilterVerifierComponent); 2798 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2799 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2800 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2801 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2802 } else { 2803 mRequiredVerifierPackage = null; 2804 mRequiredInstallerPackage = null; 2805 mIntentFilterVerifierComponent = null; 2806 mIntentFilterVerifier = null; 2807 mServicesSystemSharedLibraryPackageName = null; 2808 mSharedSystemSharedLibraryPackageName = null; 2809 } 2810 2811 mInstallerService = new PackageInstallerService(context, this); 2812 2813 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2814 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2815 // both the installer and resolver must be present to enable ephemeral 2816 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2817 if (DEBUG_EPHEMERAL) { 2818 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2819 + " installer:" + ephemeralInstallerComponent); 2820 } 2821 mEphemeralResolverComponent = ephemeralResolverComponent; 2822 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2823 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2824 mEphemeralResolverConnection = 2825 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2826 } else { 2827 if (DEBUG_EPHEMERAL) { 2828 final String missingComponent = 2829 (ephemeralResolverComponent == null) 2830 ? (ephemeralInstallerComponent == null) 2831 ? "resolver and installer" 2832 : "resolver" 2833 : "installer"; 2834 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2835 } 2836 mEphemeralResolverComponent = null; 2837 mEphemeralInstallerComponent = null; 2838 mEphemeralResolverConnection = null; 2839 } 2840 2841 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2842 } // synchronized (mPackages) 2843 } // synchronized (mInstallLock) 2844 2845 // Now after opening every single application zip, make sure they 2846 // are all flushed. Not really needed, but keeps things nice and 2847 // tidy. 2848 Runtime.getRuntime().gc(); 2849 2850 // The initial scanning above does many calls into installd while 2851 // holding the mPackages lock, but we're mostly interested in yelling 2852 // once we have a booted system. 2853 mInstaller.setWarnIfHeld(mPackages); 2854 2855 // Expose private service for system components to use. 2856 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2857 } 2858 2859 @Override 2860 public boolean isFirstBoot() { 2861 return !mRestoredSettings; 2862 } 2863 2864 @Override 2865 public boolean isOnlyCoreApps() { 2866 return mOnlyCore; 2867 } 2868 2869 @Override 2870 public boolean isUpgrade() { 2871 return mIsUpgrade; 2872 } 2873 2874 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2875 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2876 2877 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2878 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2879 UserHandle.USER_SYSTEM); 2880 if (matches.size() == 1) { 2881 return matches.get(0).getComponentInfo().packageName; 2882 } else { 2883 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2884 return null; 2885 } 2886 } 2887 2888 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2889 synchronized (mPackages) { 2890 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2891 if (libraryEntry == null) { 2892 throw new IllegalStateException("Missing required shared library:" + libraryName); 2893 } 2894 return libraryEntry.apk; 2895 } 2896 } 2897 2898 private @NonNull String getRequiredInstallerLPr() { 2899 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2900 intent.addCategory(Intent.CATEGORY_DEFAULT); 2901 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2902 2903 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2904 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2905 UserHandle.USER_SYSTEM); 2906 if (matches.size() == 1) { 2907 ResolveInfo resolveInfo = matches.get(0); 2908 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2909 throw new RuntimeException("The installer must be a privileged app"); 2910 } 2911 return matches.get(0).getComponentInfo().packageName; 2912 } else { 2913 throw new RuntimeException("There must be exactly one installer; found " + matches); 2914 } 2915 } 2916 2917 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2918 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2919 2920 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2921 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2922 UserHandle.USER_SYSTEM); 2923 ResolveInfo best = null; 2924 final int N = matches.size(); 2925 for (int i = 0; i < N; i++) { 2926 final ResolveInfo cur = matches.get(i); 2927 final String packageName = cur.getComponentInfo().packageName; 2928 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2929 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2930 continue; 2931 } 2932 2933 if (best == null || cur.priority > best.priority) { 2934 best = cur; 2935 } 2936 } 2937 2938 if (best != null) { 2939 return best.getComponentInfo().getComponentName(); 2940 } else { 2941 throw new RuntimeException("There must be at least one intent filter verifier"); 2942 } 2943 } 2944 2945 private @Nullable ComponentName getEphemeralResolverLPr() { 2946 final String[] packageArray = 2947 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2948 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2949 if (DEBUG_EPHEMERAL) { 2950 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2951 } 2952 return null; 2953 } 2954 2955 final int resolveFlags = 2956 MATCH_DIRECT_BOOT_AWARE 2957 | MATCH_DIRECT_BOOT_UNAWARE 2958 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2959 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2960 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2961 resolveFlags, UserHandle.USER_SYSTEM); 2962 2963 final int N = resolvers.size(); 2964 if (N == 0) { 2965 if (DEBUG_EPHEMERAL) { 2966 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2967 } 2968 return null; 2969 } 2970 2971 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2972 for (int i = 0; i < N; i++) { 2973 final ResolveInfo info = resolvers.get(i); 2974 2975 if (info.serviceInfo == null) { 2976 continue; 2977 } 2978 2979 final String packageName = info.serviceInfo.packageName; 2980 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2981 if (DEBUG_EPHEMERAL) { 2982 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2983 + " pkg: " + packageName + ", info:" + info); 2984 } 2985 continue; 2986 } 2987 2988 if (DEBUG_EPHEMERAL) { 2989 Slog.v(TAG, "Ephemeral resolver found;" 2990 + " pkg: " + packageName + ", info:" + info); 2991 } 2992 return new ComponentName(packageName, info.serviceInfo.name); 2993 } 2994 if (DEBUG_EPHEMERAL) { 2995 Slog.v(TAG, "Ephemeral resolver NOT found"); 2996 } 2997 return null; 2998 } 2999 3000 private @Nullable ComponentName getEphemeralInstallerLPr() { 3001 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3002 intent.addCategory(Intent.CATEGORY_DEFAULT); 3003 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3004 3005 final int resolveFlags = 3006 MATCH_DIRECT_BOOT_AWARE 3007 | MATCH_DIRECT_BOOT_UNAWARE 3008 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3009 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3010 resolveFlags, UserHandle.USER_SYSTEM); 3011 if (matches.size() == 0) { 3012 return null; 3013 } else if (matches.size() == 1) { 3014 return matches.get(0).getComponentInfo().getComponentName(); 3015 } else { 3016 throw new RuntimeException( 3017 "There must be at most one ephemeral installer; found " + matches); 3018 } 3019 } 3020 3021 private void primeDomainVerificationsLPw(int userId) { 3022 if (DEBUG_DOMAIN_VERIFICATION) { 3023 Slog.d(TAG, "Priming domain verifications in user " + userId); 3024 } 3025 3026 SystemConfig systemConfig = SystemConfig.getInstance(); 3027 ArraySet<String> packages = systemConfig.getLinkedApps(); 3028 ArraySet<String> domains = new ArraySet<String>(); 3029 3030 for (String packageName : packages) { 3031 PackageParser.Package pkg = mPackages.get(packageName); 3032 if (pkg != null) { 3033 if (!pkg.isSystemApp()) { 3034 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3035 continue; 3036 } 3037 3038 domains.clear(); 3039 for (PackageParser.Activity a : pkg.activities) { 3040 for (ActivityIntentInfo filter : a.intents) { 3041 if (hasValidDomains(filter)) { 3042 domains.addAll(filter.getHostsList()); 3043 } 3044 } 3045 } 3046 3047 if (domains.size() > 0) { 3048 if (DEBUG_DOMAIN_VERIFICATION) { 3049 Slog.v(TAG, " + " + packageName); 3050 } 3051 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3052 // state w.r.t. the formal app-linkage "no verification attempted" state; 3053 // and then 'always' in the per-user state actually used for intent resolution. 3054 final IntentFilterVerificationInfo ivi; 3055 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3056 new ArrayList<String>(domains)); 3057 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3058 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3059 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3060 } else { 3061 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3062 + "' does not handle web links"); 3063 } 3064 } else { 3065 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3066 } 3067 } 3068 3069 scheduleWritePackageRestrictionsLocked(userId); 3070 scheduleWriteSettingsLocked(); 3071 } 3072 3073 private void applyFactoryDefaultBrowserLPw(int userId) { 3074 // The default browser app's package name is stored in a string resource, 3075 // with a product-specific overlay used for vendor customization. 3076 String browserPkg = mContext.getResources().getString( 3077 com.android.internal.R.string.default_browser); 3078 if (!TextUtils.isEmpty(browserPkg)) { 3079 // non-empty string => required to be a known package 3080 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3081 if (ps == null) { 3082 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3083 browserPkg = null; 3084 } else { 3085 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3086 } 3087 } 3088 3089 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3090 // default. If there's more than one, just leave everything alone. 3091 if (browserPkg == null) { 3092 calculateDefaultBrowserLPw(userId); 3093 } 3094 } 3095 3096 private void calculateDefaultBrowserLPw(int userId) { 3097 List<String> allBrowsers = resolveAllBrowserApps(userId); 3098 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3099 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3100 } 3101 3102 private List<String> resolveAllBrowserApps(int userId) { 3103 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3104 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3105 PackageManager.MATCH_ALL, userId); 3106 3107 final int count = list.size(); 3108 List<String> result = new ArrayList<String>(count); 3109 for (int i=0; i<count; i++) { 3110 ResolveInfo info = list.get(i); 3111 if (info.activityInfo == null 3112 || !info.handleAllWebDataURI 3113 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3114 || result.contains(info.activityInfo.packageName)) { 3115 continue; 3116 } 3117 result.add(info.activityInfo.packageName); 3118 } 3119 3120 return result; 3121 } 3122 3123 private boolean packageIsBrowser(String packageName, int userId) { 3124 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3125 PackageManager.MATCH_ALL, userId); 3126 final int N = list.size(); 3127 for (int i = 0; i < N; i++) { 3128 ResolveInfo info = list.get(i); 3129 if (packageName.equals(info.activityInfo.packageName)) { 3130 return true; 3131 } 3132 } 3133 return false; 3134 } 3135 3136 private void checkDefaultBrowser() { 3137 final int myUserId = UserHandle.myUserId(); 3138 final String packageName = getDefaultBrowserPackageName(myUserId); 3139 if (packageName != null) { 3140 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3141 if (info == null) { 3142 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3143 synchronized (mPackages) { 3144 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3145 } 3146 } 3147 } 3148 } 3149 3150 @Override 3151 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3152 throws RemoteException { 3153 try { 3154 return super.onTransact(code, data, reply, flags); 3155 } catch (RuntimeException e) { 3156 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3157 Slog.wtf(TAG, "Package Manager Crash", e); 3158 } 3159 throw e; 3160 } 3161 } 3162 3163 static int[] appendInts(int[] cur, int[] add) { 3164 if (add == null) return cur; 3165 if (cur == null) return add; 3166 final int N = add.length; 3167 for (int i=0; i<N; i++) { 3168 cur = appendInt(cur, add[i]); 3169 } 3170 return cur; 3171 } 3172 3173 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3174 if (!sUserManager.exists(userId)) return null; 3175 if (ps == null) { 3176 return null; 3177 } 3178 final PackageParser.Package p = ps.pkg; 3179 if (p == null) { 3180 return null; 3181 } 3182 3183 final PermissionsState permissionsState = ps.getPermissionsState(); 3184 3185 final int[] gids = permissionsState.computeGids(userId); 3186 final Set<String> permissions = permissionsState.getPermissions(userId); 3187 final PackageUserState state = ps.readUserState(userId); 3188 3189 return PackageParser.generatePackageInfo(p, gids, flags, 3190 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3191 } 3192 3193 @Override 3194 public void checkPackageStartable(String packageName, int userId) { 3195 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3196 3197 synchronized (mPackages) { 3198 final PackageSetting ps = mSettings.mPackages.get(packageName); 3199 if (ps == null) { 3200 throw new SecurityException("Package " + packageName + " was not found!"); 3201 } 3202 3203 if (!ps.getInstalled(userId)) { 3204 throw new SecurityException( 3205 "Package " + packageName + " was not installed for user " + userId + "!"); 3206 } 3207 3208 if (mSafeMode && !ps.isSystem()) { 3209 throw new SecurityException("Package " + packageName + " not a system app!"); 3210 } 3211 3212 if (mFrozenPackages.contains(packageName)) { 3213 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3214 } 3215 3216 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3217 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3218 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3219 } 3220 } 3221 } 3222 3223 @Override 3224 public boolean isPackageAvailable(String packageName, int userId) { 3225 if (!sUserManager.exists(userId)) return false; 3226 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3227 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3228 synchronized (mPackages) { 3229 PackageParser.Package p = mPackages.get(packageName); 3230 if (p != null) { 3231 final PackageSetting ps = (PackageSetting) p.mExtras; 3232 if (ps != null) { 3233 final PackageUserState state = ps.readUserState(userId); 3234 if (state != null) { 3235 return PackageParser.isAvailable(state); 3236 } 3237 } 3238 } 3239 } 3240 return false; 3241 } 3242 3243 @Override 3244 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3245 if (!sUserManager.exists(userId)) return null; 3246 flags = updateFlagsForPackage(flags, userId, packageName); 3247 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3248 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3249 // reader 3250 synchronized (mPackages) { 3251 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3252 PackageParser.Package p = null; 3253 if (matchFactoryOnly) { 3254 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3255 if (ps != null) { 3256 return generatePackageInfo(ps, flags, userId); 3257 } 3258 } 3259 if (p == null) { 3260 p = mPackages.get(packageName); 3261 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3262 return null; 3263 } 3264 } 3265 if (DEBUG_PACKAGE_INFO) 3266 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3267 if (p != null) { 3268 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3269 } 3270 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3271 final PackageSetting ps = mSettings.mPackages.get(packageName); 3272 return generatePackageInfo(ps, flags, userId); 3273 } 3274 } 3275 return null; 3276 } 3277 3278 @Override 3279 public String[] currentToCanonicalPackageNames(String[] names) { 3280 String[] out = new String[names.length]; 3281 // reader 3282 synchronized (mPackages) { 3283 for (int i=names.length-1; i>=0; i--) { 3284 PackageSetting ps = mSettings.mPackages.get(names[i]); 3285 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3286 } 3287 } 3288 return out; 3289 } 3290 3291 @Override 3292 public String[] canonicalToCurrentPackageNames(String[] names) { 3293 String[] out = new String[names.length]; 3294 // reader 3295 synchronized (mPackages) { 3296 for (int i=names.length-1; i>=0; i--) { 3297 String cur = mSettings.mRenamedPackages.get(names[i]); 3298 out[i] = cur != null ? cur : names[i]; 3299 } 3300 } 3301 return out; 3302 } 3303 3304 @Override 3305 public int getPackageUid(String packageName, int flags, int userId) { 3306 if (!sUserManager.exists(userId)) return -1; 3307 flags = updateFlagsForPackage(flags, userId, packageName); 3308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3309 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3310 3311 // reader 3312 synchronized (mPackages) { 3313 final PackageParser.Package p = mPackages.get(packageName); 3314 if (p != null && p.isMatch(flags)) { 3315 return UserHandle.getUid(userId, p.applicationInfo.uid); 3316 } 3317 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3318 final PackageSetting ps = mSettings.mPackages.get(packageName); 3319 if (ps != null && ps.isMatch(flags)) { 3320 return UserHandle.getUid(userId, ps.appId); 3321 } 3322 } 3323 } 3324 3325 return -1; 3326 } 3327 3328 @Override 3329 public int[] getPackageGids(String packageName, int flags, int userId) { 3330 if (!sUserManager.exists(userId)) return null; 3331 flags = updateFlagsForPackage(flags, userId, packageName); 3332 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3333 false /* requireFullPermission */, false /* checkShell */, 3334 "getPackageGids"); 3335 3336 // reader 3337 synchronized (mPackages) { 3338 final PackageParser.Package p = mPackages.get(packageName); 3339 if (p != null && p.isMatch(flags)) { 3340 PackageSetting ps = (PackageSetting) p.mExtras; 3341 return ps.getPermissionsState().computeGids(userId); 3342 } 3343 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3344 final PackageSetting ps = mSettings.mPackages.get(packageName); 3345 if (ps != null && ps.isMatch(flags)) { 3346 return ps.getPermissionsState().computeGids(userId); 3347 } 3348 } 3349 } 3350 3351 return null; 3352 } 3353 3354 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3355 if (bp.perm != null) { 3356 return PackageParser.generatePermissionInfo(bp.perm, flags); 3357 } 3358 PermissionInfo pi = new PermissionInfo(); 3359 pi.name = bp.name; 3360 pi.packageName = bp.sourcePackage; 3361 pi.nonLocalizedLabel = bp.name; 3362 pi.protectionLevel = bp.protectionLevel; 3363 return pi; 3364 } 3365 3366 @Override 3367 public PermissionInfo getPermissionInfo(String name, int flags) { 3368 // reader 3369 synchronized (mPackages) { 3370 final BasePermission p = mSettings.mPermissions.get(name); 3371 if (p != null) { 3372 return generatePermissionInfo(p, flags); 3373 } 3374 return null; 3375 } 3376 } 3377 3378 @Override 3379 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3380 int flags) { 3381 // reader 3382 synchronized (mPackages) { 3383 if (group != null && !mPermissionGroups.containsKey(group)) { 3384 // This is thrown as NameNotFoundException 3385 return null; 3386 } 3387 3388 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3389 for (BasePermission p : mSettings.mPermissions.values()) { 3390 if (group == null) { 3391 if (p.perm == null || p.perm.info.group == null) { 3392 out.add(generatePermissionInfo(p, flags)); 3393 } 3394 } else { 3395 if (p.perm != null && group.equals(p.perm.info.group)) { 3396 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3397 } 3398 } 3399 } 3400 return new ParceledListSlice<>(out); 3401 } 3402 } 3403 3404 @Override 3405 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3406 // reader 3407 synchronized (mPackages) { 3408 return PackageParser.generatePermissionGroupInfo( 3409 mPermissionGroups.get(name), flags); 3410 } 3411 } 3412 3413 @Override 3414 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3415 // reader 3416 synchronized (mPackages) { 3417 final int N = mPermissionGroups.size(); 3418 ArrayList<PermissionGroupInfo> out 3419 = new ArrayList<PermissionGroupInfo>(N); 3420 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3421 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3422 } 3423 return new ParceledListSlice<>(out); 3424 } 3425 } 3426 3427 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3428 int userId) { 3429 if (!sUserManager.exists(userId)) return null; 3430 PackageSetting ps = mSettings.mPackages.get(packageName); 3431 if (ps != null) { 3432 if (ps.pkg == null) { 3433 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3434 if (pInfo != null) { 3435 return pInfo.applicationInfo; 3436 } 3437 return null; 3438 } 3439 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3440 ps.readUserState(userId), userId); 3441 } 3442 return null; 3443 } 3444 3445 @Override 3446 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3447 if (!sUserManager.exists(userId)) return null; 3448 flags = updateFlagsForApplication(flags, userId, packageName); 3449 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3450 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3451 // writer 3452 synchronized (mPackages) { 3453 PackageParser.Package p = mPackages.get(packageName); 3454 if (DEBUG_PACKAGE_INFO) Log.v( 3455 TAG, "getApplicationInfo " + packageName 3456 + ": " + p); 3457 if (p != null) { 3458 PackageSetting ps = mSettings.mPackages.get(packageName); 3459 if (ps == null) return null; 3460 // Note: isEnabledLP() does not apply here - always return info 3461 return PackageParser.generateApplicationInfo( 3462 p, flags, ps.readUserState(userId), userId); 3463 } 3464 if ("android".equals(packageName)||"system".equals(packageName)) { 3465 return mAndroidApplication; 3466 } 3467 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3468 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3469 } 3470 } 3471 return null; 3472 } 3473 3474 @Override 3475 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3476 final IPackageDataObserver observer) { 3477 mContext.enforceCallingOrSelfPermission( 3478 android.Manifest.permission.CLEAR_APP_CACHE, null); 3479 // Queue up an async operation since clearing cache may take a little while. 3480 mHandler.post(new Runnable() { 3481 public void run() { 3482 mHandler.removeCallbacks(this); 3483 boolean success = true; 3484 synchronized (mInstallLock) { 3485 try { 3486 mInstaller.freeCache(volumeUuid, freeStorageSize); 3487 } catch (InstallerException e) { 3488 Slog.w(TAG, "Couldn't clear application caches: " + e); 3489 success = false; 3490 } 3491 } 3492 if (observer != null) { 3493 try { 3494 observer.onRemoveCompleted(null, success); 3495 } catch (RemoteException e) { 3496 Slog.w(TAG, "RemoveException when invoking call back"); 3497 } 3498 } 3499 } 3500 }); 3501 } 3502 3503 @Override 3504 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3505 final IntentSender pi) { 3506 mContext.enforceCallingOrSelfPermission( 3507 android.Manifest.permission.CLEAR_APP_CACHE, null); 3508 // Queue up an async operation since clearing cache may take a little while. 3509 mHandler.post(new Runnable() { 3510 public void run() { 3511 mHandler.removeCallbacks(this); 3512 boolean success = true; 3513 synchronized (mInstallLock) { 3514 try { 3515 mInstaller.freeCache(volumeUuid, freeStorageSize); 3516 } catch (InstallerException e) { 3517 Slog.w(TAG, "Couldn't clear application caches: " + e); 3518 success = false; 3519 } 3520 } 3521 if(pi != null) { 3522 try { 3523 // Callback via pending intent 3524 int code = success ? 1 : 0; 3525 pi.sendIntent(null, code, null, 3526 null, null); 3527 } catch (SendIntentException e1) { 3528 Slog.i(TAG, "Failed to send pending intent"); 3529 } 3530 } 3531 } 3532 }); 3533 } 3534 3535 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3536 synchronized (mInstallLock) { 3537 try { 3538 mInstaller.freeCache(volumeUuid, freeStorageSize); 3539 } catch (InstallerException e) { 3540 throw new IOException("Failed to free enough space", e); 3541 } 3542 } 3543 } 3544 3545 /** 3546 * Update given flags based on encryption status of current user. 3547 */ 3548 private int updateFlags(int flags, int userId) { 3549 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3550 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3551 // Caller expressed an explicit opinion about what encryption 3552 // aware/unaware components they want to see, so fall through and 3553 // give them what they want 3554 } else { 3555 // Caller expressed no opinion, so match based on user state 3556 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3557 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3558 } else { 3559 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3560 } 3561 } 3562 return flags; 3563 } 3564 3565 private UserManagerInternal getUserManagerInternal() { 3566 if (mUserManagerInternal == null) { 3567 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3568 } 3569 return mUserManagerInternal; 3570 } 3571 3572 /** 3573 * Update given flags when being used to request {@link PackageInfo}. 3574 */ 3575 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3576 boolean triaged = true; 3577 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3578 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3579 // Caller is asking for component details, so they'd better be 3580 // asking for specific encryption matching behavior, or be triaged 3581 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3582 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3583 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3584 triaged = false; 3585 } 3586 } 3587 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3588 | PackageManager.MATCH_SYSTEM_ONLY 3589 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3590 triaged = false; 3591 } 3592 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3593 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3594 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3595 } 3596 return updateFlags(flags, userId); 3597 } 3598 3599 /** 3600 * Update given flags when being used to request {@link ApplicationInfo}. 3601 */ 3602 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3603 return updateFlagsForPackage(flags, userId, cookie); 3604 } 3605 3606 /** 3607 * Update given flags when being used to request {@link ComponentInfo}. 3608 */ 3609 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3610 if (cookie instanceof Intent) { 3611 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3612 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3613 } 3614 } 3615 3616 boolean triaged = true; 3617 // Caller is asking for component details, so they'd better be 3618 // asking for specific encryption matching behavior, or be triaged 3619 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3620 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3621 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3622 triaged = false; 3623 } 3624 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3625 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3626 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3627 } 3628 3629 return updateFlags(flags, userId); 3630 } 3631 3632 /** 3633 * Update given flags when being used to request {@link ResolveInfo}. 3634 */ 3635 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3636 // Safe mode means we shouldn't match any third-party components 3637 if (mSafeMode) { 3638 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3639 } 3640 3641 return updateFlagsForComponent(flags, userId, cookie); 3642 } 3643 3644 @Override 3645 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3646 if (!sUserManager.exists(userId)) return null; 3647 flags = updateFlagsForComponent(flags, userId, component); 3648 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3649 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3650 synchronized (mPackages) { 3651 PackageParser.Activity a = mActivities.mActivities.get(component); 3652 3653 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3654 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3655 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3656 if (ps == null) return null; 3657 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3658 userId); 3659 } 3660 if (mResolveComponentName.equals(component)) { 3661 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3662 new PackageUserState(), userId); 3663 } 3664 } 3665 return null; 3666 } 3667 3668 @Override 3669 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3670 String resolvedType) { 3671 synchronized (mPackages) { 3672 if (component.equals(mResolveComponentName)) { 3673 // The resolver supports EVERYTHING! 3674 return true; 3675 } 3676 PackageParser.Activity a = mActivities.mActivities.get(component); 3677 if (a == null) { 3678 return false; 3679 } 3680 for (int i=0; i<a.intents.size(); i++) { 3681 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3682 intent.getData(), intent.getCategories(), TAG) >= 0) { 3683 return true; 3684 } 3685 } 3686 return false; 3687 } 3688 } 3689 3690 @Override 3691 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3692 if (!sUserManager.exists(userId)) return null; 3693 flags = updateFlagsForComponent(flags, userId, component); 3694 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3695 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3696 synchronized (mPackages) { 3697 PackageParser.Activity a = mReceivers.mActivities.get(component); 3698 if (DEBUG_PACKAGE_INFO) Log.v( 3699 TAG, "getReceiverInfo " + component + ": " + a); 3700 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3701 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3702 if (ps == null) return null; 3703 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3704 userId); 3705 } 3706 } 3707 return null; 3708 } 3709 3710 @Override 3711 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3712 if (!sUserManager.exists(userId)) return null; 3713 flags = updateFlagsForComponent(flags, userId, component); 3714 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3715 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3716 synchronized (mPackages) { 3717 PackageParser.Service s = mServices.mServices.get(component); 3718 if (DEBUG_PACKAGE_INFO) Log.v( 3719 TAG, "getServiceInfo " + component + ": " + s); 3720 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3721 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3722 if (ps == null) return null; 3723 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3724 userId); 3725 } 3726 } 3727 return null; 3728 } 3729 3730 @Override 3731 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3732 if (!sUserManager.exists(userId)) return null; 3733 flags = updateFlagsForComponent(flags, userId, component); 3734 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3735 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3736 synchronized (mPackages) { 3737 PackageParser.Provider p = mProviders.mProviders.get(component); 3738 if (DEBUG_PACKAGE_INFO) Log.v( 3739 TAG, "getProviderInfo " + component + ": " + p); 3740 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3741 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3742 if (ps == null) return null; 3743 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3744 userId); 3745 } 3746 } 3747 return null; 3748 } 3749 3750 @Override 3751 public String[] getSystemSharedLibraryNames() { 3752 Set<String> libSet; 3753 synchronized (mPackages) { 3754 libSet = mSharedLibraries.keySet(); 3755 int size = libSet.size(); 3756 if (size > 0) { 3757 String[] libs = new String[size]; 3758 libSet.toArray(libs); 3759 return libs; 3760 } 3761 } 3762 return null; 3763 } 3764 3765 @Override 3766 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3767 synchronized (mPackages) { 3768 return mServicesSystemSharedLibraryPackageName; 3769 } 3770 } 3771 3772 @Override 3773 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3774 synchronized (mPackages) { 3775 return mSharedSystemSharedLibraryPackageName; 3776 } 3777 } 3778 3779 @Override 3780 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3781 synchronized (mPackages) { 3782 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3783 3784 final FeatureInfo fi = new FeatureInfo(); 3785 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3786 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3787 res.add(fi); 3788 3789 return new ParceledListSlice<>(res); 3790 } 3791 } 3792 3793 @Override 3794 public boolean hasSystemFeature(String name, int version) { 3795 synchronized (mPackages) { 3796 final FeatureInfo feat = mAvailableFeatures.get(name); 3797 if (feat == null) { 3798 return false; 3799 } else { 3800 return feat.version >= version; 3801 } 3802 } 3803 } 3804 3805 @Override 3806 public int checkPermission(String permName, String pkgName, int userId) { 3807 if (!sUserManager.exists(userId)) { 3808 return PackageManager.PERMISSION_DENIED; 3809 } 3810 3811 synchronized (mPackages) { 3812 final PackageParser.Package p = mPackages.get(pkgName); 3813 if (p != null && p.mExtras != null) { 3814 final PackageSetting ps = (PackageSetting) p.mExtras; 3815 final PermissionsState permissionsState = ps.getPermissionsState(); 3816 if (permissionsState.hasPermission(permName, userId)) { 3817 return PackageManager.PERMISSION_GRANTED; 3818 } 3819 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3820 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3821 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3822 return PackageManager.PERMISSION_GRANTED; 3823 } 3824 } 3825 } 3826 3827 return PackageManager.PERMISSION_DENIED; 3828 } 3829 3830 @Override 3831 public int checkUidPermission(String permName, int uid) { 3832 final int userId = UserHandle.getUserId(uid); 3833 3834 if (!sUserManager.exists(userId)) { 3835 return PackageManager.PERMISSION_DENIED; 3836 } 3837 3838 synchronized (mPackages) { 3839 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3840 if (obj != null) { 3841 final SettingBase ps = (SettingBase) obj; 3842 final PermissionsState permissionsState = ps.getPermissionsState(); 3843 if (permissionsState.hasPermission(permName, userId)) { 3844 return PackageManager.PERMISSION_GRANTED; 3845 } 3846 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3847 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3848 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3849 return PackageManager.PERMISSION_GRANTED; 3850 } 3851 } else { 3852 ArraySet<String> perms = mSystemPermissions.get(uid); 3853 if (perms != null) { 3854 if (perms.contains(permName)) { 3855 return PackageManager.PERMISSION_GRANTED; 3856 } 3857 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3858 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3859 return PackageManager.PERMISSION_GRANTED; 3860 } 3861 } 3862 } 3863 } 3864 3865 return PackageManager.PERMISSION_DENIED; 3866 } 3867 3868 @Override 3869 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3870 if (UserHandle.getCallingUserId() != userId) { 3871 mContext.enforceCallingPermission( 3872 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3873 "isPermissionRevokedByPolicy for user " + userId); 3874 } 3875 3876 if (checkPermission(permission, packageName, userId) 3877 == PackageManager.PERMISSION_GRANTED) { 3878 return false; 3879 } 3880 3881 final long identity = Binder.clearCallingIdentity(); 3882 try { 3883 final int flags = getPermissionFlags(permission, packageName, userId); 3884 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3885 } finally { 3886 Binder.restoreCallingIdentity(identity); 3887 } 3888 } 3889 3890 @Override 3891 public String getPermissionControllerPackageName() { 3892 synchronized (mPackages) { 3893 return mRequiredInstallerPackage; 3894 } 3895 } 3896 3897 /** 3898 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3899 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3900 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3901 * @param message the message to log on security exception 3902 */ 3903 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3904 boolean checkShell, String message) { 3905 if (userId < 0) { 3906 throw new IllegalArgumentException("Invalid userId " + userId); 3907 } 3908 if (checkShell) { 3909 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3910 } 3911 if (userId == UserHandle.getUserId(callingUid)) return; 3912 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3913 if (requireFullPermission) { 3914 mContext.enforceCallingOrSelfPermission( 3915 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3916 } else { 3917 try { 3918 mContext.enforceCallingOrSelfPermission( 3919 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3920 } catch (SecurityException se) { 3921 mContext.enforceCallingOrSelfPermission( 3922 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3923 } 3924 } 3925 } 3926 } 3927 3928 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3929 if (callingUid == Process.SHELL_UID) { 3930 if (userHandle >= 0 3931 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3932 throw new SecurityException("Shell does not have permission to access user " 3933 + userHandle); 3934 } else if (userHandle < 0) { 3935 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3936 + Debug.getCallers(3)); 3937 } 3938 } 3939 } 3940 3941 private BasePermission findPermissionTreeLP(String permName) { 3942 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3943 if (permName.startsWith(bp.name) && 3944 permName.length() > bp.name.length() && 3945 permName.charAt(bp.name.length()) == '.') { 3946 return bp; 3947 } 3948 } 3949 return null; 3950 } 3951 3952 private BasePermission checkPermissionTreeLP(String permName) { 3953 if (permName != null) { 3954 BasePermission bp = findPermissionTreeLP(permName); 3955 if (bp != null) { 3956 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3957 return bp; 3958 } 3959 throw new SecurityException("Calling uid " 3960 + Binder.getCallingUid() 3961 + " is not allowed to add to permission tree " 3962 + bp.name + " owned by uid " + bp.uid); 3963 } 3964 } 3965 throw new SecurityException("No permission tree found for " + permName); 3966 } 3967 3968 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3969 if (s1 == null) { 3970 return s2 == null; 3971 } 3972 if (s2 == null) { 3973 return false; 3974 } 3975 if (s1.getClass() != s2.getClass()) { 3976 return false; 3977 } 3978 return s1.equals(s2); 3979 } 3980 3981 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3982 if (pi1.icon != pi2.icon) return false; 3983 if (pi1.logo != pi2.logo) return false; 3984 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3985 if (!compareStrings(pi1.name, pi2.name)) return false; 3986 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3987 // We'll take care of setting this one. 3988 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3989 // These are not currently stored in settings. 3990 //if (!compareStrings(pi1.group, pi2.group)) return false; 3991 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3992 //if (pi1.labelRes != pi2.labelRes) return false; 3993 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3994 return true; 3995 } 3996 3997 int permissionInfoFootprint(PermissionInfo info) { 3998 int size = info.name.length(); 3999 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4000 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4001 return size; 4002 } 4003 4004 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4005 int size = 0; 4006 for (BasePermission perm : mSettings.mPermissions.values()) { 4007 if (perm.uid == tree.uid) { 4008 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4009 } 4010 } 4011 return size; 4012 } 4013 4014 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4015 // We calculate the max size of permissions defined by this uid and throw 4016 // if that plus the size of 'info' would exceed our stated maximum. 4017 if (tree.uid != Process.SYSTEM_UID) { 4018 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4019 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4020 throw new SecurityException("Permission tree size cap exceeded"); 4021 } 4022 } 4023 } 4024 4025 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4026 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4027 throw new SecurityException("Label must be specified in permission"); 4028 } 4029 BasePermission tree = checkPermissionTreeLP(info.name); 4030 BasePermission bp = mSettings.mPermissions.get(info.name); 4031 boolean added = bp == null; 4032 boolean changed = true; 4033 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4034 if (added) { 4035 enforcePermissionCapLocked(info, tree); 4036 bp = new BasePermission(info.name, tree.sourcePackage, 4037 BasePermission.TYPE_DYNAMIC); 4038 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4039 throw new SecurityException( 4040 "Not allowed to modify non-dynamic permission " 4041 + info.name); 4042 } else { 4043 if (bp.protectionLevel == fixedLevel 4044 && bp.perm.owner.equals(tree.perm.owner) 4045 && bp.uid == tree.uid 4046 && comparePermissionInfos(bp.perm.info, info)) { 4047 changed = false; 4048 } 4049 } 4050 bp.protectionLevel = fixedLevel; 4051 info = new PermissionInfo(info); 4052 info.protectionLevel = fixedLevel; 4053 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4054 bp.perm.info.packageName = tree.perm.info.packageName; 4055 bp.uid = tree.uid; 4056 if (added) { 4057 mSettings.mPermissions.put(info.name, bp); 4058 } 4059 if (changed) { 4060 if (!async) { 4061 mSettings.writeLPr(); 4062 } else { 4063 scheduleWriteSettingsLocked(); 4064 } 4065 } 4066 return added; 4067 } 4068 4069 @Override 4070 public boolean addPermission(PermissionInfo info) { 4071 synchronized (mPackages) { 4072 return addPermissionLocked(info, false); 4073 } 4074 } 4075 4076 @Override 4077 public boolean addPermissionAsync(PermissionInfo info) { 4078 synchronized (mPackages) { 4079 return addPermissionLocked(info, true); 4080 } 4081 } 4082 4083 @Override 4084 public void removePermission(String name) { 4085 synchronized (mPackages) { 4086 checkPermissionTreeLP(name); 4087 BasePermission bp = mSettings.mPermissions.get(name); 4088 if (bp != null) { 4089 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4090 throw new SecurityException( 4091 "Not allowed to modify non-dynamic permission " 4092 + name); 4093 } 4094 mSettings.mPermissions.remove(name); 4095 mSettings.writeLPr(); 4096 } 4097 } 4098 } 4099 4100 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4101 BasePermission bp) { 4102 int index = pkg.requestedPermissions.indexOf(bp.name); 4103 if (index == -1) { 4104 throw new SecurityException("Package " + pkg.packageName 4105 + " has not requested permission " + bp.name); 4106 } 4107 if (!bp.isRuntime() && !bp.isDevelopment()) { 4108 throw new SecurityException("Permission " + bp.name 4109 + " is not a changeable permission type"); 4110 } 4111 } 4112 4113 @Override 4114 public void grantRuntimePermission(String packageName, String name, final int userId) { 4115 if (!sUserManager.exists(userId)) { 4116 Log.e(TAG, "No such user:" + userId); 4117 return; 4118 } 4119 4120 mContext.enforceCallingOrSelfPermission( 4121 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4122 "grantRuntimePermission"); 4123 4124 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4125 true /* requireFullPermission */, true /* checkShell */, 4126 "grantRuntimePermission"); 4127 4128 final int uid; 4129 final SettingBase sb; 4130 4131 synchronized (mPackages) { 4132 final PackageParser.Package pkg = mPackages.get(packageName); 4133 if (pkg == null) { 4134 throw new IllegalArgumentException("Unknown package: " + packageName); 4135 } 4136 4137 final BasePermission bp = mSettings.mPermissions.get(name); 4138 if (bp == null) { 4139 throw new IllegalArgumentException("Unknown permission: " + name); 4140 } 4141 4142 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4143 4144 // If a permission review is required for legacy apps we represent 4145 // their permissions as always granted runtime ones since we need 4146 // to keep the review required permission flag per user while an 4147 // install permission's state is shared across all users. 4148 if (Build.PERMISSIONS_REVIEW_REQUIRED 4149 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4150 && bp.isRuntime()) { 4151 return; 4152 } 4153 4154 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4155 sb = (SettingBase) pkg.mExtras; 4156 if (sb == null) { 4157 throw new IllegalArgumentException("Unknown package: " + packageName); 4158 } 4159 4160 final PermissionsState permissionsState = sb.getPermissionsState(); 4161 4162 final int flags = permissionsState.getPermissionFlags(name, userId); 4163 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4164 throw new SecurityException("Cannot grant system fixed permission " 4165 + name + " for package " + packageName); 4166 } 4167 4168 if (bp.isDevelopment()) { 4169 // Development permissions must be handled specially, since they are not 4170 // normal runtime permissions. For now they apply to all users. 4171 if (permissionsState.grantInstallPermission(bp) != 4172 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4173 scheduleWriteSettingsLocked(); 4174 } 4175 return; 4176 } 4177 4178 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4179 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4180 return; 4181 } 4182 4183 final int result = permissionsState.grantRuntimePermission(bp, userId); 4184 switch (result) { 4185 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4186 return; 4187 } 4188 4189 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4190 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4191 mHandler.post(new Runnable() { 4192 @Override 4193 public void run() { 4194 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4195 } 4196 }); 4197 } 4198 break; 4199 } 4200 4201 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4202 4203 // Not critical if that is lost - app has to request again. 4204 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4205 } 4206 4207 // Only need to do this if user is initialized. Otherwise it's a new user 4208 // and there are no processes running as the user yet and there's no need 4209 // to make an expensive call to remount processes for the changed permissions. 4210 if (READ_EXTERNAL_STORAGE.equals(name) 4211 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4212 final long token = Binder.clearCallingIdentity(); 4213 try { 4214 if (sUserManager.isInitialized(userId)) { 4215 MountServiceInternal mountServiceInternal = LocalServices.getService( 4216 MountServiceInternal.class); 4217 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4218 } 4219 } finally { 4220 Binder.restoreCallingIdentity(token); 4221 } 4222 } 4223 } 4224 4225 @Override 4226 public void revokeRuntimePermission(String packageName, String name, int userId) { 4227 if (!sUserManager.exists(userId)) { 4228 Log.e(TAG, "No such user:" + userId); 4229 return; 4230 } 4231 4232 mContext.enforceCallingOrSelfPermission( 4233 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4234 "revokeRuntimePermission"); 4235 4236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4237 true /* requireFullPermission */, true /* checkShell */, 4238 "revokeRuntimePermission"); 4239 4240 final int appId; 4241 4242 synchronized (mPackages) { 4243 final PackageParser.Package pkg = mPackages.get(packageName); 4244 if (pkg == null) { 4245 throw new IllegalArgumentException("Unknown package: " + packageName); 4246 } 4247 4248 final BasePermission bp = mSettings.mPermissions.get(name); 4249 if (bp == null) { 4250 throw new IllegalArgumentException("Unknown permission: " + name); 4251 } 4252 4253 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4254 4255 // If a permission review is required for legacy apps we represent 4256 // their permissions as always granted runtime ones since we need 4257 // to keep the review required permission flag per user while an 4258 // install permission's state is shared across all users. 4259 if (Build.PERMISSIONS_REVIEW_REQUIRED 4260 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4261 && bp.isRuntime()) { 4262 return; 4263 } 4264 4265 SettingBase sb = (SettingBase) pkg.mExtras; 4266 if (sb == null) { 4267 throw new IllegalArgumentException("Unknown package: " + packageName); 4268 } 4269 4270 final PermissionsState permissionsState = sb.getPermissionsState(); 4271 4272 final int flags = permissionsState.getPermissionFlags(name, userId); 4273 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4274 throw new SecurityException("Cannot revoke system fixed permission " 4275 + name + " for package " + packageName); 4276 } 4277 4278 if (bp.isDevelopment()) { 4279 // Development permissions must be handled specially, since they are not 4280 // normal runtime permissions. For now they apply to all users. 4281 if (permissionsState.revokeInstallPermission(bp) != 4282 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4283 scheduleWriteSettingsLocked(); 4284 } 4285 return; 4286 } 4287 4288 if (permissionsState.revokeRuntimePermission(bp, userId) == 4289 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4290 return; 4291 } 4292 4293 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4294 4295 // Critical, after this call app should never have the permission. 4296 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4297 4298 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4299 } 4300 4301 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4302 } 4303 4304 @Override 4305 public void resetRuntimePermissions() { 4306 mContext.enforceCallingOrSelfPermission( 4307 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4308 "revokeRuntimePermission"); 4309 4310 int callingUid = Binder.getCallingUid(); 4311 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4312 mContext.enforceCallingOrSelfPermission( 4313 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4314 "resetRuntimePermissions"); 4315 } 4316 4317 synchronized (mPackages) { 4318 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4319 for (int userId : UserManagerService.getInstance().getUserIds()) { 4320 final int packageCount = mPackages.size(); 4321 for (int i = 0; i < packageCount; i++) { 4322 PackageParser.Package pkg = mPackages.valueAt(i); 4323 if (!(pkg.mExtras instanceof PackageSetting)) { 4324 continue; 4325 } 4326 PackageSetting ps = (PackageSetting) pkg.mExtras; 4327 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4328 } 4329 } 4330 } 4331 } 4332 4333 @Override 4334 public int getPermissionFlags(String name, String packageName, int userId) { 4335 if (!sUserManager.exists(userId)) { 4336 return 0; 4337 } 4338 4339 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4340 4341 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4342 true /* requireFullPermission */, false /* checkShell */, 4343 "getPermissionFlags"); 4344 4345 synchronized (mPackages) { 4346 final PackageParser.Package pkg = mPackages.get(packageName); 4347 if (pkg == null) { 4348 return 0; 4349 } 4350 4351 final BasePermission bp = mSettings.mPermissions.get(name); 4352 if (bp == null) { 4353 return 0; 4354 } 4355 4356 SettingBase sb = (SettingBase) pkg.mExtras; 4357 if (sb == null) { 4358 return 0; 4359 } 4360 4361 PermissionsState permissionsState = sb.getPermissionsState(); 4362 return permissionsState.getPermissionFlags(name, userId); 4363 } 4364 } 4365 4366 @Override 4367 public void updatePermissionFlags(String name, String packageName, int flagMask, 4368 int flagValues, int userId) { 4369 if (!sUserManager.exists(userId)) { 4370 return; 4371 } 4372 4373 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4374 4375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4376 true /* requireFullPermission */, true /* checkShell */, 4377 "updatePermissionFlags"); 4378 4379 // Only the system can change these flags and nothing else. 4380 if (getCallingUid() != Process.SYSTEM_UID) { 4381 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4382 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4383 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4384 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4385 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4386 } 4387 4388 synchronized (mPackages) { 4389 final PackageParser.Package pkg = mPackages.get(packageName); 4390 if (pkg == null) { 4391 throw new IllegalArgumentException("Unknown package: " + packageName); 4392 } 4393 4394 final BasePermission bp = mSettings.mPermissions.get(name); 4395 if (bp == null) { 4396 throw new IllegalArgumentException("Unknown permission: " + name); 4397 } 4398 4399 SettingBase sb = (SettingBase) pkg.mExtras; 4400 if (sb == null) { 4401 throw new IllegalArgumentException("Unknown package: " + packageName); 4402 } 4403 4404 PermissionsState permissionsState = sb.getPermissionsState(); 4405 4406 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4407 4408 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4409 // Install and runtime permissions are stored in different places, 4410 // so figure out what permission changed and persist the change. 4411 if (permissionsState.getInstallPermissionState(name) != null) { 4412 scheduleWriteSettingsLocked(); 4413 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4414 || hadState) { 4415 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4416 } 4417 } 4418 } 4419 } 4420 4421 /** 4422 * Update the permission flags for all packages and runtime permissions of a user in order 4423 * to allow device or profile owner to remove POLICY_FIXED. 4424 */ 4425 @Override 4426 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4427 if (!sUserManager.exists(userId)) { 4428 return; 4429 } 4430 4431 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4432 4433 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4434 true /* requireFullPermission */, true /* checkShell */, 4435 "updatePermissionFlagsForAllApps"); 4436 4437 // Only the system can change system fixed flags. 4438 if (getCallingUid() != Process.SYSTEM_UID) { 4439 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4440 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4441 } 4442 4443 synchronized (mPackages) { 4444 boolean changed = false; 4445 final int packageCount = mPackages.size(); 4446 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4447 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4448 SettingBase sb = (SettingBase) pkg.mExtras; 4449 if (sb == null) { 4450 continue; 4451 } 4452 PermissionsState permissionsState = sb.getPermissionsState(); 4453 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4454 userId, flagMask, flagValues); 4455 } 4456 if (changed) { 4457 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4458 } 4459 } 4460 } 4461 4462 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4463 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4464 != PackageManager.PERMISSION_GRANTED 4465 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4466 != PackageManager.PERMISSION_GRANTED) { 4467 throw new SecurityException(message + " requires " 4468 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4469 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4470 } 4471 } 4472 4473 @Override 4474 public boolean shouldShowRequestPermissionRationale(String permissionName, 4475 String packageName, int userId) { 4476 if (UserHandle.getCallingUserId() != userId) { 4477 mContext.enforceCallingPermission( 4478 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4479 "canShowRequestPermissionRationale for user " + userId); 4480 } 4481 4482 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4483 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4484 return false; 4485 } 4486 4487 if (checkPermission(permissionName, packageName, userId) 4488 == PackageManager.PERMISSION_GRANTED) { 4489 return false; 4490 } 4491 4492 final int flags; 4493 4494 final long identity = Binder.clearCallingIdentity(); 4495 try { 4496 flags = getPermissionFlags(permissionName, 4497 packageName, userId); 4498 } finally { 4499 Binder.restoreCallingIdentity(identity); 4500 } 4501 4502 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4503 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4504 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4505 4506 if ((flags & fixedFlags) != 0) { 4507 return false; 4508 } 4509 4510 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4511 } 4512 4513 @Override 4514 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4515 mContext.enforceCallingOrSelfPermission( 4516 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4517 "addOnPermissionsChangeListener"); 4518 4519 synchronized (mPackages) { 4520 mOnPermissionChangeListeners.addListenerLocked(listener); 4521 } 4522 } 4523 4524 @Override 4525 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4526 synchronized (mPackages) { 4527 mOnPermissionChangeListeners.removeListenerLocked(listener); 4528 } 4529 } 4530 4531 @Override 4532 public boolean isProtectedBroadcast(String actionName) { 4533 synchronized (mPackages) { 4534 if (mProtectedBroadcasts.contains(actionName)) { 4535 return true; 4536 } else if (actionName != null) { 4537 // TODO: remove these terrible hacks 4538 if (actionName.startsWith("android.net.netmon.lingerExpired") 4539 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4540 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4541 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4542 return true; 4543 } 4544 } 4545 } 4546 return false; 4547 } 4548 4549 @Override 4550 public int checkSignatures(String pkg1, String pkg2) { 4551 synchronized (mPackages) { 4552 final PackageParser.Package p1 = mPackages.get(pkg1); 4553 final PackageParser.Package p2 = mPackages.get(pkg2); 4554 if (p1 == null || p1.mExtras == null 4555 || p2 == null || p2.mExtras == null) { 4556 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4557 } 4558 return compareSignatures(p1.mSignatures, p2.mSignatures); 4559 } 4560 } 4561 4562 @Override 4563 public int checkUidSignatures(int uid1, int uid2) { 4564 // Map to base uids. 4565 uid1 = UserHandle.getAppId(uid1); 4566 uid2 = UserHandle.getAppId(uid2); 4567 // reader 4568 synchronized (mPackages) { 4569 Signature[] s1; 4570 Signature[] s2; 4571 Object obj = mSettings.getUserIdLPr(uid1); 4572 if (obj != null) { 4573 if (obj instanceof SharedUserSetting) { 4574 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4575 } else if (obj instanceof PackageSetting) { 4576 s1 = ((PackageSetting)obj).signatures.mSignatures; 4577 } else { 4578 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4579 } 4580 } else { 4581 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4582 } 4583 obj = mSettings.getUserIdLPr(uid2); 4584 if (obj != null) { 4585 if (obj instanceof SharedUserSetting) { 4586 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4587 } else if (obj instanceof PackageSetting) { 4588 s2 = ((PackageSetting)obj).signatures.mSignatures; 4589 } else { 4590 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4591 } 4592 } else { 4593 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4594 } 4595 return compareSignatures(s1, s2); 4596 } 4597 } 4598 4599 /** 4600 * This method should typically only be used when granting or revoking 4601 * permissions, since the app may immediately restart after this call. 4602 * <p> 4603 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4604 * guard your work against the app being relaunched. 4605 */ 4606 private void killUid(int appId, int userId, String reason) { 4607 final long identity = Binder.clearCallingIdentity(); 4608 try { 4609 IActivityManager am = ActivityManagerNative.getDefault(); 4610 if (am != null) { 4611 try { 4612 am.killUid(appId, userId, reason); 4613 } catch (RemoteException e) { 4614 /* ignore - same process */ 4615 } 4616 } 4617 } finally { 4618 Binder.restoreCallingIdentity(identity); 4619 } 4620 } 4621 4622 /** 4623 * Compares two sets of signatures. Returns: 4624 * <br /> 4625 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4626 * <br /> 4627 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4628 * <br /> 4629 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4630 * <br /> 4631 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4632 * <br /> 4633 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4634 */ 4635 static int compareSignatures(Signature[] s1, Signature[] s2) { 4636 if (s1 == null) { 4637 return s2 == null 4638 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4639 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4640 } 4641 4642 if (s2 == null) { 4643 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4644 } 4645 4646 if (s1.length != s2.length) { 4647 return PackageManager.SIGNATURE_NO_MATCH; 4648 } 4649 4650 // Since both signature sets are of size 1, we can compare without HashSets. 4651 if (s1.length == 1) { 4652 return s1[0].equals(s2[0]) ? 4653 PackageManager.SIGNATURE_MATCH : 4654 PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4658 for (Signature sig : s1) { 4659 set1.add(sig); 4660 } 4661 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4662 for (Signature sig : s2) { 4663 set2.add(sig); 4664 } 4665 // Make sure s2 contains all signatures in s1. 4666 if (set1.equals(set2)) { 4667 return PackageManager.SIGNATURE_MATCH; 4668 } 4669 return PackageManager.SIGNATURE_NO_MATCH; 4670 } 4671 4672 /** 4673 * If the database version for this type of package (internal storage or 4674 * external storage) is less than the version where package signatures 4675 * were updated, return true. 4676 */ 4677 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4678 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4679 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4680 } 4681 4682 /** 4683 * Used for backward compatibility to make sure any packages with 4684 * certificate chains get upgraded to the new style. {@code existingSigs} 4685 * will be in the old format (since they were stored on disk from before the 4686 * system upgrade) and {@code scannedSigs} will be in the newer format. 4687 */ 4688 private int compareSignaturesCompat(PackageSignatures existingSigs, 4689 PackageParser.Package scannedPkg) { 4690 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4691 return PackageManager.SIGNATURE_NO_MATCH; 4692 } 4693 4694 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4695 for (Signature sig : existingSigs.mSignatures) { 4696 existingSet.add(sig); 4697 } 4698 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4699 for (Signature sig : scannedPkg.mSignatures) { 4700 try { 4701 Signature[] chainSignatures = sig.getChainSignatures(); 4702 for (Signature chainSig : chainSignatures) { 4703 scannedCompatSet.add(chainSig); 4704 } 4705 } catch (CertificateEncodingException e) { 4706 scannedCompatSet.add(sig); 4707 } 4708 } 4709 /* 4710 * Make sure the expanded scanned set contains all signatures in the 4711 * existing one. 4712 */ 4713 if (scannedCompatSet.equals(existingSet)) { 4714 // Migrate the old signatures to the new scheme. 4715 existingSigs.assignSignatures(scannedPkg.mSignatures); 4716 // The new KeySets will be re-added later in the scanning process. 4717 synchronized (mPackages) { 4718 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4719 } 4720 return PackageManager.SIGNATURE_MATCH; 4721 } 4722 return PackageManager.SIGNATURE_NO_MATCH; 4723 } 4724 4725 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4726 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4727 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4728 } 4729 4730 private int compareSignaturesRecover(PackageSignatures existingSigs, 4731 PackageParser.Package scannedPkg) { 4732 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4733 return PackageManager.SIGNATURE_NO_MATCH; 4734 } 4735 4736 String msg = null; 4737 try { 4738 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4739 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4740 + scannedPkg.packageName); 4741 return PackageManager.SIGNATURE_MATCH; 4742 } 4743 } catch (CertificateException e) { 4744 msg = e.getMessage(); 4745 } 4746 4747 logCriticalInfo(Log.INFO, 4748 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4749 return PackageManager.SIGNATURE_NO_MATCH; 4750 } 4751 4752 @Override 4753 public List<String> getAllPackages() { 4754 synchronized (mPackages) { 4755 return new ArrayList<String>(mPackages.keySet()); 4756 } 4757 } 4758 4759 @Override 4760 public String[] getPackagesForUid(int uid) { 4761 uid = UserHandle.getAppId(uid); 4762 // reader 4763 synchronized (mPackages) { 4764 Object obj = mSettings.getUserIdLPr(uid); 4765 if (obj instanceof SharedUserSetting) { 4766 final SharedUserSetting sus = (SharedUserSetting) obj; 4767 final int N = sus.packages.size(); 4768 final String[] res = new String[N]; 4769 for (int i = 0; i < N; i++) { 4770 res[i] = sus.packages.valueAt(i).name; 4771 } 4772 return res; 4773 } else if (obj instanceof PackageSetting) { 4774 final PackageSetting ps = (PackageSetting) obj; 4775 return new String[] { ps.name }; 4776 } 4777 } 4778 return null; 4779 } 4780 4781 @Override 4782 public String getNameForUid(int uid) { 4783 // reader 4784 synchronized (mPackages) { 4785 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4786 if (obj instanceof SharedUserSetting) { 4787 final SharedUserSetting sus = (SharedUserSetting) obj; 4788 return sus.name + ":" + sus.userId; 4789 } else if (obj instanceof PackageSetting) { 4790 final PackageSetting ps = (PackageSetting) obj; 4791 return ps.name; 4792 } 4793 } 4794 return null; 4795 } 4796 4797 @Override 4798 public int getUidForSharedUser(String sharedUserName) { 4799 if(sharedUserName == null) { 4800 return -1; 4801 } 4802 // reader 4803 synchronized (mPackages) { 4804 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4805 if (suid == null) { 4806 return -1; 4807 } 4808 return suid.userId; 4809 } 4810 } 4811 4812 @Override 4813 public int getFlagsForUid(int uid) { 4814 synchronized (mPackages) { 4815 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4816 if (obj instanceof SharedUserSetting) { 4817 final SharedUserSetting sus = (SharedUserSetting) obj; 4818 return sus.pkgFlags; 4819 } else if (obj instanceof PackageSetting) { 4820 final PackageSetting ps = (PackageSetting) obj; 4821 return ps.pkgFlags; 4822 } 4823 } 4824 return 0; 4825 } 4826 4827 @Override 4828 public int getPrivateFlagsForUid(int uid) { 4829 synchronized (mPackages) { 4830 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4831 if (obj instanceof SharedUserSetting) { 4832 final SharedUserSetting sus = (SharedUserSetting) obj; 4833 return sus.pkgPrivateFlags; 4834 } else if (obj instanceof PackageSetting) { 4835 final PackageSetting ps = (PackageSetting) obj; 4836 return ps.pkgPrivateFlags; 4837 } 4838 } 4839 return 0; 4840 } 4841 4842 @Override 4843 public boolean isUidPrivileged(int uid) { 4844 uid = UserHandle.getAppId(uid); 4845 // reader 4846 synchronized (mPackages) { 4847 Object obj = mSettings.getUserIdLPr(uid); 4848 if (obj instanceof SharedUserSetting) { 4849 final SharedUserSetting sus = (SharedUserSetting) obj; 4850 final Iterator<PackageSetting> it = sus.packages.iterator(); 4851 while (it.hasNext()) { 4852 if (it.next().isPrivileged()) { 4853 return true; 4854 } 4855 } 4856 } else if (obj instanceof PackageSetting) { 4857 final PackageSetting ps = (PackageSetting) obj; 4858 return ps.isPrivileged(); 4859 } 4860 } 4861 return false; 4862 } 4863 4864 @Override 4865 public String[] getAppOpPermissionPackages(String permissionName) { 4866 synchronized (mPackages) { 4867 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4868 if (pkgs == null) { 4869 return null; 4870 } 4871 return pkgs.toArray(new String[pkgs.size()]); 4872 } 4873 } 4874 4875 @Override 4876 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4877 int flags, int userId) { 4878 try { 4879 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4880 4881 if (!sUserManager.exists(userId)) return null; 4882 flags = updateFlagsForResolve(flags, userId, intent); 4883 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4884 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4885 4886 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4887 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4888 flags, userId); 4889 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4890 4891 final ResolveInfo bestChoice = 4892 chooseBestActivity(intent, resolvedType, flags, query, userId); 4893 4894 if (isEphemeralAllowed(intent, query, userId)) { 4895 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4896 final EphemeralResolveInfo ai = 4897 getEphemeralResolveInfo(intent, resolvedType, userId); 4898 if (ai != null) { 4899 if (DEBUG_EPHEMERAL) { 4900 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4901 } 4902 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4903 bestChoice.ephemeralResolveInfo = ai; 4904 } 4905 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4906 } 4907 return bestChoice; 4908 } finally { 4909 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4910 } 4911 } 4912 4913 @Override 4914 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4915 IntentFilter filter, int match, ComponentName activity) { 4916 final int userId = UserHandle.getCallingUserId(); 4917 if (DEBUG_PREFERRED) { 4918 Log.v(TAG, "setLastChosenActivity intent=" + intent 4919 + " resolvedType=" + resolvedType 4920 + " flags=" + flags 4921 + " filter=" + filter 4922 + " match=" + match 4923 + " activity=" + activity); 4924 filter.dump(new PrintStreamPrinter(System.out), " "); 4925 } 4926 intent.setComponent(null); 4927 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4928 userId); 4929 // Find any earlier preferred or last chosen entries and nuke them 4930 findPreferredActivity(intent, resolvedType, 4931 flags, query, 0, false, true, false, userId); 4932 // Add the new activity as the last chosen for this filter 4933 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4934 "Setting last chosen"); 4935 } 4936 4937 @Override 4938 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4939 final int userId = UserHandle.getCallingUserId(); 4940 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4941 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4942 userId); 4943 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4944 false, false, false, userId); 4945 } 4946 4947 4948 private boolean isEphemeralAllowed( 4949 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4950 // Short circuit and return early if possible. 4951 if (DISABLE_EPHEMERAL_APPS) { 4952 return false; 4953 } 4954 final int callingUser = UserHandle.getCallingUserId(); 4955 if (callingUser != UserHandle.USER_SYSTEM) { 4956 return false; 4957 } 4958 if (mEphemeralResolverConnection == null) { 4959 return false; 4960 } 4961 if (intent.getComponent() != null) { 4962 return false; 4963 } 4964 if (intent.getPackage() != null) { 4965 return false; 4966 } 4967 final boolean isWebUri = hasWebURI(intent); 4968 if (!isWebUri) { 4969 return false; 4970 } 4971 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4972 synchronized (mPackages) { 4973 final int count = resolvedActivites.size(); 4974 for (int n = 0; n < count; n++) { 4975 ResolveInfo info = resolvedActivites.get(n); 4976 String packageName = info.activityInfo.packageName; 4977 PackageSetting ps = mSettings.mPackages.get(packageName); 4978 if (ps != null) { 4979 // Try to get the status from User settings first 4980 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4981 int status = (int) (packedStatus >> 32); 4982 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4983 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4984 if (DEBUG_EPHEMERAL) { 4985 Slog.v(TAG, "DENY ephemeral apps;" 4986 + " pkg: " + packageName + ", status: " + status); 4987 } 4988 return false; 4989 } 4990 } 4991 } 4992 } 4993 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4994 return true; 4995 } 4996 4997 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4998 int userId) { 4999 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5000 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5001 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5002 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5003 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixCount); 5004 final int[] shaPrefix = digest.getDigestPrefix(); 5005 final byte[][] digestBytes = digest.getDigestBytes(); 5006 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5007 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5008 shaPrefix, ephemeralPrefixMask); 5009 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5010 // No hash prefix match; there are no ephemeral apps for this domain. 5011 return null; 5012 } 5013 5014 // Go in reverse order so we match the narrowest scope first. 5015 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5016 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5017 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5018 continue; 5019 } 5020 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5021 // No filters; this should never happen. 5022 if (filters.isEmpty()) { 5023 continue; 5024 } 5025 // We have a domain match; resolve the filters to see if anything matches. 5026 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5027 for (int j = filters.size() - 1; j >= 0; --j) { 5028 final EphemeralResolveIntentInfo intentInfo = 5029 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5030 ephemeralResolver.addFilter(intentInfo); 5031 } 5032 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5033 intent, resolvedType, false /*defaultOnly*/, userId); 5034 if (!matchedResolveInfoList.isEmpty()) { 5035 return matchedResolveInfoList.get(0); 5036 } 5037 } 5038 } 5039 // Hash or filter mis-match; no ephemeral apps for this domain. 5040 return null; 5041 } 5042 5043 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5044 int flags, List<ResolveInfo> query, int userId) { 5045 if (query != null) { 5046 final int N = query.size(); 5047 if (N == 1) { 5048 return query.get(0); 5049 } else if (N > 1) { 5050 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5051 // If there is more than one activity with the same priority, 5052 // then let the user decide between them. 5053 ResolveInfo r0 = query.get(0); 5054 ResolveInfo r1 = query.get(1); 5055 if (DEBUG_INTENT_MATCHING || debug) { 5056 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5057 + r1.activityInfo.name + "=" + r1.priority); 5058 } 5059 // If the first activity has a higher priority, or a different 5060 // default, then it is always desirable to pick it. 5061 if (r0.priority != r1.priority 5062 || r0.preferredOrder != r1.preferredOrder 5063 || r0.isDefault != r1.isDefault) { 5064 return query.get(0); 5065 } 5066 // If we have saved a preference for a preferred activity for 5067 // this Intent, use that. 5068 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5069 flags, query, r0.priority, true, false, debug, userId); 5070 if (ri != null) { 5071 return ri; 5072 } 5073 ri = new ResolveInfo(mResolveInfo); 5074 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5075 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5076 // If all of the options come from the same package, show the application's 5077 // label and icon instead of the generic resolver's. 5078 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5079 // and then throw away the ResolveInfo itself, meaning that the caller loses 5080 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5081 // a fallback for this case; we only set the target package's resources on 5082 // the ResolveInfo, not the ActivityInfo. 5083 final String intentPackage = intent.getPackage(); 5084 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5085 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5086 ri.resolvePackageName = intentPackage; 5087 if (userNeedsBadging(userId)) { 5088 ri.noResourceId = true; 5089 } else { 5090 ri.icon = appi.icon; 5091 } 5092 ri.iconResourceId = appi.icon; 5093 ri.labelRes = appi.labelRes; 5094 } 5095 ri.activityInfo.applicationInfo = new ApplicationInfo( 5096 ri.activityInfo.applicationInfo); 5097 if (userId != 0) { 5098 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5099 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5100 } 5101 // Make sure that the resolver is displayable in car mode 5102 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5103 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5104 return ri; 5105 } 5106 } 5107 return null; 5108 } 5109 5110 /** 5111 * Return true if the given list is not empty and all of its contents have 5112 * an activityInfo with the given package name. 5113 */ 5114 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5115 if (ArrayUtils.isEmpty(list)) { 5116 return false; 5117 } 5118 for (int i = 0, N = list.size(); i < N; i++) { 5119 final ResolveInfo ri = list.get(i); 5120 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5121 if (ai == null || !packageName.equals(ai.packageName)) { 5122 return false; 5123 } 5124 } 5125 return true; 5126 } 5127 5128 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5129 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5130 final int N = query.size(); 5131 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5132 .get(userId); 5133 // Get the list of persistent preferred activities that handle the intent 5134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5135 List<PersistentPreferredActivity> pprefs = ppir != null 5136 ? ppir.queryIntent(intent, resolvedType, 5137 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5138 : null; 5139 if (pprefs != null && pprefs.size() > 0) { 5140 final int M = pprefs.size(); 5141 for (int i=0; i<M; i++) { 5142 final PersistentPreferredActivity ppa = pprefs.get(i); 5143 if (DEBUG_PREFERRED || debug) { 5144 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5145 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5146 + "\n component=" + ppa.mComponent); 5147 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5148 } 5149 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5150 flags | MATCH_DISABLED_COMPONENTS, userId); 5151 if (DEBUG_PREFERRED || debug) { 5152 Slog.v(TAG, "Found persistent preferred activity:"); 5153 if (ai != null) { 5154 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5155 } else { 5156 Slog.v(TAG, " null"); 5157 } 5158 } 5159 if (ai == null) { 5160 // This previously registered persistent preferred activity 5161 // component is no longer known. Ignore it and do NOT remove it. 5162 continue; 5163 } 5164 for (int j=0; j<N; j++) { 5165 final ResolveInfo ri = query.get(j); 5166 if (!ri.activityInfo.applicationInfo.packageName 5167 .equals(ai.applicationInfo.packageName)) { 5168 continue; 5169 } 5170 if (!ri.activityInfo.name.equals(ai.name)) { 5171 continue; 5172 } 5173 // Found a persistent preference that can handle the intent. 5174 if (DEBUG_PREFERRED || debug) { 5175 Slog.v(TAG, "Returning persistent preferred activity: " + 5176 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5177 } 5178 return ri; 5179 } 5180 } 5181 } 5182 return null; 5183 } 5184 5185 // TODO: handle preferred activities missing while user has amnesia 5186 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5187 List<ResolveInfo> query, int priority, boolean always, 5188 boolean removeMatches, boolean debug, int userId) { 5189 if (!sUserManager.exists(userId)) return null; 5190 flags = updateFlagsForResolve(flags, userId, intent); 5191 // writer 5192 synchronized (mPackages) { 5193 if (intent.getSelector() != null) { 5194 intent = intent.getSelector(); 5195 } 5196 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5197 5198 // Try to find a matching persistent preferred activity. 5199 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5200 debug, userId); 5201 5202 // If a persistent preferred activity matched, use it. 5203 if (pri != null) { 5204 return pri; 5205 } 5206 5207 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5208 // Get the list of preferred activities that handle the intent 5209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5210 List<PreferredActivity> prefs = pir != null 5211 ? pir.queryIntent(intent, resolvedType, 5212 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5213 : null; 5214 if (prefs != null && prefs.size() > 0) { 5215 boolean changed = false; 5216 try { 5217 // First figure out how good the original match set is. 5218 // We will only allow preferred activities that came 5219 // from the same match quality. 5220 int match = 0; 5221 5222 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5223 5224 final int N = query.size(); 5225 for (int j=0; j<N; j++) { 5226 final ResolveInfo ri = query.get(j); 5227 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5228 + ": 0x" + Integer.toHexString(match)); 5229 if (ri.match > match) { 5230 match = ri.match; 5231 } 5232 } 5233 5234 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5235 + Integer.toHexString(match)); 5236 5237 match &= IntentFilter.MATCH_CATEGORY_MASK; 5238 final int M = prefs.size(); 5239 for (int i=0; i<M; i++) { 5240 final PreferredActivity pa = prefs.get(i); 5241 if (DEBUG_PREFERRED || debug) { 5242 Slog.v(TAG, "Checking PreferredActivity ds=" 5243 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5244 + "\n component=" + pa.mPref.mComponent); 5245 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5246 } 5247 if (pa.mPref.mMatch != match) { 5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5249 + Integer.toHexString(pa.mPref.mMatch)); 5250 continue; 5251 } 5252 // If it's not an "always" type preferred activity and that's what we're 5253 // looking for, skip it. 5254 if (always && !pa.mPref.mAlways) { 5255 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5256 continue; 5257 } 5258 final ActivityInfo ai = getActivityInfo( 5259 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5260 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5261 userId); 5262 if (DEBUG_PREFERRED || debug) { 5263 Slog.v(TAG, "Found preferred activity:"); 5264 if (ai != null) { 5265 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5266 } else { 5267 Slog.v(TAG, " null"); 5268 } 5269 } 5270 if (ai == null) { 5271 // This previously registered preferred activity 5272 // component is no longer known. Most likely an update 5273 // to the app was installed and in the new version this 5274 // component no longer exists. Clean it up by removing 5275 // it from the preferred activities list, and skip it. 5276 Slog.w(TAG, "Removing dangling preferred activity: " 5277 + pa.mPref.mComponent); 5278 pir.removeFilter(pa); 5279 changed = true; 5280 continue; 5281 } 5282 for (int j=0; j<N; j++) { 5283 final ResolveInfo ri = query.get(j); 5284 if (!ri.activityInfo.applicationInfo.packageName 5285 .equals(ai.applicationInfo.packageName)) { 5286 continue; 5287 } 5288 if (!ri.activityInfo.name.equals(ai.name)) { 5289 continue; 5290 } 5291 5292 if (removeMatches) { 5293 pir.removeFilter(pa); 5294 changed = true; 5295 if (DEBUG_PREFERRED) { 5296 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5297 } 5298 break; 5299 } 5300 5301 // Okay we found a previously set preferred or last chosen app. 5302 // If the result set is different from when this 5303 // was created, we need to clear it and re-ask the 5304 // user their preference, if we're looking for an "always" type entry. 5305 if (always && !pa.mPref.sameSet(query)) { 5306 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5307 + intent + " type " + resolvedType); 5308 if (DEBUG_PREFERRED) { 5309 Slog.v(TAG, "Removing preferred activity since set changed " 5310 + pa.mPref.mComponent); 5311 } 5312 pir.removeFilter(pa); 5313 // Re-add the filter as a "last chosen" entry (!always) 5314 PreferredActivity lastChosen = new PreferredActivity( 5315 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5316 pir.addFilter(lastChosen); 5317 changed = true; 5318 return null; 5319 } 5320 5321 // Yay! Either the set matched or we're looking for the last chosen 5322 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5323 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5324 return ri; 5325 } 5326 } 5327 } finally { 5328 if (changed) { 5329 if (DEBUG_PREFERRED) { 5330 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5331 } 5332 scheduleWritePackageRestrictionsLocked(userId); 5333 } 5334 } 5335 } 5336 } 5337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5338 return null; 5339 } 5340 5341 /* 5342 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5343 */ 5344 @Override 5345 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5346 int targetUserId) { 5347 mContext.enforceCallingOrSelfPermission( 5348 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5349 List<CrossProfileIntentFilter> matches = 5350 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5351 if (matches != null) { 5352 int size = matches.size(); 5353 for (int i = 0; i < size; i++) { 5354 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5355 } 5356 } 5357 if (hasWebURI(intent)) { 5358 // cross-profile app linking works only towards the parent. 5359 final UserInfo parent = getProfileParent(sourceUserId); 5360 synchronized(mPackages) { 5361 int flags = updateFlagsForResolve(0, parent.id, intent); 5362 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5363 intent, resolvedType, flags, sourceUserId, parent.id); 5364 return xpDomainInfo != null; 5365 } 5366 } 5367 return false; 5368 } 5369 5370 private UserInfo getProfileParent(int userId) { 5371 final long identity = Binder.clearCallingIdentity(); 5372 try { 5373 return sUserManager.getProfileParent(userId); 5374 } finally { 5375 Binder.restoreCallingIdentity(identity); 5376 } 5377 } 5378 5379 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5380 String resolvedType, int userId) { 5381 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5382 if (resolver != null) { 5383 return resolver.queryIntent(intent, resolvedType, false, userId); 5384 } 5385 return null; 5386 } 5387 5388 @Override 5389 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5390 String resolvedType, int flags, int userId) { 5391 try { 5392 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5393 5394 return new ParceledListSlice<>( 5395 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5396 } finally { 5397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5398 } 5399 } 5400 5401 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5402 String resolvedType, int flags, int userId) { 5403 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5404 flags = updateFlagsForResolve(flags, userId, intent); 5405 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5406 false /* requireFullPermission */, false /* checkShell */, 5407 "query intent activities"); 5408 ComponentName comp = intent.getComponent(); 5409 if (comp == null) { 5410 if (intent.getSelector() != null) { 5411 intent = intent.getSelector(); 5412 comp = intent.getComponent(); 5413 } 5414 } 5415 5416 if (comp != null) { 5417 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5418 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5419 if (ai != null) { 5420 final ResolveInfo ri = new ResolveInfo(); 5421 ri.activityInfo = ai; 5422 list.add(ri); 5423 } 5424 return list; 5425 } 5426 5427 // reader 5428 synchronized (mPackages) { 5429 final String pkgName = intent.getPackage(); 5430 if (pkgName == null) { 5431 List<CrossProfileIntentFilter> matchingFilters = 5432 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5433 // Check for results that need to skip the current profile. 5434 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5435 resolvedType, flags, userId); 5436 if (xpResolveInfo != null) { 5437 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5438 result.add(xpResolveInfo); 5439 return filterIfNotSystemUser(result, userId); 5440 } 5441 5442 // Check for results in the current profile. 5443 List<ResolveInfo> result = mActivities.queryIntent( 5444 intent, resolvedType, flags, userId); 5445 result = filterIfNotSystemUser(result, userId); 5446 5447 // Check for cross profile results. 5448 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5449 xpResolveInfo = queryCrossProfileIntents( 5450 matchingFilters, intent, resolvedType, flags, userId, 5451 hasNonNegativePriorityResult); 5452 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5453 boolean isVisibleToUser = filterIfNotSystemUser( 5454 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5455 if (isVisibleToUser) { 5456 result.add(xpResolveInfo); 5457 Collections.sort(result, mResolvePrioritySorter); 5458 } 5459 } 5460 if (hasWebURI(intent)) { 5461 CrossProfileDomainInfo xpDomainInfo = null; 5462 final UserInfo parent = getProfileParent(userId); 5463 if (parent != null) { 5464 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5465 flags, userId, parent.id); 5466 } 5467 if (xpDomainInfo != null) { 5468 if (xpResolveInfo != null) { 5469 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5470 // in the result. 5471 result.remove(xpResolveInfo); 5472 } 5473 if (result.size() == 0) { 5474 result.add(xpDomainInfo.resolveInfo); 5475 return result; 5476 } 5477 } else if (result.size() <= 1) { 5478 return result; 5479 } 5480 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5481 xpDomainInfo, userId); 5482 Collections.sort(result, mResolvePrioritySorter); 5483 } 5484 return result; 5485 } 5486 final PackageParser.Package pkg = mPackages.get(pkgName); 5487 if (pkg != null) { 5488 return filterIfNotSystemUser( 5489 mActivities.queryIntentForPackage( 5490 intent, resolvedType, flags, pkg.activities, userId), 5491 userId); 5492 } 5493 return new ArrayList<ResolveInfo>(); 5494 } 5495 } 5496 5497 private static class CrossProfileDomainInfo { 5498 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5499 ResolveInfo resolveInfo; 5500 /* Best domain verification status of the activities found in the other profile */ 5501 int bestDomainVerificationStatus; 5502 } 5503 5504 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5505 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5506 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5507 sourceUserId)) { 5508 return null; 5509 } 5510 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5511 resolvedType, flags, parentUserId); 5512 5513 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5514 return null; 5515 } 5516 CrossProfileDomainInfo result = null; 5517 int size = resultTargetUser.size(); 5518 for (int i = 0; i < size; i++) { 5519 ResolveInfo riTargetUser = resultTargetUser.get(i); 5520 // Intent filter verification is only for filters that specify a host. So don't return 5521 // those that handle all web uris. 5522 if (riTargetUser.handleAllWebDataURI) { 5523 continue; 5524 } 5525 String packageName = riTargetUser.activityInfo.packageName; 5526 PackageSetting ps = mSettings.mPackages.get(packageName); 5527 if (ps == null) { 5528 continue; 5529 } 5530 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5531 int status = (int)(verificationState >> 32); 5532 if (result == null) { 5533 result = new CrossProfileDomainInfo(); 5534 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5535 sourceUserId, parentUserId); 5536 result.bestDomainVerificationStatus = status; 5537 } else { 5538 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5539 result.bestDomainVerificationStatus); 5540 } 5541 } 5542 // Don't consider matches with status NEVER across profiles. 5543 if (result != null && result.bestDomainVerificationStatus 5544 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5545 return null; 5546 } 5547 return result; 5548 } 5549 5550 /** 5551 * Verification statuses are ordered from the worse to the best, except for 5552 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5553 */ 5554 private int bestDomainVerificationStatus(int status1, int status2) { 5555 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5556 return status2; 5557 } 5558 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5559 return status1; 5560 } 5561 return (int) MathUtils.max(status1, status2); 5562 } 5563 5564 private boolean isUserEnabled(int userId) { 5565 long callingId = Binder.clearCallingIdentity(); 5566 try { 5567 UserInfo userInfo = sUserManager.getUserInfo(userId); 5568 return userInfo != null && userInfo.isEnabled(); 5569 } finally { 5570 Binder.restoreCallingIdentity(callingId); 5571 } 5572 } 5573 5574 /** 5575 * Filter out activities with systemUserOnly flag set, when current user is not System. 5576 * 5577 * @return filtered list 5578 */ 5579 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5580 if (userId == UserHandle.USER_SYSTEM) { 5581 return resolveInfos; 5582 } 5583 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5584 ResolveInfo info = resolveInfos.get(i); 5585 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5586 resolveInfos.remove(i); 5587 } 5588 } 5589 return resolveInfos; 5590 } 5591 5592 /** 5593 * @param resolveInfos list of resolve infos in descending priority order 5594 * @return if the list contains a resolve info with non-negative priority 5595 */ 5596 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5597 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5598 } 5599 5600 private static boolean hasWebURI(Intent intent) { 5601 if (intent.getData() == null) { 5602 return false; 5603 } 5604 final String scheme = intent.getScheme(); 5605 if (TextUtils.isEmpty(scheme)) { 5606 return false; 5607 } 5608 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5609 } 5610 5611 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5612 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5613 int userId) { 5614 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5615 5616 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5617 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5618 candidates.size()); 5619 } 5620 5621 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5622 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5623 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5624 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5625 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5626 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5627 5628 synchronized (mPackages) { 5629 final int count = candidates.size(); 5630 // First, try to use linked apps. Partition the candidates into four lists: 5631 // one for the final results, one for the "do not use ever", one for "undefined status" 5632 // and finally one for "browser app type". 5633 for (int n=0; n<count; n++) { 5634 ResolveInfo info = candidates.get(n); 5635 String packageName = info.activityInfo.packageName; 5636 PackageSetting ps = mSettings.mPackages.get(packageName); 5637 if (ps != null) { 5638 // Add to the special match all list (Browser use case) 5639 if (info.handleAllWebDataURI) { 5640 matchAllList.add(info); 5641 continue; 5642 } 5643 // Try to get the status from User settings first 5644 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5645 int status = (int)(packedStatus >> 32); 5646 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5647 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5648 if (DEBUG_DOMAIN_VERIFICATION) { 5649 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5650 + " : linkgen=" + linkGeneration); 5651 } 5652 // Use link-enabled generation as preferredOrder, i.e. 5653 // prefer newly-enabled over earlier-enabled. 5654 info.preferredOrder = linkGeneration; 5655 alwaysList.add(info); 5656 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5657 if (DEBUG_DOMAIN_VERIFICATION) { 5658 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5659 } 5660 neverList.add(info); 5661 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5662 if (DEBUG_DOMAIN_VERIFICATION) { 5663 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5664 } 5665 alwaysAskList.add(info); 5666 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5667 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5668 if (DEBUG_DOMAIN_VERIFICATION) { 5669 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5670 } 5671 undefinedList.add(info); 5672 } 5673 } 5674 } 5675 5676 // We'll want to include browser possibilities in a few cases 5677 boolean includeBrowser = false; 5678 5679 // First try to add the "always" resolution(s) for the current user, if any 5680 if (alwaysList.size() > 0) { 5681 result.addAll(alwaysList); 5682 } else { 5683 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5684 result.addAll(undefinedList); 5685 // Maybe add one for the other profile. 5686 if (xpDomainInfo != null && ( 5687 xpDomainInfo.bestDomainVerificationStatus 5688 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5689 result.add(xpDomainInfo.resolveInfo); 5690 } 5691 includeBrowser = true; 5692 } 5693 5694 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5695 // If there were 'always' entries their preferred order has been set, so we also 5696 // back that off to make the alternatives equivalent 5697 if (alwaysAskList.size() > 0) { 5698 for (ResolveInfo i : result) { 5699 i.preferredOrder = 0; 5700 } 5701 result.addAll(alwaysAskList); 5702 includeBrowser = true; 5703 } 5704 5705 if (includeBrowser) { 5706 // Also add browsers (all of them or only the default one) 5707 if (DEBUG_DOMAIN_VERIFICATION) { 5708 Slog.v(TAG, " ...including browsers in candidate set"); 5709 } 5710 if ((matchFlags & MATCH_ALL) != 0) { 5711 result.addAll(matchAllList); 5712 } else { 5713 // Browser/generic handling case. If there's a default browser, go straight 5714 // to that (but only if there is no other higher-priority match). 5715 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5716 int maxMatchPrio = 0; 5717 ResolveInfo defaultBrowserMatch = null; 5718 final int numCandidates = matchAllList.size(); 5719 for (int n = 0; n < numCandidates; n++) { 5720 ResolveInfo info = matchAllList.get(n); 5721 // track the highest overall match priority... 5722 if (info.priority > maxMatchPrio) { 5723 maxMatchPrio = info.priority; 5724 } 5725 // ...and the highest-priority default browser match 5726 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5727 if (defaultBrowserMatch == null 5728 || (defaultBrowserMatch.priority < info.priority)) { 5729 if (debug) { 5730 Slog.v(TAG, "Considering default browser match " + info); 5731 } 5732 defaultBrowserMatch = info; 5733 } 5734 } 5735 } 5736 if (defaultBrowserMatch != null 5737 && defaultBrowserMatch.priority >= maxMatchPrio 5738 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5739 { 5740 if (debug) { 5741 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5742 } 5743 result.add(defaultBrowserMatch); 5744 } else { 5745 result.addAll(matchAllList); 5746 } 5747 } 5748 5749 // If there is nothing selected, add all candidates and remove the ones that the user 5750 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5751 if (result.size() == 0) { 5752 result.addAll(candidates); 5753 result.removeAll(neverList); 5754 } 5755 } 5756 } 5757 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5758 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5759 result.size()); 5760 for (ResolveInfo info : result) { 5761 Slog.v(TAG, " + " + info.activityInfo); 5762 } 5763 } 5764 return result; 5765 } 5766 5767 // Returns a packed value as a long: 5768 // 5769 // high 'int'-sized word: link status: undefined/ask/never/always. 5770 // low 'int'-sized word: relative priority among 'always' results. 5771 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5772 long result = ps.getDomainVerificationStatusForUser(userId); 5773 // if none available, get the master status 5774 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5775 if (ps.getIntentFilterVerificationInfo() != null) { 5776 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5777 } 5778 } 5779 return result; 5780 } 5781 5782 private ResolveInfo querySkipCurrentProfileIntents( 5783 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5784 int flags, int sourceUserId) { 5785 if (matchingFilters != null) { 5786 int size = matchingFilters.size(); 5787 for (int i = 0; i < size; i ++) { 5788 CrossProfileIntentFilter filter = matchingFilters.get(i); 5789 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5790 // Checking if there are activities in the target user that can handle the 5791 // intent. 5792 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5793 resolvedType, flags, sourceUserId); 5794 if (resolveInfo != null) { 5795 return resolveInfo; 5796 } 5797 } 5798 } 5799 } 5800 return null; 5801 } 5802 5803 // Return matching ResolveInfo in target user if any. 5804 private ResolveInfo queryCrossProfileIntents( 5805 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5806 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5807 if (matchingFilters != null) { 5808 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5809 // match the same intent. For performance reasons, it is better not to 5810 // run queryIntent twice for the same userId 5811 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5812 int size = matchingFilters.size(); 5813 for (int i = 0; i < size; i++) { 5814 CrossProfileIntentFilter filter = matchingFilters.get(i); 5815 int targetUserId = filter.getTargetUserId(); 5816 boolean skipCurrentProfile = 5817 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5818 boolean skipCurrentProfileIfNoMatchFound = 5819 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5820 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5821 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5822 // Checking if there are activities in the target user that can handle the 5823 // intent. 5824 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5825 resolvedType, flags, sourceUserId); 5826 if (resolveInfo != null) return resolveInfo; 5827 alreadyTriedUserIds.put(targetUserId, true); 5828 } 5829 } 5830 } 5831 return null; 5832 } 5833 5834 /** 5835 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5836 * will forward the intent to the filter's target user. 5837 * Otherwise, returns null. 5838 */ 5839 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5840 String resolvedType, int flags, int sourceUserId) { 5841 int targetUserId = filter.getTargetUserId(); 5842 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5843 resolvedType, flags, targetUserId); 5844 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5845 // If all the matches in the target profile are suspended, return null. 5846 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5847 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5848 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5849 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5850 targetUserId); 5851 } 5852 } 5853 } 5854 return null; 5855 } 5856 5857 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5858 int sourceUserId, int targetUserId) { 5859 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5860 long ident = Binder.clearCallingIdentity(); 5861 boolean targetIsProfile; 5862 try { 5863 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5864 } finally { 5865 Binder.restoreCallingIdentity(ident); 5866 } 5867 String className; 5868 if (targetIsProfile) { 5869 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5870 } else { 5871 className = FORWARD_INTENT_TO_PARENT; 5872 } 5873 ComponentName forwardingActivityComponentName = new ComponentName( 5874 mAndroidApplication.packageName, className); 5875 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5876 sourceUserId); 5877 if (!targetIsProfile) { 5878 forwardingActivityInfo.showUserIcon = targetUserId; 5879 forwardingResolveInfo.noResourceId = true; 5880 } 5881 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5882 forwardingResolveInfo.priority = 0; 5883 forwardingResolveInfo.preferredOrder = 0; 5884 forwardingResolveInfo.match = 0; 5885 forwardingResolveInfo.isDefault = true; 5886 forwardingResolveInfo.filter = filter; 5887 forwardingResolveInfo.targetUserId = targetUserId; 5888 return forwardingResolveInfo; 5889 } 5890 5891 @Override 5892 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5893 Intent[] specifics, String[] specificTypes, Intent intent, 5894 String resolvedType, int flags, int userId) { 5895 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5896 specificTypes, intent, resolvedType, flags, userId)); 5897 } 5898 5899 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5900 Intent[] specifics, String[] specificTypes, Intent intent, 5901 String resolvedType, int flags, int userId) { 5902 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5903 flags = updateFlagsForResolve(flags, userId, intent); 5904 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5905 false /* requireFullPermission */, false /* checkShell */, 5906 "query intent activity options"); 5907 final String resultsAction = intent.getAction(); 5908 5909 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5910 | PackageManager.GET_RESOLVED_FILTER, userId); 5911 5912 if (DEBUG_INTENT_MATCHING) { 5913 Log.v(TAG, "Query " + intent + ": " + results); 5914 } 5915 5916 int specificsPos = 0; 5917 int N; 5918 5919 // todo: note that the algorithm used here is O(N^2). This 5920 // isn't a problem in our current environment, but if we start running 5921 // into situations where we have more than 5 or 10 matches then this 5922 // should probably be changed to something smarter... 5923 5924 // First we go through and resolve each of the specific items 5925 // that were supplied, taking care of removing any corresponding 5926 // duplicate items in the generic resolve list. 5927 if (specifics != null) { 5928 for (int i=0; i<specifics.length; i++) { 5929 final Intent sintent = specifics[i]; 5930 if (sintent == null) { 5931 continue; 5932 } 5933 5934 if (DEBUG_INTENT_MATCHING) { 5935 Log.v(TAG, "Specific #" + i + ": " + sintent); 5936 } 5937 5938 String action = sintent.getAction(); 5939 if (resultsAction != null && resultsAction.equals(action)) { 5940 // If this action was explicitly requested, then don't 5941 // remove things that have it. 5942 action = null; 5943 } 5944 5945 ResolveInfo ri = null; 5946 ActivityInfo ai = null; 5947 5948 ComponentName comp = sintent.getComponent(); 5949 if (comp == null) { 5950 ri = resolveIntent( 5951 sintent, 5952 specificTypes != null ? specificTypes[i] : null, 5953 flags, userId); 5954 if (ri == null) { 5955 continue; 5956 } 5957 if (ri == mResolveInfo) { 5958 // ACK! Must do something better with this. 5959 } 5960 ai = ri.activityInfo; 5961 comp = new ComponentName(ai.applicationInfo.packageName, 5962 ai.name); 5963 } else { 5964 ai = getActivityInfo(comp, flags, userId); 5965 if (ai == null) { 5966 continue; 5967 } 5968 } 5969 5970 // Look for any generic query activities that are duplicates 5971 // of this specific one, and remove them from the results. 5972 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5973 N = results.size(); 5974 int j; 5975 for (j=specificsPos; j<N; j++) { 5976 ResolveInfo sri = results.get(j); 5977 if ((sri.activityInfo.name.equals(comp.getClassName()) 5978 && sri.activityInfo.applicationInfo.packageName.equals( 5979 comp.getPackageName())) 5980 || (action != null && sri.filter.matchAction(action))) { 5981 results.remove(j); 5982 if (DEBUG_INTENT_MATCHING) Log.v( 5983 TAG, "Removing duplicate item from " + j 5984 + " due to specific " + specificsPos); 5985 if (ri == null) { 5986 ri = sri; 5987 } 5988 j--; 5989 N--; 5990 } 5991 } 5992 5993 // Add this specific item to its proper place. 5994 if (ri == null) { 5995 ri = new ResolveInfo(); 5996 ri.activityInfo = ai; 5997 } 5998 results.add(specificsPos, ri); 5999 ri.specificIndex = i; 6000 specificsPos++; 6001 } 6002 } 6003 6004 // Now we go through the remaining generic results and remove any 6005 // duplicate actions that are found here. 6006 N = results.size(); 6007 for (int i=specificsPos; i<N-1; i++) { 6008 final ResolveInfo rii = results.get(i); 6009 if (rii.filter == null) { 6010 continue; 6011 } 6012 6013 // Iterate over all of the actions of this result's intent 6014 // filter... typically this should be just one. 6015 final Iterator<String> it = rii.filter.actionsIterator(); 6016 if (it == null) { 6017 continue; 6018 } 6019 while (it.hasNext()) { 6020 final String action = it.next(); 6021 if (resultsAction != null && resultsAction.equals(action)) { 6022 // If this action was explicitly requested, then don't 6023 // remove things that have it. 6024 continue; 6025 } 6026 for (int j=i+1; j<N; j++) { 6027 final ResolveInfo rij = results.get(j); 6028 if (rij.filter != null && rij.filter.hasAction(action)) { 6029 results.remove(j); 6030 if (DEBUG_INTENT_MATCHING) Log.v( 6031 TAG, "Removing duplicate item from " + j 6032 + " due to action " + action + " at " + i); 6033 j--; 6034 N--; 6035 } 6036 } 6037 } 6038 6039 // If the caller didn't request filter information, drop it now 6040 // so we don't have to marshall/unmarshall it. 6041 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6042 rii.filter = null; 6043 } 6044 } 6045 6046 // Filter out the caller activity if so requested. 6047 if (caller != null) { 6048 N = results.size(); 6049 for (int i=0; i<N; i++) { 6050 ActivityInfo ainfo = results.get(i).activityInfo; 6051 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6052 && caller.getClassName().equals(ainfo.name)) { 6053 results.remove(i); 6054 break; 6055 } 6056 } 6057 } 6058 6059 // If the caller didn't request filter information, 6060 // drop them now so we don't have to 6061 // marshall/unmarshall it. 6062 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6063 N = results.size(); 6064 for (int i=0; i<N; i++) { 6065 results.get(i).filter = null; 6066 } 6067 } 6068 6069 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6070 return results; 6071 } 6072 6073 @Override 6074 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6075 String resolvedType, int flags, int userId) { 6076 return new ParceledListSlice<>( 6077 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6078 } 6079 6080 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6081 String resolvedType, int flags, int userId) { 6082 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6083 flags = updateFlagsForResolve(flags, userId, intent); 6084 ComponentName comp = intent.getComponent(); 6085 if (comp == null) { 6086 if (intent.getSelector() != null) { 6087 intent = intent.getSelector(); 6088 comp = intent.getComponent(); 6089 } 6090 } 6091 if (comp != null) { 6092 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6093 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6094 if (ai != null) { 6095 ResolveInfo ri = new ResolveInfo(); 6096 ri.activityInfo = ai; 6097 list.add(ri); 6098 } 6099 return list; 6100 } 6101 6102 // reader 6103 synchronized (mPackages) { 6104 String pkgName = intent.getPackage(); 6105 if (pkgName == null) { 6106 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6107 } 6108 final PackageParser.Package pkg = mPackages.get(pkgName); 6109 if (pkg != null) { 6110 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6111 userId); 6112 } 6113 return Collections.emptyList(); 6114 } 6115 } 6116 6117 @Override 6118 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6119 if (!sUserManager.exists(userId)) return null; 6120 flags = updateFlagsForResolve(flags, userId, intent); 6121 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6122 if (query != null) { 6123 if (query.size() >= 1) { 6124 // If there is more than one service with the same priority, 6125 // just arbitrarily pick the first one. 6126 return query.get(0); 6127 } 6128 } 6129 return null; 6130 } 6131 6132 @Override 6133 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6134 String resolvedType, int flags, int userId) { 6135 return new ParceledListSlice<>( 6136 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6137 } 6138 6139 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6140 String resolvedType, int flags, int userId) { 6141 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6142 flags = updateFlagsForResolve(flags, userId, intent); 6143 ComponentName comp = intent.getComponent(); 6144 if (comp == null) { 6145 if (intent.getSelector() != null) { 6146 intent = intent.getSelector(); 6147 comp = intent.getComponent(); 6148 } 6149 } 6150 if (comp != null) { 6151 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6152 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6153 if (si != null) { 6154 final ResolveInfo ri = new ResolveInfo(); 6155 ri.serviceInfo = si; 6156 list.add(ri); 6157 } 6158 return list; 6159 } 6160 6161 // reader 6162 synchronized (mPackages) { 6163 String pkgName = intent.getPackage(); 6164 if (pkgName == null) { 6165 return mServices.queryIntent(intent, resolvedType, flags, userId); 6166 } 6167 final PackageParser.Package pkg = mPackages.get(pkgName); 6168 if (pkg != null) { 6169 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6170 userId); 6171 } 6172 return Collections.emptyList(); 6173 } 6174 } 6175 6176 @Override 6177 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6178 String resolvedType, int flags, int userId) { 6179 return new ParceledListSlice<>( 6180 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6181 } 6182 6183 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6184 Intent intent, String resolvedType, int flags, int userId) { 6185 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6186 flags = updateFlagsForResolve(flags, userId, intent); 6187 ComponentName comp = intent.getComponent(); 6188 if (comp == null) { 6189 if (intent.getSelector() != null) { 6190 intent = intent.getSelector(); 6191 comp = intent.getComponent(); 6192 } 6193 } 6194 if (comp != null) { 6195 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6196 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6197 if (pi != null) { 6198 final ResolveInfo ri = new ResolveInfo(); 6199 ri.providerInfo = pi; 6200 list.add(ri); 6201 } 6202 return list; 6203 } 6204 6205 // reader 6206 synchronized (mPackages) { 6207 String pkgName = intent.getPackage(); 6208 if (pkgName == null) { 6209 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6210 } 6211 final PackageParser.Package pkg = mPackages.get(pkgName); 6212 if (pkg != null) { 6213 return mProviders.queryIntentForPackage( 6214 intent, resolvedType, flags, pkg.providers, userId); 6215 } 6216 return Collections.emptyList(); 6217 } 6218 } 6219 6220 @Override 6221 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6222 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6223 flags = updateFlagsForPackage(flags, userId, null); 6224 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6225 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6226 true /* requireFullPermission */, false /* checkShell */, 6227 "get installed packages"); 6228 6229 // writer 6230 synchronized (mPackages) { 6231 ArrayList<PackageInfo> list; 6232 if (listUninstalled) { 6233 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6234 for (PackageSetting ps : mSettings.mPackages.values()) { 6235 final PackageInfo pi; 6236 if (ps.pkg != null) { 6237 pi = generatePackageInfo(ps, flags, userId); 6238 } else { 6239 pi = generatePackageInfo(ps, flags, userId); 6240 } 6241 if (pi != null) { 6242 list.add(pi); 6243 } 6244 } 6245 } else { 6246 list = new ArrayList<PackageInfo>(mPackages.size()); 6247 for (PackageParser.Package p : mPackages.values()) { 6248 final PackageInfo pi = 6249 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6250 if (pi != null) { 6251 list.add(pi); 6252 } 6253 } 6254 } 6255 6256 return new ParceledListSlice<PackageInfo>(list); 6257 } 6258 } 6259 6260 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6261 String[] permissions, boolean[] tmp, int flags, int userId) { 6262 int numMatch = 0; 6263 final PermissionsState permissionsState = ps.getPermissionsState(); 6264 for (int i=0; i<permissions.length; i++) { 6265 final String permission = permissions[i]; 6266 if (permissionsState.hasPermission(permission, userId)) { 6267 tmp[i] = true; 6268 numMatch++; 6269 } else { 6270 tmp[i] = false; 6271 } 6272 } 6273 if (numMatch == 0) { 6274 return; 6275 } 6276 final PackageInfo pi; 6277 if (ps.pkg != null) { 6278 pi = generatePackageInfo(ps, flags, userId); 6279 } else { 6280 pi = generatePackageInfo(ps, flags, userId); 6281 } 6282 // The above might return null in cases of uninstalled apps or install-state 6283 // skew across users/profiles. 6284 if (pi != null) { 6285 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6286 if (numMatch == permissions.length) { 6287 pi.requestedPermissions = permissions; 6288 } else { 6289 pi.requestedPermissions = new String[numMatch]; 6290 numMatch = 0; 6291 for (int i=0; i<permissions.length; i++) { 6292 if (tmp[i]) { 6293 pi.requestedPermissions[numMatch] = permissions[i]; 6294 numMatch++; 6295 } 6296 } 6297 } 6298 } 6299 list.add(pi); 6300 } 6301 } 6302 6303 @Override 6304 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6305 String[] permissions, int flags, int userId) { 6306 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6307 flags = updateFlagsForPackage(flags, userId, permissions); 6308 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6309 6310 // writer 6311 synchronized (mPackages) { 6312 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6313 boolean[] tmpBools = new boolean[permissions.length]; 6314 if (listUninstalled) { 6315 for (PackageSetting ps : mSettings.mPackages.values()) { 6316 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6317 } 6318 } else { 6319 for (PackageParser.Package pkg : mPackages.values()) { 6320 PackageSetting ps = (PackageSetting)pkg.mExtras; 6321 if (ps != null) { 6322 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6323 userId); 6324 } 6325 } 6326 } 6327 6328 return new ParceledListSlice<PackageInfo>(list); 6329 } 6330 } 6331 6332 @Override 6333 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6334 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6335 flags = updateFlagsForApplication(flags, userId, null); 6336 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6337 6338 // writer 6339 synchronized (mPackages) { 6340 ArrayList<ApplicationInfo> list; 6341 if (listUninstalled) { 6342 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6343 for (PackageSetting ps : mSettings.mPackages.values()) { 6344 ApplicationInfo ai; 6345 if (ps.pkg != null) { 6346 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6347 ps.readUserState(userId), userId); 6348 } else { 6349 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6350 } 6351 if (ai != null) { 6352 list.add(ai); 6353 } 6354 } 6355 } else { 6356 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6357 for (PackageParser.Package p : mPackages.values()) { 6358 if (p.mExtras != null) { 6359 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6360 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6361 if (ai != null) { 6362 list.add(ai); 6363 } 6364 } 6365 } 6366 } 6367 6368 return new ParceledListSlice<ApplicationInfo>(list); 6369 } 6370 } 6371 6372 @Override 6373 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6374 if (DISABLE_EPHEMERAL_APPS) { 6375 return null; 6376 } 6377 6378 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6379 "getEphemeralApplications"); 6380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6381 true /* requireFullPermission */, false /* checkShell */, 6382 "getEphemeralApplications"); 6383 synchronized (mPackages) { 6384 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6385 .getEphemeralApplicationsLPw(userId); 6386 if (ephemeralApps != null) { 6387 return new ParceledListSlice<>(ephemeralApps); 6388 } 6389 } 6390 return null; 6391 } 6392 6393 @Override 6394 public boolean isEphemeralApplication(String packageName, int userId) { 6395 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6396 true /* requireFullPermission */, false /* checkShell */, 6397 "isEphemeral"); 6398 if (DISABLE_EPHEMERAL_APPS) { 6399 return false; 6400 } 6401 6402 if (!isCallerSameApp(packageName)) { 6403 return false; 6404 } 6405 synchronized (mPackages) { 6406 PackageParser.Package pkg = mPackages.get(packageName); 6407 if (pkg != null) { 6408 return pkg.applicationInfo.isEphemeralApp(); 6409 } 6410 } 6411 return false; 6412 } 6413 6414 @Override 6415 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6416 if (DISABLE_EPHEMERAL_APPS) { 6417 return null; 6418 } 6419 6420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6421 true /* requireFullPermission */, false /* checkShell */, 6422 "getCookie"); 6423 if (!isCallerSameApp(packageName)) { 6424 return null; 6425 } 6426 synchronized (mPackages) { 6427 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6428 packageName, userId); 6429 } 6430 } 6431 6432 @Override 6433 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6434 if (DISABLE_EPHEMERAL_APPS) { 6435 return true; 6436 } 6437 6438 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6439 true /* requireFullPermission */, true /* checkShell */, 6440 "setCookie"); 6441 if (!isCallerSameApp(packageName)) { 6442 return false; 6443 } 6444 synchronized (mPackages) { 6445 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6446 packageName, cookie, userId); 6447 } 6448 } 6449 6450 @Override 6451 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6452 if (DISABLE_EPHEMERAL_APPS) { 6453 return null; 6454 } 6455 6456 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6457 "getEphemeralApplicationIcon"); 6458 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6459 true /* requireFullPermission */, false /* checkShell */, 6460 "getEphemeralApplicationIcon"); 6461 synchronized (mPackages) { 6462 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6463 packageName, userId); 6464 } 6465 } 6466 6467 private boolean isCallerSameApp(String packageName) { 6468 PackageParser.Package pkg = mPackages.get(packageName); 6469 return pkg != null 6470 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6471 } 6472 6473 @Override 6474 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6475 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6476 } 6477 6478 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6479 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6480 6481 // reader 6482 synchronized (mPackages) { 6483 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6484 final int userId = UserHandle.getCallingUserId(); 6485 while (i.hasNext()) { 6486 final PackageParser.Package p = i.next(); 6487 if (p.applicationInfo == null) continue; 6488 6489 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6490 && !p.applicationInfo.isDirectBootAware(); 6491 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6492 && p.applicationInfo.isDirectBootAware(); 6493 6494 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6495 && (!mSafeMode || isSystemApp(p)) 6496 && (matchesUnaware || matchesAware)) { 6497 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6498 if (ps != null) { 6499 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6500 ps.readUserState(userId), userId); 6501 if (ai != null) { 6502 finalList.add(ai); 6503 } 6504 } 6505 } 6506 } 6507 } 6508 6509 return finalList; 6510 } 6511 6512 @Override 6513 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6514 if (!sUserManager.exists(userId)) return null; 6515 flags = updateFlagsForComponent(flags, userId, name); 6516 // reader 6517 synchronized (mPackages) { 6518 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6519 PackageSetting ps = provider != null 6520 ? mSettings.mPackages.get(provider.owner.packageName) 6521 : null; 6522 return ps != null 6523 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6524 ? PackageParser.generateProviderInfo(provider, flags, 6525 ps.readUserState(userId), userId) 6526 : null; 6527 } 6528 } 6529 6530 /** 6531 * @deprecated 6532 */ 6533 @Deprecated 6534 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6535 // reader 6536 synchronized (mPackages) { 6537 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6538 .entrySet().iterator(); 6539 final int userId = UserHandle.getCallingUserId(); 6540 while (i.hasNext()) { 6541 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6542 PackageParser.Provider p = entry.getValue(); 6543 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6544 6545 if (ps != null && p.syncable 6546 && (!mSafeMode || (p.info.applicationInfo.flags 6547 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6548 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6549 ps.readUserState(userId), userId); 6550 if (info != null) { 6551 outNames.add(entry.getKey()); 6552 outInfo.add(info); 6553 } 6554 } 6555 } 6556 } 6557 } 6558 6559 @Override 6560 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6561 int uid, int flags) { 6562 final int userId = processName != null ? UserHandle.getUserId(uid) 6563 : UserHandle.getCallingUserId(); 6564 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6565 flags = updateFlagsForComponent(flags, userId, processName); 6566 6567 ArrayList<ProviderInfo> finalList = null; 6568 // reader 6569 synchronized (mPackages) { 6570 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6571 while (i.hasNext()) { 6572 final PackageParser.Provider p = i.next(); 6573 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6574 if (ps != null && p.info.authority != null 6575 && (processName == null 6576 || (p.info.processName.equals(processName) 6577 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6578 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6579 if (finalList == null) { 6580 finalList = new ArrayList<ProviderInfo>(3); 6581 } 6582 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6583 ps.readUserState(userId), userId); 6584 if (info != null) { 6585 finalList.add(info); 6586 } 6587 } 6588 } 6589 } 6590 6591 if (finalList != null) { 6592 Collections.sort(finalList, mProviderInitOrderSorter); 6593 return new ParceledListSlice<ProviderInfo>(finalList); 6594 } 6595 6596 return ParceledListSlice.emptyList(); 6597 } 6598 6599 @Override 6600 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6601 // reader 6602 synchronized (mPackages) { 6603 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6604 return PackageParser.generateInstrumentationInfo(i, flags); 6605 } 6606 } 6607 6608 @Override 6609 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6610 String targetPackage, int flags) { 6611 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6612 } 6613 6614 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6615 int flags) { 6616 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6617 6618 // reader 6619 synchronized (mPackages) { 6620 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6621 while (i.hasNext()) { 6622 final PackageParser.Instrumentation p = i.next(); 6623 if (targetPackage == null 6624 || targetPackage.equals(p.info.targetPackage)) { 6625 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6626 flags); 6627 if (ii != null) { 6628 finalList.add(ii); 6629 } 6630 } 6631 } 6632 } 6633 6634 return finalList; 6635 } 6636 6637 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6638 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6639 if (overlays == null) { 6640 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6641 return; 6642 } 6643 for (PackageParser.Package opkg : overlays.values()) { 6644 // Not much to do if idmap fails: we already logged the error 6645 // and we certainly don't want to abort installation of pkg simply 6646 // because an overlay didn't fit properly. For these reasons, 6647 // ignore the return value of createIdmapForPackagePairLI. 6648 createIdmapForPackagePairLI(pkg, opkg); 6649 } 6650 } 6651 6652 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6653 PackageParser.Package opkg) { 6654 if (!opkg.mTrustedOverlay) { 6655 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6656 opkg.baseCodePath + ": overlay not trusted"); 6657 return false; 6658 } 6659 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6660 if (overlaySet == null) { 6661 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6662 opkg.baseCodePath + " but target package has no known overlays"); 6663 return false; 6664 } 6665 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6666 // TODO: generate idmap for split APKs 6667 try { 6668 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6669 } catch (InstallerException e) { 6670 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6671 + opkg.baseCodePath); 6672 return false; 6673 } 6674 PackageParser.Package[] overlayArray = 6675 overlaySet.values().toArray(new PackageParser.Package[0]); 6676 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6677 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6678 return p1.mOverlayPriority - p2.mOverlayPriority; 6679 } 6680 }; 6681 Arrays.sort(overlayArray, cmp); 6682 6683 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6684 int i = 0; 6685 for (PackageParser.Package p : overlayArray) { 6686 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6687 } 6688 return true; 6689 } 6690 6691 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6692 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6693 try { 6694 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6695 } finally { 6696 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6697 } 6698 } 6699 6700 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6701 final File[] files = dir.listFiles(); 6702 if (ArrayUtils.isEmpty(files)) { 6703 Log.d(TAG, "No files in app dir " + dir); 6704 return; 6705 } 6706 6707 if (DEBUG_PACKAGE_SCANNING) { 6708 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6709 + " flags=0x" + Integer.toHexString(parseFlags)); 6710 } 6711 6712 for (File file : files) { 6713 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6714 && !PackageInstallerService.isStageName(file.getName()); 6715 if (!isPackage) { 6716 // Ignore entries which are not packages 6717 continue; 6718 } 6719 try { 6720 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6721 scanFlags, currentTime, null); 6722 } catch (PackageManagerException e) { 6723 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6724 6725 // Delete invalid userdata apps 6726 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6727 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6728 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6729 removeCodePathLI(file); 6730 } 6731 } 6732 } 6733 } 6734 6735 private static File getSettingsProblemFile() { 6736 File dataDir = Environment.getDataDirectory(); 6737 File systemDir = new File(dataDir, "system"); 6738 File fname = new File(systemDir, "uiderrors.txt"); 6739 return fname; 6740 } 6741 6742 static void reportSettingsProblem(int priority, String msg) { 6743 logCriticalInfo(priority, msg); 6744 } 6745 6746 static void logCriticalInfo(int priority, String msg) { 6747 Slog.println(priority, TAG, msg); 6748 EventLogTags.writePmCriticalInfo(msg); 6749 try { 6750 File fname = getSettingsProblemFile(); 6751 FileOutputStream out = new FileOutputStream(fname, true); 6752 PrintWriter pw = new FastPrintWriter(out); 6753 SimpleDateFormat formatter = new SimpleDateFormat(); 6754 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6755 pw.println(dateString + ": " + msg); 6756 pw.close(); 6757 FileUtils.setPermissions( 6758 fname.toString(), 6759 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6760 -1, -1); 6761 } catch (java.io.IOException e) { 6762 } 6763 } 6764 6765 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6766 final int policyFlags) throws PackageManagerException { 6767 if (ps != null 6768 && ps.codePath.equals(srcFile) 6769 && ps.timeStamp == srcFile.lastModified() 6770 && !isCompatSignatureUpdateNeeded(pkg) 6771 && !isRecoverSignatureUpdateNeeded(pkg)) { 6772 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6773 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6774 ArraySet<PublicKey> signingKs; 6775 synchronized (mPackages) { 6776 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6777 } 6778 if (ps.signatures.mSignatures != null 6779 && ps.signatures.mSignatures.length != 0 6780 && signingKs != null) { 6781 // Optimization: reuse the existing cached certificates 6782 // if the package appears to be unchanged. 6783 pkg.mSignatures = ps.signatures.mSignatures; 6784 pkg.mSigningKeys = signingKs; 6785 return; 6786 } 6787 6788 Slog.w(TAG, "PackageSetting for " + ps.name 6789 + " is missing signatures. Collecting certs again to recover them."); 6790 } else { 6791 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6792 } 6793 6794 try { 6795 PackageParser.collectCertificates(pkg, policyFlags); 6796 } catch (PackageParserException e) { 6797 throw PackageManagerException.from(e); 6798 } 6799 } 6800 6801 /** 6802 * Traces a package scan. 6803 * @see #scanPackageLI(File, int, int, long, UserHandle) 6804 */ 6805 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6806 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6808 try { 6809 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6810 } finally { 6811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6812 } 6813 } 6814 6815 /** 6816 * Scans a package and returns the newly parsed package. 6817 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6818 */ 6819 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6820 long currentTime, UserHandle user) throws PackageManagerException { 6821 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6822 PackageParser pp = new PackageParser(); 6823 pp.setSeparateProcesses(mSeparateProcesses); 6824 pp.setOnlyCoreApps(mOnlyCore); 6825 pp.setDisplayMetrics(mMetrics); 6826 6827 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6828 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6829 } 6830 6831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6832 final PackageParser.Package pkg; 6833 try { 6834 pkg = pp.parsePackage(scanFile, parseFlags); 6835 } catch (PackageParserException e) { 6836 throw PackageManagerException.from(e); 6837 } finally { 6838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6839 } 6840 6841 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6842 } 6843 6844 /** 6845 * Scans a package and returns the newly parsed package. 6846 * @throws PackageManagerException on a parse error. 6847 */ 6848 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6849 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6850 throws PackageManagerException { 6851 // If the package has children and this is the first dive in the function 6852 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6853 // packages (parent and children) would be successfully scanned before the 6854 // actual scan since scanning mutates internal state and we want to atomically 6855 // install the package and its children. 6856 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6857 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6858 scanFlags |= SCAN_CHECK_ONLY; 6859 } 6860 } else { 6861 scanFlags &= ~SCAN_CHECK_ONLY; 6862 } 6863 6864 // Scan the parent 6865 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6866 scanFlags, currentTime, user); 6867 6868 // Scan the children 6869 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6870 for (int i = 0; i < childCount; i++) { 6871 PackageParser.Package childPackage = pkg.childPackages.get(i); 6872 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6873 currentTime, user); 6874 } 6875 6876 6877 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6878 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6879 } 6880 6881 return scannedPkg; 6882 } 6883 6884 /** 6885 * Scans a package and returns the newly parsed package. 6886 * @throws PackageManagerException on a parse error. 6887 */ 6888 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6889 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6890 throws PackageManagerException { 6891 PackageSetting ps = null; 6892 PackageSetting updatedPkg; 6893 // reader 6894 synchronized (mPackages) { 6895 // Look to see if we already know about this package. 6896 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6897 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6898 // This package has been renamed to its original name. Let's 6899 // use that. 6900 ps = mSettings.peekPackageLPr(oldName); 6901 } 6902 // If there was no original package, see one for the real package name. 6903 if (ps == null) { 6904 ps = mSettings.peekPackageLPr(pkg.packageName); 6905 } 6906 // Check to see if this package could be hiding/updating a system 6907 // package. Must look for it either under the original or real 6908 // package name depending on our state. 6909 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6910 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6911 6912 // If this is a package we don't know about on the system partition, we 6913 // may need to remove disabled child packages on the system partition 6914 // or may need to not add child packages if the parent apk is updated 6915 // on the data partition and no longer defines this child package. 6916 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6917 // If this is a parent package for an updated system app and this system 6918 // app got an OTA update which no longer defines some of the child packages 6919 // we have to prune them from the disabled system packages. 6920 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6921 if (disabledPs != null) { 6922 final int scannedChildCount = (pkg.childPackages != null) 6923 ? pkg.childPackages.size() : 0; 6924 final int disabledChildCount = disabledPs.childPackageNames != null 6925 ? disabledPs.childPackageNames.size() : 0; 6926 for (int i = 0; i < disabledChildCount; i++) { 6927 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6928 boolean disabledPackageAvailable = false; 6929 for (int j = 0; j < scannedChildCount; j++) { 6930 PackageParser.Package childPkg = pkg.childPackages.get(j); 6931 if (childPkg.packageName.equals(disabledChildPackageName)) { 6932 disabledPackageAvailable = true; 6933 break; 6934 } 6935 } 6936 if (!disabledPackageAvailable) { 6937 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6938 } 6939 } 6940 } 6941 } 6942 } 6943 6944 boolean updatedPkgBetter = false; 6945 // First check if this is a system package that may involve an update 6946 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6947 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6948 // it needs to drop FLAG_PRIVILEGED. 6949 if (locationIsPrivileged(scanFile)) { 6950 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6951 } else { 6952 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6953 } 6954 6955 if (ps != null && !ps.codePath.equals(scanFile)) { 6956 // The path has changed from what was last scanned... check the 6957 // version of the new path against what we have stored to determine 6958 // what to do. 6959 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6960 if (pkg.mVersionCode <= ps.versionCode) { 6961 // The system package has been updated and the code path does not match 6962 // Ignore entry. Skip it. 6963 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6964 + " ignored: updated version " + ps.versionCode 6965 + " better than this " + pkg.mVersionCode); 6966 if (!updatedPkg.codePath.equals(scanFile)) { 6967 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6968 + ps.name + " changing from " + updatedPkg.codePathString 6969 + " to " + scanFile); 6970 updatedPkg.codePath = scanFile; 6971 updatedPkg.codePathString = scanFile.toString(); 6972 updatedPkg.resourcePath = scanFile; 6973 updatedPkg.resourcePathString = scanFile.toString(); 6974 } 6975 updatedPkg.pkg = pkg; 6976 updatedPkg.versionCode = pkg.mVersionCode; 6977 6978 // Update the disabled system child packages to point to the package too. 6979 final int childCount = updatedPkg.childPackageNames != null 6980 ? updatedPkg.childPackageNames.size() : 0; 6981 for (int i = 0; i < childCount; i++) { 6982 String childPackageName = updatedPkg.childPackageNames.get(i); 6983 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6984 childPackageName); 6985 if (updatedChildPkg != null) { 6986 updatedChildPkg.pkg = pkg; 6987 updatedChildPkg.versionCode = pkg.mVersionCode; 6988 } 6989 } 6990 6991 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6992 + scanFile + " ignored: updated version " + ps.versionCode 6993 + " better than this " + pkg.mVersionCode); 6994 } else { 6995 // The current app on the system partition is better than 6996 // what we have updated to on the data partition; switch 6997 // back to the system partition version. 6998 // At this point, its safely assumed that package installation for 6999 // apps in system partition will go through. If not there won't be a working 7000 // version of the app 7001 // writer 7002 synchronized (mPackages) { 7003 // Just remove the loaded entries from package lists. 7004 mPackages.remove(ps.name); 7005 } 7006 7007 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7008 + " reverting from " + ps.codePathString 7009 + ": new version " + pkg.mVersionCode 7010 + " better than installed " + ps.versionCode); 7011 7012 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7013 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7014 synchronized (mInstallLock) { 7015 args.cleanUpResourcesLI(); 7016 } 7017 synchronized (mPackages) { 7018 mSettings.enableSystemPackageLPw(ps.name); 7019 } 7020 updatedPkgBetter = true; 7021 } 7022 } 7023 } 7024 7025 if (updatedPkg != null) { 7026 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7027 // initially 7028 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7029 7030 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7031 // flag set initially 7032 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7033 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7034 } 7035 } 7036 7037 // Verify certificates against what was last scanned 7038 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7039 7040 /* 7041 * A new system app appeared, but we already had a non-system one of the 7042 * same name installed earlier. 7043 */ 7044 boolean shouldHideSystemApp = false; 7045 if (updatedPkg == null && ps != null 7046 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7047 /* 7048 * Check to make sure the signatures match first. If they don't, 7049 * wipe the installed application and its data. 7050 */ 7051 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7052 != PackageManager.SIGNATURE_MATCH) { 7053 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7054 + " signatures don't match existing userdata copy; removing"); 7055 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7056 "scanPackageInternalLI")) { 7057 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7058 } 7059 ps = null; 7060 } else { 7061 /* 7062 * If the newly-added system app is an older version than the 7063 * already installed version, hide it. It will be scanned later 7064 * and re-added like an update. 7065 */ 7066 if (pkg.mVersionCode <= ps.versionCode) { 7067 shouldHideSystemApp = true; 7068 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7069 + " but new version " + pkg.mVersionCode + " better than installed " 7070 + ps.versionCode + "; hiding system"); 7071 } else { 7072 /* 7073 * The newly found system app is a newer version that the 7074 * one previously installed. Simply remove the 7075 * already-installed application and replace it with our own 7076 * while keeping the application data. 7077 */ 7078 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7079 + " reverting from " + ps.codePathString + ": new version " 7080 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7081 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7082 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7083 synchronized (mInstallLock) { 7084 args.cleanUpResourcesLI(); 7085 } 7086 } 7087 } 7088 } 7089 7090 // The apk is forward locked (not public) if its code and resources 7091 // are kept in different files. (except for app in either system or 7092 // vendor path). 7093 // TODO grab this value from PackageSettings 7094 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7095 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7096 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7097 } 7098 } 7099 7100 // TODO: extend to support forward-locked splits 7101 String resourcePath = null; 7102 String baseResourcePath = null; 7103 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7104 if (ps != null && ps.resourcePathString != null) { 7105 resourcePath = ps.resourcePathString; 7106 baseResourcePath = ps.resourcePathString; 7107 } else { 7108 // Should not happen at all. Just log an error. 7109 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7110 } 7111 } else { 7112 resourcePath = pkg.codePath; 7113 baseResourcePath = pkg.baseCodePath; 7114 } 7115 7116 // Set application objects path explicitly. 7117 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7118 pkg.setApplicationInfoCodePath(pkg.codePath); 7119 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7120 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7121 pkg.setApplicationInfoResourcePath(resourcePath); 7122 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7123 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7124 7125 // Note that we invoke the following method only if we are about to unpack an application 7126 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7127 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7128 7129 /* 7130 * If the system app should be overridden by a previously installed 7131 * data, hide the system app now and let the /data/app scan pick it up 7132 * again. 7133 */ 7134 if (shouldHideSystemApp) { 7135 synchronized (mPackages) { 7136 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7137 } 7138 } 7139 7140 return scannedPkg; 7141 } 7142 7143 private static String fixProcessName(String defProcessName, 7144 String processName, int uid) { 7145 if (processName == null) { 7146 return defProcessName; 7147 } 7148 return processName; 7149 } 7150 7151 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7152 throws PackageManagerException { 7153 if (pkgSetting.signatures.mSignatures != null) { 7154 // Already existing package. Make sure signatures match 7155 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7156 == PackageManager.SIGNATURE_MATCH; 7157 if (!match) { 7158 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7159 == PackageManager.SIGNATURE_MATCH; 7160 } 7161 if (!match) { 7162 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7163 == PackageManager.SIGNATURE_MATCH; 7164 } 7165 if (!match) { 7166 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7167 + pkg.packageName + " signatures do not match the " 7168 + "previously installed version; ignoring!"); 7169 } 7170 } 7171 7172 // Check for shared user signatures 7173 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7174 // Already existing package. Make sure signatures match 7175 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7176 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7177 if (!match) { 7178 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7179 == PackageManager.SIGNATURE_MATCH; 7180 } 7181 if (!match) { 7182 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7183 == PackageManager.SIGNATURE_MATCH; 7184 } 7185 if (!match) { 7186 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7187 "Package " + pkg.packageName 7188 + " has no signatures that match those in shared user " 7189 + pkgSetting.sharedUser.name + "; ignoring!"); 7190 } 7191 } 7192 } 7193 7194 /** 7195 * Enforces that only the system UID or root's UID can call a method exposed 7196 * via Binder. 7197 * 7198 * @param message used as message if SecurityException is thrown 7199 * @throws SecurityException if the caller is not system or root 7200 */ 7201 private static final void enforceSystemOrRoot(String message) { 7202 final int uid = Binder.getCallingUid(); 7203 if (uid != Process.SYSTEM_UID && uid != 0) { 7204 throw new SecurityException(message); 7205 } 7206 } 7207 7208 @Override 7209 public void performFstrimIfNeeded() { 7210 enforceSystemOrRoot("Only the system can request fstrim"); 7211 7212 // Before everything else, see whether we need to fstrim. 7213 try { 7214 IMountService ms = PackageHelper.getMountService(); 7215 if (ms != null) { 7216 final boolean isUpgrade = isUpgrade(); 7217 boolean doTrim = isUpgrade; 7218 if (doTrim) { 7219 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7220 } else { 7221 final long interval = android.provider.Settings.Global.getLong( 7222 mContext.getContentResolver(), 7223 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7224 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7225 if (interval > 0) { 7226 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7227 if (timeSinceLast > interval) { 7228 doTrim = true; 7229 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7230 + "; running immediately"); 7231 } 7232 } 7233 } 7234 if (doTrim) { 7235 if (!isFirstBoot()) { 7236 try { 7237 ActivityManagerNative.getDefault().showBootMessage( 7238 mContext.getResources().getString( 7239 R.string.android_upgrading_fstrim), true); 7240 } catch (RemoteException e) { 7241 } 7242 } 7243 ms.runMaintenance(); 7244 } 7245 } else { 7246 Slog.e(TAG, "Mount service unavailable!"); 7247 } 7248 } catch (RemoteException e) { 7249 // Can't happen; MountService is local 7250 } 7251 } 7252 7253 @Override 7254 public void updatePackagesIfNeeded() { 7255 enforceSystemOrRoot("Only the system can request package update"); 7256 7257 // We need to re-extract after an OTA. 7258 boolean causeUpgrade = isUpgrade(); 7259 7260 // First boot or factory reset. 7261 // Note: we also handle devices that are upgrading to N right now as if it is their 7262 // first boot, as they do not have profile data. 7263 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7264 7265 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7266 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7267 7268 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7269 return; 7270 } 7271 7272 List<PackageParser.Package> pkgs; 7273 synchronized (mPackages) { 7274 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7275 } 7276 7277 final long startTime = System.nanoTime(); 7278 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7279 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7280 7281 final int elapsedTimeSeconds = 7282 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7283 7284 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7285 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7286 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7287 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7288 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7289 } 7290 7291 /** 7292 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7293 * containing statistics about the invocation. The array consists of three elements, 7294 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7295 * and {@code numberOfPackagesFailed}. 7296 */ 7297 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7298 String compilerFilter) { 7299 7300 int numberOfPackagesVisited = 0; 7301 int numberOfPackagesOptimized = 0; 7302 int numberOfPackagesSkipped = 0; 7303 int numberOfPackagesFailed = 0; 7304 final int numberOfPackagesToDexopt = pkgs.size(); 7305 7306 for (PackageParser.Package pkg : pkgs) { 7307 numberOfPackagesVisited++; 7308 7309 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7310 if (DEBUG_DEXOPT) { 7311 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7312 } 7313 numberOfPackagesSkipped++; 7314 continue; 7315 } 7316 7317 if (DEBUG_DEXOPT) { 7318 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7319 numberOfPackagesToDexopt + ": " + pkg.packageName); 7320 } 7321 7322 if (showDialog) { 7323 try { 7324 ActivityManagerNative.getDefault().showBootMessage( 7325 mContext.getResources().getString(R.string.android_upgrading_apk, 7326 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7327 } catch (RemoteException e) { 7328 } 7329 } 7330 7331 // checkProfiles is false to avoid merging profiles during boot which 7332 // might interfere with background compilation (b/28612421). 7333 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7334 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7335 // trade-off worth doing to save boot time work. 7336 int dexOptStatus = performDexOptTraced(pkg.packageName, 7337 false /* checkProfiles */, 7338 compilerFilter, 7339 false /* force */); 7340 switch (dexOptStatus) { 7341 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7342 numberOfPackagesOptimized++; 7343 break; 7344 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7345 numberOfPackagesSkipped++; 7346 break; 7347 case PackageDexOptimizer.DEX_OPT_FAILED: 7348 numberOfPackagesFailed++; 7349 break; 7350 default: 7351 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7352 break; 7353 } 7354 } 7355 7356 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7357 numberOfPackagesFailed }; 7358 } 7359 7360 @Override 7361 public void notifyPackageUse(String packageName, int reason) { 7362 synchronized (mPackages) { 7363 PackageParser.Package p = mPackages.get(packageName); 7364 if (p == null) { 7365 return; 7366 } 7367 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7368 } 7369 } 7370 7371 // TODO: this is not used nor needed. Delete it. 7372 @Override 7373 public boolean performDexOptIfNeeded(String packageName) { 7374 int dexOptStatus = performDexOptTraced(packageName, 7375 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7376 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7377 } 7378 7379 @Override 7380 public boolean performDexOpt(String packageName, 7381 boolean checkProfiles, int compileReason, boolean force) { 7382 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7383 getCompilerFilterForReason(compileReason), force); 7384 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7385 } 7386 7387 @Override 7388 public boolean performDexOptMode(String packageName, 7389 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7390 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7391 targetCompilerFilter, force); 7392 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7393 } 7394 7395 private int performDexOptTraced(String packageName, 7396 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7397 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7398 try { 7399 return performDexOptInternal(packageName, checkProfiles, 7400 targetCompilerFilter, force); 7401 } finally { 7402 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7403 } 7404 } 7405 7406 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7407 // if the package can now be considered up to date for the given filter. 7408 private int performDexOptInternal(String packageName, 7409 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7410 PackageParser.Package p; 7411 synchronized (mPackages) { 7412 p = mPackages.get(packageName); 7413 if (p == null) { 7414 // Package could not be found. Report failure. 7415 return PackageDexOptimizer.DEX_OPT_FAILED; 7416 } 7417 mPackageUsage.write(false); 7418 } 7419 long callingId = Binder.clearCallingIdentity(); 7420 try { 7421 synchronized (mInstallLock) { 7422 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7423 targetCompilerFilter, force); 7424 } 7425 } finally { 7426 Binder.restoreCallingIdentity(callingId); 7427 } 7428 } 7429 7430 public ArraySet<String> getOptimizablePackages() { 7431 ArraySet<String> pkgs = new ArraySet<String>(); 7432 synchronized (mPackages) { 7433 for (PackageParser.Package p : mPackages.values()) { 7434 if (PackageDexOptimizer.canOptimizePackage(p)) { 7435 pkgs.add(p.packageName); 7436 } 7437 } 7438 } 7439 return pkgs; 7440 } 7441 7442 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7443 boolean checkProfiles, String targetCompilerFilter, 7444 boolean force) { 7445 // Select the dex optimizer based on the force parameter. 7446 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7447 // allocate an object here. 7448 PackageDexOptimizer pdo = force 7449 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7450 : mPackageDexOptimizer; 7451 7452 // Optimize all dependencies first. Note: we ignore the return value and march on 7453 // on errors. 7454 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7455 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7456 if (!deps.isEmpty()) { 7457 for (PackageParser.Package depPackage : deps) { 7458 // TODO: Analyze and investigate if we (should) profile libraries. 7459 // Currently this will do a full compilation of the library by default. 7460 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7461 false /* checkProfiles */, 7462 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7463 } 7464 } 7465 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7466 targetCompilerFilter); 7467 } 7468 7469 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7470 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7471 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7472 Set<String> collectedNames = new HashSet<>(); 7473 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7474 7475 retValue.remove(p); 7476 7477 return retValue; 7478 } else { 7479 return Collections.emptyList(); 7480 } 7481 } 7482 7483 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7484 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7485 if (!collectedNames.contains(p.packageName)) { 7486 collectedNames.add(p.packageName); 7487 collected.add(p); 7488 7489 if (p.usesLibraries != null) { 7490 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7491 } 7492 if (p.usesOptionalLibraries != null) { 7493 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7494 collectedNames); 7495 } 7496 } 7497 } 7498 7499 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7500 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7501 for (String libName : libs) { 7502 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7503 if (libPkg != null) { 7504 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7505 } 7506 } 7507 } 7508 7509 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7510 synchronized (mPackages) { 7511 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7512 if (lib != null && lib.apk != null) { 7513 return mPackages.get(lib.apk); 7514 } 7515 } 7516 return null; 7517 } 7518 7519 public void shutdown() { 7520 mPackageUsage.write(true); 7521 } 7522 7523 @Override 7524 public void dumpProfiles(String packageName) { 7525 PackageParser.Package pkg; 7526 synchronized (mPackages) { 7527 pkg = mPackages.get(packageName); 7528 if (pkg == null) { 7529 throw new IllegalArgumentException("Unknown package: " + packageName); 7530 } 7531 } 7532 /* Only the shell, root, or the app user should be able to dump profiles. */ 7533 int callingUid = Binder.getCallingUid(); 7534 if (callingUid != Process.SHELL_UID && 7535 callingUid != Process.ROOT_UID && 7536 callingUid != pkg.applicationInfo.uid) { 7537 throw new SecurityException("dumpProfiles"); 7538 } 7539 7540 synchronized (mInstallLock) { 7541 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7542 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7543 try { 7544 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7545 String gid = Integer.toString(sharedGid); 7546 String codePaths = TextUtils.join(";", allCodePaths); 7547 mInstaller.dumpProfiles(gid, packageName, codePaths); 7548 } catch (InstallerException e) { 7549 Slog.w(TAG, "Failed to dump profiles", e); 7550 } 7551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7552 } 7553 } 7554 7555 @Override 7556 public void forceDexOpt(String packageName) { 7557 enforceSystemOrRoot("forceDexOpt"); 7558 7559 PackageParser.Package pkg; 7560 synchronized (mPackages) { 7561 pkg = mPackages.get(packageName); 7562 if (pkg == null) { 7563 throw new IllegalArgumentException("Unknown package: " + packageName); 7564 } 7565 } 7566 7567 synchronized (mInstallLock) { 7568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7569 7570 // Whoever is calling forceDexOpt wants a fully compiled package. 7571 // Don't use profiles since that may cause compilation to be skipped. 7572 final int res = performDexOptInternalWithDependenciesLI(pkg, 7573 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7574 true /* force */); 7575 7576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7577 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7578 throw new IllegalStateException("Failed to dexopt: " + res); 7579 } 7580 } 7581 } 7582 7583 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7584 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7585 Slog.w(TAG, "Unable to update from " + oldPkg.name 7586 + " to " + newPkg.packageName 7587 + ": old package not in system partition"); 7588 return false; 7589 } else if (mPackages.get(oldPkg.name) != null) { 7590 Slog.w(TAG, "Unable to update from " + oldPkg.name 7591 + " to " + newPkg.packageName 7592 + ": old package still exists"); 7593 return false; 7594 } 7595 return true; 7596 } 7597 7598 void removeCodePathLI(File codePath) { 7599 if (codePath.isDirectory()) { 7600 try { 7601 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7602 } catch (InstallerException e) { 7603 Slog.w(TAG, "Failed to remove code path", e); 7604 } 7605 } else { 7606 codePath.delete(); 7607 } 7608 } 7609 7610 private int[] resolveUserIds(int userId) { 7611 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7612 } 7613 7614 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7615 if (pkg == null) { 7616 Slog.wtf(TAG, "Package was null!", new Throwable()); 7617 return; 7618 } 7619 clearAppDataLeafLIF(pkg, userId, flags); 7620 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7621 for (int i = 0; i < childCount; i++) { 7622 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7623 } 7624 } 7625 7626 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7627 final PackageSetting ps; 7628 synchronized (mPackages) { 7629 ps = mSettings.mPackages.get(pkg.packageName); 7630 } 7631 for (int realUserId : resolveUserIds(userId)) { 7632 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7633 try { 7634 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7635 ceDataInode); 7636 } catch (InstallerException e) { 7637 Slog.w(TAG, String.valueOf(e)); 7638 } 7639 } 7640 } 7641 7642 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7643 if (pkg == null) { 7644 Slog.wtf(TAG, "Package was null!", new Throwable()); 7645 return; 7646 } 7647 destroyAppDataLeafLIF(pkg, userId, flags); 7648 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7649 for (int i = 0; i < childCount; i++) { 7650 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7651 } 7652 } 7653 7654 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7655 final PackageSetting ps; 7656 synchronized (mPackages) { 7657 ps = mSettings.mPackages.get(pkg.packageName); 7658 } 7659 for (int realUserId : resolveUserIds(userId)) { 7660 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7661 try { 7662 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7663 ceDataInode); 7664 } catch (InstallerException e) { 7665 Slog.w(TAG, String.valueOf(e)); 7666 } 7667 } 7668 } 7669 7670 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7671 if (pkg == null) { 7672 Slog.wtf(TAG, "Package was null!", new Throwable()); 7673 return; 7674 } 7675 destroyAppProfilesLeafLIF(pkg); 7676 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7678 for (int i = 0; i < childCount; i++) { 7679 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7680 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7681 true /* removeBaseMarker */); 7682 } 7683 } 7684 7685 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7686 boolean removeBaseMarker) { 7687 if (pkg.isForwardLocked()) { 7688 return; 7689 } 7690 7691 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7692 try { 7693 path = PackageManagerServiceUtils.realpath(new File(path)); 7694 } catch (IOException e) { 7695 // TODO: Should we return early here ? 7696 Slog.w(TAG, "Failed to get canonical path", e); 7697 continue; 7698 } 7699 7700 final String useMarker = path.replace('/', '@'); 7701 for (int realUserId : resolveUserIds(userId)) { 7702 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7703 if (removeBaseMarker) { 7704 File foreignUseMark = new File(profileDir, useMarker); 7705 if (foreignUseMark.exists()) { 7706 if (!foreignUseMark.delete()) { 7707 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7708 + pkg.packageName); 7709 } 7710 } 7711 } 7712 7713 File[] markers = profileDir.listFiles(); 7714 if (markers != null) { 7715 final String searchString = "@" + pkg.packageName + "@"; 7716 // We also delete all markers that contain the package name we're 7717 // uninstalling. These are associated with secondary dex-files belonging 7718 // to the package. Reconstructing the path of these dex files is messy 7719 // in general. 7720 for (File marker : markers) { 7721 if (marker.getName().indexOf(searchString) > 0) { 7722 if (!marker.delete()) { 7723 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7724 + pkg.packageName); 7725 } 7726 } 7727 } 7728 } 7729 } 7730 } 7731 } 7732 7733 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7734 try { 7735 mInstaller.destroyAppProfiles(pkg.packageName); 7736 } catch (InstallerException e) { 7737 Slog.w(TAG, String.valueOf(e)); 7738 } 7739 } 7740 7741 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7742 if (pkg == null) { 7743 Slog.wtf(TAG, "Package was null!", new Throwable()); 7744 return; 7745 } 7746 clearAppProfilesLeafLIF(pkg); 7747 // We don't remove the base foreign use marker when clearing profiles because 7748 // we will rename it when the app is updated. Unlike the actual profile contents, 7749 // the foreign use marker is good across installs. 7750 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7751 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7752 for (int i = 0; i < childCount; i++) { 7753 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7754 } 7755 } 7756 7757 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7758 try { 7759 mInstaller.clearAppProfiles(pkg.packageName); 7760 } catch (InstallerException e) { 7761 Slog.w(TAG, String.valueOf(e)); 7762 } 7763 } 7764 7765 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7766 long lastUpdateTime) { 7767 // Set parent install/update time 7768 PackageSetting ps = (PackageSetting) pkg.mExtras; 7769 if (ps != null) { 7770 ps.firstInstallTime = firstInstallTime; 7771 ps.lastUpdateTime = lastUpdateTime; 7772 } 7773 // Set children install/update time 7774 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7775 for (int i = 0; i < childCount; i++) { 7776 PackageParser.Package childPkg = pkg.childPackages.get(i); 7777 ps = (PackageSetting) childPkg.mExtras; 7778 if (ps != null) { 7779 ps.firstInstallTime = firstInstallTime; 7780 ps.lastUpdateTime = lastUpdateTime; 7781 } 7782 } 7783 } 7784 7785 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7786 PackageParser.Package changingLib) { 7787 if (file.path != null) { 7788 usesLibraryFiles.add(file.path); 7789 return; 7790 } 7791 PackageParser.Package p = mPackages.get(file.apk); 7792 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7793 // If we are doing this while in the middle of updating a library apk, 7794 // then we need to make sure to use that new apk for determining the 7795 // dependencies here. (We haven't yet finished committing the new apk 7796 // to the package manager state.) 7797 if (p == null || p.packageName.equals(changingLib.packageName)) { 7798 p = changingLib; 7799 } 7800 } 7801 if (p != null) { 7802 usesLibraryFiles.addAll(p.getAllCodePaths()); 7803 } 7804 } 7805 7806 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7807 PackageParser.Package changingLib) throws PackageManagerException { 7808 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7809 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7810 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7811 for (int i=0; i<N; i++) { 7812 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7813 if (file == null) { 7814 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7815 "Package " + pkg.packageName + " requires unavailable shared library " 7816 + pkg.usesLibraries.get(i) + "; failing!"); 7817 } 7818 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7819 } 7820 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7821 for (int i=0; i<N; i++) { 7822 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7823 if (file == null) { 7824 Slog.w(TAG, "Package " + pkg.packageName 7825 + " desires unavailable shared library " 7826 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7827 } else { 7828 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7829 } 7830 } 7831 N = usesLibraryFiles.size(); 7832 if (N > 0) { 7833 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7834 } else { 7835 pkg.usesLibraryFiles = null; 7836 } 7837 } 7838 } 7839 7840 private static boolean hasString(List<String> list, List<String> which) { 7841 if (list == null) { 7842 return false; 7843 } 7844 for (int i=list.size()-1; i>=0; i--) { 7845 for (int j=which.size()-1; j>=0; j--) { 7846 if (which.get(j).equals(list.get(i))) { 7847 return true; 7848 } 7849 } 7850 } 7851 return false; 7852 } 7853 7854 private void updateAllSharedLibrariesLPw() { 7855 for (PackageParser.Package pkg : mPackages.values()) { 7856 try { 7857 updateSharedLibrariesLPw(pkg, null); 7858 } catch (PackageManagerException e) { 7859 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7860 } 7861 } 7862 } 7863 7864 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7865 PackageParser.Package changingPkg) { 7866 ArrayList<PackageParser.Package> res = null; 7867 for (PackageParser.Package pkg : mPackages.values()) { 7868 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7869 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7870 if (res == null) { 7871 res = new ArrayList<PackageParser.Package>(); 7872 } 7873 res.add(pkg); 7874 try { 7875 updateSharedLibrariesLPw(pkg, changingPkg); 7876 } catch (PackageManagerException e) { 7877 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7878 } 7879 } 7880 } 7881 return res; 7882 } 7883 7884 /** 7885 * Derive the value of the {@code cpuAbiOverride} based on the provided 7886 * value and an optional stored value from the package settings. 7887 */ 7888 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7889 String cpuAbiOverride = null; 7890 7891 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7892 cpuAbiOverride = null; 7893 } else if (abiOverride != null) { 7894 cpuAbiOverride = abiOverride; 7895 } else if (settings != null) { 7896 cpuAbiOverride = settings.cpuAbiOverrideString; 7897 } 7898 7899 return cpuAbiOverride; 7900 } 7901 7902 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7903 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7904 throws PackageManagerException { 7905 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7906 // If the package has children and this is the first dive in the function 7907 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7908 // whether all packages (parent and children) would be successfully scanned 7909 // before the actual scan since scanning mutates internal state and we want 7910 // to atomically install the package and its children. 7911 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7912 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7913 scanFlags |= SCAN_CHECK_ONLY; 7914 } 7915 } else { 7916 scanFlags &= ~SCAN_CHECK_ONLY; 7917 } 7918 7919 final PackageParser.Package scannedPkg; 7920 try { 7921 // Scan the parent 7922 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7923 // Scan the children 7924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7925 for (int i = 0; i < childCount; i++) { 7926 PackageParser.Package childPkg = pkg.childPackages.get(i); 7927 scanPackageLI(childPkg, policyFlags, 7928 scanFlags, currentTime, user); 7929 } 7930 } finally { 7931 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7932 } 7933 7934 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7935 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7936 } 7937 7938 return scannedPkg; 7939 } 7940 7941 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7942 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7943 boolean success = false; 7944 try { 7945 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7946 currentTime, user); 7947 success = true; 7948 return res; 7949 } finally { 7950 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7951 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7952 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7953 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7954 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7955 } 7956 } 7957 } 7958 7959 /** 7960 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7961 */ 7962 private static boolean apkHasCode(String fileName) { 7963 StrictJarFile jarFile = null; 7964 try { 7965 jarFile = new StrictJarFile(fileName, 7966 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7967 return jarFile.findEntry("classes.dex") != null; 7968 } catch (IOException ignore) { 7969 } finally { 7970 try { 7971 jarFile.close(); 7972 } catch (IOException ignore) {} 7973 } 7974 return false; 7975 } 7976 7977 /** 7978 * Enforces code policy for the package. This ensures that if an APK has 7979 * declared hasCode="true" in its manifest that the APK actually contains 7980 * code. 7981 * 7982 * @throws PackageManagerException If bytecode could not be found when it should exist 7983 */ 7984 private static void enforceCodePolicy(PackageParser.Package pkg) 7985 throws PackageManagerException { 7986 final boolean shouldHaveCode = 7987 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7988 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7989 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7990 "Package " + pkg.baseCodePath + " code is missing"); 7991 } 7992 7993 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7994 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7995 final boolean splitShouldHaveCode = 7996 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7997 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7998 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7999 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8000 } 8001 } 8002 } 8003 } 8004 8005 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8006 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8007 throws PackageManagerException { 8008 final File scanFile = new File(pkg.codePath); 8009 if (pkg.applicationInfo.getCodePath() == null || 8010 pkg.applicationInfo.getResourcePath() == null) { 8011 // Bail out. The resource and code paths haven't been set. 8012 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8013 "Code and resource paths haven't been set correctly"); 8014 } 8015 8016 // Apply policy 8017 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8018 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8019 if (pkg.applicationInfo.isDirectBootAware()) { 8020 // we're direct boot aware; set for all components 8021 for (PackageParser.Service s : pkg.services) { 8022 s.info.encryptionAware = s.info.directBootAware = true; 8023 } 8024 for (PackageParser.Provider p : pkg.providers) { 8025 p.info.encryptionAware = p.info.directBootAware = true; 8026 } 8027 for (PackageParser.Activity a : pkg.activities) { 8028 a.info.encryptionAware = a.info.directBootAware = true; 8029 } 8030 for (PackageParser.Activity r : pkg.receivers) { 8031 r.info.encryptionAware = r.info.directBootAware = true; 8032 } 8033 } 8034 } else { 8035 // Only allow system apps to be flagged as core apps. 8036 pkg.coreApp = false; 8037 // clear flags not applicable to regular apps 8038 pkg.applicationInfo.privateFlags &= 8039 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8040 pkg.applicationInfo.privateFlags &= 8041 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8042 } 8043 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8044 8045 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8046 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8047 } 8048 8049 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8050 enforceCodePolicy(pkg); 8051 } 8052 8053 if (mCustomResolverComponentName != null && 8054 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8055 setUpCustomResolverActivity(pkg); 8056 } 8057 8058 if (pkg.packageName.equals("android")) { 8059 synchronized (mPackages) { 8060 if (mAndroidApplication != null) { 8061 Slog.w(TAG, "*************************************************"); 8062 Slog.w(TAG, "Core android package being redefined. Skipping."); 8063 Slog.w(TAG, " file=" + scanFile); 8064 Slog.w(TAG, "*************************************************"); 8065 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8066 "Core android package being redefined. Skipping."); 8067 } 8068 8069 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8070 // Set up information for our fall-back user intent resolution activity. 8071 mPlatformPackage = pkg; 8072 pkg.mVersionCode = mSdkVersion; 8073 mAndroidApplication = pkg.applicationInfo; 8074 8075 if (!mResolverReplaced) { 8076 mResolveActivity.applicationInfo = mAndroidApplication; 8077 mResolveActivity.name = ResolverActivity.class.getName(); 8078 mResolveActivity.packageName = mAndroidApplication.packageName; 8079 mResolveActivity.processName = "system:ui"; 8080 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8081 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8082 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8083 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8084 mResolveActivity.exported = true; 8085 mResolveActivity.enabled = true; 8086 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8087 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8088 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8089 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8090 | ActivityInfo.CONFIG_ORIENTATION 8091 | ActivityInfo.CONFIG_KEYBOARD 8092 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8093 mResolveInfo.activityInfo = mResolveActivity; 8094 mResolveInfo.priority = 0; 8095 mResolveInfo.preferredOrder = 0; 8096 mResolveInfo.match = 0; 8097 mResolveComponentName = new ComponentName( 8098 mAndroidApplication.packageName, mResolveActivity.name); 8099 } 8100 } 8101 } 8102 } 8103 8104 if (DEBUG_PACKAGE_SCANNING) { 8105 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8106 Log.d(TAG, "Scanning package " + pkg.packageName); 8107 } 8108 8109 synchronized (mPackages) { 8110 if (mPackages.containsKey(pkg.packageName) 8111 || mSharedLibraries.containsKey(pkg.packageName)) { 8112 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8113 "Application package " + pkg.packageName 8114 + " already installed. Skipping duplicate."); 8115 } 8116 8117 // If we're only installing presumed-existing packages, require that the 8118 // scanned APK is both already known and at the path previously established 8119 // for it. Previously unknown packages we pick up normally, but if we have an 8120 // a priori expectation about this package's install presence, enforce it. 8121 // With a singular exception for new system packages. When an OTA contains 8122 // a new system package, we allow the codepath to change from a system location 8123 // to the user-installed location. If we don't allow this change, any newer, 8124 // user-installed version of the application will be ignored. 8125 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8126 if (mExpectingBetter.containsKey(pkg.packageName)) { 8127 logCriticalInfo(Log.WARN, 8128 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8129 } else { 8130 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8131 if (known != null) { 8132 if (DEBUG_PACKAGE_SCANNING) { 8133 Log.d(TAG, "Examining " + pkg.codePath 8134 + " and requiring known paths " + known.codePathString 8135 + " & " + known.resourcePathString); 8136 } 8137 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8138 || !pkg.applicationInfo.getResourcePath().equals( 8139 known.resourcePathString)) { 8140 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8141 "Application package " + pkg.packageName 8142 + " found at " + pkg.applicationInfo.getCodePath() 8143 + " but expected at " + known.codePathString 8144 + "; ignoring."); 8145 } 8146 } 8147 } 8148 } 8149 } 8150 8151 // Initialize package source and resource directories 8152 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8153 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8154 8155 SharedUserSetting suid = null; 8156 PackageSetting pkgSetting = null; 8157 8158 if (!isSystemApp(pkg)) { 8159 // Only system apps can use these features. 8160 pkg.mOriginalPackages = null; 8161 pkg.mRealPackage = null; 8162 pkg.mAdoptPermissions = null; 8163 } 8164 8165 // Getting the package setting may have a side-effect, so if we 8166 // are only checking if scan would succeed, stash a copy of the 8167 // old setting to restore at the end. 8168 PackageSetting nonMutatedPs = null; 8169 8170 // writer 8171 synchronized (mPackages) { 8172 if (pkg.mSharedUserId != null) { 8173 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8174 if (suid == null) { 8175 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8176 "Creating application package " + pkg.packageName 8177 + " for shared user failed"); 8178 } 8179 if (DEBUG_PACKAGE_SCANNING) { 8180 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8181 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8182 + "): packages=" + suid.packages); 8183 } 8184 } 8185 8186 // Check if we are renaming from an original package name. 8187 PackageSetting origPackage = null; 8188 String realName = null; 8189 if (pkg.mOriginalPackages != null) { 8190 // This package may need to be renamed to a previously 8191 // installed name. Let's check on that... 8192 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8193 if (pkg.mOriginalPackages.contains(renamed)) { 8194 // This package had originally been installed as the 8195 // original name, and we have already taken care of 8196 // transitioning to the new one. Just update the new 8197 // one to continue using the old name. 8198 realName = pkg.mRealPackage; 8199 if (!pkg.packageName.equals(renamed)) { 8200 // Callers into this function may have already taken 8201 // care of renaming the package; only do it here if 8202 // it is not already done. 8203 pkg.setPackageName(renamed); 8204 } 8205 8206 } else { 8207 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8208 if ((origPackage = mSettings.peekPackageLPr( 8209 pkg.mOriginalPackages.get(i))) != null) { 8210 // We do have the package already installed under its 8211 // original name... should we use it? 8212 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8213 // New package is not compatible with original. 8214 origPackage = null; 8215 continue; 8216 } else if (origPackage.sharedUser != null) { 8217 // Make sure uid is compatible between packages. 8218 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8219 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8220 + " to " + pkg.packageName + ": old uid " 8221 + origPackage.sharedUser.name 8222 + " differs from " + pkg.mSharedUserId); 8223 origPackage = null; 8224 continue; 8225 } 8226 // TODO: Add case when shared user id is added [b/28144775] 8227 } else { 8228 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8229 + pkg.packageName + " to old name " + origPackage.name); 8230 } 8231 break; 8232 } 8233 } 8234 } 8235 } 8236 8237 if (mTransferedPackages.contains(pkg.packageName)) { 8238 Slog.w(TAG, "Package " + pkg.packageName 8239 + " was transferred to another, but its .apk remains"); 8240 } 8241 8242 // See comments in nonMutatedPs declaration 8243 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8244 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8245 if (foundPs != null) { 8246 nonMutatedPs = new PackageSetting(foundPs); 8247 } 8248 } 8249 8250 // Just create the setting, don't add it yet. For already existing packages 8251 // the PkgSetting exists already and doesn't have to be created. 8252 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8253 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8254 pkg.applicationInfo.primaryCpuAbi, 8255 pkg.applicationInfo.secondaryCpuAbi, 8256 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8257 user, false); 8258 if (pkgSetting == null) { 8259 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8260 "Creating application package " + pkg.packageName + " failed"); 8261 } 8262 8263 if (pkgSetting.origPackage != null) { 8264 // If we are first transitioning from an original package, 8265 // fix up the new package's name now. We need to do this after 8266 // looking up the package under its new name, so getPackageLP 8267 // can take care of fiddling things correctly. 8268 pkg.setPackageName(origPackage.name); 8269 8270 // File a report about this. 8271 String msg = "New package " + pkgSetting.realName 8272 + " renamed to replace old package " + pkgSetting.name; 8273 reportSettingsProblem(Log.WARN, msg); 8274 8275 // Make a note of it. 8276 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8277 mTransferedPackages.add(origPackage.name); 8278 } 8279 8280 // No longer need to retain this. 8281 pkgSetting.origPackage = null; 8282 } 8283 8284 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8285 // Make a note of it. 8286 mTransferedPackages.add(pkg.packageName); 8287 } 8288 8289 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8290 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8291 } 8292 8293 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8294 // Check all shared libraries and map to their actual file path. 8295 // We only do this here for apps not on a system dir, because those 8296 // are the only ones that can fail an install due to this. We 8297 // will take care of the system apps by updating all of their 8298 // library paths after the scan is done. 8299 updateSharedLibrariesLPw(pkg, null); 8300 } 8301 8302 if (mFoundPolicyFile) { 8303 SELinuxMMAC.assignSeinfoValue(pkg); 8304 } 8305 8306 pkg.applicationInfo.uid = pkgSetting.appId; 8307 pkg.mExtras = pkgSetting; 8308 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8309 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8310 // We just determined the app is signed correctly, so bring 8311 // over the latest parsed certs. 8312 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8313 } else { 8314 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8315 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8316 "Package " + pkg.packageName + " upgrade keys do not match the " 8317 + "previously installed version"); 8318 } else { 8319 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8320 String msg = "System package " + pkg.packageName 8321 + " signature changed; retaining data."; 8322 reportSettingsProblem(Log.WARN, msg); 8323 } 8324 } 8325 } else { 8326 try { 8327 verifySignaturesLP(pkgSetting, pkg); 8328 // We just determined the app is signed correctly, so bring 8329 // over the latest parsed certs. 8330 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8331 } catch (PackageManagerException e) { 8332 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8333 throw e; 8334 } 8335 // The signature has changed, but this package is in the system 8336 // image... let's recover! 8337 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8338 // However... if this package is part of a shared user, but it 8339 // doesn't match the signature of the shared user, let's fail. 8340 // What this means is that you can't change the signatures 8341 // associated with an overall shared user, which doesn't seem all 8342 // that unreasonable. 8343 if (pkgSetting.sharedUser != null) { 8344 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8345 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8346 throw new PackageManagerException( 8347 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8348 "Signature mismatch for shared user: " 8349 + pkgSetting.sharedUser); 8350 } 8351 } 8352 // File a report about this. 8353 String msg = "System package " + pkg.packageName 8354 + " signature changed; retaining data."; 8355 reportSettingsProblem(Log.WARN, msg); 8356 } 8357 } 8358 // Verify that this new package doesn't have any content providers 8359 // that conflict with existing packages. Only do this if the 8360 // package isn't already installed, since we don't want to break 8361 // things that are installed. 8362 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8363 final int N = pkg.providers.size(); 8364 int i; 8365 for (i=0; i<N; i++) { 8366 PackageParser.Provider p = pkg.providers.get(i); 8367 if (p.info.authority != null) { 8368 String names[] = p.info.authority.split(";"); 8369 for (int j = 0; j < names.length; j++) { 8370 if (mProvidersByAuthority.containsKey(names[j])) { 8371 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8372 final String otherPackageName = 8373 ((other != null && other.getComponentName() != null) ? 8374 other.getComponentName().getPackageName() : "?"); 8375 throw new PackageManagerException( 8376 INSTALL_FAILED_CONFLICTING_PROVIDER, 8377 "Can't install because provider name " + names[j] 8378 + " (in package " + pkg.applicationInfo.packageName 8379 + ") is already used by " + otherPackageName); 8380 } 8381 } 8382 } 8383 } 8384 } 8385 8386 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8387 // This package wants to adopt ownership of permissions from 8388 // another package. 8389 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8390 final String origName = pkg.mAdoptPermissions.get(i); 8391 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8392 if (orig != null) { 8393 if (verifyPackageUpdateLPr(orig, pkg)) { 8394 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8395 + pkg.packageName); 8396 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8397 } 8398 } 8399 } 8400 } 8401 } 8402 8403 final String pkgName = pkg.packageName; 8404 8405 final long scanFileTime = scanFile.lastModified(); 8406 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8407 pkg.applicationInfo.processName = fixProcessName( 8408 pkg.applicationInfo.packageName, 8409 pkg.applicationInfo.processName, 8410 pkg.applicationInfo.uid); 8411 8412 if (pkg != mPlatformPackage) { 8413 // Get all of our default paths setup 8414 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8415 } 8416 8417 final String path = scanFile.getPath(); 8418 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8419 8420 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8421 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8422 8423 // Some system apps still use directory structure for native libraries 8424 // in which case we might end up not detecting abi solely based on apk 8425 // structure. Try to detect abi based on directory structure. 8426 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8427 pkg.applicationInfo.primaryCpuAbi == null) { 8428 setBundledAppAbisAndRoots(pkg, pkgSetting); 8429 setNativeLibraryPaths(pkg); 8430 } 8431 8432 } else { 8433 if ((scanFlags & SCAN_MOVE) != 0) { 8434 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8435 // but we already have this packages package info in the PackageSetting. We just 8436 // use that and derive the native library path based on the new codepath. 8437 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8438 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8439 } 8440 8441 // Set native library paths again. For moves, the path will be updated based on the 8442 // ABIs we've determined above. For non-moves, the path will be updated based on the 8443 // ABIs we determined during compilation, but the path will depend on the final 8444 // package path (after the rename away from the stage path). 8445 setNativeLibraryPaths(pkg); 8446 } 8447 8448 // This is a special case for the "system" package, where the ABI is 8449 // dictated by the zygote configuration (and init.rc). We should keep track 8450 // of this ABI so that we can deal with "normal" applications that run under 8451 // the same UID correctly. 8452 if (mPlatformPackage == pkg) { 8453 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8454 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8455 } 8456 8457 // If there's a mismatch between the abi-override in the package setting 8458 // and the abiOverride specified for the install. Warn about this because we 8459 // would've already compiled the app without taking the package setting into 8460 // account. 8461 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8462 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8463 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8464 " for package " + pkg.packageName); 8465 } 8466 } 8467 8468 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8469 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8470 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8471 8472 // Copy the derived override back to the parsed package, so that we can 8473 // update the package settings accordingly. 8474 pkg.cpuAbiOverride = cpuAbiOverride; 8475 8476 if (DEBUG_ABI_SELECTION) { 8477 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8478 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8479 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8480 } 8481 8482 // Push the derived path down into PackageSettings so we know what to 8483 // clean up at uninstall time. 8484 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8485 8486 if (DEBUG_ABI_SELECTION) { 8487 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8488 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8489 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8490 } 8491 8492 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8493 // We don't do this here during boot because we can do it all 8494 // at once after scanning all existing packages. 8495 // 8496 // We also do this *before* we perform dexopt on this package, so that 8497 // we can avoid redundant dexopts, and also to make sure we've got the 8498 // code and package path correct. 8499 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8500 pkg, true /* boot complete */); 8501 } 8502 8503 if (mFactoryTest && pkg.requestedPermissions.contains( 8504 android.Manifest.permission.FACTORY_TEST)) { 8505 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8506 } 8507 8508 ArrayList<PackageParser.Package> clientLibPkgs = null; 8509 8510 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8511 if (nonMutatedPs != null) { 8512 synchronized (mPackages) { 8513 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8514 } 8515 } 8516 return pkg; 8517 } 8518 8519 // Only privileged apps and updated privileged apps can add child packages. 8520 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8521 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8522 throw new PackageManagerException("Only privileged apps and updated " 8523 + "privileged apps can add child packages. Ignoring package " 8524 + pkg.packageName); 8525 } 8526 final int childCount = pkg.childPackages.size(); 8527 for (int i = 0; i < childCount; i++) { 8528 PackageParser.Package childPkg = pkg.childPackages.get(i); 8529 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8530 childPkg.packageName)) { 8531 throw new PackageManagerException("Cannot override a child package of " 8532 + "another disabled system app. Ignoring package " + pkg.packageName); 8533 } 8534 } 8535 } 8536 8537 // writer 8538 synchronized (mPackages) { 8539 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8540 // Only system apps can add new shared libraries. 8541 if (pkg.libraryNames != null) { 8542 for (int i=0; i<pkg.libraryNames.size(); i++) { 8543 String name = pkg.libraryNames.get(i); 8544 boolean allowed = false; 8545 if (pkg.isUpdatedSystemApp()) { 8546 // New library entries can only be added through the 8547 // system image. This is important to get rid of a lot 8548 // of nasty edge cases: for example if we allowed a non- 8549 // system update of the app to add a library, then uninstalling 8550 // the update would make the library go away, and assumptions 8551 // we made such as through app install filtering would now 8552 // have allowed apps on the device which aren't compatible 8553 // with it. Better to just have the restriction here, be 8554 // conservative, and create many fewer cases that can negatively 8555 // impact the user experience. 8556 final PackageSetting sysPs = mSettings 8557 .getDisabledSystemPkgLPr(pkg.packageName); 8558 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8559 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8560 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8561 allowed = true; 8562 break; 8563 } 8564 } 8565 } 8566 } else { 8567 allowed = true; 8568 } 8569 if (allowed) { 8570 if (!mSharedLibraries.containsKey(name)) { 8571 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8572 } else if (!name.equals(pkg.packageName)) { 8573 Slog.w(TAG, "Package " + pkg.packageName + " library " 8574 + name + " already exists; skipping"); 8575 } 8576 } else { 8577 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8578 + name + " that is not declared on system image; skipping"); 8579 } 8580 } 8581 if ((scanFlags & SCAN_BOOTING) == 0) { 8582 // If we are not booting, we need to update any applications 8583 // that are clients of our shared library. If we are booting, 8584 // this will all be done once the scan is complete. 8585 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8586 } 8587 } 8588 } 8589 } 8590 8591 if ((scanFlags & SCAN_BOOTING) != 0) { 8592 // No apps can run during boot scan, so they don't need to be frozen 8593 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8594 // Caller asked to not kill app, so it's probably not frozen 8595 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8596 // Caller asked us to ignore frozen check for some reason; they 8597 // probably didn't know the package name 8598 } else { 8599 // We're doing major surgery on this package, so it better be frozen 8600 // right now to keep it from launching 8601 checkPackageFrozen(pkgName); 8602 } 8603 8604 // Also need to kill any apps that are dependent on the library. 8605 if (clientLibPkgs != null) { 8606 for (int i=0; i<clientLibPkgs.size(); i++) { 8607 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8608 killApplication(clientPkg.applicationInfo.packageName, 8609 clientPkg.applicationInfo.uid, "update lib"); 8610 } 8611 } 8612 8613 // Make sure we're not adding any bogus keyset info 8614 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8615 ksms.assertScannedPackageValid(pkg); 8616 8617 // writer 8618 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8619 8620 boolean createIdmapFailed = false; 8621 synchronized (mPackages) { 8622 // We don't expect installation to fail beyond this point 8623 8624 if (pkgSetting.pkg != null) { 8625 // Note that |user| might be null during the initial boot scan. If a codePath 8626 // for an app has changed during a boot scan, it's due to an app update that's 8627 // part of the system partition and marker changes must be applied to all users. 8628 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8629 (user != null) ? user : UserHandle.ALL); 8630 } 8631 8632 // Add the new setting to mSettings 8633 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8634 // Add the new setting to mPackages 8635 mPackages.put(pkg.applicationInfo.packageName, pkg); 8636 // Make sure we don't accidentally delete its data. 8637 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8638 while (iter.hasNext()) { 8639 PackageCleanItem item = iter.next(); 8640 if (pkgName.equals(item.packageName)) { 8641 iter.remove(); 8642 } 8643 } 8644 8645 // Take care of first install / last update times. 8646 if (currentTime != 0) { 8647 if (pkgSetting.firstInstallTime == 0) { 8648 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8649 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8650 pkgSetting.lastUpdateTime = currentTime; 8651 } 8652 } else if (pkgSetting.firstInstallTime == 0) { 8653 // We need *something*. Take time time stamp of the file. 8654 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8655 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8656 if (scanFileTime != pkgSetting.timeStamp) { 8657 // A package on the system image has changed; consider this 8658 // to be an update. 8659 pkgSetting.lastUpdateTime = scanFileTime; 8660 } 8661 } 8662 8663 // Add the package's KeySets to the global KeySetManagerService 8664 ksms.addScannedPackageLPw(pkg); 8665 8666 int N = pkg.providers.size(); 8667 StringBuilder r = null; 8668 int i; 8669 for (i=0; i<N; i++) { 8670 PackageParser.Provider p = pkg.providers.get(i); 8671 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8672 p.info.processName, pkg.applicationInfo.uid); 8673 mProviders.addProvider(p); 8674 p.syncable = p.info.isSyncable; 8675 if (p.info.authority != null) { 8676 String names[] = p.info.authority.split(";"); 8677 p.info.authority = null; 8678 for (int j = 0; j < names.length; j++) { 8679 if (j == 1 && p.syncable) { 8680 // We only want the first authority for a provider to possibly be 8681 // syncable, so if we already added this provider using a different 8682 // authority clear the syncable flag. We copy the provider before 8683 // changing it because the mProviders object contains a reference 8684 // to a provider that we don't want to change. 8685 // Only do this for the second authority since the resulting provider 8686 // object can be the same for all future authorities for this provider. 8687 p = new PackageParser.Provider(p); 8688 p.syncable = false; 8689 } 8690 if (!mProvidersByAuthority.containsKey(names[j])) { 8691 mProvidersByAuthority.put(names[j], p); 8692 if (p.info.authority == null) { 8693 p.info.authority = names[j]; 8694 } else { 8695 p.info.authority = p.info.authority + ";" + names[j]; 8696 } 8697 if (DEBUG_PACKAGE_SCANNING) { 8698 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8699 Log.d(TAG, "Registered content provider: " + names[j] 8700 + ", className = " + p.info.name + ", isSyncable = " 8701 + p.info.isSyncable); 8702 } 8703 } else { 8704 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8705 Slog.w(TAG, "Skipping provider name " + names[j] + 8706 " (in package " + pkg.applicationInfo.packageName + 8707 "): name already used by " 8708 + ((other != null && other.getComponentName() != null) 8709 ? other.getComponentName().getPackageName() : "?")); 8710 } 8711 } 8712 } 8713 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8714 if (r == null) { 8715 r = new StringBuilder(256); 8716 } else { 8717 r.append(' '); 8718 } 8719 r.append(p.info.name); 8720 } 8721 } 8722 if (r != null) { 8723 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8724 } 8725 8726 N = pkg.services.size(); 8727 r = null; 8728 for (i=0; i<N; i++) { 8729 PackageParser.Service s = pkg.services.get(i); 8730 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8731 s.info.processName, pkg.applicationInfo.uid); 8732 mServices.addService(s); 8733 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8734 if (r == null) { 8735 r = new StringBuilder(256); 8736 } else { 8737 r.append(' '); 8738 } 8739 r.append(s.info.name); 8740 } 8741 } 8742 if (r != null) { 8743 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8744 } 8745 8746 N = pkg.receivers.size(); 8747 r = null; 8748 for (i=0; i<N; i++) { 8749 PackageParser.Activity a = pkg.receivers.get(i); 8750 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8751 a.info.processName, pkg.applicationInfo.uid); 8752 mReceivers.addActivity(a, "receiver"); 8753 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8754 if (r == null) { 8755 r = new StringBuilder(256); 8756 } else { 8757 r.append(' '); 8758 } 8759 r.append(a.info.name); 8760 } 8761 } 8762 if (r != null) { 8763 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8764 } 8765 8766 N = pkg.activities.size(); 8767 r = null; 8768 for (i=0; i<N; i++) { 8769 PackageParser.Activity a = pkg.activities.get(i); 8770 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8771 a.info.processName, pkg.applicationInfo.uid); 8772 mActivities.addActivity(a, "activity"); 8773 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8774 if (r == null) { 8775 r = new StringBuilder(256); 8776 } else { 8777 r.append(' '); 8778 } 8779 r.append(a.info.name); 8780 } 8781 } 8782 if (r != null) { 8783 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8784 } 8785 8786 N = pkg.permissionGroups.size(); 8787 r = null; 8788 for (i=0; i<N; i++) { 8789 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8790 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8791 if (cur == null) { 8792 mPermissionGroups.put(pg.info.name, pg); 8793 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8794 if (r == null) { 8795 r = new StringBuilder(256); 8796 } else { 8797 r.append(' '); 8798 } 8799 r.append(pg.info.name); 8800 } 8801 } else { 8802 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8803 + pg.info.packageName + " ignored: original from " 8804 + cur.info.packageName); 8805 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8806 if (r == null) { 8807 r = new StringBuilder(256); 8808 } else { 8809 r.append(' '); 8810 } 8811 r.append("DUP:"); 8812 r.append(pg.info.name); 8813 } 8814 } 8815 } 8816 if (r != null) { 8817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8818 } 8819 8820 N = pkg.permissions.size(); 8821 r = null; 8822 for (i=0; i<N; i++) { 8823 PackageParser.Permission p = pkg.permissions.get(i); 8824 8825 // Assume by default that we did not install this permission into the system. 8826 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8827 8828 // Now that permission groups have a special meaning, we ignore permission 8829 // groups for legacy apps to prevent unexpected behavior. In particular, 8830 // permissions for one app being granted to someone just becase they happen 8831 // to be in a group defined by another app (before this had no implications). 8832 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8833 p.group = mPermissionGroups.get(p.info.group); 8834 // Warn for a permission in an unknown group. 8835 if (p.info.group != null && p.group == null) { 8836 Slog.w(TAG, "Permission " + p.info.name + " from package " 8837 + p.info.packageName + " in an unknown group " + p.info.group); 8838 } 8839 } 8840 8841 ArrayMap<String, BasePermission> permissionMap = 8842 p.tree ? mSettings.mPermissionTrees 8843 : mSettings.mPermissions; 8844 BasePermission bp = permissionMap.get(p.info.name); 8845 8846 // Allow system apps to redefine non-system permissions 8847 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8848 final boolean currentOwnerIsSystem = (bp.perm != null 8849 && isSystemApp(bp.perm.owner)); 8850 if (isSystemApp(p.owner)) { 8851 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8852 // It's a built-in permission and no owner, take ownership now 8853 bp.packageSetting = pkgSetting; 8854 bp.perm = p; 8855 bp.uid = pkg.applicationInfo.uid; 8856 bp.sourcePackage = p.info.packageName; 8857 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8858 } else if (!currentOwnerIsSystem) { 8859 String msg = "New decl " + p.owner + " of permission " 8860 + p.info.name + " is system; overriding " + bp.sourcePackage; 8861 reportSettingsProblem(Log.WARN, msg); 8862 bp = null; 8863 } 8864 } 8865 } 8866 8867 if (bp == null) { 8868 bp = new BasePermission(p.info.name, p.info.packageName, 8869 BasePermission.TYPE_NORMAL); 8870 permissionMap.put(p.info.name, bp); 8871 } 8872 8873 if (bp.perm == null) { 8874 if (bp.sourcePackage == null 8875 || bp.sourcePackage.equals(p.info.packageName)) { 8876 BasePermission tree = findPermissionTreeLP(p.info.name); 8877 if (tree == null 8878 || tree.sourcePackage.equals(p.info.packageName)) { 8879 bp.packageSetting = pkgSetting; 8880 bp.perm = p; 8881 bp.uid = pkg.applicationInfo.uid; 8882 bp.sourcePackage = p.info.packageName; 8883 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8884 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8885 if (r == null) { 8886 r = new StringBuilder(256); 8887 } else { 8888 r.append(' '); 8889 } 8890 r.append(p.info.name); 8891 } 8892 } else { 8893 Slog.w(TAG, "Permission " + p.info.name + " from package " 8894 + p.info.packageName + " ignored: base tree " 8895 + tree.name + " is from package " 8896 + tree.sourcePackage); 8897 } 8898 } else { 8899 Slog.w(TAG, "Permission " + p.info.name + " from package " 8900 + p.info.packageName + " ignored: original from " 8901 + bp.sourcePackage); 8902 } 8903 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8904 if (r == null) { 8905 r = new StringBuilder(256); 8906 } else { 8907 r.append(' '); 8908 } 8909 r.append("DUP:"); 8910 r.append(p.info.name); 8911 } 8912 if (bp.perm == p) { 8913 bp.protectionLevel = p.info.protectionLevel; 8914 } 8915 } 8916 8917 if (r != null) { 8918 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8919 } 8920 8921 N = pkg.instrumentation.size(); 8922 r = null; 8923 for (i=0; i<N; i++) { 8924 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8925 a.info.packageName = pkg.applicationInfo.packageName; 8926 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8927 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8928 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8929 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8930 a.info.dataDir = pkg.applicationInfo.dataDir; 8931 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8932 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8933 8934 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8935 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8936 mInstrumentation.put(a.getComponentName(), a); 8937 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8938 if (r == null) { 8939 r = new StringBuilder(256); 8940 } else { 8941 r.append(' '); 8942 } 8943 r.append(a.info.name); 8944 } 8945 } 8946 if (r != null) { 8947 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8948 } 8949 8950 if (pkg.protectedBroadcasts != null) { 8951 N = pkg.protectedBroadcasts.size(); 8952 for (i=0; i<N; i++) { 8953 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8954 } 8955 } 8956 8957 pkgSetting.setTimeStamp(scanFileTime); 8958 8959 // Create idmap files for pairs of (packages, overlay packages). 8960 // Note: "android", ie framework-res.apk, is handled by native layers. 8961 if (pkg.mOverlayTarget != null) { 8962 // This is an overlay package. 8963 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8964 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8965 mOverlays.put(pkg.mOverlayTarget, 8966 new ArrayMap<String, PackageParser.Package>()); 8967 } 8968 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8969 map.put(pkg.packageName, pkg); 8970 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8971 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8972 createIdmapFailed = true; 8973 } 8974 } 8975 } else if (mOverlays.containsKey(pkg.packageName) && 8976 !pkg.packageName.equals("android")) { 8977 // This is a regular package, with one or more known overlay packages. 8978 createIdmapsForPackageLI(pkg); 8979 } 8980 } 8981 8982 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8983 8984 if (createIdmapFailed) { 8985 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8986 "scanPackageLI failed to createIdmap"); 8987 } 8988 return pkg; 8989 } 8990 8991 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8992 PackageParser.Package update, UserHandle user) { 8993 if (existing.applicationInfo == null || update.applicationInfo == null) { 8994 // This isn't due to an app installation. 8995 return; 8996 } 8997 8998 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8999 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9000 9001 // The codePath hasn't changed, so there's nothing for us to do. 9002 if (Objects.equals(oldCodePath, newCodePath)) { 9003 return; 9004 } 9005 9006 File canonicalNewCodePath; 9007 try { 9008 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9009 } catch (IOException e) { 9010 Slog.w(TAG, "Failed to get canonical path.", e); 9011 return; 9012 } 9013 9014 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9015 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9016 // that the last component of the path (i.e, the name) doesn't need canonicalization 9017 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9018 // but may change in the future. Hopefully this function won't exist at that point. 9019 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9020 oldCodePath.getName()); 9021 9022 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9023 // with "@". 9024 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9025 if (!oldMarkerPrefix.endsWith("@")) { 9026 oldMarkerPrefix += "@"; 9027 } 9028 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9029 if (!newMarkerPrefix.endsWith("@")) { 9030 newMarkerPrefix += "@"; 9031 } 9032 9033 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9034 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9035 for (String updatedPath : updatedPaths) { 9036 String updatedPathName = new File(updatedPath).getName(); 9037 markerSuffixes.add(updatedPathName.replace('/', '@')); 9038 } 9039 9040 for (int userId : resolveUserIds(user.getIdentifier())) { 9041 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9042 9043 for (String markerSuffix : markerSuffixes) { 9044 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9045 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9046 if (oldForeignUseMark.exists()) { 9047 try { 9048 Os.rename(oldForeignUseMark.getAbsolutePath(), 9049 newForeignUseMark.getAbsolutePath()); 9050 } catch (ErrnoException e) { 9051 Slog.w(TAG, "Failed to rename foreign use marker", e); 9052 oldForeignUseMark.delete(); 9053 } 9054 } 9055 } 9056 } 9057 } 9058 9059 /** 9060 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9061 * is derived purely on the basis of the contents of {@code scanFile} and 9062 * {@code cpuAbiOverride}. 9063 * 9064 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9065 */ 9066 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9067 String cpuAbiOverride, boolean extractLibs) 9068 throws PackageManagerException { 9069 // TODO: We can probably be smarter about this stuff. For installed apps, 9070 // we can calculate this information at install time once and for all. For 9071 // system apps, we can probably assume that this information doesn't change 9072 // after the first boot scan. As things stand, we do lots of unnecessary work. 9073 9074 // Give ourselves some initial paths; we'll come back for another 9075 // pass once we've determined ABI below. 9076 setNativeLibraryPaths(pkg); 9077 9078 // We would never need to extract libs for forward-locked and external packages, 9079 // since the container service will do it for us. We shouldn't attempt to 9080 // extract libs from system app when it was not updated. 9081 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9082 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9083 extractLibs = false; 9084 } 9085 9086 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9087 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9088 9089 NativeLibraryHelper.Handle handle = null; 9090 try { 9091 handle = NativeLibraryHelper.Handle.create(pkg); 9092 // TODO(multiArch): This can be null for apps that didn't go through the 9093 // usual installation process. We can calculate it again, like we 9094 // do during install time. 9095 // 9096 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9097 // unnecessary. 9098 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9099 9100 // Null out the abis so that they can be recalculated. 9101 pkg.applicationInfo.primaryCpuAbi = null; 9102 pkg.applicationInfo.secondaryCpuAbi = null; 9103 if (isMultiArch(pkg.applicationInfo)) { 9104 // Warn if we've set an abiOverride for multi-lib packages.. 9105 // By definition, we need to copy both 32 and 64 bit libraries for 9106 // such packages. 9107 if (pkg.cpuAbiOverride != null 9108 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9109 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9110 } 9111 9112 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9113 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9114 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9115 if (extractLibs) { 9116 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9117 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9118 useIsaSpecificSubdirs); 9119 } else { 9120 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9121 } 9122 } 9123 9124 maybeThrowExceptionForMultiArchCopy( 9125 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9126 9127 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9128 if (extractLibs) { 9129 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9130 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9131 useIsaSpecificSubdirs); 9132 } else { 9133 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9134 } 9135 } 9136 9137 maybeThrowExceptionForMultiArchCopy( 9138 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9139 9140 if (abi64 >= 0) { 9141 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9142 } 9143 9144 if (abi32 >= 0) { 9145 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9146 if (abi64 >= 0) { 9147 if (pkg.use32bitAbi) { 9148 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9149 pkg.applicationInfo.primaryCpuAbi = abi; 9150 } else { 9151 pkg.applicationInfo.secondaryCpuAbi = abi; 9152 } 9153 } else { 9154 pkg.applicationInfo.primaryCpuAbi = abi; 9155 } 9156 } 9157 9158 } else { 9159 String[] abiList = (cpuAbiOverride != null) ? 9160 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9161 9162 // Enable gross and lame hacks for apps that are built with old 9163 // SDK tools. We must scan their APKs for renderscript bitcode and 9164 // not launch them if it's present. Don't bother checking on devices 9165 // that don't have 64 bit support. 9166 boolean needsRenderScriptOverride = false; 9167 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9168 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9169 abiList = Build.SUPPORTED_32_BIT_ABIS; 9170 needsRenderScriptOverride = true; 9171 } 9172 9173 final int copyRet; 9174 if (extractLibs) { 9175 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9176 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9177 } else { 9178 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9179 } 9180 9181 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9182 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9183 "Error unpackaging native libs for app, errorCode=" + copyRet); 9184 } 9185 9186 if (copyRet >= 0) { 9187 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9188 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9189 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9190 } else if (needsRenderScriptOverride) { 9191 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9192 } 9193 } 9194 } catch (IOException ioe) { 9195 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9196 } finally { 9197 IoUtils.closeQuietly(handle); 9198 } 9199 9200 // Now that we've calculated the ABIs and determined if it's an internal app, 9201 // we will go ahead and populate the nativeLibraryPath. 9202 setNativeLibraryPaths(pkg); 9203 } 9204 9205 /** 9206 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9207 * i.e, so that all packages can be run inside a single process if required. 9208 * 9209 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9210 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9211 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9212 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9213 * updating a package that belongs to a shared user. 9214 * 9215 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9216 * adds unnecessary complexity. 9217 */ 9218 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9219 PackageParser.Package scannedPackage, boolean bootComplete) { 9220 String requiredInstructionSet = null; 9221 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9222 requiredInstructionSet = VMRuntime.getInstructionSet( 9223 scannedPackage.applicationInfo.primaryCpuAbi); 9224 } 9225 9226 PackageSetting requirer = null; 9227 for (PackageSetting ps : packagesForUser) { 9228 // If packagesForUser contains scannedPackage, we skip it. This will happen 9229 // when scannedPackage is an update of an existing package. Without this check, 9230 // we will never be able to change the ABI of any package belonging to a shared 9231 // user, even if it's compatible with other packages. 9232 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9233 if (ps.primaryCpuAbiString == null) { 9234 continue; 9235 } 9236 9237 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9238 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9239 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9240 // this but there's not much we can do. 9241 String errorMessage = "Instruction set mismatch, " 9242 + ((requirer == null) ? "[caller]" : requirer) 9243 + " requires " + requiredInstructionSet + " whereas " + ps 9244 + " requires " + instructionSet; 9245 Slog.w(TAG, errorMessage); 9246 } 9247 9248 if (requiredInstructionSet == null) { 9249 requiredInstructionSet = instructionSet; 9250 requirer = ps; 9251 } 9252 } 9253 } 9254 9255 if (requiredInstructionSet != null) { 9256 String adjustedAbi; 9257 if (requirer != null) { 9258 // requirer != null implies that either scannedPackage was null or that scannedPackage 9259 // did not require an ABI, in which case we have to adjust scannedPackage to match 9260 // the ABI of the set (which is the same as requirer's ABI) 9261 adjustedAbi = requirer.primaryCpuAbiString; 9262 if (scannedPackage != null) { 9263 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9264 } 9265 } else { 9266 // requirer == null implies that we're updating all ABIs in the set to 9267 // match scannedPackage. 9268 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9269 } 9270 9271 for (PackageSetting ps : packagesForUser) { 9272 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9273 if (ps.primaryCpuAbiString != null) { 9274 continue; 9275 } 9276 9277 ps.primaryCpuAbiString = adjustedAbi; 9278 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9279 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9280 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9281 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9282 + " (requirer=" 9283 + (requirer == null ? "null" : requirer.pkg.packageName) 9284 + ", scannedPackage=" 9285 + (scannedPackage != null ? scannedPackage.packageName : "null") 9286 + ")"); 9287 try { 9288 mInstaller.rmdex(ps.codePathString, 9289 getDexCodeInstructionSet(getPreferredInstructionSet())); 9290 } catch (InstallerException ignored) { 9291 } 9292 } 9293 } 9294 } 9295 } 9296 } 9297 9298 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9299 synchronized (mPackages) { 9300 mResolverReplaced = true; 9301 // Set up information for custom user intent resolution activity. 9302 mResolveActivity.applicationInfo = pkg.applicationInfo; 9303 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9304 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9305 mResolveActivity.processName = pkg.applicationInfo.packageName; 9306 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9307 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9308 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9309 mResolveActivity.theme = 0; 9310 mResolveActivity.exported = true; 9311 mResolveActivity.enabled = true; 9312 mResolveInfo.activityInfo = mResolveActivity; 9313 mResolveInfo.priority = 0; 9314 mResolveInfo.preferredOrder = 0; 9315 mResolveInfo.match = 0; 9316 mResolveComponentName = mCustomResolverComponentName; 9317 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9318 mResolveComponentName); 9319 } 9320 } 9321 9322 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9323 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9324 9325 // Set up information for ephemeral installer activity 9326 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9327 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9328 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9329 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9330 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9331 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9332 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9333 mEphemeralInstallerActivity.theme = 0; 9334 mEphemeralInstallerActivity.exported = true; 9335 mEphemeralInstallerActivity.enabled = true; 9336 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9337 mEphemeralInstallerInfo.priority = 0; 9338 mEphemeralInstallerInfo.preferredOrder = 0; 9339 mEphemeralInstallerInfo.match = 0; 9340 9341 if (DEBUG_EPHEMERAL) { 9342 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9343 } 9344 } 9345 9346 private static String calculateBundledApkRoot(final String codePathString) { 9347 final File codePath = new File(codePathString); 9348 final File codeRoot; 9349 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9350 codeRoot = Environment.getRootDirectory(); 9351 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9352 codeRoot = Environment.getOemDirectory(); 9353 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9354 codeRoot = Environment.getVendorDirectory(); 9355 } else { 9356 // Unrecognized code path; take its top real segment as the apk root: 9357 // e.g. /something/app/blah.apk => /something 9358 try { 9359 File f = codePath.getCanonicalFile(); 9360 File parent = f.getParentFile(); // non-null because codePath is a file 9361 File tmp; 9362 while ((tmp = parent.getParentFile()) != null) { 9363 f = parent; 9364 parent = tmp; 9365 } 9366 codeRoot = f; 9367 Slog.w(TAG, "Unrecognized code path " 9368 + codePath + " - using " + codeRoot); 9369 } catch (IOException e) { 9370 // Can't canonicalize the code path -- shenanigans? 9371 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9372 return Environment.getRootDirectory().getPath(); 9373 } 9374 } 9375 return codeRoot.getPath(); 9376 } 9377 9378 /** 9379 * Derive and set the location of native libraries for the given package, 9380 * which varies depending on where and how the package was installed. 9381 */ 9382 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9383 final ApplicationInfo info = pkg.applicationInfo; 9384 final String codePath = pkg.codePath; 9385 final File codeFile = new File(codePath); 9386 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9387 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9388 9389 info.nativeLibraryRootDir = null; 9390 info.nativeLibraryRootRequiresIsa = false; 9391 info.nativeLibraryDir = null; 9392 info.secondaryNativeLibraryDir = null; 9393 9394 if (isApkFile(codeFile)) { 9395 // Monolithic install 9396 if (bundledApp) { 9397 // If "/system/lib64/apkname" exists, assume that is the per-package 9398 // native library directory to use; otherwise use "/system/lib/apkname". 9399 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9400 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9401 getPrimaryInstructionSet(info)); 9402 9403 // This is a bundled system app so choose the path based on the ABI. 9404 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9405 // is just the default path. 9406 final String apkName = deriveCodePathName(codePath); 9407 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9408 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9409 apkName).getAbsolutePath(); 9410 9411 if (info.secondaryCpuAbi != null) { 9412 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9413 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9414 secondaryLibDir, apkName).getAbsolutePath(); 9415 } 9416 } else if (asecApp) { 9417 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9418 .getAbsolutePath(); 9419 } else { 9420 final String apkName = deriveCodePathName(codePath); 9421 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9422 .getAbsolutePath(); 9423 } 9424 9425 info.nativeLibraryRootRequiresIsa = false; 9426 info.nativeLibraryDir = info.nativeLibraryRootDir; 9427 } else { 9428 // Cluster install 9429 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9430 info.nativeLibraryRootRequiresIsa = true; 9431 9432 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9433 getPrimaryInstructionSet(info)).getAbsolutePath(); 9434 9435 if (info.secondaryCpuAbi != null) { 9436 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9437 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9438 } 9439 } 9440 } 9441 9442 /** 9443 * Calculate the abis and roots for a bundled app. These can uniquely 9444 * be determined from the contents of the system partition, i.e whether 9445 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9446 * of this information, and instead assume that the system was built 9447 * sensibly. 9448 */ 9449 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9450 PackageSetting pkgSetting) { 9451 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9452 9453 // If "/system/lib64/apkname" exists, assume that is the per-package 9454 // native library directory to use; otherwise use "/system/lib/apkname". 9455 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9456 setBundledAppAbi(pkg, apkRoot, apkName); 9457 // pkgSetting might be null during rescan following uninstall of updates 9458 // to a bundled app, so accommodate that possibility. The settings in 9459 // that case will be established later from the parsed package. 9460 // 9461 // If the settings aren't null, sync them up with what we've just derived. 9462 // note that apkRoot isn't stored in the package settings. 9463 if (pkgSetting != null) { 9464 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9465 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9466 } 9467 } 9468 9469 /** 9470 * Deduces the ABI of a bundled app and sets the relevant fields on the 9471 * parsed pkg object. 9472 * 9473 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9474 * under which system libraries are installed. 9475 * @param apkName the name of the installed package. 9476 */ 9477 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9478 final File codeFile = new File(pkg.codePath); 9479 9480 final boolean has64BitLibs; 9481 final boolean has32BitLibs; 9482 if (isApkFile(codeFile)) { 9483 // Monolithic install 9484 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9485 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9486 } else { 9487 // Cluster install 9488 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9489 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9490 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9491 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9492 has64BitLibs = (new File(rootDir, isa)).exists(); 9493 } else { 9494 has64BitLibs = false; 9495 } 9496 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9497 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9498 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9499 has32BitLibs = (new File(rootDir, isa)).exists(); 9500 } else { 9501 has32BitLibs = false; 9502 } 9503 } 9504 9505 if (has64BitLibs && !has32BitLibs) { 9506 // The package has 64 bit libs, but not 32 bit libs. Its primary 9507 // ABI should be 64 bit. We can safely assume here that the bundled 9508 // native libraries correspond to the most preferred ABI in the list. 9509 9510 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9511 pkg.applicationInfo.secondaryCpuAbi = null; 9512 } else if (has32BitLibs && !has64BitLibs) { 9513 // The package has 32 bit libs but not 64 bit libs. Its primary 9514 // ABI should be 32 bit. 9515 9516 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9517 pkg.applicationInfo.secondaryCpuAbi = null; 9518 } else if (has32BitLibs && has64BitLibs) { 9519 // The application has both 64 and 32 bit bundled libraries. We check 9520 // here that the app declares multiArch support, and warn if it doesn't. 9521 // 9522 // We will be lenient here and record both ABIs. The primary will be the 9523 // ABI that's higher on the list, i.e, a device that's configured to prefer 9524 // 64 bit apps will see a 64 bit primary ABI, 9525 9526 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9527 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9528 } 9529 9530 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9531 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9532 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9533 } else { 9534 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9535 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9536 } 9537 } else { 9538 pkg.applicationInfo.primaryCpuAbi = null; 9539 pkg.applicationInfo.secondaryCpuAbi = null; 9540 } 9541 } 9542 9543 private void killApplication(String pkgName, int appId, String reason) { 9544 // Request the ActivityManager to kill the process(only for existing packages) 9545 // so that we do not end up in a confused state while the user is still using the older 9546 // version of the application while the new one gets installed. 9547 final long token = Binder.clearCallingIdentity(); 9548 try { 9549 IActivityManager am = ActivityManagerNative.getDefault(); 9550 if (am != null) { 9551 try { 9552 am.killApplicationWithAppId(pkgName, appId, reason); 9553 } catch (RemoteException e) { 9554 } 9555 } 9556 } finally { 9557 Binder.restoreCallingIdentity(token); 9558 } 9559 } 9560 9561 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9562 // Remove the parent package setting 9563 PackageSetting ps = (PackageSetting) pkg.mExtras; 9564 if (ps != null) { 9565 removePackageLI(ps, chatty); 9566 } 9567 // Remove the child package setting 9568 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9569 for (int i = 0; i < childCount; i++) { 9570 PackageParser.Package childPkg = pkg.childPackages.get(i); 9571 ps = (PackageSetting) childPkg.mExtras; 9572 if (ps != null) { 9573 removePackageLI(ps, chatty); 9574 } 9575 } 9576 } 9577 9578 void removePackageLI(PackageSetting ps, boolean chatty) { 9579 if (DEBUG_INSTALL) { 9580 if (chatty) 9581 Log.d(TAG, "Removing package " + ps.name); 9582 } 9583 9584 // writer 9585 synchronized (mPackages) { 9586 mPackages.remove(ps.name); 9587 final PackageParser.Package pkg = ps.pkg; 9588 if (pkg != null) { 9589 cleanPackageDataStructuresLILPw(pkg, chatty); 9590 } 9591 } 9592 } 9593 9594 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9595 if (DEBUG_INSTALL) { 9596 if (chatty) 9597 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9598 } 9599 9600 // writer 9601 synchronized (mPackages) { 9602 // Remove the parent package 9603 mPackages.remove(pkg.applicationInfo.packageName); 9604 cleanPackageDataStructuresLILPw(pkg, chatty); 9605 9606 // Remove the child packages 9607 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9608 for (int i = 0; i < childCount; i++) { 9609 PackageParser.Package childPkg = pkg.childPackages.get(i); 9610 mPackages.remove(childPkg.applicationInfo.packageName); 9611 cleanPackageDataStructuresLILPw(childPkg, chatty); 9612 } 9613 } 9614 } 9615 9616 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9617 int N = pkg.providers.size(); 9618 StringBuilder r = null; 9619 int i; 9620 for (i=0; i<N; i++) { 9621 PackageParser.Provider p = pkg.providers.get(i); 9622 mProviders.removeProvider(p); 9623 if (p.info.authority == null) { 9624 9625 /* There was another ContentProvider with this authority when 9626 * this app was installed so this authority is null, 9627 * Ignore it as we don't have to unregister the provider. 9628 */ 9629 continue; 9630 } 9631 String names[] = p.info.authority.split(";"); 9632 for (int j = 0; j < names.length; j++) { 9633 if (mProvidersByAuthority.get(names[j]) == p) { 9634 mProvidersByAuthority.remove(names[j]); 9635 if (DEBUG_REMOVE) { 9636 if (chatty) 9637 Log.d(TAG, "Unregistered content provider: " + names[j] 9638 + ", className = " + p.info.name + ", isSyncable = " 9639 + p.info.isSyncable); 9640 } 9641 } 9642 } 9643 if (DEBUG_REMOVE && chatty) { 9644 if (r == null) { 9645 r = new StringBuilder(256); 9646 } else { 9647 r.append(' '); 9648 } 9649 r.append(p.info.name); 9650 } 9651 } 9652 if (r != null) { 9653 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9654 } 9655 9656 N = pkg.services.size(); 9657 r = null; 9658 for (i=0; i<N; i++) { 9659 PackageParser.Service s = pkg.services.get(i); 9660 mServices.removeService(s); 9661 if (chatty) { 9662 if (r == null) { 9663 r = new StringBuilder(256); 9664 } else { 9665 r.append(' '); 9666 } 9667 r.append(s.info.name); 9668 } 9669 } 9670 if (r != null) { 9671 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9672 } 9673 9674 N = pkg.receivers.size(); 9675 r = null; 9676 for (i=0; i<N; i++) { 9677 PackageParser.Activity a = pkg.receivers.get(i); 9678 mReceivers.removeActivity(a, "receiver"); 9679 if (DEBUG_REMOVE && chatty) { 9680 if (r == null) { 9681 r = new StringBuilder(256); 9682 } else { 9683 r.append(' '); 9684 } 9685 r.append(a.info.name); 9686 } 9687 } 9688 if (r != null) { 9689 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9690 } 9691 9692 N = pkg.activities.size(); 9693 r = null; 9694 for (i=0; i<N; i++) { 9695 PackageParser.Activity a = pkg.activities.get(i); 9696 mActivities.removeActivity(a, "activity"); 9697 if (DEBUG_REMOVE && chatty) { 9698 if (r == null) { 9699 r = new StringBuilder(256); 9700 } else { 9701 r.append(' '); 9702 } 9703 r.append(a.info.name); 9704 } 9705 } 9706 if (r != null) { 9707 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9708 } 9709 9710 N = pkg.permissions.size(); 9711 r = null; 9712 for (i=0; i<N; i++) { 9713 PackageParser.Permission p = pkg.permissions.get(i); 9714 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9715 if (bp == null) { 9716 bp = mSettings.mPermissionTrees.get(p.info.name); 9717 } 9718 if (bp != null && bp.perm == p) { 9719 bp.perm = null; 9720 if (DEBUG_REMOVE && chatty) { 9721 if (r == null) { 9722 r = new StringBuilder(256); 9723 } else { 9724 r.append(' '); 9725 } 9726 r.append(p.info.name); 9727 } 9728 } 9729 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9730 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9731 if (appOpPkgs != null) { 9732 appOpPkgs.remove(pkg.packageName); 9733 } 9734 } 9735 } 9736 if (r != null) { 9737 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9738 } 9739 9740 N = pkg.requestedPermissions.size(); 9741 r = null; 9742 for (i=0; i<N; i++) { 9743 String perm = pkg.requestedPermissions.get(i); 9744 BasePermission bp = mSettings.mPermissions.get(perm); 9745 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9746 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9747 if (appOpPkgs != null) { 9748 appOpPkgs.remove(pkg.packageName); 9749 if (appOpPkgs.isEmpty()) { 9750 mAppOpPermissionPackages.remove(perm); 9751 } 9752 } 9753 } 9754 } 9755 if (r != null) { 9756 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9757 } 9758 9759 N = pkg.instrumentation.size(); 9760 r = null; 9761 for (i=0; i<N; i++) { 9762 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9763 mInstrumentation.remove(a.getComponentName()); 9764 if (DEBUG_REMOVE && chatty) { 9765 if (r == null) { 9766 r = new StringBuilder(256); 9767 } else { 9768 r.append(' '); 9769 } 9770 r.append(a.info.name); 9771 } 9772 } 9773 if (r != null) { 9774 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9775 } 9776 9777 r = null; 9778 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9779 // Only system apps can hold shared libraries. 9780 if (pkg.libraryNames != null) { 9781 for (i=0; i<pkg.libraryNames.size(); i++) { 9782 String name = pkg.libraryNames.get(i); 9783 SharedLibraryEntry cur = mSharedLibraries.get(name); 9784 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9785 mSharedLibraries.remove(name); 9786 if (DEBUG_REMOVE && chatty) { 9787 if (r == null) { 9788 r = new StringBuilder(256); 9789 } else { 9790 r.append(' '); 9791 } 9792 r.append(name); 9793 } 9794 } 9795 } 9796 } 9797 } 9798 if (r != null) { 9799 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9800 } 9801 } 9802 9803 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9804 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9805 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9806 return true; 9807 } 9808 } 9809 return false; 9810 } 9811 9812 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9813 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9814 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9815 9816 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9817 // Update the parent permissions 9818 updatePermissionsLPw(pkg.packageName, pkg, flags); 9819 // Update the child permissions 9820 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9821 for (int i = 0; i < childCount; i++) { 9822 PackageParser.Package childPkg = pkg.childPackages.get(i); 9823 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9824 } 9825 } 9826 9827 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9828 int flags) { 9829 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9830 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9831 } 9832 9833 private void updatePermissionsLPw(String changingPkg, 9834 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9835 // Make sure there are no dangling permission trees. 9836 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9837 while (it.hasNext()) { 9838 final BasePermission bp = it.next(); 9839 if (bp.packageSetting == null) { 9840 // We may not yet have parsed the package, so just see if 9841 // we still know about its settings. 9842 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9843 } 9844 if (bp.packageSetting == null) { 9845 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9846 + " from package " + bp.sourcePackage); 9847 it.remove(); 9848 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9849 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9850 Slog.i(TAG, "Removing old permission tree: " + bp.name 9851 + " from package " + bp.sourcePackage); 9852 flags |= UPDATE_PERMISSIONS_ALL; 9853 it.remove(); 9854 } 9855 } 9856 } 9857 9858 // Make sure all dynamic permissions have been assigned to a package, 9859 // and make sure there are no dangling permissions. 9860 it = mSettings.mPermissions.values().iterator(); 9861 while (it.hasNext()) { 9862 final BasePermission bp = it.next(); 9863 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9864 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9865 + bp.name + " pkg=" + bp.sourcePackage 9866 + " info=" + bp.pendingInfo); 9867 if (bp.packageSetting == null && bp.pendingInfo != null) { 9868 final BasePermission tree = findPermissionTreeLP(bp.name); 9869 if (tree != null && tree.perm != null) { 9870 bp.packageSetting = tree.packageSetting; 9871 bp.perm = new PackageParser.Permission(tree.perm.owner, 9872 new PermissionInfo(bp.pendingInfo)); 9873 bp.perm.info.packageName = tree.perm.info.packageName; 9874 bp.perm.info.name = bp.name; 9875 bp.uid = tree.uid; 9876 } 9877 } 9878 } 9879 if (bp.packageSetting == null) { 9880 // We may not yet have parsed the package, so just see if 9881 // we still know about its settings. 9882 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9883 } 9884 if (bp.packageSetting == null) { 9885 Slog.w(TAG, "Removing dangling permission: " + bp.name 9886 + " from package " + bp.sourcePackage); 9887 it.remove(); 9888 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9889 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9890 Slog.i(TAG, "Removing old permission: " + bp.name 9891 + " from package " + bp.sourcePackage); 9892 flags |= UPDATE_PERMISSIONS_ALL; 9893 it.remove(); 9894 } 9895 } 9896 } 9897 9898 // Now update the permissions for all packages, in particular 9899 // replace the granted permissions of the system packages. 9900 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9901 for (PackageParser.Package pkg : mPackages.values()) { 9902 if (pkg != pkgInfo) { 9903 // Only replace for packages on requested volume 9904 final String volumeUuid = getVolumeUuidForPackage(pkg); 9905 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9906 && Objects.equals(replaceVolumeUuid, volumeUuid); 9907 grantPermissionsLPw(pkg, replace, changingPkg); 9908 } 9909 } 9910 } 9911 9912 if (pkgInfo != null) { 9913 // Only replace for packages on requested volume 9914 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9915 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9916 && Objects.equals(replaceVolumeUuid, volumeUuid); 9917 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9918 } 9919 } 9920 9921 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9922 String packageOfInterest) { 9923 // IMPORTANT: There are two types of permissions: install and runtime. 9924 // Install time permissions are granted when the app is installed to 9925 // all device users and users added in the future. Runtime permissions 9926 // are granted at runtime explicitly to specific users. Normal and signature 9927 // protected permissions are install time permissions. Dangerous permissions 9928 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9929 // otherwise they are runtime permissions. This function does not manage 9930 // runtime permissions except for the case an app targeting Lollipop MR1 9931 // being upgraded to target a newer SDK, in which case dangerous permissions 9932 // are transformed from install time to runtime ones. 9933 9934 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9935 if (ps == null) { 9936 return; 9937 } 9938 9939 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9940 9941 PermissionsState permissionsState = ps.getPermissionsState(); 9942 PermissionsState origPermissions = permissionsState; 9943 9944 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9945 9946 boolean runtimePermissionsRevoked = false; 9947 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9948 9949 boolean changedInstallPermission = false; 9950 9951 if (replace) { 9952 ps.installPermissionsFixed = false; 9953 if (!ps.isSharedUser()) { 9954 origPermissions = new PermissionsState(permissionsState); 9955 permissionsState.reset(); 9956 } else { 9957 // We need to know only about runtime permission changes since the 9958 // calling code always writes the install permissions state but 9959 // the runtime ones are written only if changed. The only cases of 9960 // changed runtime permissions here are promotion of an install to 9961 // runtime and revocation of a runtime from a shared user. 9962 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9963 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9964 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9965 runtimePermissionsRevoked = true; 9966 } 9967 } 9968 } 9969 9970 permissionsState.setGlobalGids(mGlobalGids); 9971 9972 final int N = pkg.requestedPermissions.size(); 9973 for (int i=0; i<N; i++) { 9974 final String name = pkg.requestedPermissions.get(i); 9975 final BasePermission bp = mSettings.mPermissions.get(name); 9976 9977 if (DEBUG_INSTALL) { 9978 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9979 } 9980 9981 if (bp == null || bp.packageSetting == null) { 9982 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9983 Slog.w(TAG, "Unknown permission " + name 9984 + " in package " + pkg.packageName); 9985 } 9986 continue; 9987 } 9988 9989 final String perm = bp.name; 9990 boolean allowedSig = false; 9991 int grant = GRANT_DENIED; 9992 9993 // Keep track of app op permissions. 9994 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9995 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9996 if (pkgs == null) { 9997 pkgs = new ArraySet<>(); 9998 mAppOpPermissionPackages.put(bp.name, pkgs); 9999 } 10000 pkgs.add(pkg.packageName); 10001 } 10002 10003 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10004 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10005 >= Build.VERSION_CODES.M; 10006 switch (level) { 10007 case PermissionInfo.PROTECTION_NORMAL: { 10008 // For all apps normal permissions are install time ones. 10009 grant = GRANT_INSTALL; 10010 } break; 10011 10012 case PermissionInfo.PROTECTION_DANGEROUS: { 10013 // If a permission review is required for legacy apps we represent 10014 // their permissions as always granted runtime ones since we need 10015 // to keep the review required permission flag per user while an 10016 // install permission's state is shared across all users. 10017 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10018 // For legacy apps dangerous permissions are install time ones. 10019 grant = GRANT_INSTALL; 10020 } else if (origPermissions.hasInstallPermission(bp.name)) { 10021 // For legacy apps that became modern, install becomes runtime. 10022 grant = GRANT_UPGRADE; 10023 } else if (mPromoteSystemApps 10024 && isSystemApp(ps) 10025 && mExistingSystemPackages.contains(ps.name)) { 10026 // For legacy system apps, install becomes runtime. 10027 // We cannot check hasInstallPermission() for system apps since those 10028 // permissions were granted implicitly and not persisted pre-M. 10029 grant = GRANT_UPGRADE; 10030 } else { 10031 // For modern apps keep runtime permissions unchanged. 10032 grant = GRANT_RUNTIME; 10033 } 10034 } break; 10035 10036 case PermissionInfo.PROTECTION_SIGNATURE: { 10037 // For all apps signature permissions are install time ones. 10038 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10039 if (allowedSig) { 10040 grant = GRANT_INSTALL; 10041 } 10042 } break; 10043 } 10044 10045 if (DEBUG_INSTALL) { 10046 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10047 } 10048 10049 if (grant != GRANT_DENIED) { 10050 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10051 // If this is an existing, non-system package, then 10052 // we can't add any new permissions to it. 10053 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10054 // Except... if this is a permission that was added 10055 // to the platform (note: need to only do this when 10056 // updating the platform). 10057 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10058 grant = GRANT_DENIED; 10059 } 10060 } 10061 } 10062 10063 switch (grant) { 10064 case GRANT_INSTALL: { 10065 // Revoke this as runtime permission to handle the case of 10066 // a runtime permission being downgraded to an install one. 10067 // Also in permission review mode we keep dangerous permissions 10068 // for legacy apps 10069 for (int userId : UserManagerService.getInstance().getUserIds()) { 10070 if (origPermissions.getRuntimePermissionState( 10071 bp.name, userId) != null) { 10072 // Revoke the runtime permission and clear the flags. 10073 origPermissions.revokeRuntimePermission(bp, userId); 10074 origPermissions.updatePermissionFlags(bp, userId, 10075 PackageManager.MASK_PERMISSION_FLAGS, 0); 10076 // If we revoked a permission permission, we have to write. 10077 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10078 changedRuntimePermissionUserIds, userId); 10079 } 10080 } 10081 // Grant an install permission. 10082 if (permissionsState.grantInstallPermission(bp) != 10083 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10084 changedInstallPermission = true; 10085 } 10086 } break; 10087 10088 case GRANT_RUNTIME: { 10089 // Grant previously granted runtime permissions. 10090 for (int userId : UserManagerService.getInstance().getUserIds()) { 10091 PermissionState permissionState = origPermissions 10092 .getRuntimePermissionState(bp.name, userId); 10093 int flags = permissionState != null 10094 ? permissionState.getFlags() : 0; 10095 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10096 if (permissionsState.grantRuntimePermission(bp, userId) == 10097 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10098 // If we cannot put the permission as it was, we have to write. 10099 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10100 changedRuntimePermissionUserIds, userId); 10101 } 10102 // If the app supports runtime permissions no need for a review. 10103 if (Build.PERMISSIONS_REVIEW_REQUIRED 10104 && appSupportsRuntimePermissions 10105 && (flags & PackageManager 10106 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10107 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10108 // Since we changed the flags, we have to write. 10109 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10110 changedRuntimePermissionUserIds, userId); 10111 } 10112 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10113 && !appSupportsRuntimePermissions) { 10114 // For legacy apps that need a permission review, every new 10115 // runtime permission is granted but it is pending a review. 10116 // We also need to review only platform defined runtime 10117 // permissions as these are the only ones the platform knows 10118 // how to disable the API to simulate revocation as legacy 10119 // apps don't expect to run with revoked permissions. 10120 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10121 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10122 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10123 // We changed the flags, hence have to write. 10124 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10125 changedRuntimePermissionUserIds, userId); 10126 } 10127 } 10128 if (permissionsState.grantRuntimePermission(bp, userId) 10129 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10130 // We changed the permission, hence have to write. 10131 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10132 changedRuntimePermissionUserIds, userId); 10133 } 10134 } 10135 // Propagate the permission flags. 10136 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10137 } 10138 } break; 10139 10140 case GRANT_UPGRADE: { 10141 // Grant runtime permissions for a previously held install permission. 10142 PermissionState permissionState = origPermissions 10143 .getInstallPermissionState(bp.name); 10144 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10145 10146 if (origPermissions.revokeInstallPermission(bp) 10147 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10148 // We will be transferring the permission flags, so clear them. 10149 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10150 PackageManager.MASK_PERMISSION_FLAGS, 0); 10151 changedInstallPermission = true; 10152 } 10153 10154 // If the permission is not to be promoted to runtime we ignore it and 10155 // also its other flags as they are not applicable to install permissions. 10156 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10157 for (int userId : currentUserIds) { 10158 if (permissionsState.grantRuntimePermission(bp, userId) != 10159 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10160 // Transfer the permission flags. 10161 permissionsState.updatePermissionFlags(bp, userId, 10162 flags, flags); 10163 // If we granted the permission, we have to write. 10164 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10165 changedRuntimePermissionUserIds, userId); 10166 } 10167 } 10168 } 10169 } break; 10170 10171 default: { 10172 if (packageOfInterest == null 10173 || packageOfInterest.equals(pkg.packageName)) { 10174 Slog.w(TAG, "Not granting permission " + perm 10175 + " to package " + pkg.packageName 10176 + " because it was previously installed without"); 10177 } 10178 } break; 10179 } 10180 } else { 10181 if (permissionsState.revokeInstallPermission(bp) != 10182 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10183 // Also drop the permission flags. 10184 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10185 PackageManager.MASK_PERMISSION_FLAGS, 0); 10186 changedInstallPermission = true; 10187 Slog.i(TAG, "Un-granting permission " + perm 10188 + " from package " + pkg.packageName 10189 + " (protectionLevel=" + bp.protectionLevel 10190 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10191 + ")"); 10192 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10193 // Don't print warning for app op permissions, since it is fine for them 10194 // not to be granted, there is a UI for the user to decide. 10195 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10196 Slog.w(TAG, "Not granting permission " + perm 10197 + " to package " + pkg.packageName 10198 + " (protectionLevel=" + bp.protectionLevel 10199 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10200 + ")"); 10201 } 10202 } 10203 } 10204 } 10205 10206 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10207 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10208 // This is the first that we have heard about this package, so the 10209 // permissions we have now selected are fixed until explicitly 10210 // changed. 10211 ps.installPermissionsFixed = true; 10212 } 10213 10214 // Persist the runtime permissions state for users with changes. If permissions 10215 // were revoked because no app in the shared user declares them we have to 10216 // write synchronously to avoid losing runtime permissions state. 10217 for (int userId : changedRuntimePermissionUserIds) { 10218 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10219 } 10220 10221 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10222 } 10223 10224 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10225 boolean allowed = false; 10226 final int NP = PackageParser.NEW_PERMISSIONS.length; 10227 for (int ip=0; ip<NP; ip++) { 10228 final PackageParser.NewPermissionInfo npi 10229 = PackageParser.NEW_PERMISSIONS[ip]; 10230 if (npi.name.equals(perm) 10231 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10232 allowed = true; 10233 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10234 + pkg.packageName); 10235 break; 10236 } 10237 } 10238 return allowed; 10239 } 10240 10241 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10242 BasePermission bp, PermissionsState origPermissions) { 10243 boolean allowed; 10244 allowed = (compareSignatures( 10245 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10246 == PackageManager.SIGNATURE_MATCH) 10247 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10248 == PackageManager.SIGNATURE_MATCH); 10249 if (!allowed && (bp.protectionLevel 10250 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10251 if (isSystemApp(pkg)) { 10252 // For updated system applications, a system permission 10253 // is granted only if it had been defined by the original application. 10254 if (pkg.isUpdatedSystemApp()) { 10255 final PackageSetting sysPs = mSettings 10256 .getDisabledSystemPkgLPr(pkg.packageName); 10257 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10258 // If the original was granted this permission, we take 10259 // that grant decision as read and propagate it to the 10260 // update. 10261 if (sysPs.isPrivileged()) { 10262 allowed = true; 10263 } 10264 } else { 10265 // The system apk may have been updated with an older 10266 // version of the one on the data partition, but which 10267 // granted a new system permission that it didn't have 10268 // before. In this case we do want to allow the app to 10269 // now get the new permission if the ancestral apk is 10270 // privileged to get it. 10271 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10272 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10273 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10274 allowed = true; 10275 break; 10276 } 10277 } 10278 } 10279 // Also if a privileged parent package on the system image or any of 10280 // its children requested a privileged permission, the updated child 10281 // packages can also get the permission. 10282 if (pkg.parentPackage != null) { 10283 final PackageSetting disabledSysParentPs = mSettings 10284 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10285 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10286 && disabledSysParentPs.isPrivileged()) { 10287 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10288 allowed = true; 10289 } else if (disabledSysParentPs.pkg.childPackages != null) { 10290 final int count = disabledSysParentPs.pkg.childPackages.size(); 10291 for (int i = 0; i < count; i++) { 10292 PackageParser.Package disabledSysChildPkg = 10293 disabledSysParentPs.pkg.childPackages.get(i); 10294 if (isPackageRequestingPermission(disabledSysChildPkg, 10295 perm)) { 10296 allowed = true; 10297 break; 10298 } 10299 } 10300 } 10301 } 10302 } 10303 } 10304 } else { 10305 allowed = isPrivilegedApp(pkg); 10306 } 10307 } 10308 } 10309 if (!allowed) { 10310 if (!allowed && (bp.protectionLevel 10311 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10312 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10313 // If this was a previously normal/dangerous permission that got moved 10314 // to a system permission as part of the runtime permission redesign, then 10315 // we still want to blindly grant it to old apps. 10316 allowed = true; 10317 } 10318 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10319 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10320 // If this permission is to be granted to the system installer and 10321 // this app is an installer, then it gets the permission. 10322 allowed = true; 10323 } 10324 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10325 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10326 // If this permission is to be granted to the system verifier and 10327 // this app is a verifier, then it gets the permission. 10328 allowed = true; 10329 } 10330 if (!allowed && (bp.protectionLevel 10331 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10332 && isSystemApp(pkg)) { 10333 // Any pre-installed system app is allowed to get this permission. 10334 allowed = true; 10335 } 10336 if (!allowed && (bp.protectionLevel 10337 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10338 // For development permissions, a development permission 10339 // is granted only if it was already granted. 10340 allowed = origPermissions.hasInstallPermission(perm); 10341 } 10342 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10343 && pkg.packageName.equals(mSetupWizardPackage)) { 10344 // If this permission is to be granted to the system setup wizard and 10345 // this app is a setup wizard, then it gets the permission. 10346 allowed = true; 10347 } 10348 } 10349 return allowed; 10350 } 10351 10352 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10353 final int permCount = pkg.requestedPermissions.size(); 10354 for (int j = 0; j < permCount; j++) { 10355 String requestedPermission = pkg.requestedPermissions.get(j); 10356 if (permission.equals(requestedPermission)) { 10357 return true; 10358 } 10359 } 10360 return false; 10361 } 10362 10363 final class ActivityIntentResolver 10364 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10365 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10366 boolean defaultOnly, int userId) { 10367 if (!sUserManager.exists(userId)) return null; 10368 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10369 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10370 } 10371 10372 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10373 int userId) { 10374 if (!sUserManager.exists(userId)) return null; 10375 mFlags = flags; 10376 return super.queryIntent(intent, resolvedType, 10377 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10378 } 10379 10380 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10381 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10382 if (!sUserManager.exists(userId)) return null; 10383 if (packageActivities == null) { 10384 return null; 10385 } 10386 mFlags = flags; 10387 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10388 final int N = packageActivities.size(); 10389 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10390 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10391 10392 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10393 for (int i = 0; i < N; ++i) { 10394 intentFilters = packageActivities.get(i).intents; 10395 if (intentFilters != null && intentFilters.size() > 0) { 10396 PackageParser.ActivityIntentInfo[] array = 10397 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10398 intentFilters.toArray(array); 10399 listCut.add(array); 10400 } 10401 } 10402 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10403 } 10404 10405 /** 10406 * Finds a privileged activity that matches the specified activity names. 10407 */ 10408 private PackageParser.Activity findMatchingActivity( 10409 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10410 for (PackageParser.Activity sysActivity : activityList) { 10411 if (sysActivity.info.name.equals(activityInfo.name)) { 10412 return sysActivity; 10413 } 10414 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10415 return sysActivity; 10416 } 10417 if (sysActivity.info.targetActivity != null) { 10418 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10419 return sysActivity; 10420 } 10421 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10422 return sysActivity; 10423 } 10424 } 10425 } 10426 return null; 10427 } 10428 10429 public class IterGenerator<E> { 10430 public Iterator<E> generate(ActivityIntentInfo info) { 10431 return null; 10432 } 10433 } 10434 10435 public class ActionIterGenerator extends IterGenerator<String> { 10436 @Override 10437 public Iterator<String> generate(ActivityIntentInfo info) { 10438 return info.actionsIterator(); 10439 } 10440 } 10441 10442 public class CategoriesIterGenerator extends IterGenerator<String> { 10443 @Override 10444 public Iterator<String> generate(ActivityIntentInfo info) { 10445 return info.categoriesIterator(); 10446 } 10447 } 10448 10449 public class SchemesIterGenerator extends IterGenerator<String> { 10450 @Override 10451 public Iterator<String> generate(ActivityIntentInfo info) { 10452 return info.schemesIterator(); 10453 } 10454 } 10455 10456 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10457 @Override 10458 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10459 return info.authoritiesIterator(); 10460 } 10461 } 10462 10463 /** 10464 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10465 * MODIFIED. Do not pass in a list that should not be changed. 10466 */ 10467 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10468 IterGenerator<T> generator, Iterator<T> searchIterator) { 10469 // loop through the set of actions; every one must be found in the intent filter 10470 while (searchIterator.hasNext()) { 10471 // we must have at least one filter in the list to consider a match 10472 if (intentList.size() == 0) { 10473 break; 10474 } 10475 10476 final T searchAction = searchIterator.next(); 10477 10478 // loop through the set of intent filters 10479 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10480 while (intentIter.hasNext()) { 10481 final ActivityIntentInfo intentInfo = intentIter.next(); 10482 boolean selectionFound = false; 10483 10484 // loop through the intent filter's selection criteria; at least one 10485 // of them must match the searched criteria 10486 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10487 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10488 final T intentSelection = intentSelectionIter.next(); 10489 if (intentSelection != null && intentSelection.equals(searchAction)) { 10490 selectionFound = true; 10491 break; 10492 } 10493 } 10494 10495 // the selection criteria wasn't found in this filter's set; this filter 10496 // is not a potential match 10497 if (!selectionFound) { 10498 intentIter.remove(); 10499 } 10500 } 10501 } 10502 } 10503 10504 private boolean isProtectedAction(ActivityIntentInfo filter) { 10505 final Iterator<String> actionsIter = filter.actionsIterator(); 10506 while (actionsIter != null && actionsIter.hasNext()) { 10507 final String filterAction = actionsIter.next(); 10508 if (PROTECTED_ACTIONS.contains(filterAction)) { 10509 return true; 10510 } 10511 } 10512 return false; 10513 } 10514 10515 /** 10516 * Adjusts the priority of the given intent filter according to policy. 10517 * <p> 10518 * <ul> 10519 * <li>The priority for non privileged applications is capped to '0'</li> 10520 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10521 * <li>The priority for unbundled updates to privileged applications is capped to the 10522 * priority defined on the system partition</li> 10523 * </ul> 10524 * <p> 10525 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10526 * allowed to obtain any priority on any action. 10527 */ 10528 private void adjustPriority( 10529 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10530 // nothing to do; priority is fine as-is 10531 if (intent.getPriority() <= 0) { 10532 return; 10533 } 10534 10535 final ActivityInfo activityInfo = intent.activity.info; 10536 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10537 10538 final boolean privilegedApp = 10539 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10540 if (!privilegedApp) { 10541 // non-privileged applications can never define a priority >0 10542 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10543 + " package: " + applicationInfo.packageName 10544 + " activity: " + intent.activity.className 10545 + " origPrio: " + intent.getPriority()); 10546 intent.setPriority(0); 10547 return; 10548 } 10549 10550 if (systemActivities == null) { 10551 // the system package is not disabled; we're parsing the system partition 10552 if (isProtectedAction(intent)) { 10553 if (mDeferProtectedFilters) { 10554 // We can't deal with these just yet. No component should ever obtain a 10555 // >0 priority for a protected actions, with ONE exception -- the setup 10556 // wizard. The setup wizard, however, cannot be known until we're able to 10557 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10558 // until all intent filters have been processed. Chicken, meet egg. 10559 // Let the filter temporarily have a high priority and rectify the 10560 // priorities after all system packages have been scanned. 10561 mProtectedFilters.add(intent); 10562 if (DEBUG_FILTERS) { 10563 Slog.i(TAG, "Protected action; save for later;" 10564 + " package: " + applicationInfo.packageName 10565 + " activity: " + intent.activity.className 10566 + " origPrio: " + intent.getPriority()); 10567 } 10568 return; 10569 } else { 10570 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10571 Slog.i(TAG, "No setup wizard;" 10572 + " All protected intents capped to priority 0"); 10573 } 10574 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10575 if (DEBUG_FILTERS) { 10576 Slog.i(TAG, "Found setup wizard;" 10577 + " allow priority " + intent.getPriority() + ";" 10578 + " package: " + intent.activity.info.packageName 10579 + " activity: " + intent.activity.className 10580 + " priority: " + intent.getPriority()); 10581 } 10582 // setup wizard gets whatever it wants 10583 return; 10584 } 10585 Slog.w(TAG, "Protected action; cap priority to 0;" 10586 + " package: " + intent.activity.info.packageName 10587 + " activity: " + intent.activity.className 10588 + " origPrio: " + intent.getPriority()); 10589 intent.setPriority(0); 10590 return; 10591 } 10592 } 10593 // privileged apps on the system image get whatever priority they request 10594 return; 10595 } 10596 10597 // privileged app unbundled update ... try to find the same activity 10598 final PackageParser.Activity foundActivity = 10599 findMatchingActivity(systemActivities, activityInfo); 10600 if (foundActivity == null) { 10601 // this is a new activity; it cannot obtain >0 priority 10602 if (DEBUG_FILTERS) { 10603 Slog.i(TAG, "New activity; cap priority to 0;" 10604 + " package: " + applicationInfo.packageName 10605 + " activity: " + intent.activity.className 10606 + " origPrio: " + intent.getPriority()); 10607 } 10608 intent.setPriority(0); 10609 return; 10610 } 10611 10612 // found activity, now check for filter equivalence 10613 10614 // a shallow copy is enough; we modify the list, not its contents 10615 final List<ActivityIntentInfo> intentListCopy = 10616 new ArrayList<>(foundActivity.intents); 10617 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10618 10619 // find matching action subsets 10620 final Iterator<String> actionsIterator = intent.actionsIterator(); 10621 if (actionsIterator != null) { 10622 getIntentListSubset( 10623 intentListCopy, new ActionIterGenerator(), actionsIterator); 10624 if (intentListCopy.size() == 0) { 10625 // no more intents to match; we're not equivalent 10626 if (DEBUG_FILTERS) { 10627 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10628 + " package: " + applicationInfo.packageName 10629 + " activity: " + intent.activity.className 10630 + " origPrio: " + intent.getPriority()); 10631 } 10632 intent.setPriority(0); 10633 return; 10634 } 10635 } 10636 10637 // find matching category subsets 10638 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10639 if (categoriesIterator != null) { 10640 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10641 categoriesIterator); 10642 if (intentListCopy.size() == 0) { 10643 // no more intents to match; we're not equivalent 10644 if (DEBUG_FILTERS) { 10645 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10646 + " package: " + applicationInfo.packageName 10647 + " activity: " + intent.activity.className 10648 + " origPrio: " + intent.getPriority()); 10649 } 10650 intent.setPriority(0); 10651 return; 10652 } 10653 } 10654 10655 // find matching schemes subsets 10656 final Iterator<String> schemesIterator = intent.schemesIterator(); 10657 if (schemesIterator != null) { 10658 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10659 schemesIterator); 10660 if (intentListCopy.size() == 0) { 10661 // no more intents to match; we're not equivalent 10662 if (DEBUG_FILTERS) { 10663 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10664 + " package: " + applicationInfo.packageName 10665 + " activity: " + intent.activity.className 10666 + " origPrio: " + intent.getPriority()); 10667 } 10668 intent.setPriority(0); 10669 return; 10670 } 10671 } 10672 10673 // find matching authorities subsets 10674 final Iterator<IntentFilter.AuthorityEntry> 10675 authoritiesIterator = intent.authoritiesIterator(); 10676 if (authoritiesIterator != null) { 10677 getIntentListSubset(intentListCopy, 10678 new AuthoritiesIterGenerator(), 10679 authoritiesIterator); 10680 if (intentListCopy.size() == 0) { 10681 // no more intents to match; we're not equivalent 10682 if (DEBUG_FILTERS) { 10683 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10684 + " package: " + applicationInfo.packageName 10685 + " activity: " + intent.activity.className 10686 + " origPrio: " + intent.getPriority()); 10687 } 10688 intent.setPriority(0); 10689 return; 10690 } 10691 } 10692 10693 // we found matching filter(s); app gets the max priority of all intents 10694 int cappedPriority = 0; 10695 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10696 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10697 } 10698 if (intent.getPriority() > cappedPriority) { 10699 if (DEBUG_FILTERS) { 10700 Slog.i(TAG, "Found matching filter(s);" 10701 + " cap priority to " + cappedPriority + ";" 10702 + " package: " + applicationInfo.packageName 10703 + " activity: " + intent.activity.className 10704 + " origPrio: " + intent.getPriority()); 10705 } 10706 intent.setPriority(cappedPriority); 10707 return; 10708 } 10709 // all this for nothing; the requested priority was <= what was on the system 10710 } 10711 10712 public final void addActivity(PackageParser.Activity a, String type) { 10713 mActivities.put(a.getComponentName(), a); 10714 if (DEBUG_SHOW_INFO) 10715 Log.v( 10716 TAG, " " + type + " " + 10717 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10718 if (DEBUG_SHOW_INFO) 10719 Log.v(TAG, " Class=" + a.info.name); 10720 final int NI = a.intents.size(); 10721 for (int j=0; j<NI; j++) { 10722 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10723 if ("activity".equals(type)) { 10724 final PackageSetting ps = 10725 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10726 final List<PackageParser.Activity> systemActivities = 10727 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10728 adjustPriority(systemActivities, intent); 10729 } 10730 if (DEBUG_SHOW_INFO) { 10731 Log.v(TAG, " IntentFilter:"); 10732 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10733 } 10734 if (!intent.debugCheck()) { 10735 Log.w(TAG, "==> For Activity " + a.info.name); 10736 } 10737 addFilter(intent); 10738 } 10739 } 10740 10741 public final void removeActivity(PackageParser.Activity a, String type) { 10742 mActivities.remove(a.getComponentName()); 10743 if (DEBUG_SHOW_INFO) { 10744 Log.v(TAG, " " + type + " " 10745 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10746 : a.info.name) + ":"); 10747 Log.v(TAG, " Class=" + a.info.name); 10748 } 10749 final int NI = a.intents.size(); 10750 for (int j=0; j<NI; j++) { 10751 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10752 if (DEBUG_SHOW_INFO) { 10753 Log.v(TAG, " IntentFilter:"); 10754 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10755 } 10756 removeFilter(intent); 10757 } 10758 } 10759 10760 @Override 10761 protected boolean allowFilterResult( 10762 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10763 ActivityInfo filterAi = filter.activity.info; 10764 for (int i=dest.size()-1; i>=0; i--) { 10765 ActivityInfo destAi = dest.get(i).activityInfo; 10766 if (destAi.name == filterAi.name 10767 && destAi.packageName == filterAi.packageName) { 10768 return false; 10769 } 10770 } 10771 return true; 10772 } 10773 10774 @Override 10775 protected ActivityIntentInfo[] newArray(int size) { 10776 return new ActivityIntentInfo[size]; 10777 } 10778 10779 @Override 10780 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10781 if (!sUserManager.exists(userId)) return true; 10782 PackageParser.Package p = filter.activity.owner; 10783 if (p != null) { 10784 PackageSetting ps = (PackageSetting)p.mExtras; 10785 if (ps != null) { 10786 // System apps are never considered stopped for purposes of 10787 // filtering, because there may be no way for the user to 10788 // actually re-launch them. 10789 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10790 && ps.getStopped(userId); 10791 } 10792 } 10793 return false; 10794 } 10795 10796 @Override 10797 protected boolean isPackageForFilter(String packageName, 10798 PackageParser.ActivityIntentInfo info) { 10799 return packageName.equals(info.activity.owner.packageName); 10800 } 10801 10802 @Override 10803 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10804 int match, int userId) { 10805 if (!sUserManager.exists(userId)) return null; 10806 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10807 return null; 10808 } 10809 final PackageParser.Activity activity = info.activity; 10810 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10811 if (ps == null) { 10812 return null; 10813 } 10814 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10815 ps.readUserState(userId), userId); 10816 if (ai == null) { 10817 return null; 10818 } 10819 final ResolveInfo res = new ResolveInfo(); 10820 res.activityInfo = ai; 10821 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10822 res.filter = info; 10823 } 10824 if (info != null) { 10825 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10826 } 10827 res.priority = info.getPriority(); 10828 res.preferredOrder = activity.owner.mPreferredOrder; 10829 //System.out.println("Result: " + res.activityInfo.className + 10830 // " = " + res.priority); 10831 res.match = match; 10832 res.isDefault = info.hasDefault; 10833 res.labelRes = info.labelRes; 10834 res.nonLocalizedLabel = info.nonLocalizedLabel; 10835 if (userNeedsBadging(userId)) { 10836 res.noResourceId = true; 10837 } else { 10838 res.icon = info.icon; 10839 } 10840 res.iconResourceId = info.icon; 10841 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10842 return res; 10843 } 10844 10845 @Override 10846 protected void sortResults(List<ResolveInfo> results) { 10847 Collections.sort(results, mResolvePrioritySorter); 10848 } 10849 10850 @Override 10851 protected void dumpFilter(PrintWriter out, String prefix, 10852 PackageParser.ActivityIntentInfo filter) { 10853 out.print(prefix); out.print( 10854 Integer.toHexString(System.identityHashCode(filter.activity))); 10855 out.print(' '); 10856 filter.activity.printComponentShortName(out); 10857 out.print(" filter "); 10858 out.println(Integer.toHexString(System.identityHashCode(filter))); 10859 } 10860 10861 @Override 10862 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10863 return filter.activity; 10864 } 10865 10866 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10867 PackageParser.Activity activity = (PackageParser.Activity)label; 10868 out.print(prefix); out.print( 10869 Integer.toHexString(System.identityHashCode(activity))); 10870 out.print(' '); 10871 activity.printComponentShortName(out); 10872 if (count > 1) { 10873 out.print(" ("); out.print(count); out.print(" filters)"); 10874 } 10875 out.println(); 10876 } 10877 10878 // Keys are String (activity class name), values are Activity. 10879 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10880 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10881 private int mFlags; 10882 } 10883 10884 private final class ServiceIntentResolver 10885 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10886 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10887 boolean defaultOnly, int userId) { 10888 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10889 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10890 } 10891 10892 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10893 int userId) { 10894 if (!sUserManager.exists(userId)) return null; 10895 mFlags = flags; 10896 return super.queryIntent(intent, resolvedType, 10897 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10898 } 10899 10900 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10901 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10902 if (!sUserManager.exists(userId)) return null; 10903 if (packageServices == null) { 10904 return null; 10905 } 10906 mFlags = flags; 10907 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10908 final int N = packageServices.size(); 10909 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10910 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10911 10912 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10913 for (int i = 0; i < N; ++i) { 10914 intentFilters = packageServices.get(i).intents; 10915 if (intentFilters != null && intentFilters.size() > 0) { 10916 PackageParser.ServiceIntentInfo[] array = 10917 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10918 intentFilters.toArray(array); 10919 listCut.add(array); 10920 } 10921 } 10922 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10923 } 10924 10925 public final void addService(PackageParser.Service s) { 10926 mServices.put(s.getComponentName(), s); 10927 if (DEBUG_SHOW_INFO) { 10928 Log.v(TAG, " " 10929 + (s.info.nonLocalizedLabel != null 10930 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10931 Log.v(TAG, " Class=" + s.info.name); 10932 } 10933 final int NI = s.intents.size(); 10934 int j; 10935 for (j=0; j<NI; j++) { 10936 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10937 if (DEBUG_SHOW_INFO) { 10938 Log.v(TAG, " IntentFilter:"); 10939 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10940 } 10941 if (!intent.debugCheck()) { 10942 Log.w(TAG, "==> For Service " + s.info.name); 10943 } 10944 addFilter(intent); 10945 } 10946 } 10947 10948 public final void removeService(PackageParser.Service s) { 10949 mServices.remove(s.getComponentName()); 10950 if (DEBUG_SHOW_INFO) { 10951 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10952 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10953 Log.v(TAG, " Class=" + s.info.name); 10954 } 10955 final int NI = s.intents.size(); 10956 int j; 10957 for (j=0; j<NI; j++) { 10958 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10959 if (DEBUG_SHOW_INFO) { 10960 Log.v(TAG, " IntentFilter:"); 10961 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10962 } 10963 removeFilter(intent); 10964 } 10965 } 10966 10967 @Override 10968 protected boolean allowFilterResult( 10969 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10970 ServiceInfo filterSi = filter.service.info; 10971 for (int i=dest.size()-1; i>=0; i--) { 10972 ServiceInfo destAi = dest.get(i).serviceInfo; 10973 if (destAi.name == filterSi.name 10974 && destAi.packageName == filterSi.packageName) { 10975 return false; 10976 } 10977 } 10978 return true; 10979 } 10980 10981 @Override 10982 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10983 return new PackageParser.ServiceIntentInfo[size]; 10984 } 10985 10986 @Override 10987 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10988 if (!sUserManager.exists(userId)) return true; 10989 PackageParser.Package p = filter.service.owner; 10990 if (p != null) { 10991 PackageSetting ps = (PackageSetting)p.mExtras; 10992 if (ps != null) { 10993 // System apps are never considered stopped for purposes of 10994 // filtering, because there may be no way for the user to 10995 // actually re-launch them. 10996 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10997 && ps.getStopped(userId); 10998 } 10999 } 11000 return false; 11001 } 11002 11003 @Override 11004 protected boolean isPackageForFilter(String packageName, 11005 PackageParser.ServiceIntentInfo info) { 11006 return packageName.equals(info.service.owner.packageName); 11007 } 11008 11009 @Override 11010 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11011 int match, int userId) { 11012 if (!sUserManager.exists(userId)) return null; 11013 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11014 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11015 return null; 11016 } 11017 final PackageParser.Service service = info.service; 11018 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11019 if (ps == null) { 11020 return null; 11021 } 11022 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11023 ps.readUserState(userId), userId); 11024 if (si == null) { 11025 return null; 11026 } 11027 final ResolveInfo res = new ResolveInfo(); 11028 res.serviceInfo = si; 11029 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11030 res.filter = filter; 11031 } 11032 res.priority = info.getPriority(); 11033 res.preferredOrder = service.owner.mPreferredOrder; 11034 res.match = match; 11035 res.isDefault = info.hasDefault; 11036 res.labelRes = info.labelRes; 11037 res.nonLocalizedLabel = info.nonLocalizedLabel; 11038 res.icon = info.icon; 11039 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11040 return res; 11041 } 11042 11043 @Override 11044 protected void sortResults(List<ResolveInfo> results) { 11045 Collections.sort(results, mResolvePrioritySorter); 11046 } 11047 11048 @Override 11049 protected void dumpFilter(PrintWriter out, String prefix, 11050 PackageParser.ServiceIntentInfo filter) { 11051 out.print(prefix); out.print( 11052 Integer.toHexString(System.identityHashCode(filter.service))); 11053 out.print(' '); 11054 filter.service.printComponentShortName(out); 11055 out.print(" filter "); 11056 out.println(Integer.toHexString(System.identityHashCode(filter))); 11057 } 11058 11059 @Override 11060 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11061 return filter.service; 11062 } 11063 11064 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11065 PackageParser.Service service = (PackageParser.Service)label; 11066 out.print(prefix); out.print( 11067 Integer.toHexString(System.identityHashCode(service))); 11068 out.print(' '); 11069 service.printComponentShortName(out); 11070 if (count > 1) { 11071 out.print(" ("); out.print(count); out.print(" filters)"); 11072 } 11073 out.println(); 11074 } 11075 11076// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11077// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11078// final List<ResolveInfo> retList = Lists.newArrayList(); 11079// while (i.hasNext()) { 11080// final ResolveInfo resolveInfo = (ResolveInfo) i; 11081// if (isEnabledLP(resolveInfo.serviceInfo)) { 11082// retList.add(resolveInfo); 11083// } 11084// } 11085// return retList; 11086// } 11087 11088 // Keys are String (activity class name), values are Activity. 11089 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11090 = new ArrayMap<ComponentName, PackageParser.Service>(); 11091 private int mFlags; 11092 }; 11093 11094 private final class ProviderIntentResolver 11095 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11096 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11097 boolean defaultOnly, int userId) { 11098 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11099 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11100 } 11101 11102 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11103 int userId) { 11104 if (!sUserManager.exists(userId)) 11105 return null; 11106 mFlags = flags; 11107 return super.queryIntent(intent, resolvedType, 11108 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11109 } 11110 11111 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11112 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11113 if (!sUserManager.exists(userId)) 11114 return null; 11115 if (packageProviders == null) { 11116 return null; 11117 } 11118 mFlags = flags; 11119 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11120 final int N = packageProviders.size(); 11121 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11122 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11123 11124 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11125 for (int i = 0; i < N; ++i) { 11126 intentFilters = packageProviders.get(i).intents; 11127 if (intentFilters != null && intentFilters.size() > 0) { 11128 PackageParser.ProviderIntentInfo[] array = 11129 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11130 intentFilters.toArray(array); 11131 listCut.add(array); 11132 } 11133 } 11134 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11135 } 11136 11137 public final void addProvider(PackageParser.Provider p) { 11138 if (mProviders.containsKey(p.getComponentName())) { 11139 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11140 return; 11141 } 11142 11143 mProviders.put(p.getComponentName(), p); 11144 if (DEBUG_SHOW_INFO) { 11145 Log.v(TAG, " " 11146 + (p.info.nonLocalizedLabel != null 11147 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11148 Log.v(TAG, " Class=" + p.info.name); 11149 } 11150 final int NI = p.intents.size(); 11151 int j; 11152 for (j = 0; j < NI; j++) { 11153 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11154 if (DEBUG_SHOW_INFO) { 11155 Log.v(TAG, " IntentFilter:"); 11156 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11157 } 11158 if (!intent.debugCheck()) { 11159 Log.w(TAG, "==> For Provider " + p.info.name); 11160 } 11161 addFilter(intent); 11162 } 11163 } 11164 11165 public final void removeProvider(PackageParser.Provider p) { 11166 mProviders.remove(p.getComponentName()); 11167 if (DEBUG_SHOW_INFO) { 11168 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11169 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11170 Log.v(TAG, " Class=" + p.info.name); 11171 } 11172 final int NI = p.intents.size(); 11173 int j; 11174 for (j = 0; j < NI; j++) { 11175 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11176 if (DEBUG_SHOW_INFO) { 11177 Log.v(TAG, " IntentFilter:"); 11178 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11179 } 11180 removeFilter(intent); 11181 } 11182 } 11183 11184 @Override 11185 protected boolean allowFilterResult( 11186 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11187 ProviderInfo filterPi = filter.provider.info; 11188 for (int i = dest.size() - 1; i >= 0; i--) { 11189 ProviderInfo destPi = dest.get(i).providerInfo; 11190 if (destPi.name == filterPi.name 11191 && destPi.packageName == filterPi.packageName) { 11192 return false; 11193 } 11194 } 11195 return true; 11196 } 11197 11198 @Override 11199 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11200 return new PackageParser.ProviderIntentInfo[size]; 11201 } 11202 11203 @Override 11204 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11205 if (!sUserManager.exists(userId)) 11206 return true; 11207 PackageParser.Package p = filter.provider.owner; 11208 if (p != null) { 11209 PackageSetting ps = (PackageSetting) p.mExtras; 11210 if (ps != null) { 11211 // System apps are never considered stopped for purposes of 11212 // filtering, because there may be no way for the user to 11213 // actually re-launch them. 11214 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11215 && ps.getStopped(userId); 11216 } 11217 } 11218 return false; 11219 } 11220 11221 @Override 11222 protected boolean isPackageForFilter(String packageName, 11223 PackageParser.ProviderIntentInfo info) { 11224 return packageName.equals(info.provider.owner.packageName); 11225 } 11226 11227 @Override 11228 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11229 int match, int userId) { 11230 if (!sUserManager.exists(userId)) 11231 return null; 11232 final PackageParser.ProviderIntentInfo info = filter; 11233 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11234 return null; 11235 } 11236 final PackageParser.Provider provider = info.provider; 11237 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11238 if (ps == null) { 11239 return null; 11240 } 11241 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11242 ps.readUserState(userId), userId); 11243 if (pi == null) { 11244 return null; 11245 } 11246 final ResolveInfo res = new ResolveInfo(); 11247 res.providerInfo = pi; 11248 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11249 res.filter = filter; 11250 } 11251 res.priority = info.getPriority(); 11252 res.preferredOrder = provider.owner.mPreferredOrder; 11253 res.match = match; 11254 res.isDefault = info.hasDefault; 11255 res.labelRes = info.labelRes; 11256 res.nonLocalizedLabel = info.nonLocalizedLabel; 11257 res.icon = info.icon; 11258 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11259 return res; 11260 } 11261 11262 @Override 11263 protected void sortResults(List<ResolveInfo> results) { 11264 Collections.sort(results, mResolvePrioritySorter); 11265 } 11266 11267 @Override 11268 protected void dumpFilter(PrintWriter out, String prefix, 11269 PackageParser.ProviderIntentInfo filter) { 11270 out.print(prefix); 11271 out.print( 11272 Integer.toHexString(System.identityHashCode(filter.provider))); 11273 out.print(' '); 11274 filter.provider.printComponentShortName(out); 11275 out.print(" filter "); 11276 out.println(Integer.toHexString(System.identityHashCode(filter))); 11277 } 11278 11279 @Override 11280 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11281 return filter.provider; 11282 } 11283 11284 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11285 PackageParser.Provider provider = (PackageParser.Provider)label; 11286 out.print(prefix); out.print( 11287 Integer.toHexString(System.identityHashCode(provider))); 11288 out.print(' '); 11289 provider.printComponentShortName(out); 11290 if (count > 1) { 11291 out.print(" ("); out.print(count); out.print(" filters)"); 11292 } 11293 out.println(); 11294 } 11295 11296 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11297 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11298 private int mFlags; 11299 } 11300 11301 private static final class EphemeralIntentResolver 11302 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11303 @Override 11304 protected EphemeralResolveIntentInfo[] newArray(int size) { 11305 return new EphemeralResolveIntentInfo[size]; 11306 } 11307 11308 @Override 11309 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11310 return true; 11311 } 11312 11313 @Override 11314 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11315 int userId) { 11316 if (!sUserManager.exists(userId)) { 11317 return null; 11318 } 11319 return info.getEphemeralResolveInfo(); 11320 } 11321 } 11322 11323 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11324 new Comparator<ResolveInfo>() { 11325 public int compare(ResolveInfo r1, ResolveInfo r2) { 11326 int v1 = r1.priority; 11327 int v2 = r2.priority; 11328 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11329 if (v1 != v2) { 11330 return (v1 > v2) ? -1 : 1; 11331 } 11332 v1 = r1.preferredOrder; 11333 v2 = r2.preferredOrder; 11334 if (v1 != v2) { 11335 return (v1 > v2) ? -1 : 1; 11336 } 11337 if (r1.isDefault != r2.isDefault) { 11338 return r1.isDefault ? -1 : 1; 11339 } 11340 v1 = r1.match; 11341 v2 = r2.match; 11342 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11343 if (v1 != v2) { 11344 return (v1 > v2) ? -1 : 1; 11345 } 11346 if (r1.system != r2.system) { 11347 return r1.system ? -1 : 1; 11348 } 11349 if (r1.activityInfo != null) { 11350 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11351 } 11352 if (r1.serviceInfo != null) { 11353 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11354 } 11355 if (r1.providerInfo != null) { 11356 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11357 } 11358 return 0; 11359 } 11360 }; 11361 11362 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11363 new Comparator<ProviderInfo>() { 11364 public int compare(ProviderInfo p1, ProviderInfo p2) { 11365 final int v1 = p1.initOrder; 11366 final int v2 = p2.initOrder; 11367 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11368 } 11369 }; 11370 11371 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11372 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11373 final int[] userIds) { 11374 mHandler.post(new Runnable() { 11375 @Override 11376 public void run() { 11377 try { 11378 final IActivityManager am = ActivityManagerNative.getDefault(); 11379 if (am == null) return; 11380 final int[] resolvedUserIds; 11381 if (userIds == null) { 11382 resolvedUserIds = am.getRunningUserIds(); 11383 } else { 11384 resolvedUserIds = userIds; 11385 } 11386 for (int id : resolvedUserIds) { 11387 final Intent intent = new Intent(action, 11388 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11389 if (extras != null) { 11390 intent.putExtras(extras); 11391 } 11392 if (targetPkg != null) { 11393 intent.setPackage(targetPkg); 11394 } 11395 // Modify the UID when posting to other users 11396 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11397 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11398 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11399 intent.putExtra(Intent.EXTRA_UID, uid); 11400 } 11401 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11402 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11403 if (DEBUG_BROADCASTS) { 11404 RuntimeException here = new RuntimeException("here"); 11405 here.fillInStackTrace(); 11406 Slog.d(TAG, "Sending to user " + id + ": " 11407 + intent.toShortString(false, true, false, false) 11408 + " " + intent.getExtras(), here); 11409 } 11410 am.broadcastIntent(null, intent, null, finishedReceiver, 11411 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11412 null, finishedReceiver != null, false, id); 11413 } 11414 } catch (RemoteException ex) { 11415 } 11416 } 11417 }); 11418 } 11419 11420 /** 11421 * Check if the external storage media is available. This is true if there 11422 * is a mounted external storage medium or if the external storage is 11423 * emulated. 11424 */ 11425 private boolean isExternalMediaAvailable() { 11426 return mMediaMounted || Environment.isExternalStorageEmulated(); 11427 } 11428 11429 @Override 11430 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11431 // writer 11432 synchronized (mPackages) { 11433 if (!isExternalMediaAvailable()) { 11434 // If the external storage is no longer mounted at this point, 11435 // the caller may not have been able to delete all of this 11436 // packages files and can not delete any more. Bail. 11437 return null; 11438 } 11439 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11440 if (lastPackage != null) { 11441 pkgs.remove(lastPackage); 11442 } 11443 if (pkgs.size() > 0) { 11444 return pkgs.get(0); 11445 } 11446 } 11447 return null; 11448 } 11449 11450 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11451 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11452 userId, andCode ? 1 : 0, packageName); 11453 if (mSystemReady) { 11454 msg.sendToTarget(); 11455 } else { 11456 if (mPostSystemReadyMessages == null) { 11457 mPostSystemReadyMessages = new ArrayList<>(); 11458 } 11459 mPostSystemReadyMessages.add(msg); 11460 } 11461 } 11462 11463 void startCleaningPackages() { 11464 // reader 11465 if (!isExternalMediaAvailable()) { 11466 return; 11467 } 11468 synchronized (mPackages) { 11469 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11470 return; 11471 } 11472 } 11473 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11474 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11475 IActivityManager am = ActivityManagerNative.getDefault(); 11476 if (am != null) { 11477 try { 11478 am.startService(null, intent, null, mContext.getOpPackageName(), 11479 UserHandle.USER_SYSTEM); 11480 } catch (RemoteException e) { 11481 } 11482 } 11483 } 11484 11485 @Override 11486 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11487 int installFlags, String installerPackageName, int userId) { 11488 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11489 11490 final int callingUid = Binder.getCallingUid(); 11491 enforceCrossUserPermission(callingUid, userId, 11492 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11493 11494 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11495 try { 11496 if (observer != null) { 11497 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11498 } 11499 } catch (RemoteException re) { 11500 } 11501 return; 11502 } 11503 11504 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11505 installFlags |= PackageManager.INSTALL_FROM_ADB; 11506 11507 } else { 11508 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11509 // about installerPackageName. 11510 11511 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11512 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11513 } 11514 11515 UserHandle user; 11516 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11517 user = UserHandle.ALL; 11518 } else { 11519 user = new UserHandle(userId); 11520 } 11521 11522 // Only system components can circumvent runtime permissions when installing. 11523 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11524 && mContext.checkCallingOrSelfPermission(Manifest.permission 11525 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11526 throw new SecurityException("You need the " 11527 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11528 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11529 } 11530 11531 final File originFile = new File(originPath); 11532 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11533 11534 final Message msg = mHandler.obtainMessage(INIT_COPY); 11535 final VerificationInfo verificationInfo = new VerificationInfo( 11536 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11537 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11538 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11539 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11540 null /*certificates*/); 11541 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11542 msg.obj = params; 11543 11544 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11545 System.identityHashCode(msg.obj)); 11546 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11547 System.identityHashCode(msg.obj)); 11548 11549 mHandler.sendMessage(msg); 11550 } 11551 11552 void installStage(String packageName, File stagedDir, String stagedCid, 11553 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11554 String installerPackageName, int installerUid, UserHandle user, 11555 Certificate[][] certificates) { 11556 if (DEBUG_EPHEMERAL) { 11557 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11558 Slog.d(TAG, "Ephemeral install of " + packageName); 11559 } 11560 } 11561 final VerificationInfo verificationInfo = new VerificationInfo( 11562 sessionParams.originatingUri, sessionParams.referrerUri, 11563 sessionParams.originatingUid, installerUid); 11564 11565 final OriginInfo origin; 11566 if (stagedDir != null) { 11567 origin = OriginInfo.fromStagedFile(stagedDir); 11568 } else { 11569 origin = OriginInfo.fromStagedContainer(stagedCid); 11570 } 11571 11572 final Message msg = mHandler.obtainMessage(INIT_COPY); 11573 final InstallParams params = new InstallParams(origin, null, observer, 11574 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11575 verificationInfo, user, sessionParams.abiOverride, 11576 sessionParams.grantedRuntimePermissions, certificates); 11577 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11578 msg.obj = params; 11579 11580 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11581 System.identityHashCode(msg.obj)); 11582 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11583 System.identityHashCode(msg.obj)); 11584 11585 mHandler.sendMessage(msg); 11586 } 11587 11588 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11589 int userId) { 11590 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11591 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11592 } 11593 11594 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11595 int appId, int userId) { 11596 Bundle extras = new Bundle(1); 11597 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11598 11599 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11600 packageName, extras, 0, null, null, new int[] {userId}); 11601 try { 11602 IActivityManager am = ActivityManagerNative.getDefault(); 11603 if (isSystem && am.isUserRunning(userId, 0)) { 11604 // The just-installed/enabled app is bundled on the system, so presumed 11605 // to be able to run automatically without needing an explicit launch. 11606 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11607 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11608 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11609 .setPackage(packageName); 11610 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11611 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11612 } 11613 } catch (RemoteException e) { 11614 // shouldn't happen 11615 Slog.w(TAG, "Unable to bootstrap installed package", e); 11616 } 11617 } 11618 11619 @Override 11620 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11621 int userId) { 11622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11623 PackageSetting pkgSetting; 11624 final int uid = Binder.getCallingUid(); 11625 enforceCrossUserPermission(uid, userId, 11626 true /* requireFullPermission */, true /* checkShell */, 11627 "setApplicationHiddenSetting for user " + userId); 11628 11629 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11630 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11631 return false; 11632 } 11633 11634 long callingId = Binder.clearCallingIdentity(); 11635 try { 11636 boolean sendAdded = false; 11637 boolean sendRemoved = false; 11638 // writer 11639 synchronized (mPackages) { 11640 pkgSetting = mSettings.mPackages.get(packageName); 11641 if (pkgSetting == null) { 11642 return false; 11643 } 11644 if (pkgSetting.getHidden(userId) != hidden) { 11645 pkgSetting.setHidden(hidden, userId); 11646 mSettings.writePackageRestrictionsLPr(userId); 11647 if (hidden) { 11648 sendRemoved = true; 11649 } else { 11650 sendAdded = true; 11651 } 11652 } 11653 } 11654 if (sendAdded) { 11655 sendPackageAddedForUser(packageName, pkgSetting, userId); 11656 return true; 11657 } 11658 if (sendRemoved) { 11659 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11660 "hiding pkg"); 11661 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11662 return true; 11663 } 11664 } finally { 11665 Binder.restoreCallingIdentity(callingId); 11666 } 11667 return false; 11668 } 11669 11670 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11671 int userId) { 11672 final PackageRemovedInfo info = new PackageRemovedInfo(); 11673 info.removedPackage = packageName; 11674 info.removedUsers = new int[] {userId}; 11675 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11676 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11677 } 11678 11679 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11680 if (pkgList.length > 0) { 11681 Bundle extras = new Bundle(1); 11682 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11683 11684 sendPackageBroadcast( 11685 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11686 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11687 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11688 new int[] {userId}); 11689 } 11690 } 11691 11692 /** 11693 * Returns true if application is not found or there was an error. Otherwise it returns 11694 * the hidden state of the package for the given user. 11695 */ 11696 @Override 11697 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11698 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11699 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11700 true /* requireFullPermission */, false /* checkShell */, 11701 "getApplicationHidden for user " + userId); 11702 PackageSetting pkgSetting; 11703 long callingId = Binder.clearCallingIdentity(); 11704 try { 11705 // writer 11706 synchronized (mPackages) { 11707 pkgSetting = mSettings.mPackages.get(packageName); 11708 if (pkgSetting == null) { 11709 return true; 11710 } 11711 return pkgSetting.getHidden(userId); 11712 } 11713 } finally { 11714 Binder.restoreCallingIdentity(callingId); 11715 } 11716 } 11717 11718 /** 11719 * @hide 11720 */ 11721 @Override 11722 public int installExistingPackageAsUser(String packageName, int userId) { 11723 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11724 null); 11725 PackageSetting pkgSetting; 11726 final int uid = Binder.getCallingUid(); 11727 enforceCrossUserPermission(uid, userId, 11728 true /* requireFullPermission */, true /* checkShell */, 11729 "installExistingPackage for user " + userId); 11730 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11731 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11732 } 11733 11734 long callingId = Binder.clearCallingIdentity(); 11735 try { 11736 boolean installed = false; 11737 11738 // writer 11739 synchronized (mPackages) { 11740 pkgSetting = mSettings.mPackages.get(packageName); 11741 if (pkgSetting == null) { 11742 return PackageManager.INSTALL_FAILED_INVALID_URI; 11743 } 11744 if (!pkgSetting.getInstalled(userId)) { 11745 pkgSetting.setInstalled(true, userId); 11746 pkgSetting.setHidden(false, userId); 11747 mSettings.writePackageRestrictionsLPr(userId); 11748 installed = true; 11749 } 11750 } 11751 11752 if (installed) { 11753 if (pkgSetting.pkg != null) { 11754 synchronized (mInstallLock) { 11755 // We don't need to freeze for a brand new install 11756 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11757 } 11758 } 11759 sendPackageAddedForUser(packageName, pkgSetting, userId); 11760 } 11761 } finally { 11762 Binder.restoreCallingIdentity(callingId); 11763 } 11764 11765 return PackageManager.INSTALL_SUCCEEDED; 11766 } 11767 11768 boolean isUserRestricted(int userId, String restrictionKey) { 11769 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11770 if (restrictions.getBoolean(restrictionKey, false)) { 11771 Log.w(TAG, "User is restricted: " + restrictionKey); 11772 return true; 11773 } 11774 return false; 11775 } 11776 11777 @Override 11778 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11779 int userId) { 11780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11781 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11782 true /* requireFullPermission */, true /* checkShell */, 11783 "setPackagesSuspended for user " + userId); 11784 11785 if (ArrayUtils.isEmpty(packageNames)) { 11786 return packageNames; 11787 } 11788 11789 // List of package names for whom the suspended state has changed. 11790 List<String> changedPackages = new ArrayList<>(packageNames.length); 11791 // List of package names for whom the suspended state is not set as requested in this 11792 // method. 11793 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11794 long callingId = Binder.clearCallingIdentity(); 11795 try { 11796 for (int i = 0; i < packageNames.length; i++) { 11797 String packageName = packageNames[i]; 11798 boolean changed = false; 11799 final int appId; 11800 synchronized (mPackages) { 11801 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11802 if (pkgSetting == null) { 11803 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11804 + "\". Skipping suspending/un-suspending."); 11805 unactionedPackages.add(packageName); 11806 continue; 11807 } 11808 appId = pkgSetting.appId; 11809 if (pkgSetting.getSuspended(userId) != suspended) { 11810 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11811 unactionedPackages.add(packageName); 11812 continue; 11813 } 11814 pkgSetting.setSuspended(suspended, userId); 11815 mSettings.writePackageRestrictionsLPr(userId); 11816 changed = true; 11817 changedPackages.add(packageName); 11818 } 11819 } 11820 11821 if (changed && suspended) { 11822 killApplication(packageName, UserHandle.getUid(userId, appId), 11823 "suspending package"); 11824 } 11825 } 11826 } finally { 11827 Binder.restoreCallingIdentity(callingId); 11828 } 11829 11830 if (!changedPackages.isEmpty()) { 11831 sendPackagesSuspendedForUser(changedPackages.toArray( 11832 new String[changedPackages.size()]), userId, suspended); 11833 } 11834 11835 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11836 } 11837 11838 @Override 11839 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11840 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11841 true /* requireFullPermission */, false /* checkShell */, 11842 "isPackageSuspendedForUser for user " + userId); 11843 synchronized (mPackages) { 11844 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11845 if (pkgSetting == null) { 11846 throw new IllegalArgumentException("Unknown target package: " + packageName); 11847 } 11848 return pkgSetting.getSuspended(userId); 11849 } 11850 } 11851 11852 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11853 if (isPackageDeviceAdmin(packageName, userId)) { 11854 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11855 + "\": has an active device admin"); 11856 return false; 11857 } 11858 11859 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11860 if (packageName.equals(activeLauncherPackageName)) { 11861 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11862 + "\": contains the active launcher"); 11863 return false; 11864 } 11865 11866 if (packageName.equals(mRequiredInstallerPackage)) { 11867 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11868 + "\": required for package installation"); 11869 return false; 11870 } 11871 11872 if (packageName.equals(mRequiredVerifierPackage)) { 11873 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11874 + "\": required for package verification"); 11875 return false; 11876 } 11877 11878 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11879 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11880 + "\": is the default dialer"); 11881 return false; 11882 } 11883 11884 return true; 11885 } 11886 11887 private String getActiveLauncherPackageName(int userId) { 11888 Intent intent = new Intent(Intent.ACTION_MAIN); 11889 intent.addCategory(Intent.CATEGORY_HOME); 11890 ResolveInfo resolveInfo = resolveIntent( 11891 intent, 11892 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11893 PackageManager.MATCH_DEFAULT_ONLY, 11894 userId); 11895 11896 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11897 } 11898 11899 private String getDefaultDialerPackageName(int userId) { 11900 synchronized (mPackages) { 11901 return mSettings.getDefaultDialerPackageNameLPw(userId); 11902 } 11903 } 11904 11905 @Override 11906 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11907 mContext.enforceCallingOrSelfPermission( 11908 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11909 "Only package verification agents can verify applications"); 11910 11911 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11912 final PackageVerificationResponse response = new PackageVerificationResponse( 11913 verificationCode, Binder.getCallingUid()); 11914 msg.arg1 = id; 11915 msg.obj = response; 11916 mHandler.sendMessage(msg); 11917 } 11918 11919 @Override 11920 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11921 long millisecondsToDelay) { 11922 mContext.enforceCallingOrSelfPermission( 11923 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11924 "Only package verification agents can extend verification timeouts"); 11925 11926 final PackageVerificationState state = mPendingVerification.get(id); 11927 final PackageVerificationResponse response = new PackageVerificationResponse( 11928 verificationCodeAtTimeout, Binder.getCallingUid()); 11929 11930 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11931 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11932 } 11933 if (millisecondsToDelay < 0) { 11934 millisecondsToDelay = 0; 11935 } 11936 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11937 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11938 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11939 } 11940 11941 if ((state != null) && !state.timeoutExtended()) { 11942 state.extendTimeout(); 11943 11944 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11945 msg.arg1 = id; 11946 msg.obj = response; 11947 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11948 } 11949 } 11950 11951 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11952 int verificationCode, UserHandle user) { 11953 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11954 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11955 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11956 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11957 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11958 11959 mContext.sendBroadcastAsUser(intent, user, 11960 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11961 } 11962 11963 private ComponentName matchComponentForVerifier(String packageName, 11964 List<ResolveInfo> receivers) { 11965 ActivityInfo targetReceiver = null; 11966 11967 final int NR = receivers.size(); 11968 for (int i = 0; i < NR; i++) { 11969 final ResolveInfo info = receivers.get(i); 11970 if (info.activityInfo == null) { 11971 continue; 11972 } 11973 11974 if (packageName.equals(info.activityInfo.packageName)) { 11975 targetReceiver = info.activityInfo; 11976 break; 11977 } 11978 } 11979 11980 if (targetReceiver == null) { 11981 return null; 11982 } 11983 11984 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11985 } 11986 11987 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11988 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11989 if (pkgInfo.verifiers.length == 0) { 11990 return null; 11991 } 11992 11993 final int N = pkgInfo.verifiers.length; 11994 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11995 for (int i = 0; i < N; i++) { 11996 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11997 11998 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11999 receivers); 12000 if (comp == null) { 12001 continue; 12002 } 12003 12004 final int verifierUid = getUidForVerifier(verifierInfo); 12005 if (verifierUid == -1) { 12006 continue; 12007 } 12008 12009 if (DEBUG_VERIFY) { 12010 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12011 + " with the correct signature"); 12012 } 12013 sufficientVerifiers.add(comp); 12014 verificationState.addSufficientVerifier(verifierUid); 12015 } 12016 12017 return sufficientVerifiers; 12018 } 12019 12020 private int getUidForVerifier(VerifierInfo verifierInfo) { 12021 synchronized (mPackages) { 12022 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12023 if (pkg == null) { 12024 return -1; 12025 } else if (pkg.mSignatures.length != 1) { 12026 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12027 + " has more than one signature; ignoring"); 12028 return -1; 12029 } 12030 12031 /* 12032 * If the public key of the package's signature does not match 12033 * our expected public key, then this is a different package and 12034 * we should skip. 12035 */ 12036 12037 final byte[] expectedPublicKey; 12038 try { 12039 final Signature verifierSig = pkg.mSignatures[0]; 12040 final PublicKey publicKey = verifierSig.getPublicKey(); 12041 expectedPublicKey = publicKey.getEncoded(); 12042 } catch (CertificateException e) { 12043 return -1; 12044 } 12045 12046 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12047 12048 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12049 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12050 + " does not have the expected public key; ignoring"); 12051 return -1; 12052 } 12053 12054 return pkg.applicationInfo.uid; 12055 } 12056 } 12057 12058 @Override 12059 public void finishPackageInstall(int token, boolean didLaunch) { 12060 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12061 12062 if (DEBUG_INSTALL) { 12063 Slog.v(TAG, "BM finishing package install for " + token); 12064 } 12065 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12066 12067 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12068 mHandler.sendMessage(msg); 12069 } 12070 12071 /** 12072 * Get the verification agent timeout. 12073 * 12074 * @return verification timeout in milliseconds 12075 */ 12076 private long getVerificationTimeout() { 12077 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12078 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12079 DEFAULT_VERIFICATION_TIMEOUT); 12080 } 12081 12082 /** 12083 * Get the default verification agent response code. 12084 * 12085 * @return default verification response code 12086 */ 12087 private int getDefaultVerificationResponse() { 12088 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12089 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12090 DEFAULT_VERIFICATION_RESPONSE); 12091 } 12092 12093 /** 12094 * Check whether or not package verification has been enabled. 12095 * 12096 * @return true if verification should be performed 12097 */ 12098 private boolean isVerificationEnabled(int userId, int installFlags) { 12099 if (!DEFAULT_VERIFY_ENABLE) { 12100 return false; 12101 } 12102 // Ephemeral apps don't get the full verification treatment 12103 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12104 if (DEBUG_EPHEMERAL) { 12105 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12106 } 12107 return false; 12108 } 12109 12110 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12111 12112 // Check if installing from ADB 12113 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12114 // Do not run verification in a test harness environment 12115 if (ActivityManager.isRunningInTestHarness()) { 12116 return false; 12117 } 12118 if (ensureVerifyAppsEnabled) { 12119 return true; 12120 } 12121 // Check if the developer does not want package verification for ADB installs 12122 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12123 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12124 return false; 12125 } 12126 } 12127 12128 if (ensureVerifyAppsEnabled) { 12129 return true; 12130 } 12131 12132 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12133 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12134 } 12135 12136 @Override 12137 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12138 throws RemoteException { 12139 mContext.enforceCallingOrSelfPermission( 12140 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12141 "Only intentfilter verification agents can verify applications"); 12142 12143 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12144 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12145 Binder.getCallingUid(), verificationCode, failedDomains); 12146 msg.arg1 = id; 12147 msg.obj = response; 12148 mHandler.sendMessage(msg); 12149 } 12150 12151 @Override 12152 public int getIntentVerificationStatus(String packageName, int userId) { 12153 synchronized (mPackages) { 12154 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12155 } 12156 } 12157 12158 @Override 12159 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12160 mContext.enforceCallingOrSelfPermission( 12161 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12162 12163 boolean result = false; 12164 synchronized (mPackages) { 12165 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12166 } 12167 if (result) { 12168 scheduleWritePackageRestrictionsLocked(userId); 12169 } 12170 return result; 12171 } 12172 12173 @Override 12174 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12175 String packageName) { 12176 synchronized (mPackages) { 12177 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12178 } 12179 } 12180 12181 @Override 12182 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12183 if (TextUtils.isEmpty(packageName)) { 12184 return ParceledListSlice.emptyList(); 12185 } 12186 synchronized (mPackages) { 12187 PackageParser.Package pkg = mPackages.get(packageName); 12188 if (pkg == null || pkg.activities == null) { 12189 return ParceledListSlice.emptyList(); 12190 } 12191 final int count = pkg.activities.size(); 12192 ArrayList<IntentFilter> result = new ArrayList<>(); 12193 for (int n=0; n<count; n++) { 12194 PackageParser.Activity activity = pkg.activities.get(n); 12195 if (activity.intents != null && activity.intents.size() > 0) { 12196 result.addAll(activity.intents); 12197 } 12198 } 12199 return new ParceledListSlice<>(result); 12200 } 12201 } 12202 12203 @Override 12204 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12205 mContext.enforceCallingOrSelfPermission( 12206 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12207 12208 synchronized (mPackages) { 12209 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12210 if (packageName != null) { 12211 result |= updateIntentVerificationStatus(packageName, 12212 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12213 userId); 12214 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12215 packageName, userId); 12216 } 12217 return result; 12218 } 12219 } 12220 12221 @Override 12222 public String getDefaultBrowserPackageName(int userId) { 12223 synchronized (mPackages) { 12224 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12225 } 12226 } 12227 12228 /** 12229 * Get the "allow unknown sources" setting. 12230 * 12231 * @return the current "allow unknown sources" setting 12232 */ 12233 private int getUnknownSourcesSettings() { 12234 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12235 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12236 -1); 12237 } 12238 12239 @Override 12240 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12241 final int uid = Binder.getCallingUid(); 12242 // writer 12243 synchronized (mPackages) { 12244 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12245 if (targetPackageSetting == null) { 12246 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12247 } 12248 12249 PackageSetting installerPackageSetting; 12250 if (installerPackageName != null) { 12251 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12252 if (installerPackageSetting == null) { 12253 throw new IllegalArgumentException("Unknown installer package: " 12254 + installerPackageName); 12255 } 12256 } else { 12257 installerPackageSetting = null; 12258 } 12259 12260 Signature[] callerSignature; 12261 Object obj = mSettings.getUserIdLPr(uid); 12262 if (obj != null) { 12263 if (obj instanceof SharedUserSetting) { 12264 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12265 } else if (obj instanceof PackageSetting) { 12266 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12267 } else { 12268 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12269 } 12270 } else { 12271 throw new SecurityException("Unknown calling UID: " + uid); 12272 } 12273 12274 // Verify: can't set installerPackageName to a package that is 12275 // not signed with the same cert as the caller. 12276 if (installerPackageSetting != null) { 12277 if (compareSignatures(callerSignature, 12278 installerPackageSetting.signatures.mSignatures) 12279 != PackageManager.SIGNATURE_MATCH) { 12280 throw new SecurityException( 12281 "Caller does not have same cert as new installer package " 12282 + installerPackageName); 12283 } 12284 } 12285 12286 // Verify: if target already has an installer package, it must 12287 // be signed with the same cert as the caller. 12288 if (targetPackageSetting.installerPackageName != null) { 12289 PackageSetting setting = mSettings.mPackages.get( 12290 targetPackageSetting.installerPackageName); 12291 // If the currently set package isn't valid, then it's always 12292 // okay to change it. 12293 if (setting != null) { 12294 if (compareSignatures(callerSignature, 12295 setting.signatures.mSignatures) 12296 != PackageManager.SIGNATURE_MATCH) { 12297 throw new SecurityException( 12298 "Caller does not have same cert as old installer package " 12299 + targetPackageSetting.installerPackageName); 12300 } 12301 } 12302 } 12303 12304 // Okay! 12305 targetPackageSetting.installerPackageName = installerPackageName; 12306 if (installerPackageName != null) { 12307 mSettings.mInstallerPackages.add(installerPackageName); 12308 } 12309 scheduleWriteSettingsLocked(); 12310 } 12311 } 12312 12313 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12314 // Queue up an async operation since the package installation may take a little while. 12315 mHandler.post(new Runnable() { 12316 public void run() { 12317 mHandler.removeCallbacks(this); 12318 // Result object to be returned 12319 PackageInstalledInfo res = new PackageInstalledInfo(); 12320 res.setReturnCode(currentStatus); 12321 res.uid = -1; 12322 res.pkg = null; 12323 res.removedInfo = null; 12324 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12325 args.doPreInstall(res.returnCode); 12326 synchronized (mInstallLock) { 12327 installPackageTracedLI(args, res); 12328 } 12329 args.doPostInstall(res.returnCode, res.uid); 12330 } 12331 12332 // A restore should be performed at this point if (a) the install 12333 // succeeded, (b) the operation is not an update, and (c) the new 12334 // package has not opted out of backup participation. 12335 final boolean update = res.removedInfo != null 12336 && res.removedInfo.removedPackage != null; 12337 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12338 boolean doRestore = !update 12339 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12340 12341 // Set up the post-install work request bookkeeping. This will be used 12342 // and cleaned up by the post-install event handling regardless of whether 12343 // there's a restore pass performed. Token values are >= 1. 12344 int token; 12345 if (mNextInstallToken < 0) mNextInstallToken = 1; 12346 token = mNextInstallToken++; 12347 12348 PostInstallData data = new PostInstallData(args, res); 12349 mRunningInstalls.put(token, data); 12350 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12351 12352 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12353 // Pass responsibility to the Backup Manager. It will perform a 12354 // restore if appropriate, then pass responsibility back to the 12355 // Package Manager to run the post-install observer callbacks 12356 // and broadcasts. 12357 IBackupManager bm = IBackupManager.Stub.asInterface( 12358 ServiceManager.getService(Context.BACKUP_SERVICE)); 12359 if (bm != null) { 12360 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12361 + " to BM for possible restore"); 12362 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12363 try { 12364 // TODO: http://b/22388012 12365 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12366 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12367 } else { 12368 doRestore = false; 12369 } 12370 } catch (RemoteException e) { 12371 // can't happen; the backup manager is local 12372 } catch (Exception e) { 12373 Slog.e(TAG, "Exception trying to enqueue restore", e); 12374 doRestore = false; 12375 } 12376 } else { 12377 Slog.e(TAG, "Backup Manager not found!"); 12378 doRestore = false; 12379 } 12380 } 12381 12382 if (!doRestore) { 12383 // No restore possible, or the Backup Manager was mysteriously not 12384 // available -- just fire the post-install work request directly. 12385 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12386 12387 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12388 12389 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12390 mHandler.sendMessage(msg); 12391 } 12392 } 12393 }); 12394 } 12395 12396 /** 12397 * Callback from PackageSettings whenever an app is first transitioned out of the 12398 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12399 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12400 * here whether the app is the target of an ongoing install, and only send the 12401 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12402 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12403 * handling. 12404 */ 12405 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12406 // Serialize this with the rest of the install-process message chain. In the 12407 // restore-at-install case, this Runnable will necessarily run before the 12408 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12409 // are coherent. In the non-restore case, the app has already completed install 12410 // and been launched through some other means, so it is not in a problematic 12411 // state for observers to see the FIRST_LAUNCH signal. 12412 mHandler.post(new Runnable() { 12413 @Override 12414 public void run() { 12415 for (int i = 0; i < mRunningInstalls.size(); i++) { 12416 final PostInstallData data = mRunningInstalls.valueAt(i); 12417 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12418 // right package; but is it for the right user? 12419 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12420 if (userId == data.res.newUsers[uIndex]) { 12421 if (DEBUG_BACKUP) { 12422 Slog.i(TAG, "Package " + pkgName 12423 + " being restored so deferring FIRST_LAUNCH"); 12424 } 12425 return; 12426 } 12427 } 12428 } 12429 } 12430 // didn't find it, so not being restored 12431 if (DEBUG_BACKUP) { 12432 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12433 } 12434 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12435 } 12436 }); 12437 } 12438 12439 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12440 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12441 installerPkg, null, userIds); 12442 } 12443 12444 private abstract class HandlerParams { 12445 private static final int MAX_RETRIES = 4; 12446 12447 /** 12448 * Number of times startCopy() has been attempted and had a non-fatal 12449 * error. 12450 */ 12451 private int mRetries = 0; 12452 12453 /** User handle for the user requesting the information or installation. */ 12454 private final UserHandle mUser; 12455 String traceMethod; 12456 int traceCookie; 12457 12458 HandlerParams(UserHandle user) { 12459 mUser = user; 12460 } 12461 12462 UserHandle getUser() { 12463 return mUser; 12464 } 12465 12466 HandlerParams setTraceMethod(String traceMethod) { 12467 this.traceMethod = traceMethod; 12468 return this; 12469 } 12470 12471 HandlerParams setTraceCookie(int traceCookie) { 12472 this.traceCookie = traceCookie; 12473 return this; 12474 } 12475 12476 final boolean startCopy() { 12477 boolean res; 12478 try { 12479 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12480 12481 if (++mRetries > MAX_RETRIES) { 12482 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12483 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12484 handleServiceError(); 12485 return false; 12486 } else { 12487 handleStartCopy(); 12488 res = true; 12489 } 12490 } catch (RemoteException e) { 12491 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12492 mHandler.sendEmptyMessage(MCS_RECONNECT); 12493 res = false; 12494 } 12495 handleReturnCode(); 12496 return res; 12497 } 12498 12499 final void serviceError() { 12500 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12501 handleServiceError(); 12502 handleReturnCode(); 12503 } 12504 12505 abstract void handleStartCopy() throws RemoteException; 12506 abstract void handleServiceError(); 12507 abstract void handleReturnCode(); 12508 } 12509 12510 class MeasureParams extends HandlerParams { 12511 private final PackageStats mStats; 12512 private boolean mSuccess; 12513 12514 private final IPackageStatsObserver mObserver; 12515 12516 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12517 super(new UserHandle(stats.userHandle)); 12518 mObserver = observer; 12519 mStats = stats; 12520 } 12521 12522 @Override 12523 public String toString() { 12524 return "MeasureParams{" 12525 + Integer.toHexString(System.identityHashCode(this)) 12526 + " " + mStats.packageName + "}"; 12527 } 12528 12529 @Override 12530 void handleStartCopy() throws RemoteException { 12531 synchronized (mInstallLock) { 12532 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12533 } 12534 12535 if (mSuccess) { 12536 final boolean mounted; 12537 if (Environment.isExternalStorageEmulated()) { 12538 mounted = true; 12539 } else { 12540 final String status = Environment.getExternalStorageState(); 12541 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12542 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12543 } 12544 12545 if (mounted) { 12546 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12547 12548 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12549 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12550 12551 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12552 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12553 12554 // Always subtract cache size, since it's a subdirectory 12555 mStats.externalDataSize -= mStats.externalCacheSize; 12556 12557 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12558 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12559 12560 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12561 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12562 } 12563 } 12564 } 12565 12566 @Override 12567 void handleReturnCode() { 12568 if (mObserver != null) { 12569 try { 12570 mObserver.onGetStatsCompleted(mStats, mSuccess); 12571 } catch (RemoteException e) { 12572 Slog.i(TAG, "Observer no longer exists."); 12573 } 12574 } 12575 } 12576 12577 @Override 12578 void handleServiceError() { 12579 Slog.e(TAG, "Could not measure application " + mStats.packageName 12580 + " external storage"); 12581 } 12582 } 12583 12584 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12585 throws RemoteException { 12586 long result = 0; 12587 for (File path : paths) { 12588 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12589 } 12590 return result; 12591 } 12592 12593 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12594 for (File path : paths) { 12595 try { 12596 mcs.clearDirectory(path.getAbsolutePath()); 12597 } catch (RemoteException e) { 12598 } 12599 } 12600 } 12601 12602 static class OriginInfo { 12603 /** 12604 * Location where install is coming from, before it has been 12605 * copied/renamed into place. This could be a single monolithic APK 12606 * file, or a cluster directory. This location may be untrusted. 12607 */ 12608 final File file; 12609 final String cid; 12610 12611 /** 12612 * Flag indicating that {@link #file} or {@link #cid} has already been 12613 * staged, meaning downstream users don't need to defensively copy the 12614 * contents. 12615 */ 12616 final boolean staged; 12617 12618 /** 12619 * Flag indicating that {@link #file} or {@link #cid} is an already 12620 * installed app that is being moved. 12621 */ 12622 final boolean existing; 12623 12624 final String resolvedPath; 12625 final File resolvedFile; 12626 12627 static OriginInfo fromNothing() { 12628 return new OriginInfo(null, null, false, false); 12629 } 12630 12631 static OriginInfo fromUntrustedFile(File file) { 12632 return new OriginInfo(file, null, false, false); 12633 } 12634 12635 static OriginInfo fromExistingFile(File file) { 12636 return new OriginInfo(file, null, false, true); 12637 } 12638 12639 static OriginInfo fromStagedFile(File file) { 12640 return new OriginInfo(file, null, true, false); 12641 } 12642 12643 static OriginInfo fromStagedContainer(String cid) { 12644 return new OriginInfo(null, cid, true, false); 12645 } 12646 12647 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12648 this.file = file; 12649 this.cid = cid; 12650 this.staged = staged; 12651 this.existing = existing; 12652 12653 if (cid != null) { 12654 resolvedPath = PackageHelper.getSdDir(cid); 12655 resolvedFile = new File(resolvedPath); 12656 } else if (file != null) { 12657 resolvedPath = file.getAbsolutePath(); 12658 resolvedFile = file; 12659 } else { 12660 resolvedPath = null; 12661 resolvedFile = null; 12662 } 12663 } 12664 } 12665 12666 static class MoveInfo { 12667 final int moveId; 12668 final String fromUuid; 12669 final String toUuid; 12670 final String packageName; 12671 final String dataAppName; 12672 final int appId; 12673 final String seinfo; 12674 final int targetSdkVersion; 12675 12676 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12677 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12678 this.moveId = moveId; 12679 this.fromUuid = fromUuid; 12680 this.toUuid = toUuid; 12681 this.packageName = packageName; 12682 this.dataAppName = dataAppName; 12683 this.appId = appId; 12684 this.seinfo = seinfo; 12685 this.targetSdkVersion = targetSdkVersion; 12686 } 12687 } 12688 12689 static class VerificationInfo { 12690 /** A constant used to indicate that a uid value is not present. */ 12691 public static final int NO_UID = -1; 12692 12693 /** URI referencing where the package was downloaded from. */ 12694 final Uri originatingUri; 12695 12696 /** HTTP referrer URI associated with the originatingURI. */ 12697 final Uri referrer; 12698 12699 /** UID of the application that the install request originated from. */ 12700 final int originatingUid; 12701 12702 /** UID of application requesting the install */ 12703 final int installerUid; 12704 12705 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12706 this.originatingUri = originatingUri; 12707 this.referrer = referrer; 12708 this.originatingUid = originatingUid; 12709 this.installerUid = installerUid; 12710 } 12711 } 12712 12713 class InstallParams extends HandlerParams { 12714 final OriginInfo origin; 12715 final MoveInfo move; 12716 final IPackageInstallObserver2 observer; 12717 int installFlags; 12718 final String installerPackageName; 12719 final String volumeUuid; 12720 private InstallArgs mArgs; 12721 private int mRet; 12722 final String packageAbiOverride; 12723 final String[] grantedRuntimePermissions; 12724 final VerificationInfo verificationInfo; 12725 final Certificate[][] certificates; 12726 12727 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12728 int installFlags, String installerPackageName, String volumeUuid, 12729 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12730 String[] grantedPermissions, Certificate[][] certificates) { 12731 super(user); 12732 this.origin = origin; 12733 this.move = move; 12734 this.observer = observer; 12735 this.installFlags = installFlags; 12736 this.installerPackageName = installerPackageName; 12737 this.volumeUuid = volumeUuid; 12738 this.verificationInfo = verificationInfo; 12739 this.packageAbiOverride = packageAbiOverride; 12740 this.grantedRuntimePermissions = grantedPermissions; 12741 this.certificates = certificates; 12742 } 12743 12744 @Override 12745 public String toString() { 12746 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12747 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12748 } 12749 12750 private int installLocationPolicy(PackageInfoLite pkgLite) { 12751 String packageName = pkgLite.packageName; 12752 int installLocation = pkgLite.installLocation; 12753 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12754 // reader 12755 synchronized (mPackages) { 12756 // Currently installed package which the new package is attempting to replace or 12757 // null if no such package is installed. 12758 PackageParser.Package installedPkg = mPackages.get(packageName); 12759 // Package which currently owns the data which the new package will own if installed. 12760 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12761 // will be null whereas dataOwnerPkg will contain information about the package 12762 // which was uninstalled while keeping its data. 12763 PackageParser.Package dataOwnerPkg = installedPkg; 12764 if (dataOwnerPkg == null) { 12765 PackageSetting ps = mSettings.mPackages.get(packageName); 12766 if (ps != null) { 12767 dataOwnerPkg = ps.pkg; 12768 } 12769 } 12770 12771 if (dataOwnerPkg != null) { 12772 // If installed, the package will get access to data left on the device by its 12773 // predecessor. As a security measure, this is permited only if this is not a 12774 // version downgrade or if the predecessor package is marked as debuggable and 12775 // a downgrade is explicitly requested. 12776 // 12777 // On debuggable platform builds, downgrades are permitted even for 12778 // non-debuggable packages to make testing easier. Debuggable platform builds do 12779 // not offer security guarantees and thus it's OK to disable some security 12780 // mechanisms to make debugging/testing easier on those builds. However, even on 12781 // debuggable builds downgrades of packages are permitted only if requested via 12782 // installFlags. This is because we aim to keep the behavior of debuggable 12783 // platform builds as close as possible to the behavior of non-debuggable 12784 // platform builds. 12785 final boolean downgradeRequested = 12786 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12787 final boolean packageDebuggable = 12788 (dataOwnerPkg.applicationInfo.flags 12789 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12790 final boolean downgradePermitted = 12791 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12792 if (!downgradePermitted) { 12793 try { 12794 checkDowngrade(dataOwnerPkg, pkgLite); 12795 } catch (PackageManagerException e) { 12796 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12797 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12798 } 12799 } 12800 } 12801 12802 if (installedPkg != null) { 12803 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12804 // Check for updated system application. 12805 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12806 if (onSd) { 12807 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12808 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12809 } 12810 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12811 } else { 12812 if (onSd) { 12813 // Install flag overrides everything. 12814 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12815 } 12816 // If current upgrade specifies particular preference 12817 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12818 // Application explicitly specified internal. 12819 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12820 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12821 // App explictly prefers external. Let policy decide 12822 } else { 12823 // Prefer previous location 12824 if (isExternal(installedPkg)) { 12825 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12826 } 12827 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12828 } 12829 } 12830 } else { 12831 // Invalid install. Return error code 12832 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12833 } 12834 } 12835 } 12836 // All the special cases have been taken care of. 12837 // Return result based on recommended install location. 12838 if (onSd) { 12839 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12840 } 12841 return pkgLite.recommendedInstallLocation; 12842 } 12843 12844 /* 12845 * Invoke remote method to get package information and install 12846 * location values. Override install location based on default 12847 * policy if needed and then create install arguments based 12848 * on the install location. 12849 */ 12850 public void handleStartCopy() throws RemoteException { 12851 int ret = PackageManager.INSTALL_SUCCEEDED; 12852 12853 // If we're already staged, we've firmly committed to an install location 12854 if (origin.staged) { 12855 if (origin.file != null) { 12856 installFlags |= PackageManager.INSTALL_INTERNAL; 12857 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12858 } else if (origin.cid != null) { 12859 installFlags |= PackageManager.INSTALL_EXTERNAL; 12860 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12861 } else { 12862 throw new IllegalStateException("Invalid stage location"); 12863 } 12864 } 12865 12866 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12867 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12868 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12869 PackageInfoLite pkgLite = null; 12870 12871 if (onInt && onSd) { 12872 // Check if both bits are set. 12873 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12874 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12875 } else if (onSd && ephemeral) { 12876 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12877 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12878 } else { 12879 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12880 packageAbiOverride); 12881 12882 if (DEBUG_EPHEMERAL && ephemeral) { 12883 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12884 } 12885 12886 /* 12887 * If we have too little free space, try to free cache 12888 * before giving up. 12889 */ 12890 if (!origin.staged && pkgLite.recommendedInstallLocation 12891 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12892 // TODO: focus freeing disk space on the target device 12893 final StorageManager storage = StorageManager.from(mContext); 12894 final long lowThreshold = storage.getStorageLowBytes( 12895 Environment.getDataDirectory()); 12896 12897 final long sizeBytes = mContainerService.calculateInstalledSize( 12898 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12899 12900 try { 12901 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12902 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12903 installFlags, packageAbiOverride); 12904 } catch (InstallerException e) { 12905 Slog.w(TAG, "Failed to free cache", e); 12906 } 12907 12908 /* 12909 * The cache free must have deleted the file we 12910 * downloaded to install. 12911 * 12912 * TODO: fix the "freeCache" call to not delete 12913 * the file we care about. 12914 */ 12915 if (pkgLite.recommendedInstallLocation 12916 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12917 pkgLite.recommendedInstallLocation 12918 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12919 } 12920 } 12921 } 12922 12923 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12924 int loc = pkgLite.recommendedInstallLocation; 12925 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12926 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12927 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12928 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12929 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12930 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12931 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12932 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12933 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12934 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12935 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12936 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12937 } else { 12938 // Override with defaults if needed. 12939 loc = installLocationPolicy(pkgLite); 12940 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12941 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12942 } else if (!onSd && !onInt) { 12943 // Override install location with flags 12944 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12945 // Set the flag to install on external media. 12946 installFlags |= PackageManager.INSTALL_EXTERNAL; 12947 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12948 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12949 if (DEBUG_EPHEMERAL) { 12950 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12951 } 12952 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12953 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12954 |PackageManager.INSTALL_INTERNAL); 12955 } else { 12956 // Make sure the flag for installing on external 12957 // media is unset 12958 installFlags |= PackageManager.INSTALL_INTERNAL; 12959 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12960 } 12961 } 12962 } 12963 } 12964 12965 final InstallArgs args = createInstallArgs(this); 12966 mArgs = args; 12967 12968 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12969 // TODO: http://b/22976637 12970 // Apps installed for "all" users use the device owner to verify the app 12971 UserHandle verifierUser = getUser(); 12972 if (verifierUser == UserHandle.ALL) { 12973 verifierUser = UserHandle.SYSTEM; 12974 } 12975 12976 /* 12977 * Determine if we have any installed package verifiers. If we 12978 * do, then we'll defer to them to verify the packages. 12979 */ 12980 final int requiredUid = mRequiredVerifierPackage == null ? -1 12981 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12982 verifierUser.getIdentifier()); 12983 if (!origin.existing && requiredUid != -1 12984 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12985 final Intent verification = new Intent( 12986 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12987 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12988 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12989 PACKAGE_MIME_TYPE); 12990 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12991 12992 // Query all live verifiers based on current user state 12993 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12994 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12995 12996 if (DEBUG_VERIFY) { 12997 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12998 + verification.toString() + " with " + pkgLite.verifiers.length 12999 + " optional verifiers"); 13000 } 13001 13002 final int verificationId = mPendingVerificationToken++; 13003 13004 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13005 13006 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13007 installerPackageName); 13008 13009 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13010 installFlags); 13011 13012 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13013 pkgLite.packageName); 13014 13015 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13016 pkgLite.versionCode); 13017 13018 if (verificationInfo != null) { 13019 if (verificationInfo.originatingUri != null) { 13020 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13021 verificationInfo.originatingUri); 13022 } 13023 if (verificationInfo.referrer != null) { 13024 verification.putExtra(Intent.EXTRA_REFERRER, 13025 verificationInfo.referrer); 13026 } 13027 if (verificationInfo.originatingUid >= 0) { 13028 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13029 verificationInfo.originatingUid); 13030 } 13031 if (verificationInfo.installerUid >= 0) { 13032 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13033 verificationInfo.installerUid); 13034 } 13035 } 13036 13037 final PackageVerificationState verificationState = new PackageVerificationState( 13038 requiredUid, args); 13039 13040 mPendingVerification.append(verificationId, verificationState); 13041 13042 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13043 receivers, verificationState); 13044 13045 /* 13046 * If any sufficient verifiers were listed in the package 13047 * manifest, attempt to ask them. 13048 */ 13049 if (sufficientVerifiers != null) { 13050 final int N = sufficientVerifiers.size(); 13051 if (N == 0) { 13052 Slog.i(TAG, "Additional verifiers required, but none installed."); 13053 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13054 } else { 13055 for (int i = 0; i < N; i++) { 13056 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13057 13058 final Intent sufficientIntent = new Intent(verification); 13059 sufficientIntent.setComponent(verifierComponent); 13060 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13061 } 13062 } 13063 } 13064 13065 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13066 mRequiredVerifierPackage, receivers); 13067 if (ret == PackageManager.INSTALL_SUCCEEDED 13068 && mRequiredVerifierPackage != null) { 13069 Trace.asyncTraceBegin( 13070 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13071 /* 13072 * Send the intent to the required verification agent, 13073 * but only start the verification timeout after the 13074 * target BroadcastReceivers have run. 13075 */ 13076 verification.setComponent(requiredVerifierComponent); 13077 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13078 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13079 new BroadcastReceiver() { 13080 @Override 13081 public void onReceive(Context context, Intent intent) { 13082 final Message msg = mHandler 13083 .obtainMessage(CHECK_PENDING_VERIFICATION); 13084 msg.arg1 = verificationId; 13085 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13086 } 13087 }, null, 0, null, null); 13088 13089 /* 13090 * We don't want the copy to proceed until verification 13091 * succeeds, so null out this field. 13092 */ 13093 mArgs = null; 13094 } 13095 } else { 13096 /* 13097 * No package verification is enabled, so immediately start 13098 * the remote call to initiate copy using temporary file. 13099 */ 13100 ret = args.copyApk(mContainerService, true); 13101 } 13102 } 13103 13104 mRet = ret; 13105 } 13106 13107 @Override 13108 void handleReturnCode() { 13109 // If mArgs is null, then MCS couldn't be reached. When it 13110 // reconnects, it will try again to install. At that point, this 13111 // will succeed. 13112 if (mArgs != null) { 13113 processPendingInstall(mArgs, mRet); 13114 } 13115 } 13116 13117 @Override 13118 void handleServiceError() { 13119 mArgs = createInstallArgs(this); 13120 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13121 } 13122 13123 public boolean isForwardLocked() { 13124 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13125 } 13126 } 13127 13128 /** 13129 * Used during creation of InstallArgs 13130 * 13131 * @param installFlags package installation flags 13132 * @return true if should be installed on external storage 13133 */ 13134 private static boolean installOnExternalAsec(int installFlags) { 13135 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13136 return false; 13137 } 13138 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13139 return true; 13140 } 13141 return false; 13142 } 13143 13144 /** 13145 * Used during creation of InstallArgs 13146 * 13147 * @param installFlags package installation flags 13148 * @return true if should be installed as forward locked 13149 */ 13150 private static boolean installForwardLocked(int installFlags) { 13151 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13152 } 13153 13154 private InstallArgs createInstallArgs(InstallParams params) { 13155 if (params.move != null) { 13156 return new MoveInstallArgs(params); 13157 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13158 return new AsecInstallArgs(params); 13159 } else { 13160 return new FileInstallArgs(params); 13161 } 13162 } 13163 13164 /** 13165 * Create args that describe an existing installed package. Typically used 13166 * when cleaning up old installs, or used as a move source. 13167 */ 13168 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13169 String resourcePath, String[] instructionSets) { 13170 final boolean isInAsec; 13171 if (installOnExternalAsec(installFlags)) { 13172 /* Apps on SD card are always in ASEC containers. */ 13173 isInAsec = true; 13174 } else if (installForwardLocked(installFlags) 13175 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13176 /* 13177 * Forward-locked apps are only in ASEC containers if they're the 13178 * new style 13179 */ 13180 isInAsec = true; 13181 } else { 13182 isInAsec = false; 13183 } 13184 13185 if (isInAsec) { 13186 return new AsecInstallArgs(codePath, instructionSets, 13187 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13188 } else { 13189 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13190 } 13191 } 13192 13193 static abstract class InstallArgs { 13194 /** @see InstallParams#origin */ 13195 final OriginInfo origin; 13196 /** @see InstallParams#move */ 13197 final MoveInfo move; 13198 13199 final IPackageInstallObserver2 observer; 13200 // Always refers to PackageManager flags only 13201 final int installFlags; 13202 final String installerPackageName; 13203 final String volumeUuid; 13204 final UserHandle user; 13205 final String abiOverride; 13206 final String[] installGrantPermissions; 13207 /** If non-null, drop an async trace when the install completes */ 13208 final String traceMethod; 13209 final int traceCookie; 13210 final Certificate[][] certificates; 13211 13212 // The list of instruction sets supported by this app. This is currently 13213 // only used during the rmdex() phase to clean up resources. We can get rid of this 13214 // if we move dex files under the common app path. 13215 /* nullable */ String[] instructionSets; 13216 13217 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13218 int installFlags, String installerPackageName, String volumeUuid, 13219 UserHandle user, String[] instructionSets, 13220 String abiOverride, String[] installGrantPermissions, 13221 String traceMethod, int traceCookie, Certificate[][] certificates) { 13222 this.origin = origin; 13223 this.move = move; 13224 this.installFlags = installFlags; 13225 this.observer = observer; 13226 this.installerPackageName = installerPackageName; 13227 this.volumeUuid = volumeUuid; 13228 this.user = user; 13229 this.instructionSets = instructionSets; 13230 this.abiOverride = abiOverride; 13231 this.installGrantPermissions = installGrantPermissions; 13232 this.traceMethod = traceMethod; 13233 this.traceCookie = traceCookie; 13234 this.certificates = certificates; 13235 } 13236 13237 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13238 abstract int doPreInstall(int status); 13239 13240 /** 13241 * Rename package into final resting place. All paths on the given 13242 * scanned package should be updated to reflect the rename. 13243 */ 13244 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13245 abstract int doPostInstall(int status, int uid); 13246 13247 /** @see PackageSettingBase#codePathString */ 13248 abstract String getCodePath(); 13249 /** @see PackageSettingBase#resourcePathString */ 13250 abstract String getResourcePath(); 13251 13252 // Need installer lock especially for dex file removal. 13253 abstract void cleanUpResourcesLI(); 13254 abstract boolean doPostDeleteLI(boolean delete); 13255 13256 /** 13257 * Called before the source arguments are copied. This is used mostly 13258 * for MoveParams when it needs to read the source file to put it in the 13259 * destination. 13260 */ 13261 int doPreCopy() { 13262 return PackageManager.INSTALL_SUCCEEDED; 13263 } 13264 13265 /** 13266 * Called after the source arguments are copied. This is used mostly for 13267 * MoveParams when it needs to read the source file to put it in the 13268 * destination. 13269 */ 13270 int doPostCopy(int uid) { 13271 return PackageManager.INSTALL_SUCCEEDED; 13272 } 13273 13274 protected boolean isFwdLocked() { 13275 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13276 } 13277 13278 protected boolean isExternalAsec() { 13279 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13280 } 13281 13282 protected boolean isEphemeral() { 13283 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13284 } 13285 13286 UserHandle getUser() { 13287 return user; 13288 } 13289 } 13290 13291 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13292 if (!allCodePaths.isEmpty()) { 13293 if (instructionSets == null) { 13294 throw new IllegalStateException("instructionSet == null"); 13295 } 13296 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13297 for (String codePath : allCodePaths) { 13298 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13299 try { 13300 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13301 } catch (InstallerException ignored) { 13302 } 13303 } 13304 } 13305 } 13306 } 13307 13308 /** 13309 * Logic to handle installation of non-ASEC applications, including copying 13310 * and renaming logic. 13311 */ 13312 class FileInstallArgs extends InstallArgs { 13313 private File codeFile; 13314 private File resourceFile; 13315 13316 // Example topology: 13317 // /data/app/com.example/base.apk 13318 // /data/app/com.example/split_foo.apk 13319 // /data/app/com.example/lib/arm/libfoo.so 13320 // /data/app/com.example/lib/arm64/libfoo.so 13321 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13322 13323 /** New install */ 13324 FileInstallArgs(InstallParams params) { 13325 super(params.origin, params.move, params.observer, params.installFlags, 13326 params.installerPackageName, params.volumeUuid, 13327 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13328 params.grantedRuntimePermissions, 13329 params.traceMethod, params.traceCookie, params.certificates); 13330 if (isFwdLocked()) { 13331 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13332 } 13333 } 13334 13335 /** Existing install */ 13336 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13337 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13338 null, null, null, 0, null /*certificates*/); 13339 this.codeFile = (codePath != null) ? new File(codePath) : null; 13340 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13341 } 13342 13343 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13344 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13345 try { 13346 return doCopyApk(imcs, temp); 13347 } finally { 13348 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13349 } 13350 } 13351 13352 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13353 if (origin.staged) { 13354 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13355 codeFile = origin.file; 13356 resourceFile = origin.file; 13357 return PackageManager.INSTALL_SUCCEEDED; 13358 } 13359 13360 try { 13361 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13362 final File tempDir = 13363 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13364 codeFile = tempDir; 13365 resourceFile = tempDir; 13366 } catch (IOException e) { 13367 Slog.w(TAG, "Failed to create copy file: " + e); 13368 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13369 } 13370 13371 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13372 @Override 13373 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13374 if (!FileUtils.isValidExtFilename(name)) { 13375 throw new IllegalArgumentException("Invalid filename: " + name); 13376 } 13377 try { 13378 final File file = new File(codeFile, name); 13379 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13380 O_RDWR | O_CREAT, 0644); 13381 Os.chmod(file.getAbsolutePath(), 0644); 13382 return new ParcelFileDescriptor(fd); 13383 } catch (ErrnoException e) { 13384 throw new RemoteException("Failed to open: " + e.getMessage()); 13385 } 13386 } 13387 }; 13388 13389 int ret = PackageManager.INSTALL_SUCCEEDED; 13390 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13391 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13392 Slog.e(TAG, "Failed to copy package"); 13393 return ret; 13394 } 13395 13396 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13397 NativeLibraryHelper.Handle handle = null; 13398 try { 13399 handle = NativeLibraryHelper.Handle.create(codeFile); 13400 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13401 abiOverride); 13402 } catch (IOException e) { 13403 Slog.e(TAG, "Copying native libraries failed", e); 13404 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13405 } finally { 13406 IoUtils.closeQuietly(handle); 13407 } 13408 13409 return ret; 13410 } 13411 13412 int doPreInstall(int status) { 13413 if (status != PackageManager.INSTALL_SUCCEEDED) { 13414 cleanUp(); 13415 } 13416 return status; 13417 } 13418 13419 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13420 if (status != PackageManager.INSTALL_SUCCEEDED) { 13421 cleanUp(); 13422 return false; 13423 } 13424 13425 final File targetDir = codeFile.getParentFile(); 13426 final File beforeCodeFile = codeFile; 13427 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13428 13429 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13430 try { 13431 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13432 } catch (ErrnoException e) { 13433 Slog.w(TAG, "Failed to rename", e); 13434 return false; 13435 } 13436 13437 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13438 Slog.w(TAG, "Failed to restorecon"); 13439 return false; 13440 } 13441 13442 // Reflect the rename internally 13443 codeFile = afterCodeFile; 13444 resourceFile = afterCodeFile; 13445 13446 // Reflect the rename in scanned details 13447 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13448 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13449 afterCodeFile, pkg.baseCodePath)); 13450 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13451 afterCodeFile, pkg.splitCodePaths)); 13452 13453 // Reflect the rename in app info 13454 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13455 pkg.setApplicationInfoCodePath(pkg.codePath); 13456 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13457 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13458 pkg.setApplicationInfoResourcePath(pkg.codePath); 13459 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13460 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13461 13462 return true; 13463 } 13464 13465 int doPostInstall(int status, int uid) { 13466 if (status != PackageManager.INSTALL_SUCCEEDED) { 13467 cleanUp(); 13468 } 13469 return status; 13470 } 13471 13472 @Override 13473 String getCodePath() { 13474 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13475 } 13476 13477 @Override 13478 String getResourcePath() { 13479 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13480 } 13481 13482 private boolean cleanUp() { 13483 if (codeFile == null || !codeFile.exists()) { 13484 return false; 13485 } 13486 13487 removeCodePathLI(codeFile); 13488 13489 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13490 resourceFile.delete(); 13491 } 13492 13493 return true; 13494 } 13495 13496 void cleanUpResourcesLI() { 13497 // Try enumerating all code paths before deleting 13498 List<String> allCodePaths = Collections.EMPTY_LIST; 13499 if (codeFile != null && codeFile.exists()) { 13500 try { 13501 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13502 allCodePaths = pkg.getAllCodePaths(); 13503 } catch (PackageParserException e) { 13504 // Ignored; we tried our best 13505 } 13506 } 13507 13508 cleanUp(); 13509 removeDexFiles(allCodePaths, instructionSets); 13510 } 13511 13512 boolean doPostDeleteLI(boolean delete) { 13513 // XXX err, shouldn't we respect the delete flag? 13514 cleanUpResourcesLI(); 13515 return true; 13516 } 13517 } 13518 13519 private boolean isAsecExternal(String cid) { 13520 final String asecPath = PackageHelper.getSdFilesystem(cid); 13521 return !asecPath.startsWith(mAsecInternalPath); 13522 } 13523 13524 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13525 PackageManagerException { 13526 if (copyRet < 0) { 13527 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13528 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13529 throw new PackageManagerException(copyRet, message); 13530 } 13531 } 13532 } 13533 13534 /** 13535 * Extract the MountService "container ID" from the full code path of an 13536 * .apk. 13537 */ 13538 static String cidFromCodePath(String fullCodePath) { 13539 int eidx = fullCodePath.lastIndexOf("/"); 13540 String subStr1 = fullCodePath.substring(0, eidx); 13541 int sidx = subStr1.lastIndexOf("/"); 13542 return subStr1.substring(sidx+1, eidx); 13543 } 13544 13545 /** 13546 * Logic to handle installation of ASEC applications, including copying and 13547 * renaming logic. 13548 */ 13549 class AsecInstallArgs extends InstallArgs { 13550 static final String RES_FILE_NAME = "pkg.apk"; 13551 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13552 13553 String cid; 13554 String packagePath; 13555 String resourcePath; 13556 13557 /** New install */ 13558 AsecInstallArgs(InstallParams params) { 13559 super(params.origin, params.move, params.observer, params.installFlags, 13560 params.installerPackageName, params.volumeUuid, 13561 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13562 params.grantedRuntimePermissions, 13563 params.traceMethod, params.traceCookie, params.certificates); 13564 } 13565 13566 /** Existing install */ 13567 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13568 boolean isExternal, boolean isForwardLocked) { 13569 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13570 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13571 instructionSets, null, null, null, 0, null /*certificates*/); 13572 // Hackily pretend we're still looking at a full code path 13573 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13574 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13575 } 13576 13577 // Extract cid from fullCodePath 13578 int eidx = fullCodePath.lastIndexOf("/"); 13579 String subStr1 = fullCodePath.substring(0, eidx); 13580 int sidx = subStr1.lastIndexOf("/"); 13581 cid = subStr1.substring(sidx+1, eidx); 13582 setMountPath(subStr1); 13583 } 13584 13585 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13586 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13587 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13588 instructionSets, null, null, null, 0, null /*certificates*/); 13589 this.cid = cid; 13590 setMountPath(PackageHelper.getSdDir(cid)); 13591 } 13592 13593 void createCopyFile() { 13594 cid = mInstallerService.allocateExternalStageCidLegacy(); 13595 } 13596 13597 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13598 if (origin.staged && origin.cid != null) { 13599 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13600 cid = origin.cid; 13601 setMountPath(PackageHelper.getSdDir(cid)); 13602 return PackageManager.INSTALL_SUCCEEDED; 13603 } 13604 13605 if (temp) { 13606 createCopyFile(); 13607 } else { 13608 /* 13609 * Pre-emptively destroy the container since it's destroyed if 13610 * copying fails due to it existing anyway. 13611 */ 13612 PackageHelper.destroySdDir(cid); 13613 } 13614 13615 final String newMountPath = imcs.copyPackageToContainer( 13616 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13617 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13618 13619 if (newMountPath != null) { 13620 setMountPath(newMountPath); 13621 return PackageManager.INSTALL_SUCCEEDED; 13622 } else { 13623 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13624 } 13625 } 13626 13627 @Override 13628 String getCodePath() { 13629 return packagePath; 13630 } 13631 13632 @Override 13633 String getResourcePath() { 13634 return resourcePath; 13635 } 13636 13637 int doPreInstall(int status) { 13638 if (status != PackageManager.INSTALL_SUCCEEDED) { 13639 // Destroy container 13640 PackageHelper.destroySdDir(cid); 13641 } else { 13642 boolean mounted = PackageHelper.isContainerMounted(cid); 13643 if (!mounted) { 13644 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13645 Process.SYSTEM_UID); 13646 if (newMountPath != null) { 13647 setMountPath(newMountPath); 13648 } else { 13649 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13650 } 13651 } 13652 } 13653 return status; 13654 } 13655 13656 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13657 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13658 String newMountPath = null; 13659 if (PackageHelper.isContainerMounted(cid)) { 13660 // Unmount the container 13661 if (!PackageHelper.unMountSdDir(cid)) { 13662 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13663 return false; 13664 } 13665 } 13666 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13667 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13668 " which might be stale. Will try to clean up."); 13669 // Clean up the stale container and proceed to recreate. 13670 if (!PackageHelper.destroySdDir(newCacheId)) { 13671 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13672 return false; 13673 } 13674 // Successfully cleaned up stale container. Try to rename again. 13675 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13676 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13677 + " inspite of cleaning it up."); 13678 return false; 13679 } 13680 } 13681 if (!PackageHelper.isContainerMounted(newCacheId)) { 13682 Slog.w(TAG, "Mounting container " + newCacheId); 13683 newMountPath = PackageHelper.mountSdDir(newCacheId, 13684 getEncryptKey(), Process.SYSTEM_UID); 13685 } else { 13686 newMountPath = PackageHelper.getSdDir(newCacheId); 13687 } 13688 if (newMountPath == null) { 13689 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13690 return false; 13691 } 13692 Log.i(TAG, "Succesfully renamed " + cid + 13693 " to " + newCacheId + 13694 " at new path: " + newMountPath); 13695 cid = newCacheId; 13696 13697 final File beforeCodeFile = new File(packagePath); 13698 setMountPath(newMountPath); 13699 final File afterCodeFile = new File(packagePath); 13700 13701 // Reflect the rename in scanned details 13702 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13703 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13704 afterCodeFile, pkg.baseCodePath)); 13705 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13706 afterCodeFile, pkg.splitCodePaths)); 13707 13708 // Reflect the rename in app info 13709 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13710 pkg.setApplicationInfoCodePath(pkg.codePath); 13711 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13712 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13713 pkg.setApplicationInfoResourcePath(pkg.codePath); 13714 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13715 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13716 13717 return true; 13718 } 13719 13720 private void setMountPath(String mountPath) { 13721 final File mountFile = new File(mountPath); 13722 13723 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13724 if (monolithicFile.exists()) { 13725 packagePath = monolithicFile.getAbsolutePath(); 13726 if (isFwdLocked()) { 13727 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13728 } else { 13729 resourcePath = packagePath; 13730 } 13731 } else { 13732 packagePath = mountFile.getAbsolutePath(); 13733 resourcePath = packagePath; 13734 } 13735 } 13736 13737 int doPostInstall(int status, int uid) { 13738 if (status != PackageManager.INSTALL_SUCCEEDED) { 13739 cleanUp(); 13740 } else { 13741 final int groupOwner; 13742 final String protectedFile; 13743 if (isFwdLocked()) { 13744 groupOwner = UserHandle.getSharedAppGid(uid); 13745 protectedFile = RES_FILE_NAME; 13746 } else { 13747 groupOwner = -1; 13748 protectedFile = null; 13749 } 13750 13751 if (uid < Process.FIRST_APPLICATION_UID 13752 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13753 Slog.e(TAG, "Failed to finalize " + cid); 13754 PackageHelper.destroySdDir(cid); 13755 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13756 } 13757 13758 boolean mounted = PackageHelper.isContainerMounted(cid); 13759 if (!mounted) { 13760 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13761 } 13762 } 13763 return status; 13764 } 13765 13766 private void cleanUp() { 13767 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13768 13769 // Destroy secure container 13770 PackageHelper.destroySdDir(cid); 13771 } 13772 13773 private List<String> getAllCodePaths() { 13774 final File codeFile = new File(getCodePath()); 13775 if (codeFile != null && codeFile.exists()) { 13776 try { 13777 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13778 return pkg.getAllCodePaths(); 13779 } catch (PackageParserException e) { 13780 // Ignored; we tried our best 13781 } 13782 } 13783 return Collections.EMPTY_LIST; 13784 } 13785 13786 void cleanUpResourcesLI() { 13787 // Enumerate all code paths before deleting 13788 cleanUpResourcesLI(getAllCodePaths()); 13789 } 13790 13791 private void cleanUpResourcesLI(List<String> allCodePaths) { 13792 cleanUp(); 13793 removeDexFiles(allCodePaths, instructionSets); 13794 } 13795 13796 String getPackageName() { 13797 return getAsecPackageName(cid); 13798 } 13799 13800 boolean doPostDeleteLI(boolean delete) { 13801 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13802 final List<String> allCodePaths = getAllCodePaths(); 13803 boolean mounted = PackageHelper.isContainerMounted(cid); 13804 if (mounted) { 13805 // Unmount first 13806 if (PackageHelper.unMountSdDir(cid)) { 13807 mounted = false; 13808 } 13809 } 13810 if (!mounted && delete) { 13811 cleanUpResourcesLI(allCodePaths); 13812 } 13813 return !mounted; 13814 } 13815 13816 @Override 13817 int doPreCopy() { 13818 if (isFwdLocked()) { 13819 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13820 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13821 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13822 } 13823 } 13824 13825 return PackageManager.INSTALL_SUCCEEDED; 13826 } 13827 13828 @Override 13829 int doPostCopy(int uid) { 13830 if (isFwdLocked()) { 13831 if (uid < Process.FIRST_APPLICATION_UID 13832 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13833 RES_FILE_NAME)) { 13834 Slog.e(TAG, "Failed to finalize " + cid); 13835 PackageHelper.destroySdDir(cid); 13836 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13837 } 13838 } 13839 13840 return PackageManager.INSTALL_SUCCEEDED; 13841 } 13842 } 13843 13844 /** 13845 * Logic to handle movement of existing installed applications. 13846 */ 13847 class MoveInstallArgs extends InstallArgs { 13848 private File codeFile; 13849 private File resourceFile; 13850 13851 /** New install */ 13852 MoveInstallArgs(InstallParams params) { 13853 super(params.origin, params.move, params.observer, params.installFlags, 13854 params.installerPackageName, params.volumeUuid, 13855 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13856 params.grantedRuntimePermissions, 13857 params.traceMethod, params.traceCookie, params.certificates); 13858 } 13859 13860 int copyApk(IMediaContainerService imcs, boolean temp) { 13861 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13862 + move.fromUuid + " to " + move.toUuid); 13863 synchronized (mInstaller) { 13864 try { 13865 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13866 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13867 } catch (InstallerException e) { 13868 Slog.w(TAG, "Failed to move app", e); 13869 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13870 } 13871 } 13872 13873 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13874 resourceFile = codeFile; 13875 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13876 13877 return PackageManager.INSTALL_SUCCEEDED; 13878 } 13879 13880 int doPreInstall(int status) { 13881 if (status != PackageManager.INSTALL_SUCCEEDED) { 13882 cleanUp(move.toUuid); 13883 } 13884 return status; 13885 } 13886 13887 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13888 if (status != PackageManager.INSTALL_SUCCEEDED) { 13889 cleanUp(move.toUuid); 13890 return false; 13891 } 13892 13893 // Reflect the move in app info 13894 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13895 pkg.setApplicationInfoCodePath(pkg.codePath); 13896 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13897 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13898 pkg.setApplicationInfoResourcePath(pkg.codePath); 13899 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13900 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13901 13902 return true; 13903 } 13904 13905 int doPostInstall(int status, int uid) { 13906 if (status == PackageManager.INSTALL_SUCCEEDED) { 13907 cleanUp(move.fromUuid); 13908 } else { 13909 cleanUp(move.toUuid); 13910 } 13911 return status; 13912 } 13913 13914 @Override 13915 String getCodePath() { 13916 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13917 } 13918 13919 @Override 13920 String getResourcePath() { 13921 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13922 } 13923 13924 private boolean cleanUp(String volumeUuid) { 13925 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13926 move.dataAppName); 13927 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13928 final int[] userIds = sUserManager.getUserIds(); 13929 synchronized (mInstallLock) { 13930 // Clean up both app data and code 13931 // All package moves are frozen until finished 13932 for (int userId : userIds) { 13933 try { 13934 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13935 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13936 } catch (InstallerException e) { 13937 Slog.w(TAG, String.valueOf(e)); 13938 } 13939 } 13940 removeCodePathLI(codeFile); 13941 } 13942 return true; 13943 } 13944 13945 void cleanUpResourcesLI() { 13946 throw new UnsupportedOperationException(); 13947 } 13948 13949 boolean doPostDeleteLI(boolean delete) { 13950 throw new UnsupportedOperationException(); 13951 } 13952 } 13953 13954 static String getAsecPackageName(String packageCid) { 13955 int idx = packageCid.lastIndexOf("-"); 13956 if (idx == -1) { 13957 return packageCid; 13958 } 13959 return packageCid.substring(0, idx); 13960 } 13961 13962 // Utility method used to create code paths based on package name and available index. 13963 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13964 String idxStr = ""; 13965 int idx = 1; 13966 // Fall back to default value of idx=1 if prefix is not 13967 // part of oldCodePath 13968 if (oldCodePath != null) { 13969 String subStr = oldCodePath; 13970 // Drop the suffix right away 13971 if (suffix != null && subStr.endsWith(suffix)) { 13972 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13973 } 13974 // If oldCodePath already contains prefix find out the 13975 // ending index to either increment or decrement. 13976 int sidx = subStr.lastIndexOf(prefix); 13977 if (sidx != -1) { 13978 subStr = subStr.substring(sidx + prefix.length()); 13979 if (subStr != null) { 13980 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13981 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13982 } 13983 try { 13984 idx = Integer.parseInt(subStr); 13985 if (idx <= 1) { 13986 idx++; 13987 } else { 13988 idx--; 13989 } 13990 } catch(NumberFormatException e) { 13991 } 13992 } 13993 } 13994 } 13995 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13996 return prefix + idxStr; 13997 } 13998 13999 private File getNextCodePath(File targetDir, String packageName) { 14000 int suffix = 1; 14001 File result; 14002 do { 14003 result = new File(targetDir, packageName + "-" + suffix); 14004 suffix++; 14005 } while (result.exists()); 14006 return result; 14007 } 14008 14009 // Utility method that returns the relative package path with respect 14010 // to the installation directory. Like say for /data/data/com.test-1.apk 14011 // string com.test-1 is returned. 14012 static String deriveCodePathName(String codePath) { 14013 if (codePath == null) { 14014 return null; 14015 } 14016 final File codeFile = new File(codePath); 14017 final String name = codeFile.getName(); 14018 if (codeFile.isDirectory()) { 14019 return name; 14020 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14021 final int lastDot = name.lastIndexOf('.'); 14022 return name.substring(0, lastDot); 14023 } else { 14024 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14025 return null; 14026 } 14027 } 14028 14029 static class PackageInstalledInfo { 14030 String name; 14031 int uid; 14032 // The set of users that originally had this package installed. 14033 int[] origUsers; 14034 // The set of users that now have this package installed. 14035 int[] newUsers; 14036 PackageParser.Package pkg; 14037 int returnCode; 14038 String returnMsg; 14039 PackageRemovedInfo removedInfo; 14040 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14041 14042 public void setError(int code, String msg) { 14043 setReturnCode(code); 14044 setReturnMessage(msg); 14045 Slog.w(TAG, msg); 14046 } 14047 14048 public void setError(String msg, PackageParserException e) { 14049 setReturnCode(e.error); 14050 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14051 Slog.w(TAG, msg, e); 14052 } 14053 14054 public void setError(String msg, PackageManagerException e) { 14055 returnCode = e.error; 14056 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14057 Slog.w(TAG, msg, e); 14058 } 14059 14060 public void setReturnCode(int returnCode) { 14061 this.returnCode = returnCode; 14062 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14063 for (int i = 0; i < childCount; i++) { 14064 addedChildPackages.valueAt(i).returnCode = returnCode; 14065 } 14066 } 14067 14068 private void setReturnMessage(String returnMsg) { 14069 this.returnMsg = returnMsg; 14070 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14071 for (int i = 0; i < childCount; i++) { 14072 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14073 } 14074 } 14075 14076 // In some error cases we want to convey more info back to the observer 14077 String origPackage; 14078 String origPermission; 14079 } 14080 14081 /* 14082 * Install a non-existing package. 14083 */ 14084 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14085 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14086 PackageInstalledInfo res) { 14087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14088 14089 // Remember this for later, in case we need to rollback this install 14090 String pkgName = pkg.packageName; 14091 14092 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14093 14094 synchronized(mPackages) { 14095 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14096 // A package with the same name is already installed, though 14097 // it has been renamed to an older name. The package we 14098 // are trying to install should be installed as an update to 14099 // the existing one, but that has not been requested, so bail. 14100 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14101 + " without first uninstalling package running as " 14102 + mSettings.mRenamedPackages.get(pkgName)); 14103 return; 14104 } 14105 if (mPackages.containsKey(pkgName)) { 14106 // Don't allow installation over an existing package with the same name. 14107 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14108 + " without first uninstalling."); 14109 return; 14110 } 14111 } 14112 14113 try { 14114 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14115 System.currentTimeMillis(), user); 14116 14117 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14118 14119 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14120 prepareAppDataAfterInstallLIF(newPackage); 14121 14122 } else { 14123 // Remove package from internal structures, but keep around any 14124 // data that might have already existed 14125 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14126 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14127 } 14128 } catch (PackageManagerException e) { 14129 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14130 } 14131 14132 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14133 } 14134 14135 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14136 // Can't rotate keys during boot or if sharedUser. 14137 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14138 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14139 return false; 14140 } 14141 // app is using upgradeKeySets; make sure all are valid 14142 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14143 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14144 for (int i = 0; i < upgradeKeySets.length; i++) { 14145 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14146 Slog.wtf(TAG, "Package " 14147 + (oldPs.name != null ? oldPs.name : "<null>") 14148 + " contains upgrade-key-set reference to unknown key-set: " 14149 + upgradeKeySets[i] 14150 + " reverting to signatures check."); 14151 return false; 14152 } 14153 } 14154 return true; 14155 } 14156 14157 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14158 // Upgrade keysets are being used. Determine if new package has a superset of the 14159 // required keys. 14160 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14161 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14162 for (int i = 0; i < upgradeKeySets.length; i++) { 14163 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14164 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14165 return true; 14166 } 14167 } 14168 return false; 14169 } 14170 14171 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14172 try (DigestInputStream digestStream = 14173 new DigestInputStream(new FileInputStream(file), digest)) { 14174 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14175 } 14176 } 14177 14178 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14179 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14180 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14181 14182 final PackageParser.Package oldPackage; 14183 final String pkgName = pkg.packageName; 14184 final int[] allUsers; 14185 final int[] installedUsers; 14186 14187 synchronized(mPackages) { 14188 oldPackage = mPackages.get(pkgName); 14189 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14190 14191 // don't allow upgrade to target a release SDK from a pre-release SDK 14192 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14193 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14194 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14195 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14196 if (oldTargetsPreRelease 14197 && !newTargetsPreRelease 14198 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14199 Slog.w(TAG, "Can't install package targeting released sdk"); 14200 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14201 return; 14202 } 14203 14204 // don't allow an upgrade from full to ephemeral 14205 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14206 if (isEphemeral && !oldIsEphemeral) { 14207 // can't downgrade from full to ephemeral 14208 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14209 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14210 return; 14211 } 14212 14213 // verify signatures are valid 14214 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14215 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14216 if (!checkUpgradeKeySetLP(ps, pkg)) { 14217 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14218 "New package not signed by keys specified by upgrade-keysets: " 14219 + pkgName); 14220 return; 14221 } 14222 } else { 14223 // default to original signature matching 14224 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14225 != PackageManager.SIGNATURE_MATCH) { 14226 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14227 "New package has a different signature: " + pkgName); 14228 return; 14229 } 14230 } 14231 14232 // don't allow a system upgrade unless the upgrade hash matches 14233 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14234 byte[] digestBytes = null; 14235 try { 14236 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14237 updateDigest(digest, new File(pkg.baseCodePath)); 14238 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14239 for (String path : pkg.splitCodePaths) { 14240 updateDigest(digest, new File(path)); 14241 } 14242 } 14243 digestBytes = digest.digest(); 14244 } catch (NoSuchAlgorithmException | IOException e) { 14245 res.setError(INSTALL_FAILED_INVALID_APK, 14246 "Could not compute hash: " + pkgName); 14247 return; 14248 } 14249 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14250 res.setError(INSTALL_FAILED_INVALID_APK, 14251 "New package fails restrict-update check: " + pkgName); 14252 return; 14253 } 14254 // retain upgrade restriction 14255 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14256 } 14257 14258 // Check for shared user id changes 14259 String invalidPackageName = 14260 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14261 if (invalidPackageName != null) { 14262 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14263 "Package " + invalidPackageName + " tried to change user " 14264 + oldPackage.mSharedUserId); 14265 return; 14266 } 14267 14268 // In case of rollback, remember per-user/profile install state 14269 allUsers = sUserManager.getUserIds(); 14270 installedUsers = ps.queryInstalledUsers(allUsers, true); 14271 } 14272 14273 // Update what is removed 14274 res.removedInfo = new PackageRemovedInfo(); 14275 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14276 res.removedInfo.removedPackage = oldPackage.packageName; 14277 res.removedInfo.isUpdate = true; 14278 res.removedInfo.origUsers = installedUsers; 14279 final int childCount = (oldPackage.childPackages != null) 14280 ? oldPackage.childPackages.size() : 0; 14281 for (int i = 0; i < childCount; i++) { 14282 boolean childPackageUpdated = false; 14283 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14284 if (res.addedChildPackages != null) { 14285 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14286 if (childRes != null) { 14287 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14288 childRes.removedInfo.removedPackage = childPkg.packageName; 14289 childRes.removedInfo.isUpdate = true; 14290 childPackageUpdated = true; 14291 } 14292 } 14293 if (!childPackageUpdated) { 14294 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14295 childRemovedRes.removedPackage = childPkg.packageName; 14296 childRemovedRes.isUpdate = false; 14297 childRemovedRes.dataRemoved = true; 14298 synchronized (mPackages) { 14299 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14300 if (childPs != null) { 14301 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14302 } 14303 } 14304 if (res.removedInfo.removedChildPackages == null) { 14305 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14306 } 14307 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14308 } 14309 } 14310 14311 boolean sysPkg = (isSystemApp(oldPackage)); 14312 if (sysPkg) { 14313 // Set the system/privileged flags as needed 14314 final boolean privileged = 14315 (oldPackage.applicationInfo.privateFlags 14316 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14317 final int systemPolicyFlags = policyFlags 14318 | PackageParser.PARSE_IS_SYSTEM 14319 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14320 14321 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14322 user, allUsers, installerPackageName, res); 14323 } else { 14324 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14325 user, allUsers, installerPackageName, res); 14326 } 14327 } 14328 14329 public List<String> getPreviousCodePaths(String packageName) { 14330 final PackageSetting ps = mSettings.mPackages.get(packageName); 14331 final List<String> result = new ArrayList<String>(); 14332 if (ps != null && ps.oldCodePaths != null) { 14333 result.addAll(ps.oldCodePaths); 14334 } 14335 return result; 14336 } 14337 14338 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14339 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14340 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14341 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14342 + deletedPackage); 14343 14344 String pkgName = deletedPackage.packageName; 14345 boolean deletedPkg = true; 14346 boolean addedPkg = false; 14347 boolean updatedSettings = false; 14348 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14349 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14350 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14351 14352 final long origUpdateTime = (pkg.mExtras != null) 14353 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14354 14355 // First delete the existing package while retaining the data directory 14356 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14357 res.removedInfo, true, pkg)) { 14358 // If the existing package wasn't successfully deleted 14359 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14360 deletedPkg = false; 14361 } else { 14362 // Successfully deleted the old package; proceed with replace. 14363 14364 // If deleted package lived in a container, give users a chance to 14365 // relinquish resources before killing. 14366 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14367 if (DEBUG_INSTALL) { 14368 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14369 } 14370 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14371 final ArrayList<String> pkgList = new ArrayList<String>(1); 14372 pkgList.add(deletedPackage.applicationInfo.packageName); 14373 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14374 } 14375 14376 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14377 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14378 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14379 14380 try { 14381 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14382 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14383 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14384 14385 // Update the in-memory copy of the previous code paths. 14386 PackageSetting ps = mSettings.mPackages.get(pkgName); 14387 if (!killApp) { 14388 if (ps.oldCodePaths == null) { 14389 ps.oldCodePaths = new ArraySet<>(); 14390 } 14391 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14392 if (deletedPackage.splitCodePaths != null) { 14393 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14394 } 14395 } else { 14396 ps.oldCodePaths = null; 14397 } 14398 if (ps.childPackageNames != null) { 14399 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14400 final String childPkgName = ps.childPackageNames.get(i); 14401 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14402 childPs.oldCodePaths = ps.oldCodePaths; 14403 } 14404 } 14405 prepareAppDataAfterInstallLIF(newPackage); 14406 addedPkg = true; 14407 } catch (PackageManagerException e) { 14408 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14409 } 14410 } 14411 14412 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14413 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14414 14415 // Revert all internal state mutations and added folders for the failed install 14416 if (addedPkg) { 14417 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14418 res.removedInfo, true, null); 14419 } 14420 14421 // Restore the old package 14422 if (deletedPkg) { 14423 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14424 File restoreFile = new File(deletedPackage.codePath); 14425 // Parse old package 14426 boolean oldExternal = isExternal(deletedPackage); 14427 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14428 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14429 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14430 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14431 try { 14432 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14433 null); 14434 } catch (PackageManagerException e) { 14435 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14436 + e.getMessage()); 14437 return; 14438 } 14439 14440 synchronized (mPackages) { 14441 // Ensure the installer package name up to date 14442 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14443 14444 // Update permissions for restored package 14445 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14446 14447 mSettings.writeLPr(); 14448 } 14449 14450 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14451 } 14452 } else { 14453 synchronized (mPackages) { 14454 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14455 if (ps != null) { 14456 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14457 if (res.removedInfo.removedChildPackages != null) { 14458 final int childCount = res.removedInfo.removedChildPackages.size(); 14459 // Iterate in reverse as we may modify the collection 14460 for (int i = childCount - 1; i >= 0; i--) { 14461 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14462 if (res.addedChildPackages.containsKey(childPackageName)) { 14463 res.removedInfo.removedChildPackages.removeAt(i); 14464 } else { 14465 PackageRemovedInfo childInfo = res.removedInfo 14466 .removedChildPackages.valueAt(i); 14467 childInfo.removedForAllUsers = mPackages.get( 14468 childInfo.removedPackage) == null; 14469 } 14470 } 14471 } 14472 } 14473 } 14474 } 14475 } 14476 14477 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14478 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14479 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14480 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14481 + ", old=" + deletedPackage); 14482 14483 final boolean disabledSystem; 14484 14485 // Remove existing system package 14486 removePackageLI(deletedPackage, true); 14487 14488 synchronized (mPackages) { 14489 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14490 } 14491 if (!disabledSystem) { 14492 // We didn't need to disable the .apk as a current system package, 14493 // which means we are replacing another update that is already 14494 // installed. We need to make sure to delete the older one's .apk. 14495 res.removedInfo.args = createInstallArgsForExisting(0, 14496 deletedPackage.applicationInfo.getCodePath(), 14497 deletedPackage.applicationInfo.getResourcePath(), 14498 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14499 } else { 14500 res.removedInfo.args = null; 14501 } 14502 14503 // Successfully disabled the old package. Now proceed with re-installation 14504 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14505 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14506 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14507 14508 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14509 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14510 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14511 14512 PackageParser.Package newPackage = null; 14513 try { 14514 // Add the package to the internal data structures 14515 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14516 14517 // Set the update and install times 14518 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14519 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14520 System.currentTimeMillis()); 14521 14522 // Update the package dynamic state if succeeded 14523 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14524 // Now that the install succeeded make sure we remove data 14525 // directories for any child package the update removed. 14526 final int deletedChildCount = (deletedPackage.childPackages != null) 14527 ? deletedPackage.childPackages.size() : 0; 14528 final int newChildCount = (newPackage.childPackages != null) 14529 ? newPackage.childPackages.size() : 0; 14530 for (int i = 0; i < deletedChildCount; i++) { 14531 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14532 boolean childPackageDeleted = true; 14533 for (int j = 0; j < newChildCount; j++) { 14534 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14535 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14536 childPackageDeleted = false; 14537 break; 14538 } 14539 } 14540 if (childPackageDeleted) { 14541 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14542 deletedChildPkg.packageName); 14543 if (ps != null && res.removedInfo.removedChildPackages != null) { 14544 PackageRemovedInfo removedChildRes = res.removedInfo 14545 .removedChildPackages.get(deletedChildPkg.packageName); 14546 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14547 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14548 } 14549 } 14550 } 14551 14552 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14553 prepareAppDataAfterInstallLIF(newPackage); 14554 } 14555 } catch (PackageManagerException e) { 14556 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14557 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14558 } 14559 14560 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14561 // Re installation failed. Restore old information 14562 // Remove new pkg information 14563 if (newPackage != null) { 14564 removeInstalledPackageLI(newPackage, true); 14565 } 14566 // Add back the old system package 14567 try { 14568 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14569 } catch (PackageManagerException e) { 14570 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14571 } 14572 14573 synchronized (mPackages) { 14574 if (disabledSystem) { 14575 enableSystemPackageLPw(deletedPackage); 14576 } 14577 14578 // Ensure the installer package name up to date 14579 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14580 14581 // Update permissions for restored package 14582 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14583 14584 mSettings.writeLPr(); 14585 } 14586 14587 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14588 + " after failed upgrade"); 14589 } 14590 } 14591 14592 /** 14593 * Checks whether the parent or any of the child packages have a change shared 14594 * user. For a package to be a valid update the shred users of the parent and 14595 * the children should match. We may later support changing child shared users. 14596 * @param oldPkg The updated package. 14597 * @param newPkg The update package. 14598 * @return The shared user that change between the versions. 14599 */ 14600 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14601 PackageParser.Package newPkg) { 14602 // Check parent shared user 14603 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14604 return newPkg.packageName; 14605 } 14606 // Check child shared users 14607 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14608 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14609 for (int i = 0; i < newChildCount; i++) { 14610 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14611 // If this child was present, did it have the same shared user? 14612 for (int j = 0; j < oldChildCount; j++) { 14613 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14614 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14615 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14616 return newChildPkg.packageName; 14617 } 14618 } 14619 } 14620 return null; 14621 } 14622 14623 private void removeNativeBinariesLI(PackageSetting ps) { 14624 // Remove the lib path for the parent package 14625 if (ps != null) { 14626 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14627 // Remove the lib path for the child packages 14628 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14629 for (int i = 0; i < childCount; i++) { 14630 PackageSetting childPs = null; 14631 synchronized (mPackages) { 14632 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14633 } 14634 if (childPs != null) { 14635 NativeLibraryHelper.removeNativeBinariesLI(childPs 14636 .legacyNativeLibraryPathString); 14637 } 14638 } 14639 } 14640 } 14641 14642 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14643 // Enable the parent package 14644 mSettings.enableSystemPackageLPw(pkg.packageName); 14645 // Enable the child packages 14646 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14647 for (int i = 0; i < childCount; i++) { 14648 PackageParser.Package childPkg = pkg.childPackages.get(i); 14649 mSettings.enableSystemPackageLPw(childPkg.packageName); 14650 } 14651 } 14652 14653 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14654 PackageParser.Package newPkg) { 14655 // Disable the parent package (parent always replaced) 14656 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14657 // Disable the child packages 14658 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14659 for (int i = 0; i < childCount; i++) { 14660 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14661 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14662 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14663 } 14664 return disabled; 14665 } 14666 14667 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14668 String installerPackageName) { 14669 // Enable the parent package 14670 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14671 // Enable the child packages 14672 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14673 for (int i = 0; i < childCount; i++) { 14674 PackageParser.Package childPkg = pkg.childPackages.get(i); 14675 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14676 } 14677 } 14678 14679 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14680 // Collect all used permissions in the UID 14681 ArraySet<String> usedPermissions = new ArraySet<>(); 14682 final int packageCount = su.packages.size(); 14683 for (int i = 0; i < packageCount; i++) { 14684 PackageSetting ps = su.packages.valueAt(i); 14685 if (ps.pkg == null) { 14686 continue; 14687 } 14688 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14689 for (int j = 0; j < requestedPermCount; j++) { 14690 String permission = ps.pkg.requestedPermissions.get(j); 14691 BasePermission bp = mSettings.mPermissions.get(permission); 14692 if (bp != null) { 14693 usedPermissions.add(permission); 14694 } 14695 } 14696 } 14697 14698 PermissionsState permissionsState = su.getPermissionsState(); 14699 // Prune install permissions 14700 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14701 final int installPermCount = installPermStates.size(); 14702 for (int i = installPermCount - 1; i >= 0; i--) { 14703 PermissionState permissionState = installPermStates.get(i); 14704 if (!usedPermissions.contains(permissionState.getName())) { 14705 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14706 if (bp != null) { 14707 permissionsState.revokeInstallPermission(bp); 14708 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14709 PackageManager.MASK_PERMISSION_FLAGS, 0); 14710 } 14711 } 14712 } 14713 14714 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14715 14716 // Prune runtime permissions 14717 for (int userId : allUserIds) { 14718 List<PermissionState> runtimePermStates = permissionsState 14719 .getRuntimePermissionStates(userId); 14720 final int runtimePermCount = runtimePermStates.size(); 14721 for (int i = runtimePermCount - 1; i >= 0; i--) { 14722 PermissionState permissionState = runtimePermStates.get(i); 14723 if (!usedPermissions.contains(permissionState.getName())) { 14724 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14725 if (bp != null) { 14726 permissionsState.revokeRuntimePermission(bp, userId); 14727 permissionsState.updatePermissionFlags(bp, userId, 14728 PackageManager.MASK_PERMISSION_FLAGS, 0); 14729 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14730 runtimePermissionChangedUserIds, userId); 14731 } 14732 } 14733 } 14734 } 14735 14736 return runtimePermissionChangedUserIds; 14737 } 14738 14739 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14740 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14741 // Update the parent package setting 14742 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14743 res, user); 14744 // Update the child packages setting 14745 final int childCount = (newPackage.childPackages != null) 14746 ? newPackage.childPackages.size() : 0; 14747 for (int i = 0; i < childCount; i++) { 14748 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14749 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14750 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14751 childRes.origUsers, childRes, user); 14752 } 14753 } 14754 14755 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14756 String installerPackageName, int[] allUsers, int[] installedForUsers, 14757 PackageInstalledInfo res, UserHandle user) { 14758 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14759 14760 String pkgName = newPackage.packageName; 14761 synchronized (mPackages) { 14762 //write settings. the installStatus will be incomplete at this stage. 14763 //note that the new package setting would have already been 14764 //added to mPackages. It hasn't been persisted yet. 14765 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14766 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14767 mSettings.writeLPr(); 14768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14769 } 14770 14771 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14772 synchronized (mPackages) { 14773 updatePermissionsLPw(newPackage.packageName, newPackage, 14774 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14775 ? UPDATE_PERMISSIONS_ALL : 0)); 14776 // For system-bundled packages, we assume that installing an upgraded version 14777 // of the package implies that the user actually wants to run that new code, 14778 // so we enable the package. 14779 PackageSetting ps = mSettings.mPackages.get(pkgName); 14780 final int userId = user.getIdentifier(); 14781 if (ps != null) { 14782 if (isSystemApp(newPackage)) { 14783 if (DEBUG_INSTALL) { 14784 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14785 } 14786 // Enable system package for requested users 14787 if (res.origUsers != null) { 14788 for (int origUserId : res.origUsers) { 14789 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14790 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14791 origUserId, installerPackageName); 14792 } 14793 } 14794 } 14795 // Also convey the prior install/uninstall state 14796 if (allUsers != null && installedForUsers != null) { 14797 for (int currentUserId : allUsers) { 14798 final boolean installed = ArrayUtils.contains( 14799 installedForUsers, currentUserId); 14800 if (DEBUG_INSTALL) { 14801 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14802 } 14803 ps.setInstalled(installed, currentUserId); 14804 } 14805 // these install state changes will be persisted in the 14806 // upcoming call to mSettings.writeLPr(). 14807 } 14808 } 14809 // It's implied that when a user requests installation, they want the app to be 14810 // installed and enabled. 14811 if (userId != UserHandle.USER_ALL) { 14812 ps.setInstalled(true, userId); 14813 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14814 } 14815 } 14816 res.name = pkgName; 14817 res.uid = newPackage.applicationInfo.uid; 14818 res.pkg = newPackage; 14819 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14820 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14821 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14822 //to update install status 14823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14824 mSettings.writeLPr(); 14825 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14826 } 14827 14828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14829 } 14830 14831 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14832 try { 14833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14834 installPackageLI(args, res); 14835 } finally { 14836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14837 } 14838 } 14839 14840 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14841 final int installFlags = args.installFlags; 14842 final String installerPackageName = args.installerPackageName; 14843 final String volumeUuid = args.volumeUuid; 14844 final File tmpPackageFile = new File(args.getCodePath()); 14845 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14846 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14847 || (args.volumeUuid != null)); 14848 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14849 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14850 boolean replace = false; 14851 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14852 if (args.move != null) { 14853 // moving a complete application; perform an initial scan on the new install location 14854 scanFlags |= SCAN_INITIAL; 14855 } 14856 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14857 scanFlags |= SCAN_DONT_KILL_APP; 14858 } 14859 14860 // Result object to be returned 14861 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14862 14863 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14864 14865 // Sanity check 14866 if (ephemeral && (forwardLocked || onExternal)) { 14867 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14868 + " external=" + onExternal); 14869 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14870 return; 14871 } 14872 14873 // Retrieve PackageSettings and parse package 14874 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14875 | PackageParser.PARSE_ENFORCE_CODE 14876 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14877 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14878 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14879 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14880 PackageParser pp = new PackageParser(); 14881 pp.setSeparateProcesses(mSeparateProcesses); 14882 pp.setDisplayMetrics(mMetrics); 14883 14884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14885 final PackageParser.Package pkg; 14886 try { 14887 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14888 } catch (PackageParserException e) { 14889 res.setError("Failed parse during installPackageLI", e); 14890 return; 14891 } finally { 14892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14893 } 14894 14895 // If we are installing a clustered package add results for the children 14896 if (pkg.childPackages != null) { 14897 synchronized (mPackages) { 14898 final int childCount = pkg.childPackages.size(); 14899 for (int i = 0; i < childCount; i++) { 14900 PackageParser.Package childPkg = pkg.childPackages.get(i); 14901 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14902 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14903 childRes.pkg = childPkg; 14904 childRes.name = childPkg.packageName; 14905 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14906 if (childPs != null) { 14907 childRes.origUsers = childPs.queryInstalledUsers( 14908 sUserManager.getUserIds(), true); 14909 } 14910 if ((mPackages.containsKey(childPkg.packageName))) { 14911 childRes.removedInfo = new PackageRemovedInfo(); 14912 childRes.removedInfo.removedPackage = childPkg.packageName; 14913 } 14914 if (res.addedChildPackages == null) { 14915 res.addedChildPackages = new ArrayMap<>(); 14916 } 14917 res.addedChildPackages.put(childPkg.packageName, childRes); 14918 } 14919 } 14920 } 14921 14922 // If package doesn't declare API override, mark that we have an install 14923 // time CPU ABI override. 14924 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14925 pkg.cpuAbiOverride = args.abiOverride; 14926 } 14927 14928 String pkgName = res.name = pkg.packageName; 14929 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14930 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14931 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14932 return; 14933 } 14934 } 14935 14936 try { 14937 // either use what we've been given or parse directly from the APK 14938 if (args.certificates != null) { 14939 try { 14940 PackageParser.populateCertificates(pkg, args.certificates); 14941 } catch (PackageParserException e) { 14942 // there was something wrong with the certificates we were given; 14943 // try to pull them from the APK 14944 PackageParser.collectCertificates(pkg, parseFlags); 14945 } 14946 } else { 14947 PackageParser.collectCertificates(pkg, parseFlags); 14948 } 14949 } catch (PackageParserException e) { 14950 res.setError("Failed collect during installPackageLI", e); 14951 return; 14952 } 14953 14954 // Get rid of all references to package scan path via parser. 14955 pp = null; 14956 String oldCodePath = null; 14957 boolean systemApp = false; 14958 synchronized (mPackages) { 14959 // Check if installing already existing package 14960 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14961 String oldName = mSettings.mRenamedPackages.get(pkgName); 14962 if (pkg.mOriginalPackages != null 14963 && pkg.mOriginalPackages.contains(oldName) 14964 && mPackages.containsKey(oldName)) { 14965 // This package is derived from an original package, 14966 // and this device has been updating from that original 14967 // name. We must continue using the original name, so 14968 // rename the new package here. 14969 pkg.setPackageName(oldName); 14970 pkgName = pkg.packageName; 14971 replace = true; 14972 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14973 + oldName + " pkgName=" + pkgName); 14974 } else if (mPackages.containsKey(pkgName)) { 14975 // This package, under its official name, already exists 14976 // on the device; we should replace it. 14977 replace = true; 14978 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14979 } 14980 14981 // Child packages are installed through the parent package 14982 if (pkg.parentPackage != null) { 14983 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14984 "Package " + pkg.packageName + " is child of package " 14985 + pkg.parentPackage.parentPackage + ". Child packages " 14986 + "can be updated only through the parent package."); 14987 return; 14988 } 14989 14990 if (replace) { 14991 // Prevent apps opting out from runtime permissions 14992 PackageParser.Package oldPackage = mPackages.get(pkgName); 14993 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14994 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14995 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14996 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14997 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14998 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14999 + " doesn't support runtime permissions but the old" 15000 + " target SDK " + oldTargetSdk + " does."); 15001 return; 15002 } 15003 15004 // Prevent installing of child packages 15005 if (oldPackage.parentPackage != null) { 15006 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15007 "Package " + pkg.packageName + " is child of package " 15008 + oldPackage.parentPackage + ". Child packages " 15009 + "can be updated only through the parent package."); 15010 return; 15011 } 15012 } 15013 } 15014 15015 PackageSetting ps = mSettings.mPackages.get(pkgName); 15016 if (ps != null) { 15017 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15018 15019 // Quick sanity check that we're signed correctly if updating; 15020 // we'll check this again later when scanning, but we want to 15021 // bail early here before tripping over redefined permissions. 15022 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15023 if (!checkUpgradeKeySetLP(ps, pkg)) { 15024 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15025 + pkg.packageName + " upgrade keys do not match the " 15026 + "previously installed version"); 15027 return; 15028 } 15029 } else { 15030 try { 15031 verifySignaturesLP(ps, pkg); 15032 } catch (PackageManagerException e) { 15033 res.setError(e.error, e.getMessage()); 15034 return; 15035 } 15036 } 15037 15038 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15039 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15040 systemApp = (ps.pkg.applicationInfo.flags & 15041 ApplicationInfo.FLAG_SYSTEM) != 0; 15042 } 15043 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15044 } 15045 15046 // Check whether the newly-scanned package wants to define an already-defined perm 15047 int N = pkg.permissions.size(); 15048 for (int i = N-1; i >= 0; i--) { 15049 PackageParser.Permission perm = pkg.permissions.get(i); 15050 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15051 if (bp != null) { 15052 // If the defining package is signed with our cert, it's okay. This 15053 // also includes the "updating the same package" case, of course. 15054 // "updating same package" could also involve key-rotation. 15055 final boolean sigsOk; 15056 if (bp.sourcePackage.equals(pkg.packageName) 15057 && (bp.packageSetting instanceof PackageSetting) 15058 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15059 scanFlags))) { 15060 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15061 } else { 15062 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15063 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15064 } 15065 if (!sigsOk) { 15066 // If the owning package is the system itself, we log but allow 15067 // install to proceed; we fail the install on all other permission 15068 // redefinitions. 15069 if (!bp.sourcePackage.equals("android")) { 15070 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15071 + pkg.packageName + " attempting to redeclare permission " 15072 + perm.info.name + " already owned by " + bp.sourcePackage); 15073 res.origPermission = perm.info.name; 15074 res.origPackage = bp.sourcePackage; 15075 return; 15076 } else { 15077 Slog.w(TAG, "Package " + pkg.packageName 15078 + " attempting to redeclare system permission " 15079 + perm.info.name + "; ignoring new declaration"); 15080 pkg.permissions.remove(i); 15081 } 15082 } 15083 } 15084 } 15085 } 15086 15087 if (systemApp) { 15088 if (onExternal) { 15089 // Abort update; system app can't be replaced with app on sdcard 15090 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15091 "Cannot install updates to system apps on sdcard"); 15092 return; 15093 } else if (ephemeral) { 15094 // Abort update; system app can't be replaced with an ephemeral app 15095 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15096 "Cannot update a system app with an ephemeral app"); 15097 return; 15098 } 15099 } 15100 15101 if (args.move != null) { 15102 // We did an in-place move, so dex is ready to roll 15103 scanFlags |= SCAN_NO_DEX; 15104 scanFlags |= SCAN_MOVE; 15105 15106 synchronized (mPackages) { 15107 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15108 if (ps == null) { 15109 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15110 "Missing settings for moved package " + pkgName); 15111 } 15112 15113 // We moved the entire application as-is, so bring over the 15114 // previously derived ABI information. 15115 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15116 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15117 } 15118 15119 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15120 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15121 scanFlags |= SCAN_NO_DEX; 15122 15123 try { 15124 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15125 args.abiOverride : pkg.cpuAbiOverride); 15126 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15127 true /* extract libs */); 15128 } catch (PackageManagerException pme) { 15129 Slog.e(TAG, "Error deriving application ABI", pme); 15130 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15131 return; 15132 } 15133 15134 // Shared libraries for the package need to be updated. 15135 synchronized (mPackages) { 15136 try { 15137 updateSharedLibrariesLPw(pkg, null); 15138 } catch (PackageManagerException e) { 15139 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15140 } 15141 } 15142 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15143 // Do not run PackageDexOptimizer through the local performDexOpt 15144 // method because `pkg` may not be in `mPackages` yet. 15145 // 15146 // Also, don't fail application installs if the dexopt step fails. 15147 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15148 null /* instructionSets */, false /* checkProfiles */, 15149 getCompilerFilterForReason(REASON_INSTALL)); 15150 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15151 15152 // Notify BackgroundDexOptService that the package has been changed. 15153 // If this is an update of a package which used to fail to compile, 15154 // BDOS will remove it from its blacklist. 15155 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15156 } 15157 15158 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15159 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15160 return; 15161 } 15162 15163 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15164 15165 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15166 "installPackageLI")) { 15167 if (replace) { 15168 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15169 installerPackageName, res); 15170 } else { 15171 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15172 args.user, installerPackageName, volumeUuid, res); 15173 } 15174 } 15175 synchronized (mPackages) { 15176 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15177 if (ps != null) { 15178 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15179 } 15180 15181 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15182 for (int i = 0; i < childCount; i++) { 15183 PackageParser.Package childPkg = pkg.childPackages.get(i); 15184 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15185 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15186 if (childPs != null) { 15187 childRes.newUsers = childPs.queryInstalledUsers( 15188 sUserManager.getUserIds(), true); 15189 } 15190 } 15191 } 15192 } 15193 15194 private void startIntentFilterVerifications(int userId, boolean replacing, 15195 PackageParser.Package pkg) { 15196 if (mIntentFilterVerifierComponent == null) { 15197 Slog.w(TAG, "No IntentFilter verification will not be done as " 15198 + "there is no IntentFilterVerifier available!"); 15199 return; 15200 } 15201 15202 final int verifierUid = getPackageUid( 15203 mIntentFilterVerifierComponent.getPackageName(), 15204 MATCH_DEBUG_TRIAGED_MISSING, 15205 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15206 15207 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15208 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15209 mHandler.sendMessage(msg); 15210 15211 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15212 for (int i = 0; i < childCount; i++) { 15213 PackageParser.Package childPkg = pkg.childPackages.get(i); 15214 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15215 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15216 mHandler.sendMessage(msg); 15217 } 15218 } 15219 15220 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15221 PackageParser.Package pkg) { 15222 int size = pkg.activities.size(); 15223 if (size == 0) { 15224 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15225 "No activity, so no need to verify any IntentFilter!"); 15226 return; 15227 } 15228 15229 final boolean hasDomainURLs = hasDomainURLs(pkg); 15230 if (!hasDomainURLs) { 15231 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15232 "No domain URLs, so no need to verify any IntentFilter!"); 15233 return; 15234 } 15235 15236 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15237 + " if any IntentFilter from the " + size 15238 + " Activities needs verification ..."); 15239 15240 int count = 0; 15241 final String packageName = pkg.packageName; 15242 15243 synchronized (mPackages) { 15244 // If this is a new install and we see that we've already run verification for this 15245 // package, we have nothing to do: it means the state was restored from backup. 15246 if (!replacing) { 15247 IntentFilterVerificationInfo ivi = 15248 mSettings.getIntentFilterVerificationLPr(packageName); 15249 if (ivi != null) { 15250 if (DEBUG_DOMAIN_VERIFICATION) { 15251 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15252 + ivi.getStatusString()); 15253 } 15254 return; 15255 } 15256 } 15257 15258 // If any filters need to be verified, then all need to be. 15259 boolean needToVerify = false; 15260 for (PackageParser.Activity a : pkg.activities) { 15261 for (ActivityIntentInfo filter : a.intents) { 15262 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15263 if (DEBUG_DOMAIN_VERIFICATION) { 15264 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15265 } 15266 needToVerify = true; 15267 break; 15268 } 15269 } 15270 } 15271 15272 if (needToVerify) { 15273 final int verificationId = mIntentFilterVerificationToken++; 15274 for (PackageParser.Activity a : pkg.activities) { 15275 for (ActivityIntentInfo filter : a.intents) { 15276 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15277 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15278 "Verification needed for IntentFilter:" + filter.toString()); 15279 mIntentFilterVerifier.addOneIntentFilterVerification( 15280 verifierUid, userId, verificationId, filter, packageName); 15281 count++; 15282 } 15283 } 15284 } 15285 } 15286 } 15287 15288 if (count > 0) { 15289 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15290 + " IntentFilter verification" + (count > 1 ? "s" : "") 15291 + " for userId:" + userId); 15292 mIntentFilterVerifier.startVerifications(userId); 15293 } else { 15294 if (DEBUG_DOMAIN_VERIFICATION) { 15295 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15296 } 15297 } 15298 } 15299 15300 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15301 final ComponentName cn = filter.activity.getComponentName(); 15302 final String packageName = cn.getPackageName(); 15303 15304 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15305 packageName); 15306 if (ivi == null) { 15307 return true; 15308 } 15309 int status = ivi.getStatus(); 15310 switch (status) { 15311 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15312 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15313 return true; 15314 15315 default: 15316 // Nothing to do 15317 return false; 15318 } 15319 } 15320 15321 private static boolean isMultiArch(ApplicationInfo info) { 15322 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15323 } 15324 15325 private static boolean isExternal(PackageParser.Package pkg) { 15326 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15327 } 15328 15329 private static boolean isExternal(PackageSetting ps) { 15330 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15331 } 15332 15333 private static boolean isEphemeral(PackageParser.Package pkg) { 15334 return pkg.applicationInfo.isEphemeralApp(); 15335 } 15336 15337 private static boolean isEphemeral(PackageSetting ps) { 15338 return ps.pkg != null && isEphemeral(ps.pkg); 15339 } 15340 15341 private static boolean isSystemApp(PackageParser.Package pkg) { 15342 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15343 } 15344 15345 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15346 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15347 } 15348 15349 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15350 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15351 } 15352 15353 private static boolean isSystemApp(PackageSetting ps) { 15354 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15355 } 15356 15357 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15358 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15359 } 15360 15361 private int packageFlagsToInstallFlags(PackageSetting ps) { 15362 int installFlags = 0; 15363 if (isEphemeral(ps)) { 15364 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15365 } 15366 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15367 // This existing package was an external ASEC install when we have 15368 // the external flag without a UUID 15369 installFlags |= PackageManager.INSTALL_EXTERNAL; 15370 } 15371 if (ps.isForwardLocked()) { 15372 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15373 } 15374 return installFlags; 15375 } 15376 15377 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15378 if (isExternal(pkg)) { 15379 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15380 return StorageManager.UUID_PRIMARY_PHYSICAL; 15381 } else { 15382 return pkg.volumeUuid; 15383 } 15384 } else { 15385 return StorageManager.UUID_PRIVATE_INTERNAL; 15386 } 15387 } 15388 15389 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15390 if (isExternal(pkg)) { 15391 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15392 return mSettings.getExternalVersion(); 15393 } else { 15394 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15395 } 15396 } else { 15397 return mSettings.getInternalVersion(); 15398 } 15399 } 15400 15401 private void deleteTempPackageFiles() { 15402 final FilenameFilter filter = new FilenameFilter() { 15403 public boolean accept(File dir, String name) { 15404 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15405 } 15406 }; 15407 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15408 file.delete(); 15409 } 15410 } 15411 15412 @Override 15413 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15414 int flags) { 15415 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15416 flags); 15417 } 15418 15419 @Override 15420 public void deletePackage(final String packageName, 15421 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15422 mContext.enforceCallingOrSelfPermission( 15423 android.Manifest.permission.DELETE_PACKAGES, null); 15424 Preconditions.checkNotNull(packageName); 15425 Preconditions.checkNotNull(observer); 15426 final int uid = Binder.getCallingUid(); 15427 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15428 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15429 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15430 mContext.enforceCallingOrSelfPermission( 15431 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15432 "deletePackage for user " + userId); 15433 } 15434 15435 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15436 try { 15437 observer.onPackageDeleted(packageName, 15438 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15439 } catch (RemoteException re) { 15440 } 15441 return; 15442 } 15443 15444 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15445 try { 15446 observer.onPackageDeleted(packageName, 15447 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15448 } catch (RemoteException re) { 15449 } 15450 return; 15451 } 15452 15453 if (DEBUG_REMOVE) { 15454 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15455 + " deleteAllUsers: " + deleteAllUsers ); 15456 } 15457 // Queue up an async operation since the package deletion may take a little while. 15458 mHandler.post(new Runnable() { 15459 public void run() { 15460 mHandler.removeCallbacks(this); 15461 int returnCode; 15462 if (!deleteAllUsers) { 15463 returnCode = deletePackageX(packageName, userId, deleteFlags); 15464 } else { 15465 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15466 // If nobody is blocking uninstall, proceed with delete for all users 15467 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15468 returnCode = deletePackageX(packageName, userId, deleteFlags); 15469 } else { 15470 // Otherwise uninstall individually for users with blockUninstalls=false 15471 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15472 for (int userId : users) { 15473 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15474 returnCode = deletePackageX(packageName, userId, userFlags); 15475 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15476 Slog.w(TAG, "Package delete failed for user " + userId 15477 + ", returnCode " + returnCode); 15478 } 15479 } 15480 } 15481 // The app has only been marked uninstalled for certain users. 15482 // We still need to report that delete was blocked 15483 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15484 } 15485 } 15486 try { 15487 observer.onPackageDeleted(packageName, returnCode, null); 15488 } catch (RemoteException e) { 15489 Log.i(TAG, "Observer no longer exists."); 15490 } //end catch 15491 } //end run 15492 }); 15493 } 15494 15495 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15496 int[] result = EMPTY_INT_ARRAY; 15497 for (int userId : userIds) { 15498 if (getBlockUninstallForUser(packageName, userId)) { 15499 result = ArrayUtils.appendInt(result, userId); 15500 } 15501 } 15502 return result; 15503 } 15504 15505 @Override 15506 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15507 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15508 } 15509 15510 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15511 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15512 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15513 try { 15514 if (dpm != null) { 15515 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15516 /* callingUserOnly =*/ false); 15517 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15518 : deviceOwnerComponentName.getPackageName(); 15519 // Does the package contains the device owner? 15520 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15521 // this check is probably not needed, since DO should be registered as a device 15522 // admin on some user too. (Original bug for this: b/17657954) 15523 if (packageName.equals(deviceOwnerPackageName)) { 15524 return true; 15525 } 15526 // Does it contain a device admin for any user? 15527 int[] users; 15528 if (userId == UserHandle.USER_ALL) { 15529 users = sUserManager.getUserIds(); 15530 } else { 15531 users = new int[]{userId}; 15532 } 15533 for (int i = 0; i < users.length; ++i) { 15534 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15535 return true; 15536 } 15537 } 15538 } 15539 } catch (RemoteException e) { 15540 } 15541 return false; 15542 } 15543 15544 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15545 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15546 } 15547 15548 /** 15549 * This method is an internal method that could be get invoked either 15550 * to delete an installed package or to clean up a failed installation. 15551 * After deleting an installed package, a broadcast is sent to notify any 15552 * listeners that the package has been removed. For cleaning up a failed 15553 * installation, the broadcast is not necessary since the package's 15554 * installation wouldn't have sent the initial broadcast either 15555 * The key steps in deleting a package are 15556 * deleting the package information in internal structures like mPackages, 15557 * deleting the packages base directories through installd 15558 * updating mSettings to reflect current status 15559 * persisting settings for later use 15560 * sending a broadcast if necessary 15561 */ 15562 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15563 final PackageRemovedInfo info = new PackageRemovedInfo(); 15564 final boolean res; 15565 15566 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15567 ? UserHandle.ALL : new UserHandle(userId); 15568 15569 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15570 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15571 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15572 } 15573 15574 PackageSetting uninstalledPs = null; 15575 15576 // for the uninstall-updates case and restricted profiles, remember the per- 15577 // user handle installed state 15578 int[] allUsers; 15579 synchronized (mPackages) { 15580 uninstalledPs = mSettings.mPackages.get(packageName); 15581 if (uninstalledPs == null) { 15582 Slog.w(TAG, "Not removing non-existent package " + packageName); 15583 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15584 } 15585 allUsers = sUserManager.getUserIds(); 15586 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15587 } 15588 15589 synchronized (mInstallLock) { 15590 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15591 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15592 "deletePackageX")) { 15593 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15594 deleteFlags | REMOVE_CHATTY, info, true, null); 15595 } 15596 synchronized (mPackages) { 15597 if (res) { 15598 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15599 } 15600 } 15601 } 15602 15603 if (res) { 15604 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15605 info.sendPackageRemovedBroadcasts(killApp); 15606 info.sendSystemPackageUpdatedBroadcasts(); 15607 info.sendSystemPackageAppearedBroadcasts(); 15608 } 15609 // Force a gc here. 15610 Runtime.getRuntime().gc(); 15611 // Delete the resources here after sending the broadcast to let 15612 // other processes clean up before deleting resources. 15613 if (info.args != null) { 15614 synchronized (mInstallLock) { 15615 info.args.doPostDeleteLI(true); 15616 } 15617 } 15618 15619 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15620 } 15621 15622 class PackageRemovedInfo { 15623 String removedPackage; 15624 int uid = -1; 15625 int removedAppId = -1; 15626 int[] origUsers; 15627 int[] removedUsers = null; 15628 boolean isRemovedPackageSystemUpdate = false; 15629 boolean isUpdate; 15630 boolean dataRemoved; 15631 boolean removedForAllUsers; 15632 // Clean up resources deleted packages. 15633 InstallArgs args = null; 15634 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15635 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15636 15637 void sendPackageRemovedBroadcasts(boolean killApp) { 15638 sendPackageRemovedBroadcastInternal(killApp); 15639 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15640 for (int i = 0; i < childCount; i++) { 15641 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15642 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15643 } 15644 } 15645 15646 void sendSystemPackageUpdatedBroadcasts() { 15647 if (isRemovedPackageSystemUpdate) { 15648 sendSystemPackageUpdatedBroadcastsInternal(); 15649 final int childCount = (removedChildPackages != null) 15650 ? removedChildPackages.size() : 0; 15651 for (int i = 0; i < childCount; i++) { 15652 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15653 if (childInfo.isRemovedPackageSystemUpdate) { 15654 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15655 } 15656 } 15657 } 15658 } 15659 15660 void sendSystemPackageAppearedBroadcasts() { 15661 final int packageCount = (appearedChildPackages != null) 15662 ? appearedChildPackages.size() : 0; 15663 for (int i = 0; i < packageCount; i++) { 15664 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15665 for (int userId : installedInfo.newUsers) { 15666 sendPackageAddedForUser(installedInfo.name, true, 15667 UserHandle.getAppId(installedInfo.uid), userId); 15668 } 15669 } 15670 } 15671 15672 private void sendSystemPackageUpdatedBroadcastsInternal() { 15673 Bundle extras = new Bundle(2); 15674 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15675 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15676 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15677 extras, 0, null, null, null); 15678 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15679 extras, 0, null, null, null); 15680 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15681 null, 0, removedPackage, null, null); 15682 } 15683 15684 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15685 Bundle extras = new Bundle(2); 15686 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15687 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15688 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15689 if (isUpdate || isRemovedPackageSystemUpdate) { 15690 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15691 } 15692 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15693 if (removedPackage != null) { 15694 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15695 extras, 0, null, null, removedUsers); 15696 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15697 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15698 removedPackage, extras, 0, null, null, removedUsers); 15699 } 15700 } 15701 if (removedAppId >= 0) { 15702 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15703 removedUsers); 15704 } 15705 } 15706 } 15707 15708 /* 15709 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15710 * flag is not set, the data directory is removed as well. 15711 * make sure this flag is set for partially installed apps. If not its meaningless to 15712 * delete a partially installed application. 15713 */ 15714 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15715 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15716 String packageName = ps.name; 15717 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15718 // Retrieve object to delete permissions for shared user later on 15719 final PackageParser.Package deletedPkg; 15720 final PackageSetting deletedPs; 15721 // reader 15722 synchronized (mPackages) { 15723 deletedPkg = mPackages.get(packageName); 15724 deletedPs = mSettings.mPackages.get(packageName); 15725 if (outInfo != null) { 15726 outInfo.removedPackage = packageName; 15727 outInfo.removedUsers = deletedPs != null 15728 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15729 : null; 15730 } 15731 } 15732 15733 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15734 15735 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15736 final PackageParser.Package resolvedPkg; 15737 if (deletedPkg != null) { 15738 resolvedPkg = deletedPkg; 15739 } else { 15740 // We don't have a parsed package when it lives on an ejected 15741 // adopted storage device, so fake something together 15742 resolvedPkg = new PackageParser.Package(ps.name); 15743 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15744 } 15745 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15746 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15747 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15748 if (outInfo != null) { 15749 outInfo.dataRemoved = true; 15750 } 15751 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15752 } 15753 15754 // writer 15755 synchronized (mPackages) { 15756 if (deletedPs != null) { 15757 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15758 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15759 clearDefaultBrowserIfNeeded(packageName); 15760 if (outInfo != null) { 15761 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15762 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15763 } 15764 updatePermissionsLPw(deletedPs.name, null, 0); 15765 if (deletedPs.sharedUser != null) { 15766 // Remove permissions associated with package. Since runtime 15767 // permissions are per user we have to kill the removed package 15768 // or packages running under the shared user of the removed 15769 // package if revoking the permissions requested only by the removed 15770 // package is successful and this causes a change in gids. 15771 for (int userId : UserManagerService.getInstance().getUserIds()) { 15772 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15773 userId); 15774 if (userIdToKill == UserHandle.USER_ALL 15775 || userIdToKill >= UserHandle.USER_SYSTEM) { 15776 // If gids changed for this user, kill all affected packages. 15777 mHandler.post(new Runnable() { 15778 @Override 15779 public void run() { 15780 // This has to happen with no lock held. 15781 killApplication(deletedPs.name, deletedPs.appId, 15782 KILL_APP_REASON_GIDS_CHANGED); 15783 } 15784 }); 15785 break; 15786 } 15787 } 15788 } 15789 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15790 } 15791 // make sure to preserve per-user disabled state if this removal was just 15792 // a downgrade of a system app to the factory package 15793 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15794 if (DEBUG_REMOVE) { 15795 Slog.d(TAG, "Propagating install state across downgrade"); 15796 } 15797 for (int userId : allUserHandles) { 15798 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15799 if (DEBUG_REMOVE) { 15800 Slog.d(TAG, " user " + userId + " => " + installed); 15801 } 15802 ps.setInstalled(installed, userId); 15803 } 15804 } 15805 } 15806 // can downgrade to reader 15807 if (writeSettings) { 15808 // Save settings now 15809 mSettings.writeLPr(); 15810 } 15811 } 15812 if (outInfo != null) { 15813 // A user ID was deleted here. Go through all users and remove it 15814 // from KeyStore. 15815 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15816 } 15817 } 15818 15819 static boolean locationIsPrivileged(File path) { 15820 try { 15821 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15822 .getCanonicalPath(); 15823 return path.getCanonicalPath().startsWith(privilegedAppDir); 15824 } catch (IOException e) { 15825 Slog.e(TAG, "Unable to access code path " + path); 15826 } 15827 return false; 15828 } 15829 15830 /* 15831 * Tries to delete system package. 15832 */ 15833 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15834 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15835 boolean writeSettings) { 15836 if (deletedPs.parentPackageName != null) { 15837 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15838 return false; 15839 } 15840 15841 final boolean applyUserRestrictions 15842 = (allUserHandles != null) && (outInfo.origUsers != null); 15843 final PackageSetting disabledPs; 15844 // Confirm if the system package has been updated 15845 // An updated system app can be deleted. This will also have to restore 15846 // the system pkg from system partition 15847 // reader 15848 synchronized (mPackages) { 15849 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15850 } 15851 15852 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15853 + " disabledPs=" + disabledPs); 15854 15855 if (disabledPs == null) { 15856 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15857 return false; 15858 } else if (DEBUG_REMOVE) { 15859 Slog.d(TAG, "Deleting system pkg from data partition"); 15860 } 15861 15862 if (DEBUG_REMOVE) { 15863 if (applyUserRestrictions) { 15864 Slog.d(TAG, "Remembering install states:"); 15865 for (int userId : allUserHandles) { 15866 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15867 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15868 } 15869 } 15870 } 15871 15872 // Delete the updated package 15873 outInfo.isRemovedPackageSystemUpdate = true; 15874 if (outInfo.removedChildPackages != null) { 15875 final int childCount = (deletedPs.childPackageNames != null) 15876 ? deletedPs.childPackageNames.size() : 0; 15877 for (int i = 0; i < childCount; i++) { 15878 String childPackageName = deletedPs.childPackageNames.get(i); 15879 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15880 .contains(childPackageName)) { 15881 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15882 childPackageName); 15883 if (childInfo != null) { 15884 childInfo.isRemovedPackageSystemUpdate = true; 15885 } 15886 } 15887 } 15888 } 15889 15890 if (disabledPs.versionCode < deletedPs.versionCode) { 15891 // Delete data for downgrades 15892 flags &= ~PackageManager.DELETE_KEEP_DATA; 15893 } else { 15894 // Preserve data by setting flag 15895 flags |= PackageManager.DELETE_KEEP_DATA; 15896 } 15897 15898 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15899 outInfo, writeSettings, disabledPs.pkg); 15900 if (!ret) { 15901 return false; 15902 } 15903 15904 // writer 15905 synchronized (mPackages) { 15906 // Reinstate the old system package 15907 enableSystemPackageLPw(disabledPs.pkg); 15908 // Remove any native libraries from the upgraded package. 15909 removeNativeBinariesLI(deletedPs); 15910 } 15911 15912 // Install the system package 15913 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15914 int parseFlags = mDefParseFlags 15915 | PackageParser.PARSE_MUST_BE_APK 15916 | PackageParser.PARSE_IS_SYSTEM 15917 | PackageParser.PARSE_IS_SYSTEM_DIR; 15918 if (locationIsPrivileged(disabledPs.codePath)) { 15919 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15920 } 15921 15922 final PackageParser.Package newPkg; 15923 try { 15924 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15925 } catch (PackageManagerException e) { 15926 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15927 + e.getMessage()); 15928 return false; 15929 } 15930 15931 prepareAppDataAfterInstallLIF(newPkg); 15932 15933 // writer 15934 synchronized (mPackages) { 15935 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15936 15937 // Propagate the permissions state as we do not want to drop on the floor 15938 // runtime permissions. The update permissions method below will take 15939 // care of removing obsolete permissions and grant install permissions. 15940 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15941 updatePermissionsLPw(newPkg.packageName, newPkg, 15942 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15943 15944 if (applyUserRestrictions) { 15945 if (DEBUG_REMOVE) { 15946 Slog.d(TAG, "Propagating install state across reinstall"); 15947 } 15948 for (int userId : allUserHandles) { 15949 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15950 if (DEBUG_REMOVE) { 15951 Slog.d(TAG, " user " + userId + " => " + installed); 15952 } 15953 ps.setInstalled(installed, userId); 15954 15955 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15956 } 15957 // Regardless of writeSettings we need to ensure that this restriction 15958 // state propagation is persisted 15959 mSettings.writeAllUsersPackageRestrictionsLPr(); 15960 } 15961 // can downgrade to reader here 15962 if (writeSettings) { 15963 mSettings.writeLPr(); 15964 } 15965 } 15966 return true; 15967 } 15968 15969 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15970 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15971 PackageRemovedInfo outInfo, boolean writeSettings, 15972 PackageParser.Package replacingPackage) { 15973 synchronized (mPackages) { 15974 if (outInfo != null) { 15975 outInfo.uid = ps.appId; 15976 } 15977 15978 if (outInfo != null && outInfo.removedChildPackages != null) { 15979 final int childCount = (ps.childPackageNames != null) 15980 ? ps.childPackageNames.size() : 0; 15981 for (int i = 0; i < childCount; i++) { 15982 String childPackageName = ps.childPackageNames.get(i); 15983 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15984 if (childPs == null) { 15985 return false; 15986 } 15987 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15988 childPackageName); 15989 if (childInfo != null) { 15990 childInfo.uid = childPs.appId; 15991 } 15992 } 15993 } 15994 } 15995 15996 // Delete package data from internal structures and also remove data if flag is set 15997 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15998 15999 // Delete the child packages data 16000 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16001 for (int i = 0; i < childCount; i++) { 16002 PackageSetting childPs; 16003 synchronized (mPackages) { 16004 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16005 } 16006 if (childPs != null) { 16007 PackageRemovedInfo childOutInfo = (outInfo != null 16008 && outInfo.removedChildPackages != null) 16009 ? outInfo.removedChildPackages.get(childPs.name) : null; 16010 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16011 && (replacingPackage != null 16012 && !replacingPackage.hasChildPackage(childPs.name)) 16013 ? flags & ~DELETE_KEEP_DATA : flags; 16014 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16015 deleteFlags, writeSettings); 16016 } 16017 } 16018 16019 // Delete application code and resources only for parent packages 16020 if (ps.parentPackageName == null) { 16021 if (deleteCodeAndResources && (outInfo != null)) { 16022 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16023 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16024 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16025 } 16026 } 16027 16028 return true; 16029 } 16030 16031 @Override 16032 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16033 int userId) { 16034 mContext.enforceCallingOrSelfPermission( 16035 android.Manifest.permission.DELETE_PACKAGES, null); 16036 synchronized (mPackages) { 16037 PackageSetting ps = mSettings.mPackages.get(packageName); 16038 if (ps == null) { 16039 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16040 return false; 16041 } 16042 if (!ps.getInstalled(userId)) { 16043 // Can't block uninstall for an app that is not installed or enabled. 16044 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16045 return false; 16046 } 16047 ps.setBlockUninstall(blockUninstall, userId); 16048 mSettings.writePackageRestrictionsLPr(userId); 16049 } 16050 return true; 16051 } 16052 16053 @Override 16054 public boolean getBlockUninstallForUser(String packageName, int userId) { 16055 synchronized (mPackages) { 16056 PackageSetting ps = mSettings.mPackages.get(packageName); 16057 if (ps == null) { 16058 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16059 return false; 16060 } 16061 return ps.getBlockUninstall(userId); 16062 } 16063 } 16064 16065 @Override 16066 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16067 int callingUid = Binder.getCallingUid(); 16068 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16069 throw new SecurityException( 16070 "setRequiredForSystemUser can only be run by the system or root"); 16071 } 16072 synchronized (mPackages) { 16073 PackageSetting ps = mSettings.mPackages.get(packageName); 16074 if (ps == null) { 16075 Log.w(TAG, "Package doesn't exist: " + packageName); 16076 return false; 16077 } 16078 if (systemUserApp) { 16079 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16080 } else { 16081 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16082 } 16083 mSettings.writeLPr(); 16084 } 16085 return true; 16086 } 16087 16088 /* 16089 * This method handles package deletion in general 16090 */ 16091 private boolean deletePackageLIF(String packageName, UserHandle user, 16092 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16093 PackageRemovedInfo outInfo, boolean writeSettings, 16094 PackageParser.Package replacingPackage) { 16095 if (packageName == null) { 16096 Slog.w(TAG, "Attempt to delete null packageName."); 16097 return false; 16098 } 16099 16100 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16101 16102 PackageSetting ps; 16103 16104 synchronized (mPackages) { 16105 ps = mSettings.mPackages.get(packageName); 16106 if (ps == null) { 16107 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16108 return false; 16109 } 16110 16111 if (ps.parentPackageName != null && (!isSystemApp(ps) 16112 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16113 if (DEBUG_REMOVE) { 16114 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16115 + ((user == null) ? UserHandle.USER_ALL : user)); 16116 } 16117 final int removedUserId = (user != null) ? user.getIdentifier() 16118 : UserHandle.USER_ALL; 16119 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16120 return false; 16121 } 16122 markPackageUninstalledForUserLPw(ps, user); 16123 scheduleWritePackageRestrictionsLocked(user); 16124 return true; 16125 } 16126 } 16127 16128 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16129 && user.getIdentifier() != UserHandle.USER_ALL)) { 16130 // The caller is asking that the package only be deleted for a single 16131 // user. To do this, we just mark its uninstalled state and delete 16132 // its data. If this is a system app, we only allow this to happen if 16133 // they have set the special DELETE_SYSTEM_APP which requests different 16134 // semantics than normal for uninstalling system apps. 16135 markPackageUninstalledForUserLPw(ps, user); 16136 16137 if (!isSystemApp(ps)) { 16138 // Do not uninstall the APK if an app should be cached 16139 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16140 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16141 // Other user still have this package installed, so all 16142 // we need to do is clear this user's data and save that 16143 // it is uninstalled. 16144 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16145 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16146 return false; 16147 } 16148 scheduleWritePackageRestrictionsLocked(user); 16149 return true; 16150 } else { 16151 // We need to set it back to 'installed' so the uninstall 16152 // broadcasts will be sent correctly. 16153 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16154 ps.setInstalled(true, user.getIdentifier()); 16155 } 16156 } else { 16157 // This is a system app, so we assume that the 16158 // other users still have this package installed, so all 16159 // we need to do is clear this user's data and save that 16160 // it is uninstalled. 16161 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16162 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16163 return false; 16164 } 16165 scheduleWritePackageRestrictionsLocked(user); 16166 return true; 16167 } 16168 } 16169 16170 // If we are deleting a composite package for all users, keep track 16171 // of result for each child. 16172 if (ps.childPackageNames != null && outInfo != null) { 16173 synchronized (mPackages) { 16174 final int childCount = ps.childPackageNames.size(); 16175 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16176 for (int i = 0; i < childCount; i++) { 16177 String childPackageName = ps.childPackageNames.get(i); 16178 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16179 childInfo.removedPackage = childPackageName; 16180 outInfo.removedChildPackages.put(childPackageName, childInfo); 16181 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16182 if (childPs != null) { 16183 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16184 } 16185 } 16186 } 16187 } 16188 16189 boolean ret = false; 16190 if (isSystemApp(ps)) { 16191 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16192 // When an updated system application is deleted we delete the existing resources 16193 // as well and fall back to existing code in system partition 16194 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16195 } else { 16196 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16197 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16198 outInfo, writeSettings, replacingPackage); 16199 } 16200 16201 // Take a note whether we deleted the package for all users 16202 if (outInfo != null) { 16203 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16204 if (outInfo.removedChildPackages != null) { 16205 synchronized (mPackages) { 16206 final int childCount = outInfo.removedChildPackages.size(); 16207 for (int i = 0; i < childCount; i++) { 16208 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16209 if (childInfo != null) { 16210 childInfo.removedForAllUsers = mPackages.get( 16211 childInfo.removedPackage) == null; 16212 } 16213 } 16214 } 16215 } 16216 // If we uninstalled an update to a system app there may be some 16217 // child packages that appeared as they are declared in the system 16218 // app but were not declared in the update. 16219 if (isSystemApp(ps)) { 16220 synchronized (mPackages) { 16221 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16222 final int childCount = (updatedPs.childPackageNames != null) 16223 ? updatedPs.childPackageNames.size() : 0; 16224 for (int i = 0; i < childCount; i++) { 16225 String childPackageName = updatedPs.childPackageNames.get(i); 16226 if (outInfo.removedChildPackages == null 16227 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16228 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16229 if (childPs == null) { 16230 continue; 16231 } 16232 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16233 installRes.name = childPackageName; 16234 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16235 installRes.pkg = mPackages.get(childPackageName); 16236 installRes.uid = childPs.pkg.applicationInfo.uid; 16237 if (outInfo.appearedChildPackages == null) { 16238 outInfo.appearedChildPackages = new ArrayMap<>(); 16239 } 16240 outInfo.appearedChildPackages.put(childPackageName, installRes); 16241 } 16242 } 16243 } 16244 } 16245 } 16246 16247 return ret; 16248 } 16249 16250 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16251 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16252 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16253 for (int nextUserId : userIds) { 16254 if (DEBUG_REMOVE) { 16255 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16256 } 16257 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16258 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16259 false /*hidden*/, false /*suspended*/, null, null, null, 16260 false /*blockUninstall*/, 16261 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16262 } 16263 } 16264 16265 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16266 PackageRemovedInfo outInfo) { 16267 final PackageParser.Package pkg; 16268 synchronized (mPackages) { 16269 pkg = mPackages.get(ps.name); 16270 } 16271 16272 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16273 : new int[] {userId}; 16274 for (int nextUserId : userIds) { 16275 if (DEBUG_REMOVE) { 16276 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16277 + nextUserId); 16278 } 16279 16280 destroyAppDataLIF(pkg, userId, 16281 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16282 destroyAppProfilesLIF(pkg, userId); 16283 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16284 schedulePackageCleaning(ps.name, nextUserId, false); 16285 synchronized (mPackages) { 16286 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16287 scheduleWritePackageRestrictionsLocked(nextUserId); 16288 } 16289 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16290 } 16291 } 16292 16293 if (outInfo != null) { 16294 outInfo.removedPackage = ps.name; 16295 outInfo.removedAppId = ps.appId; 16296 outInfo.removedUsers = userIds; 16297 } 16298 16299 return true; 16300 } 16301 16302 private final class ClearStorageConnection implements ServiceConnection { 16303 IMediaContainerService mContainerService; 16304 16305 @Override 16306 public void onServiceConnected(ComponentName name, IBinder service) { 16307 synchronized (this) { 16308 mContainerService = IMediaContainerService.Stub.asInterface(service); 16309 notifyAll(); 16310 } 16311 } 16312 16313 @Override 16314 public void onServiceDisconnected(ComponentName name) { 16315 } 16316 } 16317 16318 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16319 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16320 16321 final boolean mounted; 16322 if (Environment.isExternalStorageEmulated()) { 16323 mounted = true; 16324 } else { 16325 final String status = Environment.getExternalStorageState(); 16326 16327 mounted = status.equals(Environment.MEDIA_MOUNTED) 16328 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16329 } 16330 16331 if (!mounted) { 16332 return; 16333 } 16334 16335 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16336 int[] users; 16337 if (userId == UserHandle.USER_ALL) { 16338 users = sUserManager.getUserIds(); 16339 } else { 16340 users = new int[] { userId }; 16341 } 16342 final ClearStorageConnection conn = new ClearStorageConnection(); 16343 if (mContext.bindServiceAsUser( 16344 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16345 try { 16346 for (int curUser : users) { 16347 long timeout = SystemClock.uptimeMillis() + 5000; 16348 synchronized (conn) { 16349 long now; 16350 while (conn.mContainerService == null && 16351 (now = SystemClock.uptimeMillis()) < timeout) { 16352 try { 16353 conn.wait(timeout - now); 16354 } catch (InterruptedException e) { 16355 } 16356 } 16357 } 16358 if (conn.mContainerService == null) { 16359 return; 16360 } 16361 16362 final UserEnvironment userEnv = new UserEnvironment(curUser); 16363 clearDirectory(conn.mContainerService, 16364 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16365 if (allData) { 16366 clearDirectory(conn.mContainerService, 16367 userEnv.buildExternalStorageAppDataDirs(packageName)); 16368 clearDirectory(conn.mContainerService, 16369 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16370 } 16371 } 16372 } finally { 16373 mContext.unbindService(conn); 16374 } 16375 } 16376 } 16377 16378 @Override 16379 public void clearApplicationProfileData(String packageName) { 16380 enforceSystemOrRoot("Only the system can clear all profile data"); 16381 16382 final PackageParser.Package pkg; 16383 synchronized (mPackages) { 16384 pkg = mPackages.get(packageName); 16385 } 16386 16387 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16388 synchronized (mInstallLock) { 16389 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16390 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16391 true /* removeBaseMarker */); 16392 } 16393 } 16394 } 16395 16396 @Override 16397 public void clearApplicationUserData(final String packageName, 16398 final IPackageDataObserver observer, final int userId) { 16399 mContext.enforceCallingOrSelfPermission( 16400 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16401 16402 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16403 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16404 16405 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16406 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16407 } 16408 // Queue up an async operation since the package deletion may take a little while. 16409 mHandler.post(new Runnable() { 16410 public void run() { 16411 mHandler.removeCallbacks(this); 16412 final boolean succeeded; 16413 try (PackageFreezer freezer = freezePackage(packageName, 16414 "clearApplicationUserData")) { 16415 synchronized (mInstallLock) { 16416 succeeded = clearApplicationUserDataLIF(packageName, userId); 16417 } 16418 clearExternalStorageDataSync(packageName, userId, true); 16419 } 16420 if (succeeded) { 16421 // invoke DeviceStorageMonitor's update method to clear any notifications 16422 DeviceStorageMonitorInternal dsm = LocalServices 16423 .getService(DeviceStorageMonitorInternal.class); 16424 if (dsm != null) { 16425 dsm.checkMemory(); 16426 } 16427 } 16428 if(observer != null) { 16429 try { 16430 observer.onRemoveCompleted(packageName, succeeded); 16431 } catch (RemoteException e) { 16432 Log.i(TAG, "Observer no longer exists."); 16433 } 16434 } //end if observer 16435 } //end run 16436 }); 16437 } 16438 16439 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16440 if (packageName == null) { 16441 Slog.w(TAG, "Attempt to delete null packageName."); 16442 return false; 16443 } 16444 16445 // Try finding details about the requested package 16446 PackageParser.Package pkg; 16447 synchronized (mPackages) { 16448 pkg = mPackages.get(packageName); 16449 if (pkg == null) { 16450 final PackageSetting ps = mSettings.mPackages.get(packageName); 16451 if (ps != null) { 16452 pkg = ps.pkg; 16453 } 16454 } 16455 16456 if (pkg == null) { 16457 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16458 return false; 16459 } 16460 16461 PackageSetting ps = (PackageSetting) pkg.mExtras; 16462 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16463 } 16464 16465 clearAppDataLIF(pkg, userId, 16466 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16467 16468 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16469 removeKeystoreDataIfNeeded(userId, appId); 16470 16471 UserManagerInternal umInternal = getUserManagerInternal(); 16472 final int flags; 16473 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16474 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16475 } else if (umInternal.isUserRunning(userId)) { 16476 flags = StorageManager.FLAG_STORAGE_DE; 16477 } else { 16478 flags = 0; 16479 } 16480 prepareAppDataContentsLIF(pkg, userId, flags); 16481 16482 return true; 16483 } 16484 16485 /** 16486 * Reverts user permission state changes (permissions and flags) in 16487 * all packages for a given user. 16488 * 16489 * @param userId The device user for which to do a reset. 16490 */ 16491 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16492 final int packageCount = mPackages.size(); 16493 for (int i = 0; i < packageCount; i++) { 16494 PackageParser.Package pkg = mPackages.valueAt(i); 16495 PackageSetting ps = (PackageSetting) pkg.mExtras; 16496 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16497 } 16498 } 16499 16500 private void resetNetworkPolicies(int userId) { 16501 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16502 } 16503 16504 /** 16505 * Reverts user permission state changes (permissions and flags). 16506 * 16507 * @param ps The package for which to reset. 16508 * @param userId The device user for which to do a reset. 16509 */ 16510 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16511 final PackageSetting ps, final int userId) { 16512 if (ps.pkg == null) { 16513 return; 16514 } 16515 16516 // These are flags that can change base on user actions. 16517 final int userSettableMask = FLAG_PERMISSION_USER_SET 16518 | FLAG_PERMISSION_USER_FIXED 16519 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16520 | FLAG_PERMISSION_REVIEW_REQUIRED; 16521 16522 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16523 | FLAG_PERMISSION_POLICY_FIXED; 16524 16525 boolean writeInstallPermissions = false; 16526 boolean writeRuntimePermissions = false; 16527 16528 final int permissionCount = ps.pkg.requestedPermissions.size(); 16529 for (int i = 0; i < permissionCount; i++) { 16530 String permission = ps.pkg.requestedPermissions.get(i); 16531 16532 BasePermission bp = mSettings.mPermissions.get(permission); 16533 if (bp == null) { 16534 continue; 16535 } 16536 16537 // If shared user we just reset the state to which only this app contributed. 16538 if (ps.sharedUser != null) { 16539 boolean used = false; 16540 final int packageCount = ps.sharedUser.packages.size(); 16541 for (int j = 0; j < packageCount; j++) { 16542 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16543 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16544 && pkg.pkg.requestedPermissions.contains(permission)) { 16545 used = true; 16546 break; 16547 } 16548 } 16549 if (used) { 16550 continue; 16551 } 16552 } 16553 16554 PermissionsState permissionsState = ps.getPermissionsState(); 16555 16556 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16557 16558 // Always clear the user settable flags. 16559 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16560 bp.name) != null; 16561 // If permission review is enabled and this is a legacy app, mark the 16562 // permission as requiring a review as this is the initial state. 16563 int flags = 0; 16564 if (Build.PERMISSIONS_REVIEW_REQUIRED 16565 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16566 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16567 } 16568 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16569 if (hasInstallState) { 16570 writeInstallPermissions = true; 16571 } else { 16572 writeRuntimePermissions = true; 16573 } 16574 } 16575 16576 // Below is only runtime permission handling. 16577 if (!bp.isRuntime()) { 16578 continue; 16579 } 16580 16581 // Never clobber system or policy. 16582 if ((oldFlags & policyOrSystemFlags) != 0) { 16583 continue; 16584 } 16585 16586 // If this permission was granted by default, make sure it is. 16587 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16588 if (permissionsState.grantRuntimePermission(bp, userId) 16589 != PERMISSION_OPERATION_FAILURE) { 16590 writeRuntimePermissions = true; 16591 } 16592 // If permission review is enabled the permissions for a legacy apps 16593 // are represented as constantly granted runtime ones, so don't revoke. 16594 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16595 // Otherwise, reset the permission. 16596 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16597 switch (revokeResult) { 16598 case PERMISSION_OPERATION_SUCCESS: 16599 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16600 writeRuntimePermissions = true; 16601 final int appId = ps.appId; 16602 mHandler.post(new Runnable() { 16603 @Override 16604 public void run() { 16605 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16606 } 16607 }); 16608 } break; 16609 } 16610 } 16611 } 16612 16613 // Synchronously write as we are taking permissions away. 16614 if (writeRuntimePermissions) { 16615 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16616 } 16617 16618 // Synchronously write as we are taking permissions away. 16619 if (writeInstallPermissions) { 16620 mSettings.writeLPr(); 16621 } 16622 } 16623 16624 /** 16625 * Remove entries from the keystore daemon. Will only remove it if the 16626 * {@code appId} is valid. 16627 */ 16628 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16629 if (appId < 0) { 16630 return; 16631 } 16632 16633 final KeyStore keyStore = KeyStore.getInstance(); 16634 if (keyStore != null) { 16635 if (userId == UserHandle.USER_ALL) { 16636 for (final int individual : sUserManager.getUserIds()) { 16637 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16638 } 16639 } else { 16640 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16641 } 16642 } else { 16643 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16644 } 16645 } 16646 16647 @Override 16648 public void deleteApplicationCacheFiles(final String packageName, 16649 final IPackageDataObserver observer) { 16650 final int userId = UserHandle.getCallingUserId(); 16651 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16652 } 16653 16654 @Override 16655 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16656 final IPackageDataObserver observer) { 16657 mContext.enforceCallingOrSelfPermission( 16658 android.Manifest.permission.DELETE_CACHE_FILES, null); 16659 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16660 /* requireFullPermission= */ true, /* checkShell= */ false, 16661 "delete application cache files"); 16662 16663 final PackageParser.Package pkg; 16664 synchronized (mPackages) { 16665 pkg = mPackages.get(packageName); 16666 } 16667 16668 // Queue up an async operation since the package deletion may take a little while. 16669 mHandler.post(new Runnable() { 16670 public void run() { 16671 synchronized (mInstallLock) { 16672 final int flags = StorageManager.FLAG_STORAGE_DE 16673 | StorageManager.FLAG_STORAGE_CE; 16674 // We're only clearing cache files, so we don't care if the 16675 // app is unfrozen and still able to run 16676 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16677 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16678 } 16679 clearExternalStorageDataSync(packageName, userId, false); 16680 if (observer != null) { 16681 try { 16682 observer.onRemoveCompleted(packageName, true); 16683 } catch (RemoteException e) { 16684 Log.i(TAG, "Observer no longer exists."); 16685 } 16686 } 16687 } 16688 }); 16689 } 16690 16691 @Override 16692 public void getPackageSizeInfo(final String packageName, int userHandle, 16693 final IPackageStatsObserver observer) { 16694 mContext.enforceCallingOrSelfPermission( 16695 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16696 if (packageName == null) { 16697 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16698 } 16699 16700 PackageStats stats = new PackageStats(packageName, userHandle); 16701 16702 /* 16703 * Queue up an async operation since the package measurement may take a 16704 * little while. 16705 */ 16706 Message msg = mHandler.obtainMessage(INIT_COPY); 16707 msg.obj = new MeasureParams(stats, observer); 16708 mHandler.sendMessage(msg); 16709 } 16710 16711 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16712 final PackageSetting ps; 16713 synchronized (mPackages) { 16714 ps = mSettings.mPackages.get(packageName); 16715 if (ps == null) { 16716 Slog.w(TAG, "Failed to find settings for " + packageName); 16717 return false; 16718 } 16719 } 16720 try { 16721 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16722 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16723 ps.getCeDataInode(userId), ps.codePathString, stats); 16724 } catch (InstallerException e) { 16725 Slog.w(TAG, String.valueOf(e)); 16726 return false; 16727 } 16728 16729 // For now, ignore code size of packages on system partition 16730 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16731 stats.codeSize = 0; 16732 } 16733 16734 return true; 16735 } 16736 16737 private int getUidTargetSdkVersionLockedLPr(int uid) { 16738 Object obj = mSettings.getUserIdLPr(uid); 16739 if (obj instanceof SharedUserSetting) { 16740 final SharedUserSetting sus = (SharedUserSetting) obj; 16741 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16742 final Iterator<PackageSetting> it = sus.packages.iterator(); 16743 while (it.hasNext()) { 16744 final PackageSetting ps = it.next(); 16745 if (ps.pkg != null) { 16746 int v = ps.pkg.applicationInfo.targetSdkVersion; 16747 if (v < vers) vers = v; 16748 } 16749 } 16750 return vers; 16751 } else if (obj instanceof PackageSetting) { 16752 final PackageSetting ps = (PackageSetting) obj; 16753 if (ps.pkg != null) { 16754 return ps.pkg.applicationInfo.targetSdkVersion; 16755 } 16756 } 16757 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16758 } 16759 16760 @Override 16761 public void addPreferredActivity(IntentFilter filter, int match, 16762 ComponentName[] set, ComponentName activity, int userId) { 16763 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16764 "Adding preferred"); 16765 } 16766 16767 private void addPreferredActivityInternal(IntentFilter filter, int match, 16768 ComponentName[] set, ComponentName activity, boolean always, int userId, 16769 String opname) { 16770 // writer 16771 int callingUid = Binder.getCallingUid(); 16772 enforceCrossUserPermission(callingUid, userId, 16773 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16774 if (filter.countActions() == 0) { 16775 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16776 return; 16777 } 16778 synchronized (mPackages) { 16779 if (mContext.checkCallingOrSelfPermission( 16780 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16781 != PackageManager.PERMISSION_GRANTED) { 16782 if (getUidTargetSdkVersionLockedLPr(callingUid) 16783 < Build.VERSION_CODES.FROYO) { 16784 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16785 + callingUid); 16786 return; 16787 } 16788 mContext.enforceCallingOrSelfPermission( 16789 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16790 } 16791 16792 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16793 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16794 + userId + ":"); 16795 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16796 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16797 scheduleWritePackageRestrictionsLocked(userId); 16798 } 16799 } 16800 16801 @Override 16802 public void replacePreferredActivity(IntentFilter filter, int match, 16803 ComponentName[] set, ComponentName activity, int userId) { 16804 if (filter.countActions() != 1) { 16805 throw new IllegalArgumentException( 16806 "replacePreferredActivity expects filter to have only 1 action."); 16807 } 16808 if (filter.countDataAuthorities() != 0 16809 || filter.countDataPaths() != 0 16810 || filter.countDataSchemes() > 1 16811 || filter.countDataTypes() != 0) { 16812 throw new IllegalArgumentException( 16813 "replacePreferredActivity expects filter to have no data authorities, " + 16814 "paths, or types; and at most one scheme."); 16815 } 16816 16817 final int callingUid = Binder.getCallingUid(); 16818 enforceCrossUserPermission(callingUid, userId, 16819 true /* requireFullPermission */, false /* checkShell */, 16820 "replace preferred activity"); 16821 synchronized (mPackages) { 16822 if (mContext.checkCallingOrSelfPermission( 16823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16824 != PackageManager.PERMISSION_GRANTED) { 16825 if (getUidTargetSdkVersionLockedLPr(callingUid) 16826 < Build.VERSION_CODES.FROYO) { 16827 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16828 + Binder.getCallingUid()); 16829 return; 16830 } 16831 mContext.enforceCallingOrSelfPermission( 16832 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16833 } 16834 16835 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16836 if (pir != null) { 16837 // Get all of the existing entries that exactly match this filter. 16838 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16839 if (existing != null && existing.size() == 1) { 16840 PreferredActivity cur = existing.get(0); 16841 if (DEBUG_PREFERRED) { 16842 Slog.i(TAG, "Checking replace of preferred:"); 16843 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16844 if (!cur.mPref.mAlways) { 16845 Slog.i(TAG, " -- CUR; not mAlways!"); 16846 } else { 16847 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16848 Slog.i(TAG, " -- CUR: mSet=" 16849 + Arrays.toString(cur.mPref.mSetComponents)); 16850 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16851 Slog.i(TAG, " -- NEW: mMatch=" 16852 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16853 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16854 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16855 } 16856 } 16857 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16858 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16859 && cur.mPref.sameSet(set)) { 16860 // Setting the preferred activity to what it happens to be already 16861 if (DEBUG_PREFERRED) { 16862 Slog.i(TAG, "Replacing with same preferred activity " 16863 + cur.mPref.mShortComponent + " for user " 16864 + userId + ":"); 16865 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16866 } 16867 return; 16868 } 16869 } 16870 16871 if (existing != null) { 16872 if (DEBUG_PREFERRED) { 16873 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16874 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16875 } 16876 for (int i = 0; i < existing.size(); i++) { 16877 PreferredActivity pa = existing.get(i); 16878 if (DEBUG_PREFERRED) { 16879 Slog.i(TAG, "Removing existing preferred activity " 16880 + pa.mPref.mComponent + ":"); 16881 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16882 } 16883 pir.removeFilter(pa); 16884 } 16885 } 16886 } 16887 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16888 "Replacing preferred"); 16889 } 16890 } 16891 16892 @Override 16893 public void clearPackagePreferredActivities(String packageName) { 16894 final int uid = Binder.getCallingUid(); 16895 // writer 16896 synchronized (mPackages) { 16897 PackageParser.Package pkg = mPackages.get(packageName); 16898 if (pkg == null || pkg.applicationInfo.uid != uid) { 16899 if (mContext.checkCallingOrSelfPermission( 16900 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16901 != PackageManager.PERMISSION_GRANTED) { 16902 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16903 < Build.VERSION_CODES.FROYO) { 16904 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16905 + Binder.getCallingUid()); 16906 return; 16907 } 16908 mContext.enforceCallingOrSelfPermission( 16909 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16910 } 16911 } 16912 16913 int user = UserHandle.getCallingUserId(); 16914 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16915 scheduleWritePackageRestrictionsLocked(user); 16916 } 16917 } 16918 } 16919 16920 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16921 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16922 ArrayList<PreferredActivity> removed = null; 16923 boolean changed = false; 16924 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16925 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16926 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16927 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16928 continue; 16929 } 16930 Iterator<PreferredActivity> it = pir.filterIterator(); 16931 while (it.hasNext()) { 16932 PreferredActivity pa = it.next(); 16933 // Mark entry for removal only if it matches the package name 16934 // and the entry is of type "always". 16935 if (packageName == null || 16936 (pa.mPref.mComponent.getPackageName().equals(packageName) 16937 && pa.mPref.mAlways)) { 16938 if (removed == null) { 16939 removed = new ArrayList<PreferredActivity>(); 16940 } 16941 removed.add(pa); 16942 } 16943 } 16944 if (removed != null) { 16945 for (int j=0; j<removed.size(); j++) { 16946 PreferredActivity pa = removed.get(j); 16947 pir.removeFilter(pa); 16948 } 16949 changed = true; 16950 } 16951 } 16952 return changed; 16953 } 16954 16955 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16956 private void clearIntentFilterVerificationsLPw(int userId) { 16957 final int packageCount = mPackages.size(); 16958 for (int i = 0; i < packageCount; i++) { 16959 PackageParser.Package pkg = mPackages.valueAt(i); 16960 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16961 } 16962 } 16963 16964 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16965 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16966 if (userId == UserHandle.USER_ALL) { 16967 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16968 sUserManager.getUserIds())) { 16969 for (int oneUserId : sUserManager.getUserIds()) { 16970 scheduleWritePackageRestrictionsLocked(oneUserId); 16971 } 16972 } 16973 } else { 16974 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16975 scheduleWritePackageRestrictionsLocked(userId); 16976 } 16977 } 16978 } 16979 16980 void clearDefaultBrowserIfNeeded(String packageName) { 16981 for (int oneUserId : sUserManager.getUserIds()) { 16982 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16983 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16984 if (packageName.equals(defaultBrowserPackageName)) { 16985 setDefaultBrowserPackageName(null, oneUserId); 16986 } 16987 } 16988 } 16989 16990 @Override 16991 public void resetApplicationPreferences(int userId) { 16992 mContext.enforceCallingOrSelfPermission( 16993 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16994 final long identity = Binder.clearCallingIdentity(); 16995 // writer 16996 try { 16997 synchronized (mPackages) { 16998 clearPackagePreferredActivitiesLPw(null, userId); 16999 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17000 // TODO: We have to reset the default SMS and Phone. This requires 17001 // significant refactoring to keep all default apps in the package 17002 // manager (cleaner but more work) or have the services provide 17003 // callbacks to the package manager to request a default app reset. 17004 applyFactoryDefaultBrowserLPw(userId); 17005 clearIntentFilterVerificationsLPw(userId); 17006 primeDomainVerificationsLPw(userId); 17007 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17008 scheduleWritePackageRestrictionsLocked(userId); 17009 } 17010 resetNetworkPolicies(userId); 17011 } finally { 17012 Binder.restoreCallingIdentity(identity); 17013 } 17014 } 17015 17016 @Override 17017 public int getPreferredActivities(List<IntentFilter> outFilters, 17018 List<ComponentName> outActivities, String packageName) { 17019 17020 int num = 0; 17021 final int userId = UserHandle.getCallingUserId(); 17022 // reader 17023 synchronized (mPackages) { 17024 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17025 if (pir != null) { 17026 final Iterator<PreferredActivity> it = pir.filterIterator(); 17027 while (it.hasNext()) { 17028 final PreferredActivity pa = it.next(); 17029 if (packageName == null 17030 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17031 && pa.mPref.mAlways)) { 17032 if (outFilters != null) { 17033 outFilters.add(new IntentFilter(pa)); 17034 } 17035 if (outActivities != null) { 17036 outActivities.add(pa.mPref.mComponent); 17037 } 17038 } 17039 } 17040 } 17041 } 17042 17043 return num; 17044 } 17045 17046 @Override 17047 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17048 int userId) { 17049 int callingUid = Binder.getCallingUid(); 17050 if (callingUid != Process.SYSTEM_UID) { 17051 throw new SecurityException( 17052 "addPersistentPreferredActivity can only be run by the system"); 17053 } 17054 if (filter.countActions() == 0) { 17055 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17056 return; 17057 } 17058 synchronized (mPackages) { 17059 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17060 ":"); 17061 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17062 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17063 new PersistentPreferredActivity(filter, activity)); 17064 scheduleWritePackageRestrictionsLocked(userId); 17065 } 17066 } 17067 17068 @Override 17069 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17070 int callingUid = Binder.getCallingUid(); 17071 if (callingUid != Process.SYSTEM_UID) { 17072 throw new SecurityException( 17073 "clearPackagePersistentPreferredActivities can only be run by the system"); 17074 } 17075 ArrayList<PersistentPreferredActivity> removed = null; 17076 boolean changed = false; 17077 synchronized (mPackages) { 17078 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17079 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17080 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17081 .valueAt(i); 17082 if (userId != thisUserId) { 17083 continue; 17084 } 17085 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17086 while (it.hasNext()) { 17087 PersistentPreferredActivity ppa = it.next(); 17088 // Mark entry for removal only if it matches the package name. 17089 if (ppa.mComponent.getPackageName().equals(packageName)) { 17090 if (removed == null) { 17091 removed = new ArrayList<PersistentPreferredActivity>(); 17092 } 17093 removed.add(ppa); 17094 } 17095 } 17096 if (removed != null) { 17097 for (int j=0; j<removed.size(); j++) { 17098 PersistentPreferredActivity ppa = removed.get(j); 17099 ppir.removeFilter(ppa); 17100 } 17101 changed = true; 17102 } 17103 } 17104 17105 if (changed) { 17106 scheduleWritePackageRestrictionsLocked(userId); 17107 } 17108 } 17109 } 17110 17111 /** 17112 * Common machinery for picking apart a restored XML blob and passing 17113 * it to a caller-supplied functor to be applied to the running system. 17114 */ 17115 private void restoreFromXml(XmlPullParser parser, int userId, 17116 String expectedStartTag, BlobXmlRestorer functor) 17117 throws IOException, XmlPullParserException { 17118 int type; 17119 while ((type = parser.next()) != XmlPullParser.START_TAG 17120 && type != XmlPullParser.END_DOCUMENT) { 17121 } 17122 if (type != XmlPullParser.START_TAG) { 17123 // oops didn't find a start tag?! 17124 if (DEBUG_BACKUP) { 17125 Slog.e(TAG, "Didn't find start tag during restore"); 17126 } 17127 return; 17128 } 17129Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17130 // this is supposed to be TAG_PREFERRED_BACKUP 17131 if (!expectedStartTag.equals(parser.getName())) { 17132 if (DEBUG_BACKUP) { 17133 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17134 } 17135 return; 17136 } 17137 17138 // skip interfering stuff, then we're aligned with the backing implementation 17139 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17140Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17141 functor.apply(parser, userId); 17142 } 17143 17144 private interface BlobXmlRestorer { 17145 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17146 } 17147 17148 /** 17149 * Non-Binder method, support for the backup/restore mechanism: write the 17150 * full set of preferred activities in its canonical XML format. Returns the 17151 * XML output as a byte array, or null if there is none. 17152 */ 17153 @Override 17154 public byte[] getPreferredActivityBackup(int userId) { 17155 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17156 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17157 } 17158 17159 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17160 try { 17161 final XmlSerializer serializer = new FastXmlSerializer(); 17162 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17163 serializer.startDocument(null, true); 17164 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17165 17166 synchronized (mPackages) { 17167 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17168 } 17169 17170 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17171 serializer.endDocument(); 17172 serializer.flush(); 17173 } catch (Exception e) { 17174 if (DEBUG_BACKUP) { 17175 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17176 } 17177 return null; 17178 } 17179 17180 return dataStream.toByteArray(); 17181 } 17182 17183 @Override 17184 public void restorePreferredActivities(byte[] backup, int userId) { 17185 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17186 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17187 } 17188 17189 try { 17190 final XmlPullParser parser = Xml.newPullParser(); 17191 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17192 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17193 new BlobXmlRestorer() { 17194 @Override 17195 public void apply(XmlPullParser parser, int userId) 17196 throws XmlPullParserException, IOException { 17197 synchronized (mPackages) { 17198 mSettings.readPreferredActivitiesLPw(parser, userId); 17199 } 17200 } 17201 } ); 17202 } catch (Exception e) { 17203 if (DEBUG_BACKUP) { 17204 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17205 } 17206 } 17207 } 17208 17209 /** 17210 * Non-Binder method, support for the backup/restore mechanism: write the 17211 * default browser (etc) settings in its canonical XML format. Returns the default 17212 * browser XML representation as a byte array, or null if there is none. 17213 */ 17214 @Override 17215 public byte[] getDefaultAppsBackup(int userId) { 17216 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17217 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17218 } 17219 17220 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17221 try { 17222 final XmlSerializer serializer = new FastXmlSerializer(); 17223 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17224 serializer.startDocument(null, true); 17225 serializer.startTag(null, TAG_DEFAULT_APPS); 17226 17227 synchronized (mPackages) { 17228 mSettings.writeDefaultAppsLPr(serializer, userId); 17229 } 17230 17231 serializer.endTag(null, TAG_DEFAULT_APPS); 17232 serializer.endDocument(); 17233 serializer.flush(); 17234 } catch (Exception e) { 17235 if (DEBUG_BACKUP) { 17236 Slog.e(TAG, "Unable to write default apps for backup", e); 17237 } 17238 return null; 17239 } 17240 17241 return dataStream.toByteArray(); 17242 } 17243 17244 @Override 17245 public void restoreDefaultApps(byte[] backup, int userId) { 17246 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17247 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17248 } 17249 17250 try { 17251 final XmlPullParser parser = Xml.newPullParser(); 17252 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17253 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17254 new BlobXmlRestorer() { 17255 @Override 17256 public void apply(XmlPullParser parser, int userId) 17257 throws XmlPullParserException, IOException { 17258 synchronized (mPackages) { 17259 mSettings.readDefaultAppsLPw(parser, userId); 17260 } 17261 } 17262 } ); 17263 } catch (Exception e) { 17264 if (DEBUG_BACKUP) { 17265 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17266 } 17267 } 17268 } 17269 17270 @Override 17271 public byte[] getIntentFilterVerificationBackup(int userId) { 17272 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17273 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17274 } 17275 17276 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17277 try { 17278 final XmlSerializer serializer = new FastXmlSerializer(); 17279 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17280 serializer.startDocument(null, true); 17281 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17282 17283 synchronized (mPackages) { 17284 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17285 } 17286 17287 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17288 serializer.endDocument(); 17289 serializer.flush(); 17290 } catch (Exception e) { 17291 if (DEBUG_BACKUP) { 17292 Slog.e(TAG, "Unable to write default apps for backup", e); 17293 } 17294 return null; 17295 } 17296 17297 return dataStream.toByteArray(); 17298 } 17299 17300 @Override 17301 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17302 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17303 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17304 } 17305 17306 try { 17307 final XmlPullParser parser = Xml.newPullParser(); 17308 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17309 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17310 new BlobXmlRestorer() { 17311 @Override 17312 public void apply(XmlPullParser parser, int userId) 17313 throws XmlPullParserException, IOException { 17314 synchronized (mPackages) { 17315 mSettings.readAllDomainVerificationsLPr(parser, userId); 17316 mSettings.writeLPr(); 17317 } 17318 } 17319 } ); 17320 } catch (Exception e) { 17321 if (DEBUG_BACKUP) { 17322 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17323 } 17324 } 17325 } 17326 17327 @Override 17328 public byte[] getPermissionGrantBackup(int userId) { 17329 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17330 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17331 } 17332 17333 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17334 try { 17335 final XmlSerializer serializer = new FastXmlSerializer(); 17336 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17337 serializer.startDocument(null, true); 17338 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17339 17340 synchronized (mPackages) { 17341 serializeRuntimePermissionGrantsLPr(serializer, userId); 17342 } 17343 17344 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17345 serializer.endDocument(); 17346 serializer.flush(); 17347 } catch (Exception e) { 17348 if (DEBUG_BACKUP) { 17349 Slog.e(TAG, "Unable to write default apps for backup", e); 17350 } 17351 return null; 17352 } 17353 17354 return dataStream.toByteArray(); 17355 } 17356 17357 @Override 17358 public void restorePermissionGrants(byte[] backup, int userId) { 17359 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17360 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17361 } 17362 17363 try { 17364 final XmlPullParser parser = Xml.newPullParser(); 17365 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17366 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17367 new BlobXmlRestorer() { 17368 @Override 17369 public void apply(XmlPullParser parser, int userId) 17370 throws XmlPullParserException, IOException { 17371 synchronized (mPackages) { 17372 processRestoredPermissionGrantsLPr(parser, userId); 17373 } 17374 } 17375 } ); 17376 } catch (Exception e) { 17377 if (DEBUG_BACKUP) { 17378 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17379 } 17380 } 17381 } 17382 17383 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17384 throws IOException { 17385 serializer.startTag(null, TAG_ALL_GRANTS); 17386 17387 final int N = mSettings.mPackages.size(); 17388 for (int i = 0; i < N; i++) { 17389 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17390 boolean pkgGrantsKnown = false; 17391 17392 PermissionsState packagePerms = ps.getPermissionsState(); 17393 17394 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17395 final int grantFlags = state.getFlags(); 17396 // only look at grants that are not system/policy fixed 17397 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17398 final boolean isGranted = state.isGranted(); 17399 // And only back up the user-twiddled state bits 17400 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17401 final String packageName = mSettings.mPackages.keyAt(i); 17402 if (!pkgGrantsKnown) { 17403 serializer.startTag(null, TAG_GRANT); 17404 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17405 pkgGrantsKnown = true; 17406 } 17407 17408 final boolean userSet = 17409 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17410 final boolean userFixed = 17411 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17412 final boolean revoke = 17413 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17414 17415 serializer.startTag(null, TAG_PERMISSION); 17416 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17417 if (isGranted) { 17418 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17419 } 17420 if (userSet) { 17421 serializer.attribute(null, ATTR_USER_SET, "true"); 17422 } 17423 if (userFixed) { 17424 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17425 } 17426 if (revoke) { 17427 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17428 } 17429 serializer.endTag(null, TAG_PERMISSION); 17430 } 17431 } 17432 } 17433 17434 if (pkgGrantsKnown) { 17435 serializer.endTag(null, TAG_GRANT); 17436 } 17437 } 17438 17439 serializer.endTag(null, TAG_ALL_GRANTS); 17440 } 17441 17442 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17443 throws XmlPullParserException, IOException { 17444 String pkgName = null; 17445 int outerDepth = parser.getDepth(); 17446 int type; 17447 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17448 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17449 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17450 continue; 17451 } 17452 17453 final String tagName = parser.getName(); 17454 if (tagName.equals(TAG_GRANT)) { 17455 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17456 if (DEBUG_BACKUP) { 17457 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17458 } 17459 } else if (tagName.equals(TAG_PERMISSION)) { 17460 17461 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17462 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17463 17464 int newFlagSet = 0; 17465 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17466 newFlagSet |= FLAG_PERMISSION_USER_SET; 17467 } 17468 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17469 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17470 } 17471 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17472 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17473 } 17474 if (DEBUG_BACKUP) { 17475 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17476 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17477 } 17478 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17479 if (ps != null) { 17480 // Already installed so we apply the grant immediately 17481 if (DEBUG_BACKUP) { 17482 Slog.v(TAG, " + already installed; applying"); 17483 } 17484 PermissionsState perms = ps.getPermissionsState(); 17485 BasePermission bp = mSettings.mPermissions.get(permName); 17486 if (bp != null) { 17487 if (isGranted) { 17488 perms.grantRuntimePermission(bp, userId); 17489 } 17490 if (newFlagSet != 0) { 17491 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17492 } 17493 } 17494 } else { 17495 // Need to wait for post-restore install to apply the grant 17496 if (DEBUG_BACKUP) { 17497 Slog.v(TAG, " - not yet installed; saving for later"); 17498 } 17499 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17500 isGranted, newFlagSet, userId); 17501 } 17502 } else { 17503 PackageManagerService.reportSettingsProblem(Log.WARN, 17504 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17505 XmlUtils.skipCurrentTag(parser); 17506 } 17507 } 17508 17509 scheduleWriteSettingsLocked(); 17510 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17511 } 17512 17513 @Override 17514 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17515 int sourceUserId, int targetUserId, int flags) { 17516 mContext.enforceCallingOrSelfPermission( 17517 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17518 int callingUid = Binder.getCallingUid(); 17519 enforceOwnerRights(ownerPackage, callingUid); 17520 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17521 if (intentFilter.countActions() == 0) { 17522 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17523 return; 17524 } 17525 synchronized (mPackages) { 17526 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17527 ownerPackage, targetUserId, flags); 17528 CrossProfileIntentResolver resolver = 17529 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17530 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17531 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17532 if (existing != null) { 17533 int size = existing.size(); 17534 for (int i = 0; i < size; i++) { 17535 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17536 return; 17537 } 17538 } 17539 } 17540 resolver.addFilter(newFilter); 17541 scheduleWritePackageRestrictionsLocked(sourceUserId); 17542 } 17543 } 17544 17545 @Override 17546 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17547 mContext.enforceCallingOrSelfPermission( 17548 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17549 int callingUid = Binder.getCallingUid(); 17550 enforceOwnerRights(ownerPackage, callingUid); 17551 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17552 synchronized (mPackages) { 17553 CrossProfileIntentResolver resolver = 17554 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17555 ArraySet<CrossProfileIntentFilter> set = 17556 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17557 for (CrossProfileIntentFilter filter : set) { 17558 if (filter.getOwnerPackage().equals(ownerPackage)) { 17559 resolver.removeFilter(filter); 17560 } 17561 } 17562 scheduleWritePackageRestrictionsLocked(sourceUserId); 17563 } 17564 } 17565 17566 // Enforcing that callingUid is owning pkg on userId 17567 private void enforceOwnerRights(String pkg, int callingUid) { 17568 // The system owns everything. 17569 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17570 return; 17571 } 17572 int callingUserId = UserHandle.getUserId(callingUid); 17573 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17574 if (pi == null) { 17575 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17576 + callingUserId); 17577 } 17578 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17579 throw new SecurityException("Calling uid " + callingUid 17580 + " does not own package " + pkg); 17581 } 17582 } 17583 17584 @Override 17585 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17586 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17587 } 17588 17589 private Intent getHomeIntent() { 17590 Intent intent = new Intent(Intent.ACTION_MAIN); 17591 intent.addCategory(Intent.CATEGORY_HOME); 17592 return intent; 17593 } 17594 17595 private IntentFilter getHomeFilter() { 17596 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17597 filter.addCategory(Intent.CATEGORY_HOME); 17598 filter.addCategory(Intent.CATEGORY_DEFAULT); 17599 return filter; 17600 } 17601 17602 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17603 int userId) { 17604 Intent intent = getHomeIntent(); 17605 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17606 PackageManager.GET_META_DATA, userId); 17607 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17608 true, false, false, userId); 17609 17610 allHomeCandidates.clear(); 17611 if (list != null) { 17612 for (ResolveInfo ri : list) { 17613 allHomeCandidates.add(ri); 17614 } 17615 } 17616 return (preferred == null || preferred.activityInfo == null) 17617 ? null 17618 : new ComponentName(preferred.activityInfo.packageName, 17619 preferred.activityInfo.name); 17620 } 17621 17622 @Override 17623 public void setHomeActivity(ComponentName comp, int userId) { 17624 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17625 getHomeActivitiesAsUser(homeActivities, userId); 17626 17627 boolean found = false; 17628 17629 final int size = homeActivities.size(); 17630 final ComponentName[] set = new ComponentName[size]; 17631 for (int i = 0; i < size; i++) { 17632 final ResolveInfo candidate = homeActivities.get(i); 17633 final ActivityInfo info = candidate.activityInfo; 17634 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17635 set[i] = activityName; 17636 if (!found && activityName.equals(comp)) { 17637 found = true; 17638 } 17639 } 17640 if (!found) { 17641 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17642 + userId); 17643 } 17644 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17645 set, comp, userId); 17646 } 17647 17648 private @Nullable String getSetupWizardPackageName() { 17649 final Intent intent = new Intent(Intent.ACTION_MAIN); 17650 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17651 17652 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17653 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17654 | MATCH_DISABLED_COMPONENTS, 17655 UserHandle.myUserId()); 17656 if (matches.size() == 1) { 17657 return matches.get(0).getComponentInfo().packageName; 17658 } else { 17659 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17660 + ": matches=" + matches); 17661 return null; 17662 } 17663 } 17664 17665 @Override 17666 public void setApplicationEnabledSetting(String appPackageName, 17667 int newState, int flags, int userId, String callingPackage) { 17668 if (!sUserManager.exists(userId)) return; 17669 if (callingPackage == null) { 17670 callingPackage = Integer.toString(Binder.getCallingUid()); 17671 } 17672 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17673 } 17674 17675 @Override 17676 public void setComponentEnabledSetting(ComponentName componentName, 17677 int newState, int flags, int userId) { 17678 if (!sUserManager.exists(userId)) return; 17679 setEnabledSetting(componentName.getPackageName(), 17680 componentName.getClassName(), newState, flags, userId, null); 17681 } 17682 17683 private void setEnabledSetting(final String packageName, String className, int newState, 17684 final int flags, int userId, String callingPackage) { 17685 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17686 || newState == COMPONENT_ENABLED_STATE_ENABLED 17687 || newState == COMPONENT_ENABLED_STATE_DISABLED 17688 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17689 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17690 throw new IllegalArgumentException("Invalid new component state: " 17691 + newState); 17692 } 17693 PackageSetting pkgSetting; 17694 final int uid = Binder.getCallingUid(); 17695 final int permission; 17696 if (uid == Process.SYSTEM_UID) { 17697 permission = PackageManager.PERMISSION_GRANTED; 17698 } else { 17699 permission = mContext.checkCallingOrSelfPermission( 17700 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17701 } 17702 enforceCrossUserPermission(uid, userId, 17703 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17704 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17705 boolean sendNow = false; 17706 boolean isApp = (className == null); 17707 String componentName = isApp ? packageName : className; 17708 int packageUid = -1; 17709 ArrayList<String> components; 17710 17711 // writer 17712 synchronized (mPackages) { 17713 pkgSetting = mSettings.mPackages.get(packageName); 17714 if (pkgSetting == null) { 17715 if (className == null) { 17716 throw new IllegalArgumentException("Unknown package: " + packageName); 17717 } 17718 throw new IllegalArgumentException( 17719 "Unknown component: " + packageName + "/" + className); 17720 } 17721 } 17722 17723 // Limit who can change which apps 17724 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17725 // Don't allow apps that don't have permission to modify other apps 17726 if (!allowedByPermission) { 17727 throw new SecurityException( 17728 "Permission Denial: attempt to change component state from pid=" 17729 + Binder.getCallingPid() 17730 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17731 } 17732 // Don't allow changing profile and device owners. 17733 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17734 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17735 } 17736 } 17737 17738 synchronized (mPackages) { 17739 if (uid == Process.SHELL_UID) { 17740 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17741 int oldState = pkgSetting.getEnabled(userId); 17742 if (className == null 17743 && 17744 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17745 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17746 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17747 && 17748 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17749 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17750 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17751 // ok 17752 } else { 17753 throw new SecurityException( 17754 "Shell cannot change component state for " + packageName + "/" 17755 + className + " to " + newState); 17756 } 17757 } 17758 if (className == null) { 17759 // We're dealing with an application/package level state change 17760 if (pkgSetting.getEnabled(userId) == newState) { 17761 // Nothing to do 17762 return; 17763 } 17764 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17765 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17766 // Don't care about who enables an app. 17767 callingPackage = null; 17768 } 17769 pkgSetting.setEnabled(newState, userId, callingPackage); 17770 // pkgSetting.pkg.mSetEnabled = newState; 17771 } else { 17772 // We're dealing with a component level state change 17773 // First, verify that this is a valid class name. 17774 PackageParser.Package pkg = pkgSetting.pkg; 17775 if (pkg == null || !pkg.hasComponentClassName(className)) { 17776 if (pkg != null && 17777 pkg.applicationInfo.targetSdkVersion >= 17778 Build.VERSION_CODES.JELLY_BEAN) { 17779 throw new IllegalArgumentException("Component class " + className 17780 + " does not exist in " + packageName); 17781 } else { 17782 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17783 + className + " does not exist in " + packageName); 17784 } 17785 } 17786 switch (newState) { 17787 case COMPONENT_ENABLED_STATE_ENABLED: 17788 if (!pkgSetting.enableComponentLPw(className, userId)) { 17789 return; 17790 } 17791 break; 17792 case COMPONENT_ENABLED_STATE_DISABLED: 17793 if (!pkgSetting.disableComponentLPw(className, userId)) { 17794 return; 17795 } 17796 break; 17797 case COMPONENT_ENABLED_STATE_DEFAULT: 17798 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17799 return; 17800 } 17801 break; 17802 default: 17803 Slog.e(TAG, "Invalid new component state: " + newState); 17804 return; 17805 } 17806 } 17807 scheduleWritePackageRestrictionsLocked(userId); 17808 components = mPendingBroadcasts.get(userId, packageName); 17809 final boolean newPackage = components == null; 17810 if (newPackage) { 17811 components = new ArrayList<String>(); 17812 } 17813 if (!components.contains(componentName)) { 17814 components.add(componentName); 17815 } 17816 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17817 sendNow = true; 17818 // Purge entry from pending broadcast list if another one exists already 17819 // since we are sending one right away. 17820 mPendingBroadcasts.remove(userId, packageName); 17821 } else { 17822 if (newPackage) { 17823 mPendingBroadcasts.put(userId, packageName, components); 17824 } 17825 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17826 // Schedule a message 17827 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17828 } 17829 } 17830 } 17831 17832 long callingId = Binder.clearCallingIdentity(); 17833 try { 17834 if (sendNow) { 17835 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17836 sendPackageChangedBroadcast(packageName, 17837 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17838 } 17839 } finally { 17840 Binder.restoreCallingIdentity(callingId); 17841 } 17842 } 17843 17844 @Override 17845 public void flushPackageRestrictionsAsUser(int userId) { 17846 if (!sUserManager.exists(userId)) { 17847 return; 17848 } 17849 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17850 false /* checkShell */, "flushPackageRestrictions"); 17851 synchronized (mPackages) { 17852 mSettings.writePackageRestrictionsLPr(userId); 17853 mDirtyUsers.remove(userId); 17854 if (mDirtyUsers.isEmpty()) { 17855 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17856 } 17857 } 17858 } 17859 17860 private void sendPackageChangedBroadcast(String packageName, 17861 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17862 if (DEBUG_INSTALL) 17863 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17864 + componentNames); 17865 Bundle extras = new Bundle(4); 17866 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17867 String nameList[] = new String[componentNames.size()]; 17868 componentNames.toArray(nameList); 17869 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17870 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17871 extras.putInt(Intent.EXTRA_UID, packageUid); 17872 // If this is not reporting a change of the overall package, then only send it 17873 // to registered receivers. We don't want to launch a swath of apps for every 17874 // little component state change. 17875 final int flags = !componentNames.contains(packageName) 17876 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17877 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17878 new int[] {UserHandle.getUserId(packageUid)}); 17879 } 17880 17881 @Override 17882 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17883 if (!sUserManager.exists(userId)) return; 17884 final int uid = Binder.getCallingUid(); 17885 final int permission = mContext.checkCallingOrSelfPermission( 17886 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17887 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17888 enforceCrossUserPermission(uid, userId, 17889 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17890 // writer 17891 synchronized (mPackages) { 17892 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17893 allowedByPermission, uid, userId)) { 17894 scheduleWritePackageRestrictionsLocked(userId); 17895 } 17896 } 17897 } 17898 17899 @Override 17900 public String getInstallerPackageName(String packageName) { 17901 // reader 17902 synchronized (mPackages) { 17903 return mSettings.getInstallerPackageNameLPr(packageName); 17904 } 17905 } 17906 17907 public boolean isOrphaned(String packageName) { 17908 // reader 17909 synchronized (mPackages) { 17910 return mSettings.isOrphaned(packageName); 17911 } 17912 } 17913 17914 @Override 17915 public int getApplicationEnabledSetting(String packageName, int userId) { 17916 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17917 int uid = Binder.getCallingUid(); 17918 enforceCrossUserPermission(uid, userId, 17919 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17920 // reader 17921 synchronized (mPackages) { 17922 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17923 } 17924 } 17925 17926 @Override 17927 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17928 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17929 int uid = Binder.getCallingUid(); 17930 enforceCrossUserPermission(uid, userId, 17931 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17932 // reader 17933 synchronized (mPackages) { 17934 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17935 } 17936 } 17937 17938 @Override 17939 public void enterSafeMode() { 17940 enforceSystemOrRoot("Only the system can request entering safe mode"); 17941 17942 if (!mSystemReady) { 17943 mSafeMode = true; 17944 } 17945 } 17946 17947 @Override 17948 public void systemReady() { 17949 mSystemReady = true; 17950 17951 // Read the compatibilty setting when the system is ready. 17952 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17953 mContext.getContentResolver(), 17954 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17955 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17956 if (DEBUG_SETTINGS) { 17957 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17958 } 17959 17960 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17961 17962 synchronized (mPackages) { 17963 // Verify that all of the preferred activity components actually 17964 // exist. It is possible for applications to be updated and at 17965 // that point remove a previously declared activity component that 17966 // had been set as a preferred activity. We try to clean this up 17967 // the next time we encounter that preferred activity, but it is 17968 // possible for the user flow to never be able to return to that 17969 // situation so here we do a sanity check to make sure we haven't 17970 // left any junk around. 17971 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17972 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17973 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17974 removed.clear(); 17975 for (PreferredActivity pa : pir.filterSet()) { 17976 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17977 removed.add(pa); 17978 } 17979 } 17980 if (removed.size() > 0) { 17981 for (int r=0; r<removed.size(); r++) { 17982 PreferredActivity pa = removed.get(r); 17983 Slog.w(TAG, "Removing dangling preferred activity: " 17984 + pa.mPref.mComponent); 17985 pir.removeFilter(pa); 17986 } 17987 mSettings.writePackageRestrictionsLPr( 17988 mSettings.mPreferredActivities.keyAt(i)); 17989 } 17990 } 17991 17992 for (int userId : UserManagerService.getInstance().getUserIds()) { 17993 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17994 grantPermissionsUserIds = ArrayUtils.appendInt( 17995 grantPermissionsUserIds, userId); 17996 } 17997 } 17998 } 17999 sUserManager.systemReady(); 18000 18001 // If we upgraded grant all default permissions before kicking off. 18002 for (int userId : grantPermissionsUserIds) { 18003 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18004 } 18005 18006 // Kick off any messages waiting for system ready 18007 if (mPostSystemReadyMessages != null) { 18008 for (Message msg : mPostSystemReadyMessages) { 18009 msg.sendToTarget(); 18010 } 18011 mPostSystemReadyMessages = null; 18012 } 18013 18014 // Watch for external volumes that come and go over time 18015 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18016 storage.registerListener(mStorageListener); 18017 18018 mInstallerService.systemReady(); 18019 mPackageDexOptimizer.systemReady(); 18020 18021 MountServiceInternal mountServiceInternal = LocalServices.getService( 18022 MountServiceInternal.class); 18023 mountServiceInternal.addExternalStoragePolicy( 18024 new MountServiceInternal.ExternalStorageMountPolicy() { 18025 @Override 18026 public int getMountMode(int uid, String packageName) { 18027 if (Process.isIsolated(uid)) { 18028 return Zygote.MOUNT_EXTERNAL_NONE; 18029 } 18030 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18031 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18032 } 18033 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18034 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18035 } 18036 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18037 return Zygote.MOUNT_EXTERNAL_READ; 18038 } 18039 return Zygote.MOUNT_EXTERNAL_WRITE; 18040 } 18041 18042 @Override 18043 public boolean hasExternalStorage(int uid, String packageName) { 18044 return true; 18045 } 18046 }); 18047 18048 // Now that we're mostly running, clean up stale users and apps 18049 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18050 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18051 } 18052 18053 @Override 18054 public boolean isSafeMode() { 18055 return mSafeMode; 18056 } 18057 18058 @Override 18059 public boolean hasSystemUidErrors() { 18060 return mHasSystemUidErrors; 18061 } 18062 18063 static String arrayToString(int[] array) { 18064 StringBuffer buf = new StringBuffer(128); 18065 buf.append('['); 18066 if (array != null) { 18067 for (int i=0; i<array.length; i++) { 18068 if (i > 0) buf.append(", "); 18069 buf.append(array[i]); 18070 } 18071 } 18072 buf.append(']'); 18073 return buf.toString(); 18074 } 18075 18076 static class DumpState { 18077 public static final int DUMP_LIBS = 1 << 0; 18078 public static final int DUMP_FEATURES = 1 << 1; 18079 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18080 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18081 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18082 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18083 public static final int DUMP_PERMISSIONS = 1 << 6; 18084 public static final int DUMP_PACKAGES = 1 << 7; 18085 public static final int DUMP_SHARED_USERS = 1 << 8; 18086 public static final int DUMP_MESSAGES = 1 << 9; 18087 public static final int DUMP_PROVIDERS = 1 << 10; 18088 public static final int DUMP_VERIFIERS = 1 << 11; 18089 public static final int DUMP_PREFERRED = 1 << 12; 18090 public static final int DUMP_PREFERRED_XML = 1 << 13; 18091 public static final int DUMP_KEYSETS = 1 << 14; 18092 public static final int DUMP_VERSION = 1 << 15; 18093 public static final int DUMP_INSTALLS = 1 << 16; 18094 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18095 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18096 public static final int DUMP_FROZEN = 1 << 19; 18097 public static final int DUMP_DEXOPT = 1 << 20; 18098 18099 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18100 18101 private int mTypes; 18102 18103 private int mOptions; 18104 18105 private boolean mTitlePrinted; 18106 18107 private SharedUserSetting mSharedUser; 18108 18109 public boolean isDumping(int type) { 18110 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18111 return true; 18112 } 18113 18114 return (mTypes & type) != 0; 18115 } 18116 18117 public void setDump(int type) { 18118 mTypes |= type; 18119 } 18120 18121 public boolean isOptionEnabled(int option) { 18122 return (mOptions & option) != 0; 18123 } 18124 18125 public void setOptionEnabled(int option) { 18126 mOptions |= option; 18127 } 18128 18129 public boolean onTitlePrinted() { 18130 final boolean printed = mTitlePrinted; 18131 mTitlePrinted = true; 18132 return printed; 18133 } 18134 18135 public boolean getTitlePrinted() { 18136 return mTitlePrinted; 18137 } 18138 18139 public void setTitlePrinted(boolean enabled) { 18140 mTitlePrinted = enabled; 18141 } 18142 18143 public SharedUserSetting getSharedUser() { 18144 return mSharedUser; 18145 } 18146 18147 public void setSharedUser(SharedUserSetting user) { 18148 mSharedUser = user; 18149 } 18150 } 18151 18152 @Override 18153 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18154 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18155 (new PackageManagerShellCommand(this)).exec( 18156 this, in, out, err, args, resultReceiver); 18157 } 18158 18159 @Override 18160 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18161 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18162 != PackageManager.PERMISSION_GRANTED) { 18163 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18164 + Binder.getCallingPid() 18165 + ", uid=" + Binder.getCallingUid() 18166 + " without permission " 18167 + android.Manifest.permission.DUMP); 18168 return; 18169 } 18170 18171 DumpState dumpState = new DumpState(); 18172 boolean fullPreferred = false; 18173 boolean checkin = false; 18174 18175 String packageName = null; 18176 ArraySet<String> permissionNames = null; 18177 18178 int opti = 0; 18179 while (opti < args.length) { 18180 String opt = args[opti]; 18181 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18182 break; 18183 } 18184 opti++; 18185 18186 if ("-a".equals(opt)) { 18187 // Right now we only know how to print all. 18188 } else if ("-h".equals(opt)) { 18189 pw.println("Package manager dump options:"); 18190 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18191 pw.println(" --checkin: dump for a checkin"); 18192 pw.println(" -f: print details of intent filters"); 18193 pw.println(" -h: print this help"); 18194 pw.println(" cmd may be one of:"); 18195 pw.println(" l[ibraries]: list known shared libraries"); 18196 pw.println(" f[eatures]: list device features"); 18197 pw.println(" k[eysets]: print known keysets"); 18198 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18199 pw.println(" perm[issions]: dump permissions"); 18200 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18201 pw.println(" pref[erred]: print preferred package settings"); 18202 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18203 pw.println(" prov[iders]: dump content providers"); 18204 pw.println(" p[ackages]: dump installed packages"); 18205 pw.println(" s[hared-users]: dump shared user IDs"); 18206 pw.println(" m[essages]: print collected runtime messages"); 18207 pw.println(" v[erifiers]: print package verifier info"); 18208 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18209 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18210 pw.println(" version: print database version info"); 18211 pw.println(" write: write current settings now"); 18212 pw.println(" installs: details about install sessions"); 18213 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18214 pw.println(" dexopt: dump dexopt state"); 18215 pw.println(" <package.name>: info about given package"); 18216 return; 18217 } else if ("--checkin".equals(opt)) { 18218 checkin = true; 18219 } else if ("-f".equals(opt)) { 18220 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18221 } else { 18222 pw.println("Unknown argument: " + opt + "; use -h for help"); 18223 } 18224 } 18225 18226 // Is the caller requesting to dump a particular piece of data? 18227 if (opti < args.length) { 18228 String cmd = args[opti]; 18229 opti++; 18230 // Is this a package name? 18231 if ("android".equals(cmd) || cmd.contains(".")) { 18232 packageName = cmd; 18233 // When dumping a single package, we always dump all of its 18234 // filter information since the amount of data will be reasonable. 18235 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18236 } else if ("check-permission".equals(cmd)) { 18237 if (opti >= args.length) { 18238 pw.println("Error: check-permission missing permission argument"); 18239 return; 18240 } 18241 String perm = args[opti]; 18242 opti++; 18243 if (opti >= args.length) { 18244 pw.println("Error: check-permission missing package argument"); 18245 return; 18246 } 18247 String pkg = args[opti]; 18248 opti++; 18249 int user = UserHandle.getUserId(Binder.getCallingUid()); 18250 if (opti < args.length) { 18251 try { 18252 user = Integer.parseInt(args[opti]); 18253 } catch (NumberFormatException e) { 18254 pw.println("Error: check-permission user argument is not a number: " 18255 + args[opti]); 18256 return; 18257 } 18258 } 18259 pw.println(checkPermission(perm, pkg, user)); 18260 return; 18261 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18262 dumpState.setDump(DumpState.DUMP_LIBS); 18263 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18264 dumpState.setDump(DumpState.DUMP_FEATURES); 18265 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18266 if (opti >= args.length) { 18267 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18268 | DumpState.DUMP_SERVICE_RESOLVERS 18269 | DumpState.DUMP_RECEIVER_RESOLVERS 18270 | DumpState.DUMP_CONTENT_RESOLVERS); 18271 } else { 18272 while (opti < args.length) { 18273 String name = args[opti]; 18274 if ("a".equals(name) || "activity".equals(name)) { 18275 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18276 } else if ("s".equals(name) || "service".equals(name)) { 18277 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18278 } else if ("r".equals(name) || "receiver".equals(name)) { 18279 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18280 } else if ("c".equals(name) || "content".equals(name)) { 18281 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18282 } else { 18283 pw.println("Error: unknown resolver table type: " + name); 18284 return; 18285 } 18286 opti++; 18287 } 18288 } 18289 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18290 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18291 } else if ("permission".equals(cmd)) { 18292 if (opti >= args.length) { 18293 pw.println("Error: permission requires permission name"); 18294 return; 18295 } 18296 permissionNames = new ArraySet<>(); 18297 while (opti < args.length) { 18298 permissionNames.add(args[opti]); 18299 opti++; 18300 } 18301 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18302 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18303 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18304 dumpState.setDump(DumpState.DUMP_PREFERRED); 18305 } else if ("preferred-xml".equals(cmd)) { 18306 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18307 if (opti < args.length && "--full".equals(args[opti])) { 18308 fullPreferred = true; 18309 opti++; 18310 } 18311 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18312 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18313 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18314 dumpState.setDump(DumpState.DUMP_PACKAGES); 18315 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18316 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18317 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18318 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18319 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18320 dumpState.setDump(DumpState.DUMP_MESSAGES); 18321 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18322 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18323 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18324 || "intent-filter-verifiers".equals(cmd)) { 18325 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18326 } else if ("version".equals(cmd)) { 18327 dumpState.setDump(DumpState.DUMP_VERSION); 18328 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18329 dumpState.setDump(DumpState.DUMP_KEYSETS); 18330 } else if ("installs".equals(cmd)) { 18331 dumpState.setDump(DumpState.DUMP_INSTALLS); 18332 } else if ("frozen".equals(cmd)) { 18333 dumpState.setDump(DumpState.DUMP_FROZEN); 18334 } else if ("dexopt".equals(cmd)) { 18335 dumpState.setDump(DumpState.DUMP_DEXOPT); 18336 } else if ("write".equals(cmd)) { 18337 synchronized (mPackages) { 18338 mSettings.writeLPr(); 18339 pw.println("Settings written."); 18340 return; 18341 } 18342 } 18343 } 18344 18345 if (checkin) { 18346 pw.println("vers,1"); 18347 } 18348 18349 // reader 18350 synchronized (mPackages) { 18351 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18352 if (!checkin) { 18353 if (dumpState.onTitlePrinted()) 18354 pw.println(); 18355 pw.println("Database versions:"); 18356 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18357 } 18358 } 18359 18360 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18361 if (!checkin) { 18362 if (dumpState.onTitlePrinted()) 18363 pw.println(); 18364 pw.println("Verifiers:"); 18365 pw.print(" Required: "); 18366 pw.print(mRequiredVerifierPackage); 18367 pw.print(" (uid="); 18368 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18369 UserHandle.USER_SYSTEM)); 18370 pw.println(")"); 18371 } else if (mRequiredVerifierPackage != null) { 18372 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18373 pw.print(","); 18374 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18375 UserHandle.USER_SYSTEM)); 18376 } 18377 } 18378 18379 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18380 packageName == null) { 18381 if (mIntentFilterVerifierComponent != null) { 18382 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18383 if (!checkin) { 18384 if (dumpState.onTitlePrinted()) 18385 pw.println(); 18386 pw.println("Intent Filter Verifier:"); 18387 pw.print(" Using: "); 18388 pw.print(verifierPackageName); 18389 pw.print(" (uid="); 18390 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18391 UserHandle.USER_SYSTEM)); 18392 pw.println(")"); 18393 } else if (verifierPackageName != null) { 18394 pw.print("ifv,"); pw.print(verifierPackageName); 18395 pw.print(","); 18396 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18397 UserHandle.USER_SYSTEM)); 18398 } 18399 } else { 18400 pw.println(); 18401 pw.println("No Intent Filter Verifier available!"); 18402 } 18403 } 18404 18405 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18406 boolean printedHeader = false; 18407 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18408 while (it.hasNext()) { 18409 String name = it.next(); 18410 SharedLibraryEntry ent = mSharedLibraries.get(name); 18411 if (!checkin) { 18412 if (!printedHeader) { 18413 if (dumpState.onTitlePrinted()) 18414 pw.println(); 18415 pw.println("Libraries:"); 18416 printedHeader = true; 18417 } 18418 pw.print(" "); 18419 } else { 18420 pw.print("lib,"); 18421 } 18422 pw.print(name); 18423 if (!checkin) { 18424 pw.print(" -> "); 18425 } 18426 if (ent.path != null) { 18427 if (!checkin) { 18428 pw.print("(jar) "); 18429 pw.print(ent.path); 18430 } else { 18431 pw.print(",jar,"); 18432 pw.print(ent.path); 18433 } 18434 } else { 18435 if (!checkin) { 18436 pw.print("(apk) "); 18437 pw.print(ent.apk); 18438 } else { 18439 pw.print(",apk,"); 18440 pw.print(ent.apk); 18441 } 18442 } 18443 pw.println(); 18444 } 18445 } 18446 18447 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18448 if (dumpState.onTitlePrinted()) 18449 pw.println(); 18450 if (!checkin) { 18451 pw.println("Features:"); 18452 } 18453 18454 for (FeatureInfo feat : mAvailableFeatures.values()) { 18455 if (checkin) { 18456 pw.print("feat,"); 18457 pw.print(feat.name); 18458 pw.print(","); 18459 pw.println(feat.version); 18460 } else { 18461 pw.print(" "); 18462 pw.print(feat.name); 18463 if (feat.version > 0) { 18464 pw.print(" version="); 18465 pw.print(feat.version); 18466 } 18467 pw.println(); 18468 } 18469 } 18470 } 18471 18472 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18473 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18474 : "Activity Resolver Table:", " ", packageName, 18475 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18476 dumpState.setTitlePrinted(true); 18477 } 18478 } 18479 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18480 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18481 : "Receiver Resolver Table:", " ", packageName, 18482 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18483 dumpState.setTitlePrinted(true); 18484 } 18485 } 18486 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18487 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18488 : "Service Resolver Table:", " ", packageName, 18489 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18490 dumpState.setTitlePrinted(true); 18491 } 18492 } 18493 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18494 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18495 : "Provider Resolver Table:", " ", packageName, 18496 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18497 dumpState.setTitlePrinted(true); 18498 } 18499 } 18500 18501 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18502 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18503 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18504 int user = mSettings.mPreferredActivities.keyAt(i); 18505 if (pir.dump(pw, 18506 dumpState.getTitlePrinted() 18507 ? "\nPreferred Activities User " + user + ":" 18508 : "Preferred Activities User " + user + ":", " ", 18509 packageName, true, false)) { 18510 dumpState.setTitlePrinted(true); 18511 } 18512 } 18513 } 18514 18515 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18516 pw.flush(); 18517 FileOutputStream fout = new FileOutputStream(fd); 18518 BufferedOutputStream str = new BufferedOutputStream(fout); 18519 XmlSerializer serializer = new FastXmlSerializer(); 18520 try { 18521 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18522 serializer.startDocument(null, true); 18523 serializer.setFeature( 18524 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18525 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18526 serializer.endDocument(); 18527 serializer.flush(); 18528 } catch (IllegalArgumentException e) { 18529 pw.println("Failed writing: " + e); 18530 } catch (IllegalStateException e) { 18531 pw.println("Failed writing: " + e); 18532 } catch (IOException e) { 18533 pw.println("Failed writing: " + e); 18534 } 18535 } 18536 18537 if (!checkin 18538 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18539 && packageName == null) { 18540 pw.println(); 18541 int count = mSettings.mPackages.size(); 18542 if (count == 0) { 18543 pw.println("No applications!"); 18544 pw.println(); 18545 } else { 18546 final String prefix = " "; 18547 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18548 if (allPackageSettings.size() == 0) { 18549 pw.println("No domain preferred apps!"); 18550 pw.println(); 18551 } else { 18552 pw.println("App verification status:"); 18553 pw.println(); 18554 count = 0; 18555 for (PackageSetting ps : allPackageSettings) { 18556 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18557 if (ivi == null || ivi.getPackageName() == null) continue; 18558 pw.println(prefix + "Package: " + ivi.getPackageName()); 18559 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18560 pw.println(prefix + "Status: " + ivi.getStatusString()); 18561 pw.println(); 18562 count++; 18563 } 18564 if (count == 0) { 18565 pw.println(prefix + "No app verification established."); 18566 pw.println(); 18567 } 18568 for (int userId : sUserManager.getUserIds()) { 18569 pw.println("App linkages for user " + userId + ":"); 18570 pw.println(); 18571 count = 0; 18572 for (PackageSetting ps : allPackageSettings) { 18573 final long status = ps.getDomainVerificationStatusForUser(userId); 18574 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18575 continue; 18576 } 18577 pw.println(prefix + "Package: " + ps.name); 18578 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18579 String statusStr = IntentFilterVerificationInfo. 18580 getStatusStringFromValue(status); 18581 pw.println(prefix + "Status: " + statusStr); 18582 pw.println(); 18583 count++; 18584 } 18585 if (count == 0) { 18586 pw.println(prefix + "No configured app linkages."); 18587 pw.println(); 18588 } 18589 } 18590 } 18591 } 18592 } 18593 18594 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18595 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18596 if (packageName == null && permissionNames == null) { 18597 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18598 if (iperm == 0) { 18599 if (dumpState.onTitlePrinted()) 18600 pw.println(); 18601 pw.println("AppOp Permissions:"); 18602 } 18603 pw.print(" AppOp Permission "); 18604 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18605 pw.println(":"); 18606 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18607 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18608 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18609 } 18610 } 18611 } 18612 } 18613 18614 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18615 boolean printedSomething = false; 18616 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18617 if (packageName != null && !packageName.equals(p.info.packageName)) { 18618 continue; 18619 } 18620 if (!printedSomething) { 18621 if (dumpState.onTitlePrinted()) 18622 pw.println(); 18623 pw.println("Registered ContentProviders:"); 18624 printedSomething = true; 18625 } 18626 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18627 pw.print(" "); pw.println(p.toString()); 18628 } 18629 printedSomething = false; 18630 for (Map.Entry<String, PackageParser.Provider> entry : 18631 mProvidersByAuthority.entrySet()) { 18632 PackageParser.Provider p = entry.getValue(); 18633 if (packageName != null && !packageName.equals(p.info.packageName)) { 18634 continue; 18635 } 18636 if (!printedSomething) { 18637 if (dumpState.onTitlePrinted()) 18638 pw.println(); 18639 pw.println("ContentProvider Authorities:"); 18640 printedSomething = true; 18641 } 18642 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18643 pw.print(" "); pw.println(p.toString()); 18644 if (p.info != null && p.info.applicationInfo != null) { 18645 final String appInfo = p.info.applicationInfo.toString(); 18646 pw.print(" applicationInfo="); pw.println(appInfo); 18647 } 18648 } 18649 } 18650 18651 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18652 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18653 } 18654 18655 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18656 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18657 } 18658 18659 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18660 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18661 } 18662 18663 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18664 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18665 } 18666 18667 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18668 // XXX should handle packageName != null by dumping only install data that 18669 // the given package is involved with. 18670 if (dumpState.onTitlePrinted()) pw.println(); 18671 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18672 } 18673 18674 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18675 // XXX should handle packageName != null by dumping only install data that 18676 // the given package is involved with. 18677 if (dumpState.onTitlePrinted()) pw.println(); 18678 18679 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18680 ipw.println(); 18681 ipw.println("Frozen packages:"); 18682 ipw.increaseIndent(); 18683 if (mFrozenPackages.size() == 0) { 18684 ipw.println("(none)"); 18685 } else { 18686 for (int i = 0; i < mFrozenPackages.size(); i++) { 18687 ipw.println(mFrozenPackages.valueAt(i)); 18688 } 18689 } 18690 ipw.decreaseIndent(); 18691 } 18692 18693 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18694 if (dumpState.onTitlePrinted()) pw.println(); 18695 dumpDexoptStateLPr(pw, packageName); 18696 } 18697 18698 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18699 if (dumpState.onTitlePrinted()) pw.println(); 18700 mSettings.dumpReadMessagesLPr(pw, dumpState); 18701 18702 pw.println(); 18703 pw.println("Package warning messages:"); 18704 BufferedReader in = null; 18705 String line = null; 18706 try { 18707 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18708 while ((line = in.readLine()) != null) { 18709 if (line.contains("ignored: updated version")) continue; 18710 pw.println(line); 18711 } 18712 } catch (IOException ignored) { 18713 } finally { 18714 IoUtils.closeQuietly(in); 18715 } 18716 } 18717 18718 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18719 BufferedReader in = null; 18720 String line = null; 18721 try { 18722 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18723 while ((line = in.readLine()) != null) { 18724 if (line.contains("ignored: updated version")) continue; 18725 pw.print("msg,"); 18726 pw.println(line); 18727 } 18728 } catch (IOException ignored) { 18729 } finally { 18730 IoUtils.closeQuietly(in); 18731 } 18732 } 18733 } 18734 } 18735 18736 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18737 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18738 ipw.println(); 18739 ipw.println("Dexopt state:"); 18740 ipw.increaseIndent(); 18741 Collection<PackageParser.Package> packages = null; 18742 if (packageName != null) { 18743 PackageParser.Package targetPackage = mPackages.get(packageName); 18744 if (targetPackage != null) { 18745 packages = Collections.singletonList(targetPackage); 18746 } else { 18747 ipw.println("Unable to find package: " + packageName); 18748 return; 18749 } 18750 } else { 18751 packages = mPackages.values(); 18752 } 18753 18754 for (PackageParser.Package pkg : packages) { 18755 ipw.println("[" + pkg.packageName + "]"); 18756 ipw.increaseIndent(); 18757 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18758 ipw.decreaseIndent(); 18759 } 18760 } 18761 18762 private String dumpDomainString(String packageName) { 18763 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18764 .getList(); 18765 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18766 18767 ArraySet<String> result = new ArraySet<>(); 18768 if (iviList.size() > 0) { 18769 for (IntentFilterVerificationInfo ivi : iviList) { 18770 for (String host : ivi.getDomains()) { 18771 result.add(host); 18772 } 18773 } 18774 } 18775 if (filters != null && filters.size() > 0) { 18776 for (IntentFilter filter : filters) { 18777 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18778 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18779 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18780 result.addAll(filter.getHostsList()); 18781 } 18782 } 18783 } 18784 18785 StringBuilder sb = new StringBuilder(result.size() * 16); 18786 for (String domain : result) { 18787 if (sb.length() > 0) sb.append(" "); 18788 sb.append(domain); 18789 } 18790 return sb.toString(); 18791 } 18792 18793 // ------- apps on sdcard specific code ------- 18794 static final boolean DEBUG_SD_INSTALL = false; 18795 18796 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18797 18798 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18799 18800 private boolean mMediaMounted = false; 18801 18802 static String getEncryptKey() { 18803 try { 18804 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18805 SD_ENCRYPTION_KEYSTORE_NAME); 18806 if (sdEncKey == null) { 18807 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18808 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18809 if (sdEncKey == null) { 18810 Slog.e(TAG, "Failed to create encryption keys"); 18811 return null; 18812 } 18813 } 18814 return sdEncKey; 18815 } catch (NoSuchAlgorithmException nsae) { 18816 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18817 return null; 18818 } catch (IOException ioe) { 18819 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18820 return null; 18821 } 18822 } 18823 18824 /* 18825 * Update media status on PackageManager. 18826 */ 18827 @Override 18828 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18829 int callingUid = Binder.getCallingUid(); 18830 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18831 throw new SecurityException("Media status can only be updated by the system"); 18832 } 18833 // reader; this apparently protects mMediaMounted, but should probably 18834 // be a different lock in that case. 18835 synchronized (mPackages) { 18836 Log.i(TAG, "Updating external media status from " 18837 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18838 + (mediaStatus ? "mounted" : "unmounted")); 18839 if (DEBUG_SD_INSTALL) 18840 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18841 + ", mMediaMounted=" + mMediaMounted); 18842 if (mediaStatus == mMediaMounted) { 18843 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18844 : 0, -1); 18845 mHandler.sendMessage(msg); 18846 return; 18847 } 18848 mMediaMounted = mediaStatus; 18849 } 18850 // Queue up an async operation since the package installation may take a 18851 // little while. 18852 mHandler.post(new Runnable() { 18853 public void run() { 18854 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18855 } 18856 }); 18857 } 18858 18859 /** 18860 * Called by MountService when the initial ASECs to scan are available. 18861 * Should block until all the ASEC containers are finished being scanned. 18862 */ 18863 public void scanAvailableAsecs() { 18864 updateExternalMediaStatusInner(true, false, false); 18865 } 18866 18867 /* 18868 * Collect information of applications on external media, map them against 18869 * existing containers and update information based on current mount status. 18870 * Please note that we always have to report status if reportStatus has been 18871 * set to true especially when unloading packages. 18872 */ 18873 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18874 boolean externalStorage) { 18875 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18876 int[] uidArr = EmptyArray.INT; 18877 18878 final String[] list = PackageHelper.getSecureContainerList(); 18879 if (ArrayUtils.isEmpty(list)) { 18880 Log.i(TAG, "No secure containers found"); 18881 } else { 18882 // Process list of secure containers and categorize them 18883 // as active or stale based on their package internal state. 18884 18885 // reader 18886 synchronized (mPackages) { 18887 for (String cid : list) { 18888 // Leave stages untouched for now; installer service owns them 18889 if (PackageInstallerService.isStageName(cid)) continue; 18890 18891 if (DEBUG_SD_INSTALL) 18892 Log.i(TAG, "Processing container " + cid); 18893 String pkgName = getAsecPackageName(cid); 18894 if (pkgName == null) { 18895 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18896 continue; 18897 } 18898 if (DEBUG_SD_INSTALL) 18899 Log.i(TAG, "Looking for pkg : " + pkgName); 18900 18901 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18902 if (ps == null) { 18903 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18904 continue; 18905 } 18906 18907 /* 18908 * Skip packages that are not external if we're unmounting 18909 * external storage. 18910 */ 18911 if (externalStorage && !isMounted && !isExternal(ps)) { 18912 continue; 18913 } 18914 18915 final AsecInstallArgs args = new AsecInstallArgs(cid, 18916 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18917 // The package status is changed only if the code path 18918 // matches between settings and the container id. 18919 if (ps.codePathString != null 18920 && ps.codePathString.startsWith(args.getCodePath())) { 18921 if (DEBUG_SD_INSTALL) { 18922 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18923 + " at code path: " + ps.codePathString); 18924 } 18925 18926 // We do have a valid package installed on sdcard 18927 processCids.put(args, ps.codePathString); 18928 final int uid = ps.appId; 18929 if (uid != -1) { 18930 uidArr = ArrayUtils.appendInt(uidArr, uid); 18931 } 18932 } else { 18933 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18934 + ps.codePathString); 18935 } 18936 } 18937 } 18938 18939 Arrays.sort(uidArr); 18940 } 18941 18942 // Process packages with valid entries. 18943 if (isMounted) { 18944 if (DEBUG_SD_INSTALL) 18945 Log.i(TAG, "Loading packages"); 18946 loadMediaPackages(processCids, uidArr, externalStorage); 18947 startCleaningPackages(); 18948 mInstallerService.onSecureContainersAvailable(); 18949 } else { 18950 if (DEBUG_SD_INSTALL) 18951 Log.i(TAG, "Unloading packages"); 18952 unloadMediaPackages(processCids, uidArr, reportStatus); 18953 } 18954 } 18955 18956 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18957 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18958 final int size = infos.size(); 18959 final String[] packageNames = new String[size]; 18960 final int[] packageUids = new int[size]; 18961 for (int i = 0; i < size; i++) { 18962 final ApplicationInfo info = infos.get(i); 18963 packageNames[i] = info.packageName; 18964 packageUids[i] = info.uid; 18965 } 18966 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18967 finishedReceiver); 18968 } 18969 18970 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18971 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18972 sendResourcesChangedBroadcast(mediaStatus, replacing, 18973 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18974 } 18975 18976 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18977 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18978 int size = pkgList.length; 18979 if (size > 0) { 18980 // Send broadcasts here 18981 Bundle extras = new Bundle(); 18982 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18983 if (uidArr != null) { 18984 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18985 } 18986 if (replacing) { 18987 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18988 } 18989 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18990 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18991 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18992 } 18993 } 18994 18995 /* 18996 * Look at potentially valid container ids from processCids If package 18997 * information doesn't match the one on record or package scanning fails, 18998 * the cid is added to list of removeCids. We currently don't delete stale 18999 * containers. 19000 */ 19001 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19002 boolean externalStorage) { 19003 ArrayList<String> pkgList = new ArrayList<String>(); 19004 Set<AsecInstallArgs> keys = processCids.keySet(); 19005 19006 for (AsecInstallArgs args : keys) { 19007 String codePath = processCids.get(args); 19008 if (DEBUG_SD_INSTALL) 19009 Log.i(TAG, "Loading container : " + args.cid); 19010 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19011 try { 19012 // Make sure there are no container errors first. 19013 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19014 Slog.e(TAG, "Failed to mount cid : " + args.cid 19015 + " when installing from sdcard"); 19016 continue; 19017 } 19018 // Check code path here. 19019 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19020 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19021 + " does not match one in settings " + codePath); 19022 continue; 19023 } 19024 // Parse package 19025 int parseFlags = mDefParseFlags; 19026 if (args.isExternalAsec()) { 19027 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19028 } 19029 if (args.isFwdLocked()) { 19030 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19031 } 19032 19033 synchronized (mInstallLock) { 19034 PackageParser.Package pkg = null; 19035 try { 19036 // Sadly we don't know the package name yet to freeze it 19037 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19038 SCAN_IGNORE_FROZEN, 0, null); 19039 } catch (PackageManagerException e) { 19040 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19041 } 19042 // Scan the package 19043 if (pkg != null) { 19044 /* 19045 * TODO why is the lock being held? doPostInstall is 19046 * called in other places without the lock. This needs 19047 * to be straightened out. 19048 */ 19049 // writer 19050 synchronized (mPackages) { 19051 retCode = PackageManager.INSTALL_SUCCEEDED; 19052 pkgList.add(pkg.packageName); 19053 // Post process args 19054 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19055 pkg.applicationInfo.uid); 19056 } 19057 } else { 19058 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19059 } 19060 } 19061 19062 } finally { 19063 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19064 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19065 } 19066 } 19067 } 19068 // writer 19069 synchronized (mPackages) { 19070 // If the platform SDK has changed since the last time we booted, 19071 // we need to re-grant app permission to catch any new ones that 19072 // appear. This is really a hack, and means that apps can in some 19073 // cases get permissions that the user didn't initially explicitly 19074 // allow... it would be nice to have some better way to handle 19075 // this situation. 19076 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19077 : mSettings.getInternalVersion(); 19078 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19079 : StorageManager.UUID_PRIVATE_INTERNAL; 19080 19081 int updateFlags = UPDATE_PERMISSIONS_ALL; 19082 if (ver.sdkVersion != mSdkVersion) { 19083 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19084 + mSdkVersion + "; regranting permissions for external"); 19085 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19086 } 19087 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19088 19089 // Yay, everything is now upgraded 19090 ver.forceCurrent(); 19091 19092 // can downgrade to reader 19093 // Persist settings 19094 mSettings.writeLPr(); 19095 } 19096 // Send a broadcast to let everyone know we are done processing 19097 if (pkgList.size() > 0) { 19098 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19099 } 19100 } 19101 19102 /* 19103 * Utility method to unload a list of specified containers 19104 */ 19105 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19106 // Just unmount all valid containers. 19107 for (AsecInstallArgs arg : cidArgs) { 19108 synchronized (mInstallLock) { 19109 arg.doPostDeleteLI(false); 19110 } 19111 } 19112 } 19113 19114 /* 19115 * Unload packages mounted on external media. This involves deleting package 19116 * data from internal structures, sending broadcasts about disabled packages, 19117 * gc'ing to free up references, unmounting all secure containers 19118 * corresponding to packages on external media, and posting a 19119 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19120 * that we always have to post this message if status has been requested no 19121 * matter what. 19122 */ 19123 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19124 final boolean reportStatus) { 19125 if (DEBUG_SD_INSTALL) 19126 Log.i(TAG, "unloading media packages"); 19127 ArrayList<String> pkgList = new ArrayList<String>(); 19128 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19129 final Set<AsecInstallArgs> keys = processCids.keySet(); 19130 for (AsecInstallArgs args : keys) { 19131 String pkgName = args.getPackageName(); 19132 if (DEBUG_SD_INSTALL) 19133 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19134 // Delete package internally 19135 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19136 synchronized (mInstallLock) { 19137 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19138 final boolean res; 19139 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19140 "unloadMediaPackages")) { 19141 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19142 null); 19143 } 19144 if (res) { 19145 pkgList.add(pkgName); 19146 } else { 19147 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19148 failedList.add(args); 19149 } 19150 } 19151 } 19152 19153 // reader 19154 synchronized (mPackages) { 19155 // We didn't update the settings after removing each package; 19156 // write them now for all packages. 19157 mSettings.writeLPr(); 19158 } 19159 19160 // We have to absolutely send UPDATED_MEDIA_STATUS only 19161 // after confirming that all the receivers processed the ordered 19162 // broadcast when packages get disabled, force a gc to clean things up. 19163 // and unload all the containers. 19164 if (pkgList.size() > 0) { 19165 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19166 new IIntentReceiver.Stub() { 19167 public void performReceive(Intent intent, int resultCode, String data, 19168 Bundle extras, boolean ordered, boolean sticky, 19169 int sendingUser) throws RemoteException { 19170 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19171 reportStatus ? 1 : 0, 1, keys); 19172 mHandler.sendMessage(msg); 19173 } 19174 }); 19175 } else { 19176 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19177 keys); 19178 mHandler.sendMessage(msg); 19179 } 19180 } 19181 19182 private void loadPrivatePackages(final VolumeInfo vol) { 19183 mHandler.post(new Runnable() { 19184 @Override 19185 public void run() { 19186 loadPrivatePackagesInner(vol); 19187 } 19188 }); 19189 } 19190 19191 private void loadPrivatePackagesInner(VolumeInfo vol) { 19192 final String volumeUuid = vol.fsUuid; 19193 if (TextUtils.isEmpty(volumeUuid)) { 19194 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19195 return; 19196 } 19197 19198 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19199 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19200 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19201 19202 final VersionInfo ver; 19203 final List<PackageSetting> packages; 19204 synchronized (mPackages) { 19205 ver = mSettings.findOrCreateVersion(volumeUuid); 19206 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19207 } 19208 19209 for (PackageSetting ps : packages) { 19210 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19211 synchronized (mInstallLock) { 19212 final PackageParser.Package pkg; 19213 try { 19214 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19215 loaded.add(pkg.applicationInfo); 19216 19217 } catch (PackageManagerException e) { 19218 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19219 } 19220 19221 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19222 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19223 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19224 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19225 } 19226 } 19227 } 19228 19229 // Reconcile app data for all started/unlocked users 19230 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19231 final UserManager um = mContext.getSystemService(UserManager.class); 19232 UserManagerInternal umInternal = getUserManagerInternal(); 19233 for (UserInfo user : um.getUsers()) { 19234 final int flags; 19235 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19236 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19237 } else if (umInternal.isUserRunning(user.id)) { 19238 flags = StorageManager.FLAG_STORAGE_DE; 19239 } else { 19240 continue; 19241 } 19242 19243 try { 19244 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19245 synchronized (mInstallLock) { 19246 reconcileAppsDataLI(volumeUuid, user.id, flags); 19247 } 19248 } catch (IllegalStateException e) { 19249 // Device was probably ejected, and we'll process that event momentarily 19250 Slog.w(TAG, "Failed to prepare storage: " + e); 19251 } 19252 } 19253 19254 synchronized (mPackages) { 19255 int updateFlags = UPDATE_PERMISSIONS_ALL; 19256 if (ver.sdkVersion != mSdkVersion) { 19257 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19258 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19259 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19260 } 19261 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19262 19263 // Yay, everything is now upgraded 19264 ver.forceCurrent(); 19265 19266 mSettings.writeLPr(); 19267 } 19268 19269 for (PackageFreezer freezer : freezers) { 19270 freezer.close(); 19271 } 19272 19273 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19274 sendResourcesChangedBroadcast(true, false, loaded, null); 19275 } 19276 19277 private void unloadPrivatePackages(final VolumeInfo vol) { 19278 mHandler.post(new Runnable() { 19279 @Override 19280 public void run() { 19281 unloadPrivatePackagesInner(vol); 19282 } 19283 }); 19284 } 19285 19286 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19287 final String volumeUuid = vol.fsUuid; 19288 if (TextUtils.isEmpty(volumeUuid)) { 19289 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19290 return; 19291 } 19292 19293 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19294 synchronized (mInstallLock) { 19295 synchronized (mPackages) { 19296 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19297 for (PackageSetting ps : packages) { 19298 if (ps.pkg == null) continue; 19299 19300 final ApplicationInfo info = ps.pkg.applicationInfo; 19301 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19302 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19303 19304 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19305 "unloadPrivatePackagesInner")) { 19306 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19307 false, null)) { 19308 unloaded.add(info); 19309 } else { 19310 Slog.w(TAG, "Failed to unload " + ps.codePath); 19311 } 19312 } 19313 19314 // Try very hard to release any references to this package 19315 // so we don't risk the system server being killed due to 19316 // open FDs 19317 AttributeCache.instance().removePackage(ps.name); 19318 } 19319 19320 mSettings.writeLPr(); 19321 } 19322 } 19323 19324 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19325 sendResourcesChangedBroadcast(false, false, unloaded, null); 19326 19327 // Try very hard to release any references to this path so we don't risk 19328 // the system server being killed due to open FDs 19329 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19330 19331 for (int i = 0; i < 3; i++) { 19332 System.gc(); 19333 System.runFinalization(); 19334 } 19335 } 19336 19337 /** 19338 * Prepare storage areas for given user on all mounted devices. 19339 */ 19340 void prepareUserData(int userId, int userSerial, int flags) { 19341 synchronized (mInstallLock) { 19342 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19343 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19344 final String volumeUuid = vol.getFsUuid(); 19345 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19346 } 19347 } 19348 } 19349 19350 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19351 boolean allowRecover) { 19352 // Prepare storage and verify that serial numbers are consistent; if 19353 // there's a mismatch we need to destroy to avoid leaking data 19354 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19355 try { 19356 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19357 19358 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19359 UserManagerService.enforceSerialNumber( 19360 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19361 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19362 UserManagerService.enforceSerialNumber( 19363 Environment.getDataSystemDeDirectory(userId), userSerial); 19364 } 19365 } 19366 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19367 UserManagerService.enforceSerialNumber( 19368 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19369 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19370 UserManagerService.enforceSerialNumber( 19371 Environment.getDataSystemCeDirectory(userId), userSerial); 19372 } 19373 } 19374 19375 synchronized (mInstallLock) { 19376 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19377 } 19378 } catch (Exception e) { 19379 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19380 + " because we failed to prepare: " + e); 19381 destroyUserDataLI(volumeUuid, userId, 19382 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19383 19384 if (allowRecover) { 19385 // Try one last time; if we fail again we're really in trouble 19386 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19387 } 19388 } 19389 } 19390 19391 /** 19392 * Destroy storage areas for given user on all mounted devices. 19393 */ 19394 void destroyUserData(int userId, int flags) { 19395 synchronized (mInstallLock) { 19396 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19397 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19398 final String volumeUuid = vol.getFsUuid(); 19399 destroyUserDataLI(volumeUuid, userId, flags); 19400 } 19401 } 19402 } 19403 19404 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19405 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19406 try { 19407 // Clean up app data, profile data, and media data 19408 mInstaller.destroyUserData(volumeUuid, userId, flags); 19409 19410 // Clean up system data 19411 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19412 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19413 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19414 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19415 } 19416 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19417 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19418 } 19419 } 19420 19421 // Data with special labels is now gone, so finish the job 19422 storage.destroyUserStorage(volumeUuid, userId, flags); 19423 19424 } catch (Exception e) { 19425 logCriticalInfo(Log.WARN, 19426 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19427 } 19428 } 19429 19430 /** 19431 * Examine all users present on given mounted volume, and destroy data 19432 * belonging to users that are no longer valid, or whose user ID has been 19433 * recycled. 19434 */ 19435 private void reconcileUsers(String volumeUuid) { 19436 final List<File> files = new ArrayList<>(); 19437 Collections.addAll(files, FileUtils 19438 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19439 Collections.addAll(files, FileUtils 19440 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19441 Collections.addAll(files, FileUtils 19442 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19443 Collections.addAll(files, FileUtils 19444 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19445 for (File file : files) { 19446 if (!file.isDirectory()) continue; 19447 19448 final int userId; 19449 final UserInfo info; 19450 try { 19451 userId = Integer.parseInt(file.getName()); 19452 info = sUserManager.getUserInfo(userId); 19453 } catch (NumberFormatException e) { 19454 Slog.w(TAG, "Invalid user directory " + file); 19455 continue; 19456 } 19457 19458 boolean destroyUser = false; 19459 if (info == null) { 19460 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19461 + " because no matching user was found"); 19462 destroyUser = true; 19463 } else if (!mOnlyCore) { 19464 try { 19465 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19466 } catch (IOException e) { 19467 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19468 + " because we failed to enforce serial number: " + e); 19469 destroyUser = true; 19470 } 19471 } 19472 19473 if (destroyUser) { 19474 synchronized (mInstallLock) { 19475 destroyUserDataLI(volumeUuid, userId, 19476 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19477 } 19478 } 19479 } 19480 } 19481 19482 private void assertPackageKnown(String volumeUuid, String packageName) 19483 throws PackageManagerException { 19484 synchronized (mPackages) { 19485 final PackageSetting ps = mSettings.mPackages.get(packageName); 19486 if (ps == null) { 19487 throw new PackageManagerException("Package " + packageName + " is unknown"); 19488 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19489 throw new PackageManagerException( 19490 "Package " + packageName + " found on unknown volume " + volumeUuid 19491 + "; expected volume " + ps.volumeUuid); 19492 } 19493 } 19494 } 19495 19496 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19497 throws PackageManagerException { 19498 synchronized (mPackages) { 19499 final PackageSetting ps = mSettings.mPackages.get(packageName); 19500 if (ps == null) { 19501 throw new PackageManagerException("Package " + packageName + " is unknown"); 19502 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19503 throw new PackageManagerException( 19504 "Package " + packageName + " found on unknown volume " + volumeUuid 19505 + "; expected volume " + ps.volumeUuid); 19506 } else if (!ps.getInstalled(userId)) { 19507 throw new PackageManagerException( 19508 "Package " + packageName + " not installed for user " + userId); 19509 } 19510 } 19511 } 19512 19513 /** 19514 * Examine all apps present on given mounted volume, and destroy apps that 19515 * aren't expected, either due to uninstallation or reinstallation on 19516 * another volume. 19517 */ 19518 private void reconcileApps(String volumeUuid) { 19519 final File[] files = FileUtils 19520 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19521 for (File file : files) { 19522 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19523 && !PackageInstallerService.isStageName(file.getName()); 19524 if (!isPackage) { 19525 // Ignore entries which are not packages 19526 continue; 19527 } 19528 19529 try { 19530 final PackageLite pkg = PackageParser.parsePackageLite(file, 19531 PackageParser.PARSE_MUST_BE_APK); 19532 assertPackageKnown(volumeUuid, pkg.packageName); 19533 19534 } catch (PackageParserException | PackageManagerException e) { 19535 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19536 synchronized (mInstallLock) { 19537 removeCodePathLI(file); 19538 } 19539 } 19540 } 19541 } 19542 19543 /** 19544 * Reconcile all app data for the given user. 19545 * <p> 19546 * Verifies that directories exist and that ownership and labeling is 19547 * correct for all installed apps on all mounted volumes. 19548 */ 19549 void reconcileAppsData(int userId, int flags) { 19550 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19551 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19552 final String volumeUuid = vol.getFsUuid(); 19553 synchronized (mInstallLock) { 19554 reconcileAppsDataLI(volumeUuid, userId, flags); 19555 } 19556 } 19557 } 19558 19559 /** 19560 * Reconcile all app data on given mounted volume. 19561 * <p> 19562 * Destroys app data that isn't expected, either due to uninstallation or 19563 * reinstallation on another volume. 19564 * <p> 19565 * Verifies that directories exist and that ownership and labeling is 19566 * correct for all installed apps. 19567 */ 19568 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19569 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19570 + Integer.toHexString(flags)); 19571 19572 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19573 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19574 19575 boolean restoreconNeeded = false; 19576 19577 // First look for stale data that doesn't belong, and check if things 19578 // have changed since we did our last restorecon 19579 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19580 if (StorageManager.isFileEncryptedNativeOrEmulated() 19581 && !StorageManager.isUserKeyUnlocked(userId)) { 19582 throw new RuntimeException( 19583 "Yikes, someone asked us to reconcile CE storage while " + userId 19584 + " was still locked; this would have caused massive data loss!"); 19585 } 19586 19587 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19588 19589 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19590 for (File file : files) { 19591 final String packageName = file.getName(); 19592 try { 19593 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19594 } catch (PackageManagerException e) { 19595 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19596 try { 19597 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19598 StorageManager.FLAG_STORAGE_CE, 0); 19599 } catch (InstallerException e2) { 19600 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19601 } 19602 } 19603 } 19604 } 19605 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19606 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19607 19608 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19609 for (File file : files) { 19610 final String packageName = file.getName(); 19611 try { 19612 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19613 } catch (PackageManagerException e) { 19614 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19615 try { 19616 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19617 StorageManager.FLAG_STORAGE_DE, 0); 19618 } catch (InstallerException e2) { 19619 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19620 } 19621 } 19622 } 19623 } 19624 19625 // Ensure that data directories are ready to roll for all packages 19626 // installed for this volume and user 19627 final List<PackageSetting> packages; 19628 synchronized (mPackages) { 19629 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19630 } 19631 int preparedCount = 0; 19632 for (PackageSetting ps : packages) { 19633 final String packageName = ps.name; 19634 if (ps.pkg == null) { 19635 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19636 // TODO: might be due to legacy ASEC apps; we should circle back 19637 // and reconcile again once they're scanned 19638 continue; 19639 } 19640 19641 if (ps.getInstalled(userId)) { 19642 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19643 19644 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19645 // We may have just shuffled around app data directories, so 19646 // prepare them one more time 19647 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19648 } 19649 19650 preparedCount++; 19651 } 19652 } 19653 19654 if (restoreconNeeded) { 19655 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19656 SELinuxMMAC.setRestoreconDone(ceDir); 19657 } 19658 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19659 SELinuxMMAC.setRestoreconDone(deDir); 19660 } 19661 } 19662 19663 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19664 + " packages; restoreconNeeded was " + restoreconNeeded); 19665 } 19666 19667 /** 19668 * Prepare app data for the given app just after it was installed or 19669 * upgraded. This method carefully only touches users that it's installed 19670 * for, and it forces a restorecon to handle any seinfo changes. 19671 * <p> 19672 * Verifies that directories exist and that ownership and labeling is 19673 * correct for all installed apps. If there is an ownership mismatch, it 19674 * will try recovering system apps by wiping data; third-party app data is 19675 * left intact. 19676 * <p> 19677 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19678 */ 19679 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19680 final PackageSetting ps; 19681 synchronized (mPackages) { 19682 ps = mSettings.mPackages.get(pkg.packageName); 19683 mSettings.writeKernelMappingLPr(ps); 19684 } 19685 19686 final UserManager um = mContext.getSystemService(UserManager.class); 19687 UserManagerInternal umInternal = getUserManagerInternal(); 19688 for (UserInfo user : um.getUsers()) { 19689 final int flags; 19690 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19691 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19692 } else if (umInternal.isUserRunning(user.id)) { 19693 flags = StorageManager.FLAG_STORAGE_DE; 19694 } else { 19695 continue; 19696 } 19697 19698 if (ps.getInstalled(user.id)) { 19699 // Whenever an app changes, force a restorecon of its data 19700 // TODO: when user data is locked, mark that we're still dirty 19701 prepareAppDataLIF(pkg, user.id, flags, true); 19702 } 19703 } 19704 } 19705 19706 /** 19707 * Prepare app data for the given app. 19708 * <p> 19709 * Verifies that directories exist and that ownership and labeling is 19710 * correct for all installed apps. If there is an ownership mismatch, this 19711 * will try recovering system apps by wiping data; third-party app data is 19712 * left intact. 19713 */ 19714 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19715 boolean restoreconNeeded) { 19716 if (pkg == null) { 19717 Slog.wtf(TAG, "Package was null!", new Throwable()); 19718 return; 19719 } 19720 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19721 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19722 for (int i = 0; i < childCount; i++) { 19723 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19724 } 19725 } 19726 19727 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19728 boolean restoreconNeeded) { 19729 if (DEBUG_APP_DATA) { 19730 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19731 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19732 } 19733 19734 final String volumeUuid = pkg.volumeUuid; 19735 final String packageName = pkg.packageName; 19736 final ApplicationInfo app = pkg.applicationInfo; 19737 final int appId = UserHandle.getAppId(app.uid); 19738 19739 Preconditions.checkNotNull(app.seinfo); 19740 19741 try { 19742 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19743 appId, app.seinfo, app.targetSdkVersion); 19744 } catch (InstallerException e) { 19745 if (app.isSystemApp()) { 19746 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19747 + ", but trying to recover: " + e); 19748 destroyAppDataLeafLIF(pkg, userId, flags); 19749 try { 19750 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19751 appId, app.seinfo, app.targetSdkVersion); 19752 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19753 } catch (InstallerException e2) { 19754 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19755 } 19756 } else { 19757 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19758 } 19759 } 19760 19761 if (restoreconNeeded) { 19762 try { 19763 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19764 app.seinfo); 19765 } catch (InstallerException e) { 19766 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19767 } 19768 } 19769 19770 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19771 try { 19772 // CE storage is unlocked right now, so read out the inode and 19773 // remember for use later when it's locked 19774 // TODO: mark this structure as dirty so we persist it! 19775 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19776 StorageManager.FLAG_STORAGE_CE); 19777 synchronized (mPackages) { 19778 final PackageSetting ps = mSettings.mPackages.get(packageName); 19779 if (ps != null) { 19780 ps.setCeDataInode(ceDataInode, userId); 19781 } 19782 } 19783 } catch (InstallerException e) { 19784 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19785 } 19786 } 19787 19788 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19789 } 19790 19791 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19792 if (pkg == null) { 19793 Slog.wtf(TAG, "Package was null!", new Throwable()); 19794 return; 19795 } 19796 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19797 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19798 for (int i = 0; i < childCount; i++) { 19799 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19800 } 19801 } 19802 19803 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19804 final String volumeUuid = pkg.volumeUuid; 19805 final String packageName = pkg.packageName; 19806 final ApplicationInfo app = pkg.applicationInfo; 19807 19808 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19809 // Create a native library symlink only if we have native libraries 19810 // and if the native libraries are 32 bit libraries. We do not provide 19811 // this symlink for 64 bit libraries. 19812 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19813 final String nativeLibPath = app.nativeLibraryDir; 19814 try { 19815 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19816 nativeLibPath, userId); 19817 } catch (InstallerException e) { 19818 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19819 } 19820 } 19821 } 19822 } 19823 19824 /** 19825 * For system apps on non-FBE devices, this method migrates any existing 19826 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19827 * requested by the app. 19828 */ 19829 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19830 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19831 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19832 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19833 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19834 try { 19835 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19836 storageTarget); 19837 } catch (InstallerException e) { 19838 logCriticalInfo(Log.WARN, 19839 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19840 } 19841 return true; 19842 } else { 19843 return false; 19844 } 19845 } 19846 19847 public PackageFreezer freezePackage(String packageName, String killReason) { 19848 return new PackageFreezer(packageName, killReason); 19849 } 19850 19851 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19852 String killReason) { 19853 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19854 return new PackageFreezer(); 19855 } else { 19856 return freezePackage(packageName, killReason); 19857 } 19858 } 19859 19860 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19861 String killReason) { 19862 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19863 return new PackageFreezer(); 19864 } else { 19865 return freezePackage(packageName, killReason); 19866 } 19867 } 19868 19869 /** 19870 * Class that freezes and kills the given package upon creation, and 19871 * unfreezes it upon closing. This is typically used when doing surgery on 19872 * app code/data to prevent the app from running while you're working. 19873 */ 19874 private class PackageFreezer implements AutoCloseable { 19875 private final String mPackageName; 19876 private final PackageFreezer[] mChildren; 19877 19878 private final boolean mWeFroze; 19879 19880 private final AtomicBoolean mClosed = new AtomicBoolean(); 19881 private final CloseGuard mCloseGuard = CloseGuard.get(); 19882 19883 /** 19884 * Create and return a stub freezer that doesn't actually do anything, 19885 * typically used when someone requested 19886 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19887 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19888 */ 19889 public PackageFreezer() { 19890 mPackageName = null; 19891 mChildren = null; 19892 mWeFroze = false; 19893 mCloseGuard.open("close"); 19894 } 19895 19896 public PackageFreezer(String packageName, String killReason) { 19897 synchronized (mPackages) { 19898 mPackageName = packageName; 19899 mWeFroze = mFrozenPackages.add(mPackageName); 19900 19901 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19902 if (ps != null) { 19903 killApplication(ps.name, ps.appId, killReason); 19904 } 19905 19906 final PackageParser.Package p = mPackages.get(packageName); 19907 if (p != null && p.childPackages != null) { 19908 final int N = p.childPackages.size(); 19909 mChildren = new PackageFreezer[N]; 19910 for (int i = 0; i < N; i++) { 19911 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19912 killReason); 19913 } 19914 } else { 19915 mChildren = null; 19916 } 19917 } 19918 mCloseGuard.open("close"); 19919 } 19920 19921 @Override 19922 protected void finalize() throws Throwable { 19923 try { 19924 mCloseGuard.warnIfOpen(); 19925 close(); 19926 } finally { 19927 super.finalize(); 19928 } 19929 } 19930 19931 @Override 19932 public void close() { 19933 mCloseGuard.close(); 19934 if (mClosed.compareAndSet(false, true)) { 19935 synchronized (mPackages) { 19936 if (mWeFroze) { 19937 mFrozenPackages.remove(mPackageName); 19938 } 19939 19940 if (mChildren != null) { 19941 for (PackageFreezer freezer : mChildren) { 19942 freezer.close(); 19943 } 19944 } 19945 } 19946 } 19947 } 19948 } 19949 19950 /** 19951 * Verify that given package is currently frozen. 19952 */ 19953 private void checkPackageFrozen(String packageName) { 19954 synchronized (mPackages) { 19955 if (!mFrozenPackages.contains(packageName)) { 19956 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19957 } 19958 } 19959 } 19960 19961 @Override 19962 public int movePackage(final String packageName, final String volumeUuid) { 19963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19964 19965 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19966 final int moveId = mNextMoveId.getAndIncrement(); 19967 mHandler.post(new Runnable() { 19968 @Override 19969 public void run() { 19970 try { 19971 movePackageInternal(packageName, volumeUuid, moveId, user); 19972 } catch (PackageManagerException e) { 19973 Slog.w(TAG, "Failed to move " + packageName, e); 19974 mMoveCallbacks.notifyStatusChanged(moveId, 19975 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19976 } 19977 } 19978 }); 19979 return moveId; 19980 } 19981 19982 private void movePackageInternal(final String packageName, final String volumeUuid, 19983 final int moveId, UserHandle user) throws PackageManagerException { 19984 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19985 final PackageManager pm = mContext.getPackageManager(); 19986 19987 final boolean currentAsec; 19988 final String currentVolumeUuid; 19989 final File codeFile; 19990 final String installerPackageName; 19991 final String packageAbiOverride; 19992 final int appId; 19993 final String seinfo; 19994 final String label; 19995 final int targetSdkVersion; 19996 final PackageFreezer freezer; 19997 final int[] installedUserIds; 19998 19999 // reader 20000 synchronized (mPackages) { 20001 final PackageParser.Package pkg = mPackages.get(packageName); 20002 final PackageSetting ps = mSettings.mPackages.get(packageName); 20003 if (pkg == null || ps == null) { 20004 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20005 } 20006 20007 if (pkg.applicationInfo.isSystemApp()) { 20008 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20009 "Cannot move system application"); 20010 } 20011 20012 if (pkg.applicationInfo.isExternalAsec()) { 20013 currentAsec = true; 20014 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20015 } else if (pkg.applicationInfo.isForwardLocked()) { 20016 currentAsec = true; 20017 currentVolumeUuid = "forward_locked"; 20018 } else { 20019 currentAsec = false; 20020 currentVolumeUuid = ps.volumeUuid; 20021 20022 final File probe = new File(pkg.codePath); 20023 final File probeOat = new File(probe, "oat"); 20024 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20025 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20026 "Move only supported for modern cluster style installs"); 20027 } 20028 } 20029 20030 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20031 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20032 "Package already moved to " + volumeUuid); 20033 } 20034 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20035 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20036 "Device admin cannot be moved"); 20037 } 20038 20039 if (mFrozenPackages.contains(packageName)) { 20040 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20041 "Failed to move already frozen package"); 20042 } 20043 20044 codeFile = new File(pkg.codePath); 20045 installerPackageName = ps.installerPackageName; 20046 packageAbiOverride = ps.cpuAbiOverrideString; 20047 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20048 seinfo = pkg.applicationInfo.seinfo; 20049 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20050 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20051 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20052 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20053 } 20054 20055 final Bundle extras = new Bundle(); 20056 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20057 extras.putString(Intent.EXTRA_TITLE, label); 20058 mMoveCallbacks.notifyCreated(moveId, extras); 20059 20060 int installFlags; 20061 final boolean moveCompleteApp; 20062 final File measurePath; 20063 20064 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20065 installFlags = INSTALL_INTERNAL; 20066 moveCompleteApp = !currentAsec; 20067 measurePath = Environment.getDataAppDirectory(volumeUuid); 20068 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20069 installFlags = INSTALL_EXTERNAL; 20070 moveCompleteApp = false; 20071 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20072 } else { 20073 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20074 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20075 || !volume.isMountedWritable()) { 20076 freezer.close(); 20077 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20078 "Move location not mounted private volume"); 20079 } 20080 20081 Preconditions.checkState(!currentAsec); 20082 20083 installFlags = INSTALL_INTERNAL; 20084 moveCompleteApp = true; 20085 measurePath = Environment.getDataAppDirectory(volumeUuid); 20086 } 20087 20088 final PackageStats stats = new PackageStats(null, -1); 20089 synchronized (mInstaller) { 20090 for (int userId : installedUserIds) { 20091 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20092 freezer.close(); 20093 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20094 "Failed to measure package size"); 20095 } 20096 } 20097 } 20098 20099 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20100 + stats.dataSize); 20101 20102 final long startFreeBytes = measurePath.getFreeSpace(); 20103 final long sizeBytes; 20104 if (moveCompleteApp) { 20105 sizeBytes = stats.codeSize + stats.dataSize; 20106 } else { 20107 sizeBytes = stats.codeSize; 20108 } 20109 20110 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20111 freezer.close(); 20112 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20113 "Not enough free space to move"); 20114 } 20115 20116 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20117 20118 final CountDownLatch installedLatch = new CountDownLatch(1); 20119 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20120 @Override 20121 public void onUserActionRequired(Intent intent) throws RemoteException { 20122 throw new IllegalStateException(); 20123 } 20124 20125 @Override 20126 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20127 Bundle extras) throws RemoteException { 20128 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20129 + PackageManager.installStatusToString(returnCode, msg)); 20130 20131 installedLatch.countDown(); 20132 freezer.close(); 20133 20134 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20135 switch (status) { 20136 case PackageInstaller.STATUS_SUCCESS: 20137 mMoveCallbacks.notifyStatusChanged(moveId, 20138 PackageManager.MOVE_SUCCEEDED); 20139 break; 20140 case PackageInstaller.STATUS_FAILURE_STORAGE: 20141 mMoveCallbacks.notifyStatusChanged(moveId, 20142 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20143 break; 20144 default: 20145 mMoveCallbacks.notifyStatusChanged(moveId, 20146 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20147 break; 20148 } 20149 } 20150 }; 20151 20152 final MoveInfo move; 20153 if (moveCompleteApp) { 20154 // Kick off a thread to report progress estimates 20155 new Thread() { 20156 @Override 20157 public void run() { 20158 while (true) { 20159 try { 20160 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20161 break; 20162 } 20163 } catch (InterruptedException ignored) { 20164 } 20165 20166 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20167 final int progress = 10 + (int) MathUtils.constrain( 20168 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20169 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20170 } 20171 } 20172 }.start(); 20173 20174 final String dataAppName = codeFile.getName(); 20175 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20176 dataAppName, appId, seinfo, targetSdkVersion); 20177 } else { 20178 move = null; 20179 } 20180 20181 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20182 20183 final Message msg = mHandler.obtainMessage(INIT_COPY); 20184 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20185 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20186 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20187 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20188 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20189 msg.obj = params; 20190 20191 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20192 System.identityHashCode(msg.obj)); 20193 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20194 System.identityHashCode(msg.obj)); 20195 20196 mHandler.sendMessage(msg); 20197 } 20198 20199 @Override 20200 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20201 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20202 20203 final int realMoveId = mNextMoveId.getAndIncrement(); 20204 final Bundle extras = new Bundle(); 20205 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20206 mMoveCallbacks.notifyCreated(realMoveId, extras); 20207 20208 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20209 @Override 20210 public void onCreated(int moveId, Bundle extras) { 20211 // Ignored 20212 } 20213 20214 @Override 20215 public void onStatusChanged(int moveId, int status, long estMillis) { 20216 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20217 } 20218 }; 20219 20220 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20221 storage.setPrimaryStorageUuid(volumeUuid, callback); 20222 return realMoveId; 20223 } 20224 20225 @Override 20226 public int getMoveStatus(int moveId) { 20227 mContext.enforceCallingOrSelfPermission( 20228 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20229 return mMoveCallbacks.mLastStatus.get(moveId); 20230 } 20231 20232 @Override 20233 public void registerMoveCallback(IPackageMoveObserver callback) { 20234 mContext.enforceCallingOrSelfPermission( 20235 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20236 mMoveCallbacks.register(callback); 20237 } 20238 20239 @Override 20240 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20241 mContext.enforceCallingOrSelfPermission( 20242 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20243 mMoveCallbacks.unregister(callback); 20244 } 20245 20246 @Override 20247 public boolean setInstallLocation(int loc) { 20248 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20249 null); 20250 if (getInstallLocation() == loc) { 20251 return true; 20252 } 20253 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20254 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20255 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20256 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20257 return true; 20258 } 20259 return false; 20260 } 20261 20262 @Override 20263 public int getInstallLocation() { 20264 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20265 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20266 PackageHelper.APP_INSTALL_AUTO); 20267 } 20268 20269 /** Called by UserManagerService */ 20270 void cleanUpUser(UserManagerService userManager, int userHandle) { 20271 synchronized (mPackages) { 20272 mDirtyUsers.remove(userHandle); 20273 mUserNeedsBadging.delete(userHandle); 20274 mSettings.removeUserLPw(userHandle); 20275 mPendingBroadcasts.remove(userHandle); 20276 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20277 removeUnusedPackagesLPw(userManager, userHandle); 20278 } 20279 } 20280 20281 /** 20282 * We're removing userHandle and would like to remove any downloaded packages 20283 * that are no longer in use by any other user. 20284 * @param userHandle the user being removed 20285 */ 20286 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20287 final boolean DEBUG_CLEAN_APKS = false; 20288 int [] users = userManager.getUserIds(); 20289 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20290 while (psit.hasNext()) { 20291 PackageSetting ps = psit.next(); 20292 if (ps.pkg == null) { 20293 continue; 20294 } 20295 final String packageName = ps.pkg.packageName; 20296 // Skip over if system app 20297 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20298 continue; 20299 } 20300 if (DEBUG_CLEAN_APKS) { 20301 Slog.i(TAG, "Checking package " + packageName); 20302 } 20303 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20304 if (keep) { 20305 if (DEBUG_CLEAN_APKS) { 20306 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20307 } 20308 } else { 20309 for (int i = 0; i < users.length; i++) { 20310 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20311 keep = true; 20312 if (DEBUG_CLEAN_APKS) { 20313 Slog.i(TAG, " Keeping package " + packageName + " for user " 20314 + users[i]); 20315 } 20316 break; 20317 } 20318 } 20319 } 20320 if (!keep) { 20321 if (DEBUG_CLEAN_APKS) { 20322 Slog.i(TAG, " Removing package " + packageName); 20323 } 20324 mHandler.post(new Runnable() { 20325 public void run() { 20326 deletePackageX(packageName, userHandle, 0); 20327 } //end run 20328 }); 20329 } 20330 } 20331 } 20332 20333 /** Called by UserManagerService */ 20334 void createNewUser(int userId) { 20335 synchronized (mInstallLock) { 20336 mSettings.createNewUserLI(this, mInstaller, userId); 20337 } 20338 synchronized (mPackages) { 20339 scheduleWritePackageRestrictionsLocked(userId); 20340 scheduleWritePackageListLocked(userId); 20341 applyFactoryDefaultBrowserLPw(userId); 20342 primeDomainVerificationsLPw(userId); 20343 } 20344 } 20345 20346 void onBeforeUserStartUninitialized(final int userId) { 20347 synchronized (mPackages) { 20348 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20349 return; 20350 } 20351 } 20352 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20353 // If permission review for legacy apps is required, we represent 20354 // dagerous permissions for such apps as always granted runtime 20355 // permissions to keep per user flag state whether review is needed. 20356 // Hence, if a new user is added we have to propagate dangerous 20357 // permission grants for these legacy apps. 20358 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20359 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20360 | UPDATE_PERMISSIONS_REPLACE_ALL); 20361 } 20362 } 20363 20364 @Override 20365 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20366 mContext.enforceCallingOrSelfPermission( 20367 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20368 "Only package verification agents can read the verifier device identity"); 20369 20370 synchronized (mPackages) { 20371 return mSettings.getVerifierDeviceIdentityLPw(); 20372 } 20373 } 20374 20375 @Override 20376 public void setPermissionEnforced(String permission, boolean enforced) { 20377 // TODO: Now that we no longer change GID for storage, this should to away. 20378 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20379 "setPermissionEnforced"); 20380 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20381 synchronized (mPackages) { 20382 if (mSettings.mReadExternalStorageEnforced == null 20383 || mSettings.mReadExternalStorageEnforced != enforced) { 20384 mSettings.mReadExternalStorageEnforced = enforced; 20385 mSettings.writeLPr(); 20386 } 20387 } 20388 // kill any non-foreground processes so we restart them and 20389 // grant/revoke the GID. 20390 final IActivityManager am = ActivityManagerNative.getDefault(); 20391 if (am != null) { 20392 final long token = Binder.clearCallingIdentity(); 20393 try { 20394 am.killProcessesBelowForeground("setPermissionEnforcement"); 20395 } catch (RemoteException e) { 20396 } finally { 20397 Binder.restoreCallingIdentity(token); 20398 } 20399 } 20400 } else { 20401 throw new IllegalArgumentException("No selective enforcement for " + permission); 20402 } 20403 } 20404 20405 @Override 20406 @Deprecated 20407 public boolean isPermissionEnforced(String permission) { 20408 return true; 20409 } 20410 20411 @Override 20412 public boolean isStorageLow() { 20413 final long token = Binder.clearCallingIdentity(); 20414 try { 20415 final DeviceStorageMonitorInternal 20416 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20417 if (dsm != null) { 20418 return dsm.isMemoryLow(); 20419 } else { 20420 return false; 20421 } 20422 } finally { 20423 Binder.restoreCallingIdentity(token); 20424 } 20425 } 20426 20427 @Override 20428 public IPackageInstaller getPackageInstaller() { 20429 return mInstallerService; 20430 } 20431 20432 private boolean userNeedsBadging(int userId) { 20433 int index = mUserNeedsBadging.indexOfKey(userId); 20434 if (index < 0) { 20435 final UserInfo userInfo; 20436 final long token = Binder.clearCallingIdentity(); 20437 try { 20438 userInfo = sUserManager.getUserInfo(userId); 20439 } finally { 20440 Binder.restoreCallingIdentity(token); 20441 } 20442 final boolean b; 20443 if (userInfo != null && userInfo.isManagedProfile()) { 20444 b = true; 20445 } else { 20446 b = false; 20447 } 20448 mUserNeedsBadging.put(userId, b); 20449 return b; 20450 } 20451 return mUserNeedsBadging.valueAt(index); 20452 } 20453 20454 @Override 20455 public KeySet getKeySetByAlias(String packageName, String alias) { 20456 if (packageName == null || alias == null) { 20457 return null; 20458 } 20459 synchronized(mPackages) { 20460 final PackageParser.Package pkg = mPackages.get(packageName); 20461 if (pkg == null) { 20462 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20463 throw new IllegalArgumentException("Unknown package: " + packageName); 20464 } 20465 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20466 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20467 } 20468 } 20469 20470 @Override 20471 public KeySet getSigningKeySet(String packageName) { 20472 if (packageName == null) { 20473 return null; 20474 } 20475 synchronized(mPackages) { 20476 final PackageParser.Package pkg = mPackages.get(packageName); 20477 if (pkg == null) { 20478 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20479 throw new IllegalArgumentException("Unknown package: " + packageName); 20480 } 20481 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20482 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20483 throw new SecurityException("May not access signing KeySet of other apps."); 20484 } 20485 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20486 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20487 } 20488 } 20489 20490 @Override 20491 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20492 if (packageName == null || ks == null) { 20493 return false; 20494 } 20495 synchronized(mPackages) { 20496 final PackageParser.Package pkg = mPackages.get(packageName); 20497 if (pkg == null) { 20498 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20499 throw new IllegalArgumentException("Unknown package: " + packageName); 20500 } 20501 IBinder ksh = ks.getToken(); 20502 if (ksh instanceof KeySetHandle) { 20503 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20504 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20505 } 20506 return false; 20507 } 20508 } 20509 20510 @Override 20511 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20512 if (packageName == null || ks == null) { 20513 return false; 20514 } 20515 synchronized(mPackages) { 20516 final PackageParser.Package pkg = mPackages.get(packageName); 20517 if (pkg == null) { 20518 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20519 throw new IllegalArgumentException("Unknown package: " + packageName); 20520 } 20521 IBinder ksh = ks.getToken(); 20522 if (ksh instanceof KeySetHandle) { 20523 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20524 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20525 } 20526 return false; 20527 } 20528 } 20529 20530 private void deletePackageIfUnusedLPr(final String packageName) { 20531 PackageSetting ps = mSettings.mPackages.get(packageName); 20532 if (ps == null) { 20533 return; 20534 } 20535 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20536 // TODO Implement atomic delete if package is unused 20537 // It is currently possible that the package will be deleted even if it is installed 20538 // after this method returns. 20539 mHandler.post(new Runnable() { 20540 public void run() { 20541 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20542 } 20543 }); 20544 } 20545 } 20546 20547 /** 20548 * Check and throw if the given before/after packages would be considered a 20549 * downgrade. 20550 */ 20551 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20552 throws PackageManagerException { 20553 if (after.versionCode < before.mVersionCode) { 20554 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20555 "Update version code " + after.versionCode + " is older than current " 20556 + before.mVersionCode); 20557 } else if (after.versionCode == before.mVersionCode) { 20558 if (after.baseRevisionCode < before.baseRevisionCode) { 20559 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20560 "Update base revision code " + after.baseRevisionCode 20561 + " is older than current " + before.baseRevisionCode); 20562 } 20563 20564 if (!ArrayUtils.isEmpty(after.splitNames)) { 20565 for (int i = 0; i < after.splitNames.length; i++) { 20566 final String splitName = after.splitNames[i]; 20567 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20568 if (j != -1) { 20569 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20570 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20571 "Update split " + splitName + " revision code " 20572 + after.splitRevisionCodes[i] + " is older than current " 20573 + before.splitRevisionCodes[j]); 20574 } 20575 } 20576 } 20577 } 20578 } 20579 } 20580 20581 private static class MoveCallbacks extends Handler { 20582 private static final int MSG_CREATED = 1; 20583 private static final int MSG_STATUS_CHANGED = 2; 20584 20585 private final RemoteCallbackList<IPackageMoveObserver> 20586 mCallbacks = new RemoteCallbackList<>(); 20587 20588 private final SparseIntArray mLastStatus = new SparseIntArray(); 20589 20590 public MoveCallbacks(Looper looper) { 20591 super(looper); 20592 } 20593 20594 public void register(IPackageMoveObserver callback) { 20595 mCallbacks.register(callback); 20596 } 20597 20598 public void unregister(IPackageMoveObserver callback) { 20599 mCallbacks.unregister(callback); 20600 } 20601 20602 @Override 20603 public void handleMessage(Message msg) { 20604 final SomeArgs args = (SomeArgs) msg.obj; 20605 final int n = mCallbacks.beginBroadcast(); 20606 for (int i = 0; i < n; i++) { 20607 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20608 try { 20609 invokeCallback(callback, msg.what, args); 20610 } catch (RemoteException ignored) { 20611 } 20612 } 20613 mCallbacks.finishBroadcast(); 20614 args.recycle(); 20615 } 20616 20617 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20618 throws RemoteException { 20619 switch (what) { 20620 case MSG_CREATED: { 20621 callback.onCreated(args.argi1, (Bundle) args.arg2); 20622 break; 20623 } 20624 case MSG_STATUS_CHANGED: { 20625 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20626 break; 20627 } 20628 } 20629 } 20630 20631 private void notifyCreated(int moveId, Bundle extras) { 20632 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20633 20634 final SomeArgs args = SomeArgs.obtain(); 20635 args.argi1 = moveId; 20636 args.arg2 = extras; 20637 obtainMessage(MSG_CREATED, args).sendToTarget(); 20638 } 20639 20640 private void notifyStatusChanged(int moveId, int status) { 20641 notifyStatusChanged(moveId, status, -1); 20642 } 20643 20644 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20645 Slog.v(TAG, "Move " + moveId + " status " + status); 20646 20647 final SomeArgs args = SomeArgs.obtain(); 20648 args.argi1 = moveId; 20649 args.argi2 = status; 20650 args.arg3 = estMillis; 20651 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20652 20653 synchronized (mLastStatus) { 20654 mLastStatus.put(moveId, status); 20655 } 20656 } 20657 } 20658 20659 private final static class OnPermissionChangeListeners extends Handler { 20660 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20661 20662 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20663 new RemoteCallbackList<>(); 20664 20665 public OnPermissionChangeListeners(Looper looper) { 20666 super(looper); 20667 } 20668 20669 @Override 20670 public void handleMessage(Message msg) { 20671 switch (msg.what) { 20672 case MSG_ON_PERMISSIONS_CHANGED: { 20673 final int uid = msg.arg1; 20674 handleOnPermissionsChanged(uid); 20675 } break; 20676 } 20677 } 20678 20679 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20680 mPermissionListeners.register(listener); 20681 20682 } 20683 20684 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20685 mPermissionListeners.unregister(listener); 20686 } 20687 20688 public void onPermissionsChanged(int uid) { 20689 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20690 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20691 } 20692 } 20693 20694 private void handleOnPermissionsChanged(int uid) { 20695 final int count = mPermissionListeners.beginBroadcast(); 20696 try { 20697 for (int i = 0; i < count; i++) { 20698 IOnPermissionsChangeListener callback = mPermissionListeners 20699 .getBroadcastItem(i); 20700 try { 20701 callback.onPermissionsChanged(uid); 20702 } catch (RemoteException e) { 20703 Log.e(TAG, "Permission listener is dead", e); 20704 } 20705 } 20706 } finally { 20707 mPermissionListeners.finishBroadcast(); 20708 } 20709 } 20710 } 20711 20712 private class PackageManagerInternalImpl extends PackageManagerInternal { 20713 @Override 20714 public void setLocationPackagesProvider(PackagesProvider provider) { 20715 synchronized (mPackages) { 20716 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20717 } 20718 } 20719 20720 @Override 20721 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20722 synchronized (mPackages) { 20723 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20724 } 20725 } 20726 20727 @Override 20728 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20729 synchronized (mPackages) { 20730 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20731 } 20732 } 20733 20734 @Override 20735 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20736 synchronized (mPackages) { 20737 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20738 } 20739 } 20740 20741 @Override 20742 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20743 synchronized (mPackages) { 20744 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20745 } 20746 } 20747 20748 @Override 20749 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20750 synchronized (mPackages) { 20751 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20752 } 20753 } 20754 20755 @Override 20756 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20757 synchronized (mPackages) { 20758 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20759 packageName, userId); 20760 } 20761 } 20762 20763 @Override 20764 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20765 synchronized (mPackages) { 20766 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20767 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20768 packageName, userId); 20769 } 20770 } 20771 20772 @Override 20773 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20774 synchronized (mPackages) { 20775 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20776 packageName, userId); 20777 } 20778 } 20779 20780 @Override 20781 public void setKeepUninstalledPackages(final List<String> packageList) { 20782 Preconditions.checkNotNull(packageList); 20783 List<String> removedFromList = null; 20784 synchronized (mPackages) { 20785 if (mKeepUninstalledPackages != null) { 20786 final int packagesCount = mKeepUninstalledPackages.size(); 20787 for (int i = 0; i < packagesCount; i++) { 20788 String oldPackage = mKeepUninstalledPackages.get(i); 20789 if (packageList != null && packageList.contains(oldPackage)) { 20790 continue; 20791 } 20792 if (removedFromList == null) { 20793 removedFromList = new ArrayList<>(); 20794 } 20795 removedFromList.add(oldPackage); 20796 } 20797 } 20798 mKeepUninstalledPackages = new ArrayList<>(packageList); 20799 if (removedFromList != null) { 20800 final int removedCount = removedFromList.size(); 20801 for (int i = 0; i < removedCount; i++) { 20802 deletePackageIfUnusedLPr(removedFromList.get(i)); 20803 } 20804 } 20805 } 20806 } 20807 20808 @Override 20809 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20810 synchronized (mPackages) { 20811 // If we do not support permission review, done. 20812 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20813 return false; 20814 } 20815 20816 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20817 if (packageSetting == null) { 20818 return false; 20819 } 20820 20821 // Permission review applies only to apps not supporting the new permission model. 20822 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20823 return false; 20824 } 20825 20826 // Legacy apps have the permission and get user consent on launch. 20827 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20828 return permissionsState.isPermissionReviewRequired(userId); 20829 } 20830 } 20831 20832 @Override 20833 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20834 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20835 } 20836 20837 @Override 20838 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20839 int userId) { 20840 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20841 } 20842 20843 @Override 20844 public void setDeviceAndProfileOwnerPackages( 20845 int deviceOwnerUserId, String deviceOwnerPackage, 20846 SparseArray<String> profileOwnerPackages) { 20847 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20848 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20849 } 20850 20851 @Override 20852 public boolean canPackageBeWiped(int userId, String packageName) { 20853 return mProtectedPackages.canPackageBeWiped(userId, 20854 packageName); 20855 } 20856 } 20857 20858 @Override 20859 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20860 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20861 synchronized (mPackages) { 20862 final long identity = Binder.clearCallingIdentity(); 20863 try { 20864 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20865 packageNames, userId); 20866 } finally { 20867 Binder.restoreCallingIdentity(identity); 20868 } 20869 } 20870 } 20871 20872 private static void enforceSystemOrPhoneCaller(String tag) { 20873 int callingUid = Binder.getCallingUid(); 20874 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20875 throw new SecurityException( 20876 "Cannot call " + tag + " from UID " + callingUid); 20877 } 20878 } 20879 20880 boolean isHistoricalPackageUsageAvailable() { 20881 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20882 } 20883 20884 /** 20885 * Return a <b>copy</b> of the collection of packages known to the package manager. 20886 * @return A copy of the values of mPackages. 20887 */ 20888 Collection<PackageParser.Package> getPackages() { 20889 synchronized (mPackages) { 20890 return new ArrayList<>(mPackages.values()); 20891 } 20892 } 20893 20894 /** 20895 * Logs process start information (including base APK hash) to the security log. 20896 * @hide 20897 */ 20898 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20899 String apkFile, int pid) { 20900 if (!SecurityLog.isLoggingEnabled()) { 20901 return; 20902 } 20903 Bundle data = new Bundle(); 20904 data.putLong("startTimestamp", System.currentTimeMillis()); 20905 data.putString("processName", processName); 20906 data.putInt("uid", uid); 20907 data.putString("seinfo", seinfo); 20908 data.putString("apkFile", apkFile); 20909 data.putInt("pid", pid); 20910 Message msg = mProcessLoggingHandler.obtainMessage( 20911 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20912 msg.setData(data); 20913 mProcessLoggingHandler.sendMessage(msg); 20914 } 20915} 20916